@utsp/render 0.10.0 → 0.11.0-nightly.20251213232121.8b318c1

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.mjs CHANGED
@@ -1,11 +1,11 @@
1
- var J=Object.defineProperty;var tt=(C,t,e)=>t in C?J(C,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):C[t]=e;var v=(C,t)=>J(C,"name",{value:t,configurable:!0});var n=(C,t,e)=>(tt(C,typeof t!="symbol"?t+"":t,e),e);var H=["#000000","#800000","#008000","#808000","#000080","#800080","#008080","#c0c0c0","#808080","#ff0000","#00ff00","#ffff00","#0000ff","#ff00ff","#00ffff","#ffffff","#080808","#121212","#1c1c1c","#262626","#303030","#3a3a3a","#444444","#4e4e4e","#585858","#626262","#6c6c6c","#767676","#808080","#8a8a8a","#949494","#9e9e9e","#a80000","#00a800","#a8a800","#0000a8","#a800a8","#00a8a8","#a8a8a8","#545454","#fc5454","#54fc54","#fcfc54","#5454fc","#fc54fc","#54fcfc","#fcfcfc","#000000",...Array(192).fill("#808080")];function et(C,t=H){return C<0||C>=t.length?"#ff00ff":t[C]}v(et,"paletteIndexToColor");function it(C,t=H){let e=t.indexOf(C.toLowerCase());return e>=0?e:0}v(it,"colorToPaletteIndex");var _=class _{constructor(t,e){n(this,"canvas");n(this,"ctx");n(this,"container");n(this,"cols",0);n(this,"rows",0);n(this,"cellWidth",0);n(this,"cellHeight",0);n(this,"offsetX",0);n(this,"offsetY",0);n(this,"strokeColor","rgba(80, 80, 80, 0.4)");n(this,"lineWidth",1);this.container=t,this.canvas=document.createElement("canvas"),this.canvas.className="grid-overlay-canvas";let i=e?.zIndex??10;this.canvas.style.cssText=`
1
+ var it=Object.defineProperty;var at=(b,t,e)=>t in b?it(b,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):b[t]=e;var v=(b,t)=>it(b,"name",{value:t,configurable:!0});var n=(b,t,e)=>(at(b,typeof t!="symbol"?t+"":t,e),e);var G=["#000000","#800000","#008000","#808000","#000080","#800080","#008080","#c0c0c0","#808080","#ff0000","#00ff00","#ffff00","#0000ff","#ff00ff","#00ffff","#ffffff","#080808","#121212","#1c1c1c","#262626","#303030","#3a3a3a","#444444","#4e4e4e","#585858","#626262","#6c6c6c","#767676","#808080","#8a8a8a","#949494","#9e9e9e","#a80000","#00a800","#a8a800","#0000a8","#a800a8","#00a8a8","#a8a8a8","#545454","#fc5454","#54fc54","#fcfc54","#5454fc","#fc54fc","#54fcfc","#fcfcfc","#000000",...Array(192).fill("#808080")];function nt(b,t=G){return b<0||b>=t.length?"#ff00ff":t[b]}v(nt,"paletteIndexToColor");function ot(b,t=G){let e=t.indexOf(b.toLowerCase());return e>=0?e:0}v(ot,"colorToPaletteIndex");var _=class _{constructor(t,e){n(this,"canvas");n(this,"ctx");n(this,"container");n(this,"cols",0);n(this,"rows",0);n(this,"cellWidth",0);n(this,"cellHeight",0);n(this,"offsetX",0);n(this,"offsetY",0);n(this,"strokeColor","rgba(80, 80, 80, 0.4)");n(this,"lineWidth",1);this.container=t,this.canvas=document.createElement("canvas"),this.canvas.className="grid-overlay-canvas";let i=e?.zIndex??10;this.canvas.style.cssText=`
2
2
  display: block !important;
3
3
  position: absolute !important;
4
4
  pointer-events: none !important;
5
5
  image-rendering: pixelated !important;
6
6
  image-rendering: crisp-edges !important;
7
7
  z-index: ${i} !important;
8
- `,this.container.appendChild(this.canvas);let s=this.canvas.getContext("2d");if(!s)throw new Error("[GridOverlay] Impossible de cr\xE9er le contexte 2D");this.ctx=s,e&&(e.strokeColor&&(this.strokeColor=e.strokeColor),e.lineWidth!==void 0&&(this.lineWidth=e.lineWidth))}setDimensions(t,e,i,s,r=0,a=0){this.cols=t,this.rows=e,this.cellWidth=i,this.cellHeight=s,this.offsetX=r,this.offsetY=a}setCanvasSize(t,e){this.canvas.width=t,this.canvas.height=e,this.ctx.setTransform(1,0,0,1,0,0)}setStyle(t){t.strokeColor&&(this.strokeColor=t.strokeColor),t.lineWidth!==void 0&&(this.lineWidth=t.lineWidth)}setTransform(t,e,i,s,r){let a=s.left-r.left,l=s.top-r.top,o=s.width,h=s.height;(this.canvas.width!==o||this.canvas.height!==h)&&(this.canvas.width=o,this.canvas.height=h);let c=this.canvas.style;c.width=`${o}px`,c.height=`${h}px`,c.left=`${a}px`,c.top=`${l}px`}render(){if(!this.ctx)return;let t=this.cols*this.cellWidth,e=this.rows*this.cellHeight,i=t>0?this.canvas.width/t:1,s=e>0?this.canvas.height/e:1,r=Math.min(i,s),a=this.cellWidth*r,l=this.cellHeight*r,o=this.cols*a,h=this.rows*l,c=this.offsetX*r,d=this.offsetY*r;if(!(o===0||h===0)){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.strokeStyle=this.strokeColor,this.ctx.lineWidth=Math.max(1,this.lineWidth*r),this.ctx.beginPath();for(let f=0;f<=this.cols;f++){let u=c+f*a+.5;this.ctx.moveTo(u,d),this.ctx.lineTo(u,d+h)}for(let f=0;f<=this.rows;f++){let u=d+f*l+.5;this.ctx.moveTo(c,u),this.ctx.lineTo(c+o,u)}this.ctx.stroke()}}update(t,e,i,s,r,a,l=0,o=0){this.setDimensions(t,e,i,s,l,o),this.setCanvasSize(r,a),this.render()}setVisible(t){this.canvas.style.display=t?"block":"none"}destroy(){this.canvas.parentElement&&this.canvas.parentElement.removeChild(this.canvas)}getCanvas(){return this.canvas}};v(_,"GridOverlay");var T=_;function M(C){return Math.sqrt(C)*16}v(M,"getAtlasColumns");function F(C){return C*256-1}v(F,"getMaxCharCode");function D(C,t){let e=Math.floor(C/256),i=C%256,s=Math.sqrt(t),r=e%s,a=Math.floor(e/s),l=i%16,o=Math.floor(i/16);return{col:r*16+l,row:a*16+o}}v(D,"getCharGridPosition");import{POST_PROCESS_DEFAULTS as W,ScalingMode as R}from"@utsp/types";var U=class U{constructor(t,e){n(this,"canvas");n(this,"gl");n(this,"parentElement");n(this,"containerDiv");n(this,"cols");n(this,"rows");n(this,"charWidth");n(this,"charHeight");n(this,"cellWidth",8);n(this,"cellHeight",8);n(this,"glyphOffsetX",0);n(this,"glyphOffsetY",0);n(this,"canvasBgColor");n(this,"showGrid");n(this,"supportsUint32Indices",!1);n(this,"useUint16Indices",!1);n(this,"gridOverlay");n(this,"bitmapFont");n(this,"atlasTexture",null);n(this,"atlasCanvas");n(this,"atlasColumns",0);n(this,"fontLoaded",!1);n(this,"paletteTexture",null);n(this,"program",null);n(this,"positionBuffer",null);n(this,"texCoordBuffer",null);n(this,"colorIndexBuffer",null);n(this,"indexBuffer",null);n(this,"aPosition");n(this,"aTexCoord");n(this,"aColorIndex");n(this,"uResolution",null);n(this,"uTexture",null);n(this,"uPalette",null);n(this,"resizeObserver");n(this,"charCodeToAtlasIndex",new Uint16Array(65536).fill(65535));n(this,"atlasUVs",new Float32Array(0));n(this,"cachedAtlasWidth",0);n(this,"cachedAtlasHeight",0);n(this,"paletteFloat",new Float32Array(256*4));n(this,"maxCells",0);n(this,"renderPositions",new Float32Array(0));n(this,"renderTexCoords",new Float32Array(0));n(this,"renderColorIndices",new Float32Array(0));n(this,"renderIndices",new Uint32Array(0));n(this,"cachedResolution",[0,0]);n(this,"cachedTextureUnit",-1);n(this,"cachedPaletteUnit",-1);n(this,"cachedTextureUniform",!1);n(this,"cachedPaletteUniform",!1);n(this,"paletteHash",0);n(this,"currentScale",1);n(this,"scalingMode",R.None);n(this,"ambientEffectEnabled",!1);n(this,"ambientEffectCanvas",null);n(this,"ambientEffectCtx",null);n(this,"ambientEffectBlur",W.ambientEffect.blur);n(this,"ambientEffectScale",W.ambientEffect.scale);n(this,"ambientEffectOpacity",.7);n(this,"onResizeCallback");n(this,"staticPositionsInitialized",!1);n(this,"vaoExtension",null);n(this,"vao",null);n(this,"instancedExtension",null);n(this,"useInstancing",!1);n(this,"instanceDataBuffer",null);n(this,"instanceData",new Float32Array(0));n(this,"templateQuadPositions",new Float32Array(0));n(this,"templateQuadIndices",new Uint16Array(0));if(!t)throw new Error("TerminalGL: Parent element is required");if(!Number.isInteger(e.cols)||e.cols<=0)throw new Error(`TerminalGL: Invalid cols: ${e.cols}. Must be a positive integer.`);if(!Number.isInteger(e.rows)||e.rows<=0)throw new Error(`TerminalGL: Invalid rows: ${e.rows}. Must be a positive integer.`);let i=e.cols*e.rows,s=U.checkCompatibility();if(s.errors.length>0)throw new Error(`TerminalGL: WebGL incompatible - ${s.errors.join(", ")}`);let r=e.forceUint16??!1;if(r&&i>s.maxCellsUint16)throw new Error(`TerminalGL: Terminal size ${e.cols}\xD7${e.rows} (${i} cells) exceeds Uint16 limit of ${s.maxCellsUint16} cells. Maximum size with Uint16: ${Math.floor(Math.sqrt(s.maxCellsUint16))}\xD7${Math.floor(Math.sqrt(s.maxCellsUint16))} (or smaller rectangles like 127\xD764)`);if(!s.uint32Indices&&i>s.maxCellsUint16)throw new Error(`TerminalGL: Terminal size ${e.cols}\xD7${e.rows} (${i} cells) exceeds device limit of ${s.maxCellsUint16} cells (OES_element_index_uint not supported). Maximum size: ${Math.floor(Math.sqrt(s.maxCellsUint16))}\xD7${Math.floor(Math.sqrt(s.maxCellsUint16))}`);i>s.recommendedMaxCells&&console.warn(`[TerminalGL] \u26A0\uFE0F Large terminal size ${e.cols}\xD7${e.rows} (${i} cells) exceeds recommended limit of ${s.recommendedMaxCells} cells. Performance may be impacted.`),s.warnings.length>0&&console.warn("[TerminalGL] WebGL Compatibility Warnings:",s.warnings);let a=e.charWidth??8,l=e.charHeight??8;if(!Number.isFinite(a)||a<=0)throw new Error(`TerminalGL: Invalid charWidth: ${a}. Must be a positive number.`);if(!Number.isFinite(l)||l<=0)throw new Error(`TerminalGL: Invalid charHeight: ${l}. Must be a positive number.`);for(this.parentElement=t,this.cols=e.cols,this.rows=e.rows,this.charWidth=a,this.charHeight=l,this.canvasBgColor=e.canvasBgColor!==void 0?e.canvasBgColor:null,this.showGrid=e.showGrid??!1,this.scalingMode=e.scalingMode??R.None,e.ambientEffect&&(this.ambientEffectEnabled=!0,typeof e.ambientEffect=="object"&&(this.ambientEffectBlur=e.ambientEffect.blur??W.ambientEffect.blur,this.ambientEffectScale=e.ambientEffect.scale??W.ambientEffect.scale,this.ambientEffectOpacity=e.ambientEffect.opacity??.7));this.parentElement.firstChild;)this.parentElement.removeChild(this.parentElement.firstChild);let o=window.getComputedStyle(this.parentElement).position;o!=="relative"&&o!=="absolute"&&o!=="fixed"&&(this.parentElement.style.position="relative"),this.containerDiv=document.createElement("div"),this.containerDiv.className="terminalgl-container",this.containerDiv.style.cssText=`
8
+ `,this.container.appendChild(this.canvas);let s=this.canvas.getContext("2d");if(!s)throw new Error("[GridOverlay] Impossible de cr\xE9er le contexte 2D");this.ctx=s,e&&(e.strokeColor&&(this.strokeColor=e.strokeColor),e.lineWidth!==void 0&&(this.lineWidth=e.lineWidth))}setDimensions(t,e,i,s,r=0,a=0){this.cols=t,this.rows=e,this.cellWidth=i,this.cellHeight=s,this.offsetX=r,this.offsetY=a}setCanvasSize(t,e){this.canvas.width=t,this.canvas.height=e,this.ctx.setTransform(1,0,0,1,0,0)}setStyle(t){t.strokeColor&&(this.strokeColor=t.strokeColor),t.lineWidth!==void 0&&(this.lineWidth=t.lineWidth)}setTransform(t,e,i,s,r){let a=s.left-r.left,l=s.top-r.top,o=s.width,h=s.height;(this.canvas.width!==o||this.canvas.height!==h)&&(this.canvas.width=o,this.canvas.height=h);let c=this.canvas.style;c.width=`${o}px`,c.height=`${h}px`,c.left=`${a}px`,c.top=`${l}px`}render(){if(!this.ctx)return;let t=this.cols*this.cellWidth,e=this.rows*this.cellHeight,i=t>0?this.canvas.width/t:1,s=e>0?this.canvas.height/e:1,r=Math.min(i,s),a=this.cellWidth*r,l=this.cellHeight*r,o=this.cols*a,h=this.rows*l,c=this.offsetX*r,d=this.offsetY*r;if(!(o===0||h===0)){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.strokeStyle=this.strokeColor,this.ctx.lineWidth=Math.max(1,this.lineWidth*r),this.ctx.beginPath();for(let f=0;f<=this.cols;f++){let u=c+f*a+.5;this.ctx.moveTo(u,d),this.ctx.lineTo(u,d+h)}for(let f=0;f<=this.rows;f++){let u=d+f*l+.5;this.ctx.moveTo(c,u),this.ctx.lineTo(c+o,u)}this.ctx.stroke()}}update(t,e,i,s,r,a,l=0,o=0){this.setDimensions(t,e,i,s,l,o),this.setCanvasSize(r,a),this.render()}setVisible(t){this.canvas.style.display=t?"block":"none"}destroy(){this.canvas.parentElement&&this.canvas.parentElement.removeChild(this.canvas)}getCanvas(){return this.canvas}};v(_,"GridOverlay");var R=_;function S(b){return Math.sqrt(b)*16}v(S,"getAtlasColumns");function M(b){return b*256-1}v(M,"getMaxCharCode");function D(b,t){let e=Math.floor(b/256),i=b%256,s=Math.sqrt(t),r=e%s,a=Math.floor(e/s),l=i%16,o=Math.floor(i/16);return{col:r*16+l,row:a*16+o}}v(D,"getCharGridPosition");import{POST_PROCESS_DEFAULTS as W,ScalingMode as T}from"@utsp/types";var F=class F{constructor(t,e){n(this,"canvas");n(this,"gl");n(this,"parentElement");n(this,"containerDiv");n(this,"cols");n(this,"rows");n(this,"charWidth");n(this,"charHeight");n(this,"cellWidth",8);n(this,"cellHeight",8);n(this,"glyphOffsetX",0);n(this,"glyphOffsetY",0);n(this,"canvasBgColor");n(this,"showGrid");n(this,"supportsUint32Indices",!1);n(this,"useUint16Indices",!1);n(this,"gridOverlay");n(this,"bitmapFont");n(this,"atlasTexture",null);n(this,"atlasCanvas");n(this,"atlasColumns",0);n(this,"fontLoaded",!1);n(this,"paletteTexture",null);n(this,"program",null);n(this,"positionBuffer",null);n(this,"texCoordBuffer",null);n(this,"colorIndexBuffer",null);n(this,"indexBuffer",null);n(this,"aPosition");n(this,"aTexCoord");n(this,"aColorIndex");n(this,"uResolution",null);n(this,"uTexture",null);n(this,"uPalette",null);n(this,"resizeObserver");n(this,"charCodeToAtlasIndex",new Uint16Array(65536).fill(65535));n(this,"atlasUVs",new Float32Array(0));n(this,"cachedAtlasWidth",0);n(this,"cachedAtlasHeight",0);n(this,"paletteFloat",new Float32Array(256*4));n(this,"maxCells",0);n(this,"renderPositions",new Float32Array(0));n(this,"renderTexCoords",new Float32Array(0));n(this,"renderColorIndices",new Float32Array(0));n(this,"renderIndices",new Uint32Array(0));n(this,"cachedResolution",[0,0]);n(this,"cachedTextureUnit",-1);n(this,"cachedPaletteUnit",-1);n(this,"cachedTextureUniform",!1);n(this,"cachedPaletteUniform",!1);n(this,"paletteHash",0);n(this,"currentScale",1);n(this,"scalingMode",T.None);n(this,"ambientEffectEnabled",!1);n(this,"ambientEffectCanvas",null);n(this,"ambientEffectCtx",null);n(this,"ambientEffectBlur",W.ambientEffect.blur);n(this,"ambientEffectScale",W.ambientEffect.scale);n(this,"ambientEffectOpacity",.7);n(this,"onResizeCallback");n(this,"staticPositionsInitialized",!1);n(this,"vaoExtension",null);n(this,"vao",null);n(this,"instancedExtension",null);n(this,"useInstancing",!1);n(this,"instanceDataBuffer",null);n(this,"instanceData",new Float32Array(0));n(this,"templateQuadPositions",new Float32Array(0));n(this,"templateQuadIndices",new Uint16Array(0));if(!t)throw new Error("TerminalGL: Parent element is required");if(!Number.isInteger(e.cols)||e.cols<=0)throw new Error(`TerminalGL: Invalid cols: ${e.cols}. Must be a positive integer.`);if(!Number.isInteger(e.rows)||e.rows<=0)throw new Error(`TerminalGL: Invalid rows: ${e.rows}. Must be a positive integer.`);let i=e.cols*e.rows,s=F.checkCompatibility();if(s.errors.length>0)throw new Error(`TerminalGL: WebGL incompatible - ${s.errors.join(", ")}`);let r=e.forceUint16??!1;if(r&&i>s.maxCellsUint16)throw new Error(`TerminalGL: Terminal size ${e.cols}\xD7${e.rows} (${i} cells) exceeds Uint16 limit of ${s.maxCellsUint16} cells. Maximum size with Uint16: ${Math.floor(Math.sqrt(s.maxCellsUint16))}\xD7${Math.floor(Math.sqrt(s.maxCellsUint16))} (or smaller rectangles like 127\xD764)`);if(!s.uint32Indices&&i>s.maxCellsUint16)throw new Error(`TerminalGL: Terminal size ${e.cols}\xD7${e.rows} (${i} cells) exceeds device limit of ${s.maxCellsUint16} cells (OES_element_index_uint not supported). Maximum size: ${Math.floor(Math.sqrt(s.maxCellsUint16))}\xD7${Math.floor(Math.sqrt(s.maxCellsUint16))}`);i>s.recommendedMaxCells&&console.warn(`[TerminalGL] \u26A0\uFE0F Large terminal size ${e.cols}\xD7${e.rows} (${i} cells) exceeds recommended limit of ${s.recommendedMaxCells} cells. Performance may be impacted.`),s.warnings.length>0&&console.warn("[TerminalGL] WebGL Compatibility Warnings:",s.warnings);let a=e.charWidth??8,l=e.charHeight??8;if(!Number.isFinite(a)||a<=0)throw new Error(`TerminalGL: Invalid charWidth: ${a}. Must be a positive number.`);if(!Number.isFinite(l)||l<=0)throw new Error(`TerminalGL: Invalid charHeight: ${l}. Must be a positive number.`);for(this.parentElement=t,this.cols=e.cols,this.rows=e.rows,this.charWidth=a,this.charHeight=l,this.canvasBgColor=e.canvasBgColor!==void 0?e.canvasBgColor:null,this.showGrid=e.showGrid??!1,this.scalingMode=e.scalingMode??T.None,e.ambientEffect&&(this.ambientEffectEnabled=!0,typeof e.ambientEffect=="object"&&(this.ambientEffectBlur=e.ambientEffect.blur??W.ambientEffect.blur,this.ambientEffectScale=e.ambientEffect.scale??W.ambientEffect.scale,this.ambientEffectOpacity=e.ambientEffect.opacity??.7));this.parentElement.firstChild;)this.parentElement.removeChild(this.parentElement.firstChild);let o=window.getComputedStyle(this.parentElement).position;o!=="relative"&&o!=="absolute"&&o!=="fixed"&&(this.parentElement.style.position="relative"),this.containerDiv=document.createElement("div"),this.containerDiv.className="terminalgl-container",this.containerDiv.style.cssText=`
9
9
  position: absolute !important;
10
10
  top: 0 !important;
11
11
  left: 0 !important;
@@ -32,7 +32,7 @@ var J=Object.defineProperty;var tt=(C,t,e)=>t in C?J(C,t,{enumerable:!0,configur
32
32
  backface-visibility: hidden !important;
33
33
  position: relative !important;
34
34
  z-index: 1 !important;
35
- `;let h=this.canvas.getContext("webgl",{alpha:this.canvasBgColor===null,premultipliedAlpha:!1});if(!h)throw new Error("TerminalGL: WebGL not supported");this.gl=h,this.supportsUint32Indices=!!h.getExtension("OES_element_index_uint"),this.useUint16Indices=r||!this.supportsUint32Indices,this.useUint16Indices?console.warn(`[TerminalGL] \u{1F4CA} Using Uint16 indices (max ${s.maxCellsUint16} cells)`):console.warn(`[TerminalGL] \u{1F4CA} Using Uint32 indices (max ${s.maxCellsUint32} cells)`),this.vaoExtension=h.getExtension("OES_vertex_array_object"),this.vaoExtension&&console.warn("[TerminalGL] \u2705 VAO extension enabled (faster attribute binding)"),this.instancedExtension=h.getExtension("ANGLE_instanced_arrays"),this.instancedExtension?(this.useInstancing=!0,console.warn("[TerminalGL] \u{1F680} Instanced rendering enabled (massive draw call reduction)")):console.warn("[TerminalGL] \u26A0\uFE0F Instanced rendering not available (fallback to standard rendering)"),this.containerDiv.appendChild(this.canvas),this.ambientEffectEnabled&&(this.createAmbientEffectCanvas(),console.warn("[TerminalGL] \u{1F308} Ambient effect enabled at startup")),this.parentElement.appendChild(this.containerDiv),this.initRenderBuffers();try{this.initWebGL()}catch(c){throw console.error("[TerminalGL] \u274C Failed to initialize WebGL:",c),c}this.showGrid&&this.initGridOverlay(),this.setupResizeObserver()}static checkCompatibility(){let t={webgl1:!1,uint32Indices:!1,maxTextureSize:0,maxViewportDims:[0,0],maxCellsUint16:0,maxCellsUint32:0,recommendedMaxCells:0,warnings:[],errors:[]},e=document.createElement("canvas"),i=e.getContext("webgl")||e.getContext("experimental-webgl");if(!i||!(i instanceof WebGLRenderingContext))return t.errors.push("\u274C WebGL 1.0 not supported by this browser/device"),t;let s=i;t.webgl1=!0;try{t.maxTextureSize=s.getParameter(s.MAX_TEXTURE_SIZE);let o=s.getParameter(s.MAX_VIEWPORT_DIMS);t.maxViewportDims=[o[0],o[1]]}catch(o){return t.errors.push(`\u274C Failed to query WebGL parameters: ${o}`),t}let r=s.getExtension("OES_element_index_uint");t.uint32Indices=!!r;let a=8;if(t.maxCellsUint16=Math.floor(65535/a),t.uint32Indices){let o=Math.floor(t.maxTextureSize*t.maxTextureSize/64);t.maxCellsUint32=Math.min(o,262144)}else t.maxCellsUint32=t.maxCellsUint16,t.warnings.push(`\u26A0\uFE0F OES_element_index_uint not supported - limited to ${t.maxCellsUint16} cells (e.g., 90\xD790 or 127\xD764)`);return t.recommendedMaxCells=Math.floor((t.uint32Indices?t.maxCellsUint32:t.maxCellsUint16)*.8),t.maxTextureSize<256?t.errors.push(`\u274C MAX_TEXTURE_SIZE too small: ${t.maxTextureSize} (minimum 256 required for font atlas)`):t.maxTextureSize<2048&&t.warnings.push(`\u26A0\uFE0F Small MAX_TEXTURE_SIZE: ${t.maxTextureSize} (may limit font atlas)`),(t.maxViewportDims[0]<1024||t.maxViewportDims[1]<768)&&t.warnings.push(`\u26A0\uFE0F Small MAX_VIEWPORT_DIMS: ${t.maxViewportDims[0]}\xD7${t.maxViewportDims[1]}`),s.getExtension("WEBGL_lose_context")||t.warnings.push("\u26A0\uFE0F WEBGL_lose_context not supported - may cause memory leaks"),t}initInstancedBuffers(){let t=this.gl;this.templateQuadPositions=new Float32Array([0,0,this.cellWidth,0,0,this.cellHeight,this.cellWidth,this.cellHeight]),this.templateQuadIndices=new Uint16Array([0,1,2,2,1,3]),t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,this.templateQuadPositions,t.STATIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,this.templateQuadIndices,t.STATIC_DRAW);let e=this.cols*this.rows*2;this.instanceData=new Float32Array(e*8),t.bindBuffer(t.ARRAY_BUFFER,this.instanceDataBuffer),t.bufferData(t.ARRAY_BUFFER,this.instanceData.byteLength,t.DYNAMIC_DRAW)}initRenderBuffers(){this.maxCells=this.cols*this.rows*2,this.renderPositions=new Float32Array(this.maxCells*4*2),this.renderTexCoords=new Float32Array(this.maxCells*4*2),this.renderColorIndices=new Float32Array(this.maxCells*4),this.useUint16Indices?this.renderIndices=new Uint16Array(this.maxCells*6):this.renderIndices=new Uint32Array(this.maxCells*6),this.staticPositionsInitialized=!1}precomputeStaticPositions(){let t=this.cellWidth,e=this.cellHeight,i=this.glyphOffsetX,s=this.glyphOffsetY,r=this.charWidth,a=this.charHeight,l=0,o=0,h=0;for(let d=0;d<this.rows;d++){let f=Math.round(d*e),u=Math.round(f+e);for(let m=0;m<this.cols;m++){let g=Math.round(m*t),p=Math.round(g+t);this.renderPositions[l++]=g,this.renderPositions[l++]=f,this.renderPositions[l++]=p,this.renderPositions[l++]=f,this.renderPositions[l++]=g,this.renderPositions[l++]=u,this.renderPositions[l++]=p,this.renderPositions[l++]=u,this.renderIndices[o++]=h,this.renderIndices[o++]=h+1,this.renderIndices[o++]=h+2,this.renderIndices[o++]=h+2,this.renderIndices[o++]=h+1,this.renderIndices[o++]=h+3,h+=4;let x=Math.round(g+i),w=Math.round(f+s),b=Math.round(x+r),E=Math.round(w+a);this.renderPositions[l++]=x,this.renderPositions[l++]=w,this.renderPositions[l++]=b,this.renderPositions[l++]=w,this.renderPositions[l++]=x,this.renderPositions[l++]=E,this.renderPositions[l++]=b,this.renderPositions[l++]=E,this.renderIndices[o++]=h,this.renderIndices[o++]=h+1,this.renderIndices[o++]=h+2,this.renderIndices[o++]=h+2,this.renderIndices[o++]=h+1,this.renderIndices[o++]=h+3,h+=4}}let c=this.gl;c.bindBuffer(c.ARRAY_BUFFER,this.positionBuffer),c.bufferSubData(c.ARRAY_BUFFER,0,this.renderPositions),c.bindBuffer(c.ELEMENT_ARRAY_BUFFER,this.indexBuffer),c.bufferSubData(c.ELEMENT_ARRAY_BUFFER,0,this.renderIndices),this.staticPositionsInitialized=!0}initWebGL(){let t=this.gl,e;this.useInstancing?e=`
35
+ `;let h=this.canvas.getContext("webgl",{alpha:this.canvasBgColor===null,premultipliedAlpha:!1});if(!h)throw new Error("TerminalGL: WebGL not supported");this.gl=h,this.supportsUint32Indices=!!h.getExtension("OES_element_index_uint"),this.useUint16Indices=r||!this.supportsUint32Indices,this.useUint16Indices?console.warn(`[TerminalGL] \u{1F4CA} Using Uint16 indices (max ${s.maxCellsUint16} cells)`):console.warn(`[TerminalGL] \u{1F4CA} Using Uint32 indices (max ${s.maxCellsUint32} cells)`),this.vaoExtension=h.getExtension("OES_vertex_array_object"),this.vaoExtension&&console.warn("[TerminalGL] \u2705 VAO extension enabled (faster attribute binding)"),this.instancedExtension=h.getExtension("ANGLE_instanced_arrays"),this.instancedExtension?(this.useInstancing=!0,console.warn("[TerminalGL] \u{1F680} Instanced rendering enabled (massive draw call reduction)")):console.warn("[TerminalGL] \u26A0\uFE0F Instanced rendering not available (fallback to standard rendering)"),this.containerDiv.appendChild(this.canvas),this.ambientEffectEnabled&&(this.createAmbientEffectCanvas(),console.warn("[TerminalGL] \u{1F308} Ambient effect enabled at startup")),this.parentElement.appendChild(this.containerDiv),this.initRenderBuffers();try{this.initWebGL()}catch(c){throw console.error("[TerminalGL] \u274C Failed to initialize WebGL:",c),c}this.showGrid&&this.initGridOverlay(),this.setupResizeObserver()}static checkCompatibility(){let t={webgl1:!1,uint32Indices:!1,maxTextureSize:0,maxViewportDims:[0,0],maxCellsUint16:0,maxCellsUint32:0,recommendedMaxCells:0,warnings:[],errors:[]},e=document.createElement("canvas"),i=e.getContext("webgl")||e.getContext("experimental-webgl");if(!i||!(i instanceof WebGLRenderingContext))return t.errors.push("\u274C WebGL 1.0 not supported by this browser/device"),t;let s=i;t.webgl1=!0;try{t.maxTextureSize=s.getParameter(s.MAX_TEXTURE_SIZE);let o=s.getParameter(s.MAX_VIEWPORT_DIMS);t.maxViewportDims=[o[0],o[1]]}catch(o){return t.errors.push(`\u274C Failed to query WebGL parameters: ${o}`),t}let r=s.getExtension("OES_element_index_uint");t.uint32Indices=!!r;let a=8;if(t.maxCellsUint16=Math.floor(65535/a),t.uint32Indices){let o=Math.floor(t.maxTextureSize*t.maxTextureSize/64);t.maxCellsUint32=Math.min(o,262144)}else t.maxCellsUint32=t.maxCellsUint16,t.warnings.push(`\u26A0\uFE0F OES_element_index_uint not supported - limited to ${t.maxCellsUint16} cells (e.g., 90\xD790 or 127\xD764)`);return t.recommendedMaxCells=Math.floor((t.uint32Indices?t.maxCellsUint32:t.maxCellsUint16)*.8),t.maxTextureSize<256?t.errors.push(`\u274C MAX_TEXTURE_SIZE too small: ${t.maxTextureSize} (minimum 256 required for font atlas)`):t.maxTextureSize<2048&&t.warnings.push(`\u26A0\uFE0F Small MAX_TEXTURE_SIZE: ${t.maxTextureSize} (may limit font atlas)`),(t.maxViewportDims[0]<1024||t.maxViewportDims[1]<768)&&t.warnings.push(`\u26A0\uFE0F Small MAX_VIEWPORT_DIMS: ${t.maxViewportDims[0]}\xD7${t.maxViewportDims[1]}`),s.getExtension("WEBGL_lose_context")||t.warnings.push("\u26A0\uFE0F WEBGL_lose_context not supported - may cause memory leaks"),t}initInstancedBuffers(){let t=this.gl;this.templateQuadPositions=new Float32Array([0,0,this.cellWidth,0,0,this.cellHeight,this.cellWidth,this.cellHeight]),this.templateQuadIndices=new Uint16Array([0,1,2,2,1,3]),t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,this.templateQuadPositions,t.STATIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,this.templateQuadIndices,t.STATIC_DRAW);let e=this.cols*this.rows*2;this.instanceData=new Float32Array(e*8),t.bindBuffer(t.ARRAY_BUFFER,this.instanceDataBuffer),t.bufferData(t.ARRAY_BUFFER,this.instanceData.byteLength,t.DYNAMIC_DRAW)}initRenderBuffers(){this.maxCells=this.cols*this.rows*2,this.renderPositions=new Float32Array(this.maxCells*4*2),this.renderTexCoords=new Float32Array(this.maxCells*4*2),this.renderColorIndices=new Float32Array(this.maxCells*4),this.useUint16Indices?this.renderIndices=new Uint16Array(this.maxCells*6):this.renderIndices=new Uint32Array(this.maxCells*6),this.staticPositionsInitialized=!1}precomputeStaticPositions(){let t=this.cellWidth,e=this.cellHeight,i=this.glyphOffsetX,s=this.glyphOffsetY,r=this.charWidth,a=this.charHeight,l=0,o=0,h=0;for(let d=0;d<this.rows;d++){let f=Math.round(d*e),u=Math.round(f+e);for(let m=0;m<this.cols;m++){let g=Math.round(m*t),p=Math.round(g+t);this.renderPositions[l++]=g,this.renderPositions[l++]=f,this.renderPositions[l++]=p,this.renderPositions[l++]=f,this.renderPositions[l++]=g,this.renderPositions[l++]=u,this.renderPositions[l++]=p,this.renderPositions[l++]=u,this.renderIndices[o++]=h,this.renderIndices[o++]=h+1,this.renderIndices[o++]=h+2,this.renderIndices[o++]=h+2,this.renderIndices[o++]=h+1,this.renderIndices[o++]=h+3,h+=4;let x=Math.round(g+i),w=Math.round(f+s),C=Math.round(x+r),E=Math.round(w+a);this.renderPositions[l++]=x,this.renderPositions[l++]=w,this.renderPositions[l++]=C,this.renderPositions[l++]=w,this.renderPositions[l++]=x,this.renderPositions[l++]=E,this.renderPositions[l++]=C,this.renderPositions[l++]=E,this.renderIndices[o++]=h,this.renderIndices[o++]=h+1,this.renderIndices[o++]=h+2,this.renderIndices[o++]=h+2,this.renderIndices[o++]=h+1,this.renderIndices[o++]=h+3,h+=4}}let c=this.gl;c.bindBuffer(c.ARRAY_BUFFER,this.positionBuffer),c.bufferSubData(c.ARRAY_BUFFER,0,this.renderPositions),c.bindBuffer(c.ELEMENT_ARRAY_BUFFER,this.indexBuffer),c.bufferSubData(c.ELEMENT_ARRAY_BUFFER,0,this.renderIndices),this.staticPositionsInitialized=!0}initWebGL(){let t=this.gl,e;this.useInstancing?e=`
36
36
  // Per-vertex attributes (template quad)
37
37
  attribute vec2 aPosition; // Local quad position (0,0 to cellW,cellH)
38
38
 
@@ -113,7 +113,7 @@ var J=Object.defineProperty;var tt=(C,t,e)=>t in C?J(C,t,{enumerable:!0,configur
113
113
  gl_FragColor = vec4(texColor.rgb * vColor.rgb, texColor.a);
114
114
  }
115
115
  }
116
- `,s=this.compileShader(t.VERTEX_SHADER,e),r=this.compileShader(t.FRAGMENT_SHADER,i);if(!s||!r)throw new Error("Shader compilation error");let a=t.createProgram();if(!a)throw new Error("Unable to create WebGL program");if(t.attachShader(a,s),t.attachShader(a,r),t.linkProgram(a),!t.getProgramParameter(a,t.LINK_STATUS)){let l=t.getProgramInfoLog(a);throw new Error("Program linking error: "+l)}this.program=a,this.cachedTextureUniform=!1,this.cachedPaletteUniform=!1,this.aPosition=t.getAttribLocation(a,"aPosition"),this.useInstancing?(this.aTexCoord=t.getAttribLocation(a,"aInstanceOffset"),this.aColorIndex=t.getAttribLocation(a,"aInstanceUVs"),this.instanceDataBuffer=t.createBuffer()):(this.aTexCoord=t.getAttribLocation(a,"aTexCoord"),this.aColorIndex=t.getAttribLocation(a,"aColorIndex")),this.uResolution=t.getUniformLocation(a,"uResolution"),this.uTexture=t.getUniformLocation(a,"uTexture"),this.uPalette=t.getUniformLocation(a,"uPalette"),this.positionBuffer=t.createBuffer(),this.texCoordBuffer=t.createBuffer(),this.colorIndexBuffer=t.createBuffer(),this.indexBuffer=t.createBuffer(),t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,this.renderPositions.byteLength,t.DYNAMIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,this.renderTexCoords.byteLength,t.DYNAMIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,this.colorIndexBuffer),t.bufferData(t.ARRAY_BUFFER,this.renderColorIndices.byteLength,t.DYNAMIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,this.renderIndices.byteLength,t.DYNAMIC_DRAW),this.vaoExtension&&(this.vao=this.vaoExtension.createVertexArrayOES(),this.vao&&(this.vaoExtension.bindVertexArrayOES(this.vao),t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.enableVertexAttribArray(this.aPosition),t.vertexAttribPointer(this.aPosition,2,t.FLOAT,!1,0,0),t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.enableVertexAttribArray(this.aTexCoord),t.vertexAttribPointer(this.aTexCoord,2,t.FLOAT,!1,0,0),t.bindBuffer(t.ARRAY_BUFFER,this.colorIndexBuffer),t.enableVertexAttribArray(this.aColorIndex),t.vertexAttribPointer(this.aColorIndex,1,t.FLOAT,!1,0,0),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),this.vaoExtension.bindVertexArrayOES(null))),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),t.viewport(0,0,this.canvas.width,this.canvas.height)}compileShader(t,e){let i=this.gl,s=i.createShader(t);return s?(i.shaderSource(s,e),i.compileShader(s),i.getShaderParameter(s,i.COMPILE_STATUS)?s:(console.error("Shader compilation error:",i.getShaderInfoLog(s)),i.deleteShader(s),null)):null}initGridOverlay(){this.gridOverlay=new T(this.containerDiv,{strokeColor:"rgba(144, 24, 24, 1)",lineWidth:1,zIndex:10}),this.updateGridOverlay()}updateGridOverlay(){if(!this.gridOverlay)return;let t=this.cols*this.cellWidth,e=this.rows*this.cellHeight,i=this.canvas.getBoundingClientRect(),s=this.containerDiv.getBoundingClientRect();this.gridOverlay.setDimensions(this.cols,this.rows,this.cellWidth,this.cellHeight,0,0),this.gridOverlay.setTransform(this.currentScale,t,e,i,s),this.gridOverlay.render()}setBitmapFont(t,e,i,s,r){this.bitmapFont=t,this.fontLoaded=!0,this.charWidth=Math.round(e),this.charHeight=Math.round(i),this.cellWidth=Math.round(s),this.cellHeight=Math.round(r),this.glyphOffsetX=Math.round((this.cellWidth-this.charWidth)/2),this.glyphOffsetY=Math.round((this.cellHeight-this.charHeight)/2),this.useInstancing&&(console.warn("[TerminalGL] \u{1F680} Initializing instanced buffers..."),this.initInstancedBuffers());try{this.generateAtlas()}catch(a){throw console.error("[TerminalGL] \u274C Failed to generate atlas:",a),a}this.buildCharCodeMap(),this.precomputeAtlasUVs(),this.canvas.width=this.cols*this.cellWidth,this.canvas.height=this.rows*this.cellHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.useInstancing||this.precomputeStaticPositions(),this.showGrid&&this.gridOverlay&&this.updateGridOverlay()}async setImageFont(t,e,i,s,r,a){this.fontLoaded=!0,this.charWidth=Math.round(e),this.charHeight=Math.round(i),this.cellWidth=Math.round(s),this.cellHeight=Math.round(r),this.atlasColumns=M(a);let l=F(a);this.glyphOffsetX=Math.round((this.cellWidth-this.charWidth)/2),this.glyphOffsetY=Math.round((this.cellHeight-this.charHeight)/2),this.useInstancing&&(console.warn("[TerminalGL] \u{1F680} Initializing instanced buffers for ImageFont..."),this.initInstancedBuffers()),await this.loadImageFontAtlas(t),this.charCodeToAtlasIndex.fill(65535);for(let o=0;o<=l;o++)this.charCodeToAtlasIndex[o]=o;this.precomputeImageFontUVs(a),this.canvas.width=this.cols*this.cellWidth,this.canvas.height=this.rows*this.cellHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.useInstancing||this.precomputeStaticPositions(),this.showGrid&&this.gridOverlay&&this.updateGridOverlay()}async loadImageFontAtlas(t){return new Promise((e,i)=>{let s=new Uint8Array(t),r=new Blob([s],{type:"image/png"}),a=URL.createObjectURL(r),l=new Image;l.onload=()=>{URL.revokeObjectURL(a),this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=l.width,this.atlasCanvas.height=l.height;let o=this.atlasCanvas.getContext("2d");if(!o){i(new Error("Failed to create 2D context for atlas"));return}o.drawImage(l,0,0),this.cachedAtlasWidth=l.width,this.cachedAtlasHeight=l.height,this.createAtlasTexture(),e()},l.onerror=()=>{URL.revokeObjectURL(a),i(new Error("Failed to load PNG image for ImageFont atlas"))},l.src=a})}precomputeImageFontUVs(t){let e=t*256;this.atlasUVs=new Float32Array(e*4);let i=this.cachedAtlasWidth,s=this.cachedAtlasHeight,r=.5/i,a=.5/s;for(let l=0;l<e;l++){let{col:o,row:h}=D(l,t),c=(o*this.charWidth+r)/i,d=(h*this.charHeight+a)/s,f=((o+1)*this.charWidth-r)/i,u=((h+1)*this.charHeight-a)/s,m=l*4;this.atlasUVs[m]=c,this.atlasUVs[m+1]=d,this.atlasUVs[m+2]=f,this.atlasUVs[m+3]=u}}generateAtlas(){if(!this.bitmapFont)return;let t=Array.from(this.bitmapFont.keys()).sort((o,h)=>o-h),e=t.length;this.atlasColumns=Math.ceil(Math.sqrt(e));let i=Math.ceil(e/this.atlasColumns),s=this.atlasColumns*this.charWidth,r=i*this.charHeight;this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=s,this.atlasCanvas.height=r;let a=this.atlasCanvas.getContext("2d");if(!a)throw new Error("Unable to create 2D context for atlas");a.clearRect(0,0,s,r),a.fillStyle="#ffffff";let l=0;for(let o of t){let h=this.bitmapFont.get(o);if(!h)continue;let c=l%this.atlasColumns,d=Math.floor(l/this.atlasColumns),f=c*this.charWidth,u=d*this.charHeight;for(let m=0;m<Math.min(h.length,this.charHeight);m++){let g=h[m];for(let p=0;p<this.charWidth;p++){let x=1<<7-p;g&x&&a.fillRect(f+p,u+m,1,1)}}l++}this.createAtlasTexture()}buildCharCodeMap(){if(!this.bitmapFont)return;this.charCodeToAtlasIndex.fill(65535);let t=Array.from(this.bitmapFont.keys()).sort((e,i)=>e-i);for(let e=0;e<t.length;e++)this.charCodeToAtlasIndex[t[e]]=e}precomputeAtlasUVs(){if(!this.bitmapFont)return;let t=this.bitmapFont.size;this.atlasUVs=new Float32Array(t*4),this.cachedAtlasWidth=this.atlasColumns*this.charWidth,this.cachedAtlasHeight=Math.ceil(t/this.atlasColumns)*this.charHeight;let e=this.cachedAtlasWidth,i=this.cachedAtlasHeight,s=.5/e,r=.5/i;for(let a=0;a<t;a++){let l=a%this.atlasColumns,o=Math.floor(a/this.atlasColumns),h=(l*this.charWidth+s)/e,c=(o*this.charHeight+r)/i,d=((l+1)*this.charWidth-s)/e,f=((o+1)*this.charHeight-r)/i,u=a*4;this.atlasUVs[u]=h,this.atlasUVs[u+1]=c,this.atlasUVs[u+2]=d,this.atlasUVs[u+3]=f}}createAtlasTexture(){if(this.atlasCanvas)try{let t=this.gl,e=t.createTexture();if(!e)throw new Error("Unable to create texture");t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.atlasCanvas),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),this.atlasTexture=e}catch(t){throw console.error("[TerminalGL] \u274C Failed to create atlas texture:",t),t}}clear(){let t=this.gl;t&&t.clear(t.COLOR_BUFFER_BIT)}parseColor(t){if(t.startsWith("#")){let e=t.slice(1),i=0,s=0,r=0;return e.length===3?(i=parseInt(e[0]+e[0],16),s=parseInt(e[1]+e[1],16),r=parseInt(e[2]+e[2],16)):e.length===6&&(i=parseInt(e.slice(0,2),16),s=parseInt(e.slice(2,4),16),r=parseInt(e.slice(4,6),16)),[i/255,s/255,r/255,1]}if(t.startsWith("rgb")){let e=t.match(/rgba?\(([^)]+)\)/);if(e){let i=e[1].split(",").map(s=>parseFloat(s.trim()));return[i[0]/255,i[1]/255,i[2]/255,i[3]!==void 0?i[3]:1]}}return[1,1,1,1]}setupResizeObserver(){if(!(typeof ResizeObserver>"u"))try{this.resizeObserver=new ResizeObserver(()=>{try{this.updateCanvasSize()}catch(t){console.error("[TerminalGL] \u274C Error in resize callback:",t)}}),this.resizeObserver.observe(this.parentElement),this.updateCanvasSize()}catch(t){console.error("[TerminalGL] \u274C Failed to setup ResizeObserver:",t)}}updateCanvasSize(){let t=this.parentElement.clientWidth,e=this.parentElement.clientHeight;if(t===0||e===0)return;let i=this.cols*this.cellWidth,s=this.rows*this.cellHeight;if(i===0||s===0)return;let r=t/i,a=e/s,l=Math.min(r,a),o;switch(this.scalingMode){case R.Integer:o=Math.max(1,Math.floor(l));break;case R.Half:o=Math.max(1,Math.floor(l*2)/2);break;case R.Quarter:o=Math.max(1,Math.floor(l*4)/4);break;case R.Eighth:o=Math.max(1,Math.floor(l*8)/8);break;case R.None:default:o=Math.max(.1,l);break}if(this.canvas.style.transform=`scale(${o})`,this.ambientEffectEnabled&&this.ambientEffectCanvas){let h=o*this.ambientEffectScale;this.ambientEffectCanvas.style.transform=`scale(${h})`}this.currentScale=o,this.onResizeCallback&&this.onResizeCallback(),this.showGrid&&this.gridOverlay&&this.updateGridOverlay()}updateAmbientEffect(){!this.ambientEffectCanvas||!this.ambientEffectCtx||this.ambientEffectCtx.drawImage(this.canvas,0,0)}setPalette(t){let e=0;for(let i=0;i<Math.min(t.length,256);i++){let s=t[i];e=(e<<5)-e+s.r,e=(e<<5)-e+s.g,e=(e<<5)-e+s.b,e=(e<<5)-e+s.a,e=e|0}if(e!==this.paletteHash){this.paletteHash=e;for(let i=0;i<t.length&&i<256;i++){let s=t[i],r=i*4;this.paletteFloat[r]=s.r/255,this.paletteFloat[r+1]=s.g/255,this.paletteFloat[r+2]=s.b/255,this.paletteFloat[r+3]=s.a/255}this.updatePaletteTexture()}}updatePaletteTexture(){try{let t=this.gl;this.paletteTexture||(this.paletteTexture=t.createTexture()),t.bindTexture(t.TEXTURE_2D,this.paletteTexture);let e=new Uint8Array(256*4);for(let i=0;i<256;i++){let s=i*4;e[s]=this.paletteFloat[s]*255,e[s+1]=this.paletteFloat[s+1]*255,e[s+2]=this.paletteFloat[s+2]*255,e[s+3]=this.paletteFloat[s+3]*255}t.texImage2D(t.TEXTURE_2D,0,t.RGBA,256,1,0,t.RGBA,t.UNSIGNED_BYTE,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.bindTexture(t.TEXTURE_2D,null)}catch(t){throw console.error("[TerminalGL] \u274C Failed to update palette texture:",t),t}}renderDisplayData(t){try{if(!this.isReady()){console.warn("[TerminalGL] \u26A0\uFE0F Not ready: font not loaded yet");return}(t.width!==this.cols||t.height!==this.rows)&&this.resize(t.width,t.height),this.renderDirect(t),this.ambientEffectEnabled&&this.ambientEffectCanvas&&this.ambientEffectCtx&&this.updateAmbientEffect()}catch(e){console.error("[TerminalGL] \u274C Error rendering display data:",e)}}renderDirect(t){let e=this.gl;if(!this.staticPositionsInitialized&&!this.useInstancing&&this.precomputeStaticPositions(),this.canvasBgColor!==null){let i=this.parseColor(this.canvasBgColor);e.clearColor(i[0],i[1],i[2],i[3])}else e.clearColor(0,0,0,0);e.clear(e.COLOR_BUFFER_BIT),this.useInstancing?this.renderInstanced(t):this.renderDirectBuffers(t)}renderInstanced(t){let e=this.gl,i=this.instancedExtension;if(!this.instanceData||this.instanceData.length===0){console.warn("[TerminalGL] \u26A0\uFE0F Instance data not initialized, falling back to standard rendering"),this.useInstancing=!1,this.renderDirectBuffers(t);return}let s=t.width*t.height;if(this.useUint16Indices&&s>8191){console.warn(`[TerminalGL] \u26A0\uFE0F Terminal too large for instanced rendering with Uint16 (${s} cells > 8191). Falling back to standard rendering.`),this.useInstancing=!1,this.renderDirectBuffers(t);return}let r=0,a=this.instanceData.length/8;for(let f=0;f<t.height;f++)for(let u=0;u<t.width;u++){let m=t.cells[f*t.width+u],g=m.bgColorIndex,p=m.fgColorIndex,x=this.canvasBgColor!==null&&g===255,w=m.char===" "||p===255;if(!x){if(r>=a){console.error(`[TerminalGL] \u274C Instance buffer overflow! instanceIdx=${r}, max=${a}`);break}let b=r*8;this.instanceData[b]=u,this.instanceData[b+1]=f,this.instanceData[b+2]=0,this.instanceData[b+3]=0,this.instanceData[b+4]=0,this.instanceData[b+5]=0,this.instanceData[b+6]=g,this.instanceData[b+7]=0,r++}if(!w){let b=m.char.charCodeAt(0),E=this.charCodeToAtlasIndex[b];if(E!==65535){if(r>=a){console.error(`[TerminalGL] \u274C Instance buffer overflow! instanceIdx=${r}, max=${a}`);break}let A=E*4,y=r*8;this.instanceData[y]=u,this.instanceData[y+1]=f,this.instanceData[y+2]=this.atlasUVs[A],this.instanceData[y+3]=this.atlasUVs[A+1],this.instanceData[y+4]=this.atlasUVs[A+2],this.instanceData[y+5]=this.atlasUVs[A+3],this.instanceData[y+6]=0,this.instanceData[y+7]=p,r++}}}if(r===0){console.warn("[TerminalGL] \u26A0\uFE0F No instances to draw (all cells skipped)");return}e.bindBuffer(e.ARRAY_BUFFER,this.instanceDataBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.instanceData.subarray(0,r*8)),e.useProgram(this.program),e.bindBuffer(e.ARRAY_BUFFER,this.positionBuffer),e.enableVertexAttribArray(this.aPosition),e.vertexAttribPointer(this.aPosition,2,e.FLOAT,!1,0,0),i.vertexAttribDivisorANGLE(this.aPosition,0),e.bindBuffer(e.ARRAY_BUFFER,this.instanceDataBuffer);let l=8*Float32Array.BYTES_PER_ELEMENT,o=e.getAttribLocation(this.program,"aInstanceOffset");e.enableVertexAttribArray(o),e.vertexAttribPointer(o,2,e.FLOAT,!1,l,0),i.vertexAttribDivisorANGLE(o,1);let h=e.getAttribLocation(this.program,"aInstanceUVs");e.enableVertexAttribArray(h),e.vertexAttribPointer(h,4,e.FLOAT,!1,l,2*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisorANGLE(h,1);let c=e.getAttribLocation(this.program,"aInstanceColors");e.enableVertexAttribArray(c),e.vertexAttribPointer(c,2,e.FLOAT,!1,l,6*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisorANGLE(c,1),e.uniform2f(this.uResolution,this.canvas.width,this.canvas.height);let d=e.getUniformLocation(this.program,"uCellSize");e.uniform2f(d,this.cellWidth,this.cellHeight),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.atlasTexture),e.uniform1i(this.uTexture,0),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,this.paletteTexture),e.uniform1i(this.uPalette,1),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer),i.drawElementsInstancedANGLE(e.TRIANGLES,6,e.UNSIGNED_SHORT,0,r),i.vertexAttribDivisorANGLE(this.aPosition,0),i.vertexAttribDivisorANGLE(o,0),i.vertexAttribDivisorANGLE(h,0),i.vertexAttribDivisorANGLE(c,0)}renderDirectBuffers(t){let e=this.gl,i=t.width*t.height,s=i*2;if(s>this.maxCells){console.error(`[TerminalGL] \u274C Buffer overflow detected! Trying to render ${s} quads but buffer capacity is ${this.maxCells}. This should not happen - resize() should have reallocated.`);return}let r=0,a=0,l=t.cells,o=i;for(let m=0;m<o;m++){let g=l[m],p=g.bgColorIndex,w=this.canvasBgColor!==null&&p===255?255:p,b=0;for(let y=0;y<4;y++)this.renderTexCoords[r++]=b,this.renderTexCoords[r++]=b,this.renderColorIndices[a++]=w;let E=g.fgColorIndex,A=g.char;if(A===" "||E===255)for(let y=0;y<4;y++)this.renderTexCoords[r++]=0,this.renderTexCoords[r++]=0,this.renderColorIndices[a++]=255;else{let y=A.charCodeAt(0),q=this.charCodeToAtlasIndex[y];if(q!==65535){let I=q*4,j=this.atlasUVs[I],Q=this.atlasUVs[I+1],Z=this.atlasUVs[I+2],K=this.atlasUVs[I+3];this.renderTexCoords[r++]=j,this.renderTexCoords[r++]=Q,this.renderColorIndices[a++]=E,this.renderTexCoords[r++]=Z,this.renderTexCoords[r++]=Q,this.renderColorIndices[a++]=E,this.renderTexCoords[r++]=j,this.renderTexCoords[r++]=K,this.renderColorIndices[a++]=E,this.renderTexCoords[r++]=Z,this.renderTexCoords[r++]=K,this.renderColorIndices[a++]=E}else for(let I=0;I<4;I++)this.renderTexCoords[r++]=0,this.renderTexCoords[r++]=0,this.renderColorIndices[a++]=255}}(r!==o*2*4*2||a!==o*2*4)&&console.error("[TerminalGL] \u274C Buffer index mismatch!",{texIdx:r,colorIdx:a,expected:o*2*4}),e.useProgram(this.program),this.vao&&this.vaoExtension?(this.vaoExtension.bindVertexArrayOES(this.vao),e.bindBuffer(e.ARRAY_BUFFER,this.texCoordBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.renderTexCoords.subarray(0,r)),e.bindBuffer(e.ARRAY_BUFFER,this.colorIndexBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.renderColorIndices.subarray(0,a))):(e.bindBuffer(e.ARRAY_BUFFER,this.positionBuffer),e.enableVertexAttribArray(this.aPosition),e.vertexAttribPointer(this.aPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this.texCoordBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.renderTexCoords.subarray(0,r)),e.enableVertexAttribArray(this.aTexCoord),e.vertexAttribPointer(this.aTexCoord,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this.colorIndexBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.renderColorIndices.subarray(0,a)),e.enableVertexAttribArray(this.aColorIndex),e.vertexAttribPointer(this.aColorIndex,1,e.FLOAT,!1,0,0));let h=this.canvas.width,c=this.canvas.height;(this.cachedResolution[0]!==h||this.cachedResolution[1]!==c)&&(e.uniform2f(this.uResolution,h,c),this.cachedResolution[0]=h,this.cachedResolution[1]=c),this.cachedTextureUnit!==0&&(e.activeTexture(e.TEXTURE0),this.cachedTextureUnit=0),e.bindTexture(e.TEXTURE_2D,this.atlasTexture),this.cachedTextureUniform||(e.uniform1i(this.uTexture,0),this.cachedTextureUniform=!0),this.cachedPaletteUnit!==1&&(e.activeTexture(e.TEXTURE1),this.cachedPaletteUnit=1),e.bindTexture(e.TEXTURE_2D,this.paletteTexture),this.cachedPaletteUniform||(e.uniform1i(this.uPalette,1),this.cachedPaletteUniform=!0),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer);let f=t.width*t.height*2*6,u=this.useUint16Indices?e.UNSIGNED_SHORT:e.UNSIGNED_INT;e.drawElements(e.TRIANGLES,f,u,0)}resize(t,e){if(!Number.isInteger(t)||t<=0){console.error(`[TerminalGL] \u274C Invalid cols: ${t}. Must be positive integer.`);return}if(!Number.isInteger(e)||e<=0){console.error(`[TerminalGL] \u274C Invalid rows: ${e}. Must be positive integer.`);return}if(t===this.cols&&e===this.rows)return;let i=t*e,s=this.useUint16Indices?8191:262144;if(i>s){let c=Math.floor(Math.sqrt(s));console.error(`[TerminalGL] \u274C Cannot resize to ${t}\xD7${e} (${i} cells). Device limit: ${s} cells (max ~${c}\xD7${c}). ${this.useUint16Indices?"Device lacks OES_element_index_uint extension.":""}`);return}let r=U.checkCompatibility();i>r.recommendedMaxCells&&console.warn(`[TerminalGL] \u26A0\uFE0F Resizing to ${t}\xD7${e} (${i} cells) exceeds recommended limit (${r.recommendedMaxCells} cells). Performance may degrade.`),this.cols=t,this.rows=e,this.staticPositionsInitialized=!1;let a=this.cols*this.rows*2,l=Math.ceil(a*1.5),o=a>this.maxCells,h=this.maxCells>l*4;if(o||h){let c=this.maxCells;this.maxCells=l,this.renderPositions=new Float32Array(this.maxCells*4*2),this.renderTexCoords=new Float32Array(this.maxCells*4*2),this.renderColorIndices=new Float32Array(this.maxCells*4),this.useUint16Indices?this.renderIndices=new Uint16Array(this.maxCells*6):this.renderIndices=new Uint32Array(this.maxCells*6);let d=this.gl;this.useInstancing||(d.bindBuffer(d.ARRAY_BUFFER,this.positionBuffer),d.bufferData(d.ARRAY_BUFFER,this.renderPositions.byteLength,d.DYNAMIC_DRAW)),d.bindBuffer(d.ARRAY_BUFFER,this.texCoordBuffer),d.bufferData(d.ARRAY_BUFFER,this.renderTexCoords.byteLength,d.DYNAMIC_DRAW),d.bindBuffer(d.ARRAY_BUFFER,this.colorIndexBuffer),d.bufferData(d.ARRAY_BUFFER,this.renderColorIndices.byteLength,d.DYNAMIC_DRAW),d.bindBuffer(d.ELEMENT_ARRAY_BUFFER,this.indexBuffer),d.bufferData(d.ELEMENT_ARRAY_BUFFER,this.renderIndices.byteLength,d.DYNAMIC_DRAW),this.vaoExtension&&this.vao&&(this.vaoExtension.deleteVertexArrayOES(this.vao),this.vao=this.vaoExtension.createVertexArrayOES(),this.vao&&(this.vaoExtension.bindVertexArrayOES(this.vao),d.bindBuffer(d.ARRAY_BUFFER,this.positionBuffer),d.enableVertexAttribArray(this.aPosition),d.vertexAttribPointer(this.aPosition,2,d.FLOAT,!1,0,0),d.bindBuffer(d.ARRAY_BUFFER,this.texCoordBuffer),d.enableVertexAttribArray(this.aTexCoord),d.vertexAttribPointer(this.aTexCoord,2,d.FLOAT,!1,0,0),d.bindBuffer(d.ARRAY_BUFFER,this.colorIndexBuffer),d.enableVertexAttribArray(this.aColorIndex),d.vertexAttribPointer(this.aColorIndex,1,d.FLOAT,!1,0,0),d.bindBuffer(d.ELEMENT_ARRAY_BUFFER,this.indexBuffer),this.vaoExtension.bindVertexArrayOES(null)));let f=o?"\u{1F4C8} Growing":"\u{1F4C9} Shrinking",u=c*160/1048576,m=this.maxCells*160/1048576;console.warn(`[TerminalGL] ${f} buffers: ${u.toFixed(2)}MB \u2192 ${m.toFixed(2)}MB (${c} \u2192 ${this.maxCells} quads)`)}this.canvas.width=this.cols*this.cellWidth,this.canvas.height=this.rows*this.cellHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.ambientEffectEnabled&&this.ambientEffectCanvas&&(this.ambientEffectCanvas.width=this.canvas.width,this.ambientEffectCanvas.height=this.canvas.height,this.ambientEffectCanvas.style.width=`${this.canvas.width}px`,this.ambientEffectCanvas.style.height=`${this.canvas.height}px`),this.showGrid&&this.gridOverlay&&this.updateGridOverlay(),this.updateCanvasSize()}getCanvas(){return this.canvas}getGridSize(){return{cols:this.cols,rows:this.rows}}getCellWidth(){return this.cellWidth}getCellHeight(){return this.cellHeight}getCurrentScale(){return this.currentScale}getBaseDimensions(){return{width:this.cols*this.cellWidth,height:this.rows*this.cellHeight}}setOnResizeCallback(t){this.onResizeCallback=t}clearOnResizeCallback(){this.onResizeCallback=void 0}setScalingMode(t){this.scalingMode!==t&&(this.scalingMode=t,this.updateCanvasSize())}getScalingMode(){return this.scalingMode}setGrid(t){t.enabled?(this.gridOverlay?this.gridOverlay.setStyle({strokeColor:t.color,lineWidth:t.lineWidth}):this.gridOverlay=new T(this.containerDiv,{strokeColor:t.color??"rgba(144, 24, 24, 1)",lineWidth:t.lineWidth??1,zIndex:10}),this.showGrid=!0,this.gridOverlay.setVisible(!0),this.updateGridOverlay()):(this.showGrid=!1,this.gridOverlay&&this.gridOverlay.setVisible(!1))}isGridEnabled(){return this.showGrid}setAmbientEffect(t){typeof t=="boolean"?this.ambientEffectEnabled=t:(this.ambientEffectEnabled=!0,t.blur!==void 0&&(this.ambientEffectBlur=t.blur),t.scale!==void 0&&(this.ambientEffectScale=t.scale)),this.ambientEffectEnabled&&!this.ambientEffectCanvas&&this.createAmbientEffectCanvas(),this.ambientEffectCanvas&&(this.ambientEffectEnabled?(this.ambientEffectCanvas.style.display="block",this.ambientEffectCanvas.style.filter=`blur(${this.ambientEffectBlur}px)`,this.ambientEffectCanvas.style.transform=`scale(${this.ambientEffectScale})`,this.updateAmbientEffect()):this.ambientEffectCanvas.style.display="none")}createAmbientEffectCanvas(){this.ambientEffectCanvas||(this.ambientEffectCanvas=document.createElement("canvas"),this.ambientEffectCanvas.className="terminalgl-ambient-effect-canvas",this.ambientEffectCanvas.width=this.canvas.width,this.ambientEffectCanvas.height=this.canvas.height,this.ambientEffectCanvas.style.cssText=`
116
+ `,s=this.compileShader(t.VERTEX_SHADER,e),r=this.compileShader(t.FRAGMENT_SHADER,i);if(!s||!r)throw new Error("Shader compilation error");let a=t.createProgram();if(!a)throw new Error("Unable to create WebGL program");if(t.attachShader(a,s),t.attachShader(a,r),t.linkProgram(a),!t.getProgramParameter(a,t.LINK_STATUS)){let l=t.getProgramInfoLog(a);throw new Error("Program linking error: "+l)}this.program=a,this.cachedTextureUniform=!1,this.cachedPaletteUniform=!1,this.aPosition=t.getAttribLocation(a,"aPosition"),this.useInstancing?(this.aTexCoord=t.getAttribLocation(a,"aInstanceOffset"),this.aColorIndex=t.getAttribLocation(a,"aInstanceUVs"),this.instanceDataBuffer=t.createBuffer()):(this.aTexCoord=t.getAttribLocation(a,"aTexCoord"),this.aColorIndex=t.getAttribLocation(a,"aColorIndex")),this.uResolution=t.getUniformLocation(a,"uResolution"),this.uTexture=t.getUniformLocation(a,"uTexture"),this.uPalette=t.getUniformLocation(a,"uPalette"),this.positionBuffer=t.createBuffer(),this.texCoordBuffer=t.createBuffer(),this.colorIndexBuffer=t.createBuffer(),this.indexBuffer=t.createBuffer(),t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.bufferData(t.ARRAY_BUFFER,this.renderPositions.byteLength,t.DYNAMIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferData(t.ARRAY_BUFFER,this.renderTexCoords.byteLength,t.DYNAMIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,this.colorIndexBuffer),t.bufferData(t.ARRAY_BUFFER,this.renderColorIndices.byteLength,t.DYNAMIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,this.renderIndices.byteLength,t.DYNAMIC_DRAW),this.vaoExtension&&(this.vao=this.vaoExtension.createVertexArrayOES(),this.vao&&(this.vaoExtension.bindVertexArrayOES(this.vao),t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.enableVertexAttribArray(this.aPosition),t.vertexAttribPointer(this.aPosition,2,t.FLOAT,!1,0,0),t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.enableVertexAttribArray(this.aTexCoord),t.vertexAttribPointer(this.aTexCoord,2,t.FLOAT,!1,0,0),t.bindBuffer(t.ARRAY_BUFFER,this.colorIndexBuffer),t.enableVertexAttribArray(this.aColorIndex),t.vertexAttribPointer(this.aColorIndex,1,t.FLOAT,!1,0,0),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),this.vaoExtension.bindVertexArrayOES(null))),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),t.viewport(0,0,this.canvas.width,this.canvas.height)}compileShader(t,e){let i=this.gl,s=i.createShader(t);return s?(i.shaderSource(s,e),i.compileShader(s),i.getShaderParameter(s,i.COMPILE_STATUS)?s:(console.error("Shader compilation error:",i.getShaderInfoLog(s)),i.deleteShader(s),null)):null}initGridOverlay(){this.gridOverlay=new R(this.containerDiv,{strokeColor:"rgba(144, 24, 24, 1)",lineWidth:1,zIndex:10}),this.updateGridOverlay()}updateGridOverlay(){if(!this.gridOverlay)return;let t=this.cols*this.cellWidth,e=this.rows*this.cellHeight,i=this.canvas.getBoundingClientRect(),s=this.containerDiv.getBoundingClientRect();this.gridOverlay.setDimensions(this.cols,this.rows,this.cellWidth,this.cellHeight,0,0),this.gridOverlay.setTransform(this.currentScale,t,e,i,s),this.gridOverlay.render()}setBitmapFont(t,e,i,s,r){this.bitmapFont=t,this.fontLoaded=!0,this.charWidth=Math.round(e),this.charHeight=Math.round(i),this.cellWidth=Math.round(s),this.cellHeight=Math.round(r),this.glyphOffsetX=Math.round((this.cellWidth-this.charWidth)/2),this.glyphOffsetY=Math.round((this.cellHeight-this.charHeight)/2),this.useInstancing&&(console.warn("[TerminalGL] \u{1F680} Initializing instanced buffers..."),this.initInstancedBuffers());try{this.generateAtlas()}catch(a){throw console.error("[TerminalGL] \u274C Failed to generate atlas:",a),a}this.buildCharCodeMap(),this.precomputeAtlasUVs(),this.canvas.width=this.cols*this.cellWidth,this.canvas.height=this.rows*this.cellHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.useInstancing||this.precomputeStaticPositions(),this.showGrid&&this.gridOverlay&&this.updateGridOverlay()}async setImageFont(t,e,i,s,r,a){this.fontLoaded=!0,this.charWidth=Math.round(e),this.charHeight=Math.round(i),this.cellWidth=Math.round(s),this.cellHeight=Math.round(r),this.atlasColumns=S(a);let l=M(a);this.glyphOffsetX=Math.round((this.cellWidth-this.charWidth)/2),this.glyphOffsetY=Math.round((this.cellHeight-this.charHeight)/2),this.useInstancing&&(console.warn("[TerminalGL] \u{1F680} Initializing instanced buffers for ImageFont..."),this.initInstancedBuffers()),await this.loadImageFontAtlas(t),this.charCodeToAtlasIndex.fill(65535);for(let o=0;o<=l;o++)this.charCodeToAtlasIndex[o]=o;this.precomputeImageFontUVs(a),this.canvas.width=this.cols*this.cellWidth,this.canvas.height=this.rows*this.cellHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.useInstancing||this.precomputeStaticPositions(),this.showGrid&&this.gridOverlay&&this.updateGridOverlay()}async loadImageFontAtlas(t){return new Promise((e,i)=>{let s=new Uint8Array(t),r=new Blob([s],{type:"image/png"}),a=URL.createObjectURL(r),l=new Image;l.onload=()=>{URL.revokeObjectURL(a),this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=l.width,this.atlasCanvas.height=l.height;let o=this.atlasCanvas.getContext("2d");if(!o){i(new Error("Failed to create 2D context for atlas"));return}o.drawImage(l,0,0),this.cachedAtlasWidth=l.width,this.cachedAtlasHeight=l.height,this.createAtlasTexture(),e()},l.onerror=()=>{URL.revokeObjectURL(a),i(new Error("Failed to load PNG image for ImageFont atlas"))},l.src=a})}precomputeImageFontUVs(t){let e=t*256;this.atlasUVs=new Float32Array(e*4);let i=this.cachedAtlasWidth,s=this.cachedAtlasHeight,r=.5/i,a=.5/s;for(let l=0;l<e;l++){let{col:o,row:h}=D(l,t),c=(o*this.charWidth+r)/i,d=(h*this.charHeight+a)/s,f=((o+1)*this.charWidth-r)/i,u=((h+1)*this.charHeight-a)/s,m=l*4;this.atlasUVs[m]=c,this.atlasUVs[m+1]=d,this.atlasUVs[m+2]=f,this.atlasUVs[m+3]=u}}generateAtlas(){if(!this.bitmapFont)return;let t=Array.from(this.bitmapFont.keys()).sort((o,h)=>o-h),e=t.length;this.atlasColumns=Math.ceil(Math.sqrt(e));let i=Math.ceil(e/this.atlasColumns),s=this.atlasColumns*this.charWidth,r=i*this.charHeight;this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=s,this.atlasCanvas.height=r;let a=this.atlasCanvas.getContext("2d");if(!a)throw new Error("Unable to create 2D context for atlas");a.clearRect(0,0,s,r),a.fillStyle="#ffffff";let l=0;for(let o of t){let h=this.bitmapFont.get(o);if(!h)continue;let c=l%this.atlasColumns,d=Math.floor(l/this.atlasColumns),f=c*this.charWidth,u=d*this.charHeight;for(let m=0;m<Math.min(h.length,this.charHeight);m++){let g=h[m];for(let p=0;p<this.charWidth;p++){let x=1<<7-p;g&x&&a.fillRect(f+p,u+m,1,1)}}l++}this.createAtlasTexture()}buildCharCodeMap(){if(!this.bitmapFont)return;this.charCodeToAtlasIndex.fill(65535);let t=Array.from(this.bitmapFont.keys()).sort((e,i)=>e-i);for(let e=0;e<t.length;e++)this.charCodeToAtlasIndex[t[e]]=e}precomputeAtlasUVs(){if(!this.bitmapFont)return;let t=this.bitmapFont.size;this.atlasUVs=new Float32Array(t*4),this.cachedAtlasWidth=this.atlasColumns*this.charWidth,this.cachedAtlasHeight=Math.ceil(t/this.atlasColumns)*this.charHeight;let e=this.cachedAtlasWidth,i=this.cachedAtlasHeight,s=.5/e,r=.5/i;for(let a=0;a<t;a++){let l=a%this.atlasColumns,o=Math.floor(a/this.atlasColumns),h=(l*this.charWidth+s)/e,c=(o*this.charHeight+r)/i,d=((l+1)*this.charWidth-s)/e,f=((o+1)*this.charHeight-r)/i,u=a*4;this.atlasUVs[u]=h,this.atlasUVs[u+1]=c,this.atlasUVs[u+2]=d,this.atlasUVs[u+3]=f}}createAtlasTexture(){if(this.atlasCanvas)try{let t=this.gl,e=t.createTexture();if(!e)throw new Error("Unable to create texture");t.bindTexture(t.TEXTURE_2D,e),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,this.atlasCanvas),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),this.atlasTexture=e}catch(t){throw console.error("[TerminalGL] \u274C Failed to create atlas texture:",t),t}}clear(){let t=this.gl;t&&t.clear(t.COLOR_BUFFER_BIT)}parseColor(t){if(t.startsWith("#")){let e=t.slice(1),i=0,s=0,r=0;return e.length===3?(i=parseInt(e[0]+e[0],16),s=parseInt(e[1]+e[1],16),r=parseInt(e[2]+e[2],16)):e.length===6&&(i=parseInt(e.slice(0,2),16),s=parseInt(e.slice(2,4),16),r=parseInt(e.slice(4,6),16)),[i/255,s/255,r/255,1]}if(t.startsWith("rgb")){let e=t.match(/rgba?\(([^)]+)\)/);if(e){let i=e[1].split(",").map(s=>parseFloat(s.trim()));return[i[0]/255,i[1]/255,i[2]/255,i[3]!==void 0?i[3]:1]}}return[1,1,1,1]}setupResizeObserver(){if(!(typeof ResizeObserver>"u"))try{this.resizeObserver=new ResizeObserver(()=>{try{this.updateCanvasSize()}catch(t){console.error("[TerminalGL] \u274C Error in resize callback:",t)}}),this.resizeObserver.observe(this.parentElement),this.updateCanvasSize()}catch(t){console.error("[TerminalGL] \u274C Failed to setup ResizeObserver:",t)}}updateCanvasSize(){let t=this.parentElement.clientWidth,e=this.parentElement.clientHeight;if(t===0||e===0)return;let i=this.cols*this.cellWidth,s=this.rows*this.cellHeight;if(i===0||s===0)return;let r=t/i,a=e/s,l=Math.min(r,a),o;switch(this.scalingMode){case T.Integer:o=Math.max(1,Math.floor(l));break;case T.Half:o=Math.max(1,Math.floor(l*2)/2);break;case T.Quarter:o=Math.max(1,Math.floor(l*4)/4);break;case T.Eighth:o=Math.max(1,Math.floor(l*8)/8);break;case T.None:default:o=Math.max(.1,l);break}if(this.canvas.style.transform=`scale(${o})`,this.ambientEffectEnabled&&this.ambientEffectCanvas){let h=o*this.ambientEffectScale;this.ambientEffectCanvas.style.transform=`scale(${h})`}this.currentScale=o,this.onResizeCallback&&this.onResizeCallback(),this.showGrid&&this.gridOverlay&&this.updateGridOverlay()}updateAmbientEffect(){!this.ambientEffectCanvas||!this.ambientEffectCtx||this.ambientEffectCtx.drawImage(this.canvas,0,0)}setPalette(t){let e=0;for(let i=0;i<Math.min(t.length,256);i++){let s=t[i];e=(e<<5)-e+s.r,e=(e<<5)-e+s.g,e=(e<<5)-e+s.b,e=(e<<5)-e+s.a,e=e|0}if(e!==this.paletteHash){this.paletteHash=e;for(let i=0;i<t.length&&i<256;i++){let s=t[i],r=i*4;this.paletteFloat[r]=s.r/255,this.paletteFloat[r+1]=s.g/255,this.paletteFloat[r+2]=s.b/255,this.paletteFloat[r+3]=s.a/255}this.updatePaletteTexture()}}updatePaletteTexture(){try{let t=this.gl;this.paletteTexture||(this.paletteTexture=t.createTexture()),t.bindTexture(t.TEXTURE_2D,this.paletteTexture);let e=new Uint8Array(256*4);for(let i=0;i<256;i++){let s=i*4;e[s]=this.paletteFloat[s]*255,e[s+1]=this.paletteFloat[s+1]*255,e[s+2]=this.paletteFloat[s+2]*255,e[s+3]=this.paletteFloat[s+3]*255}t.texImage2D(t.TEXTURE_2D,0,t.RGBA,256,1,0,t.RGBA,t.UNSIGNED_BYTE,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.bindTexture(t.TEXTURE_2D,null)}catch(t){throw console.error("[TerminalGL] \u274C Failed to update palette texture:",t),t}}renderDisplayData(t){try{if(!this.isReady()){console.warn("[TerminalGL] \u26A0\uFE0F Not ready: font not loaded yet");return}(t.width!==this.cols||t.height!==this.rows)&&this.resize(t.width,t.height),this.renderDirect(t),this.ambientEffectEnabled&&this.ambientEffectCanvas&&this.ambientEffectCtx&&this.updateAmbientEffect()}catch(e){console.error("[TerminalGL] \u274C Error rendering display data:",e)}}renderDirect(t){let e=this.gl;if(!this.staticPositionsInitialized&&!this.useInstancing&&this.precomputeStaticPositions(),this.canvasBgColor!==null){let i=this.parseColor(this.canvasBgColor);e.clearColor(i[0],i[1],i[2],i[3])}else e.clearColor(0,0,0,0);e.clear(e.COLOR_BUFFER_BIT),this.useInstancing?this.renderInstanced(t):this.renderDirectBuffers(t)}renderInstanced(t){let e=this.gl,i=this.instancedExtension;if(!this.instanceData||this.instanceData.length===0){console.warn("[TerminalGL] \u26A0\uFE0F Instance data not initialized, falling back to standard rendering"),this.useInstancing=!1,this.renderDirectBuffers(t);return}let s=t.width*t.height;if(this.useUint16Indices&&s>8191){console.warn(`[TerminalGL] \u26A0\uFE0F Terminal too large for instanced rendering with Uint16 (${s} cells > 8191). Falling back to standard rendering.`),this.useInstancing=!1,this.renderDirectBuffers(t);return}let r=0,a=this.instanceData.length/8;for(let f=0;f<t.height;f++)for(let u=0;u<t.width;u++){let m=t.cells[f*t.width+u],g=m.bgColorIndex,p=m.fgColorIndex,x=this.canvasBgColor!==null&&g===255,w=m.char===" "||p===255;if(!x){if(r>=a){console.error(`[TerminalGL] \u274C Instance buffer overflow! instanceIdx=${r}, max=${a}`);break}let C=r*8;this.instanceData[C]=u,this.instanceData[C+1]=f,this.instanceData[C+2]=0,this.instanceData[C+3]=0,this.instanceData[C+4]=0,this.instanceData[C+5]=0,this.instanceData[C+6]=g,this.instanceData[C+7]=0,r++}if(!w){let C=m.char.charCodeAt(0),E=this.charCodeToAtlasIndex[C];if(E!==65535){if(r>=a){console.error(`[TerminalGL] \u274C Instance buffer overflow! instanceIdx=${r}, max=${a}`);break}let A=E*4,y=r*8;this.instanceData[y]=u,this.instanceData[y+1]=f,this.instanceData[y+2]=this.atlasUVs[A],this.instanceData[y+3]=this.atlasUVs[A+1],this.instanceData[y+4]=this.atlasUVs[A+2],this.instanceData[y+5]=this.atlasUVs[A+3],this.instanceData[y+6]=0,this.instanceData[y+7]=p,r++}}}if(r===0){console.warn("[TerminalGL] \u26A0\uFE0F No instances to draw (all cells skipped)");return}e.bindBuffer(e.ARRAY_BUFFER,this.instanceDataBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.instanceData.subarray(0,r*8)),e.useProgram(this.program),e.bindBuffer(e.ARRAY_BUFFER,this.positionBuffer),e.enableVertexAttribArray(this.aPosition),e.vertexAttribPointer(this.aPosition,2,e.FLOAT,!1,0,0),i.vertexAttribDivisorANGLE(this.aPosition,0),e.bindBuffer(e.ARRAY_BUFFER,this.instanceDataBuffer);let l=8*Float32Array.BYTES_PER_ELEMENT,o=e.getAttribLocation(this.program,"aInstanceOffset");e.enableVertexAttribArray(o),e.vertexAttribPointer(o,2,e.FLOAT,!1,l,0),i.vertexAttribDivisorANGLE(o,1);let h=e.getAttribLocation(this.program,"aInstanceUVs");e.enableVertexAttribArray(h),e.vertexAttribPointer(h,4,e.FLOAT,!1,l,2*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisorANGLE(h,1);let c=e.getAttribLocation(this.program,"aInstanceColors");e.enableVertexAttribArray(c),e.vertexAttribPointer(c,2,e.FLOAT,!1,l,6*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisorANGLE(c,1),e.uniform2f(this.uResolution,this.canvas.width,this.canvas.height);let d=e.getUniformLocation(this.program,"uCellSize");e.uniform2f(d,this.cellWidth,this.cellHeight),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.atlasTexture),e.uniform1i(this.uTexture,0),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,this.paletteTexture),e.uniform1i(this.uPalette,1),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer),i.drawElementsInstancedANGLE(e.TRIANGLES,6,e.UNSIGNED_SHORT,0,r),i.vertexAttribDivisorANGLE(this.aPosition,0),i.vertexAttribDivisorANGLE(o,0),i.vertexAttribDivisorANGLE(h,0),i.vertexAttribDivisorANGLE(c,0)}renderDirectBuffers(t){let e=this.gl,i=t.width*t.height,s=i*2;if(s>this.maxCells){console.error(`[TerminalGL] \u274C Buffer overflow detected! Trying to render ${s} quads but buffer capacity is ${this.maxCells}. This should not happen - resize() should have reallocated.`);return}let r=0,a=0,l=t.cells,o=i;for(let m=0;m<o;m++){let g=l[m],p=g.bgColorIndex,w=this.canvasBgColor!==null&&p===255?255:p,C=0;for(let y=0;y<4;y++)this.renderTexCoords[r++]=C,this.renderTexCoords[r++]=C,this.renderColorIndices[a++]=w;let E=g.fgColorIndex,A=g.char;if(A===" "||E===255)for(let y=0;y<4;y++)this.renderTexCoords[r++]=0,this.renderTexCoords[r++]=0,this.renderColorIndices[a++]=255;else{let y=A.charCodeAt(0),Z=this.charCodeToAtlasIndex[y];if(Z!==65535){let I=Z*4,K=this.atlasUVs[I],J=this.atlasUVs[I+1],tt=this.atlasUVs[I+2],et=this.atlasUVs[I+3];this.renderTexCoords[r++]=K,this.renderTexCoords[r++]=J,this.renderColorIndices[a++]=E,this.renderTexCoords[r++]=tt,this.renderTexCoords[r++]=J,this.renderColorIndices[a++]=E,this.renderTexCoords[r++]=K,this.renderTexCoords[r++]=et,this.renderColorIndices[a++]=E,this.renderTexCoords[r++]=tt,this.renderTexCoords[r++]=et,this.renderColorIndices[a++]=E}else for(let I=0;I<4;I++)this.renderTexCoords[r++]=0,this.renderTexCoords[r++]=0,this.renderColorIndices[a++]=255}}(r!==o*2*4*2||a!==o*2*4)&&console.error("[TerminalGL] \u274C Buffer index mismatch!",{texIdx:r,colorIdx:a,expected:o*2*4}),e.useProgram(this.program),this.vao&&this.vaoExtension?(this.vaoExtension.bindVertexArrayOES(this.vao),e.bindBuffer(e.ARRAY_BUFFER,this.texCoordBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.renderTexCoords.subarray(0,r)),e.bindBuffer(e.ARRAY_BUFFER,this.colorIndexBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.renderColorIndices.subarray(0,a))):(e.bindBuffer(e.ARRAY_BUFFER,this.positionBuffer),e.enableVertexAttribArray(this.aPosition),e.vertexAttribPointer(this.aPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this.texCoordBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.renderTexCoords.subarray(0,r)),e.enableVertexAttribArray(this.aTexCoord),e.vertexAttribPointer(this.aTexCoord,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this.colorIndexBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.renderColorIndices.subarray(0,a)),e.enableVertexAttribArray(this.aColorIndex),e.vertexAttribPointer(this.aColorIndex,1,e.FLOAT,!1,0,0));let h=this.canvas.width,c=this.canvas.height;(this.cachedResolution[0]!==h||this.cachedResolution[1]!==c)&&(e.uniform2f(this.uResolution,h,c),this.cachedResolution[0]=h,this.cachedResolution[1]=c),this.cachedTextureUnit!==0&&(e.activeTexture(e.TEXTURE0),this.cachedTextureUnit=0),e.bindTexture(e.TEXTURE_2D,this.atlasTexture),this.cachedTextureUniform||(e.uniform1i(this.uTexture,0),this.cachedTextureUniform=!0),this.cachedPaletteUnit!==1&&(e.activeTexture(e.TEXTURE1),this.cachedPaletteUnit=1),e.bindTexture(e.TEXTURE_2D,this.paletteTexture),this.cachedPaletteUniform||(e.uniform1i(this.uPalette,1),this.cachedPaletteUniform=!0),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer);let f=t.width*t.height*2*6,u=this.useUint16Indices?e.UNSIGNED_SHORT:e.UNSIGNED_INT;e.drawElements(e.TRIANGLES,f,u,0)}resize(t,e){if(!Number.isInteger(t)||t<=0){console.error(`[TerminalGL] \u274C Invalid cols: ${t}. Must be positive integer.`);return}if(!Number.isInteger(e)||e<=0){console.error(`[TerminalGL] \u274C Invalid rows: ${e}. Must be positive integer.`);return}if(t===this.cols&&e===this.rows)return;let i=t*e,s=this.useUint16Indices?8191:262144;if(i>s){let c=Math.floor(Math.sqrt(s));console.error(`[TerminalGL] \u274C Cannot resize to ${t}\xD7${e} (${i} cells). Device limit: ${s} cells (max ~${c}\xD7${c}). ${this.useUint16Indices?"Device lacks OES_element_index_uint extension.":""}`);return}let r=F.checkCompatibility();i>r.recommendedMaxCells&&console.warn(`[TerminalGL] \u26A0\uFE0F Resizing to ${t}\xD7${e} (${i} cells) exceeds recommended limit (${r.recommendedMaxCells} cells). Performance may degrade.`),this.cols=t,this.rows=e,this.staticPositionsInitialized=!1;let a=this.cols*this.rows*2,l=Math.ceil(a*1.5),o=a>this.maxCells,h=this.maxCells>l*4;if(o||h){let c=this.maxCells;this.maxCells=l,this.renderPositions=new Float32Array(this.maxCells*4*2),this.renderTexCoords=new Float32Array(this.maxCells*4*2),this.renderColorIndices=new Float32Array(this.maxCells*4),this.useUint16Indices?this.renderIndices=new Uint16Array(this.maxCells*6):this.renderIndices=new Uint32Array(this.maxCells*6);let d=this.gl;this.useInstancing||(d.bindBuffer(d.ARRAY_BUFFER,this.positionBuffer),d.bufferData(d.ARRAY_BUFFER,this.renderPositions.byteLength,d.DYNAMIC_DRAW)),d.bindBuffer(d.ARRAY_BUFFER,this.texCoordBuffer),d.bufferData(d.ARRAY_BUFFER,this.renderTexCoords.byteLength,d.DYNAMIC_DRAW),d.bindBuffer(d.ARRAY_BUFFER,this.colorIndexBuffer),d.bufferData(d.ARRAY_BUFFER,this.renderColorIndices.byteLength,d.DYNAMIC_DRAW),d.bindBuffer(d.ELEMENT_ARRAY_BUFFER,this.indexBuffer),d.bufferData(d.ELEMENT_ARRAY_BUFFER,this.renderIndices.byteLength,d.DYNAMIC_DRAW),this.vaoExtension&&this.vao&&(this.vaoExtension.deleteVertexArrayOES(this.vao),this.vao=this.vaoExtension.createVertexArrayOES(),this.vao&&(this.vaoExtension.bindVertexArrayOES(this.vao),d.bindBuffer(d.ARRAY_BUFFER,this.positionBuffer),d.enableVertexAttribArray(this.aPosition),d.vertexAttribPointer(this.aPosition,2,d.FLOAT,!1,0,0),d.bindBuffer(d.ARRAY_BUFFER,this.texCoordBuffer),d.enableVertexAttribArray(this.aTexCoord),d.vertexAttribPointer(this.aTexCoord,2,d.FLOAT,!1,0,0),d.bindBuffer(d.ARRAY_BUFFER,this.colorIndexBuffer),d.enableVertexAttribArray(this.aColorIndex),d.vertexAttribPointer(this.aColorIndex,1,d.FLOAT,!1,0,0),d.bindBuffer(d.ELEMENT_ARRAY_BUFFER,this.indexBuffer),this.vaoExtension.bindVertexArrayOES(null)));let f=o?"\u{1F4C8} Growing":"\u{1F4C9} Shrinking",u=c*160/1048576,m=this.maxCells*160/1048576;console.warn(`[TerminalGL] ${f} buffers: ${u.toFixed(2)}MB \u2192 ${m.toFixed(2)}MB (${c} \u2192 ${this.maxCells} quads)`)}this.canvas.width=this.cols*this.cellWidth,this.canvas.height=this.rows*this.cellHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.ambientEffectEnabled&&this.ambientEffectCanvas&&(this.ambientEffectCanvas.width=this.canvas.width,this.ambientEffectCanvas.height=this.canvas.height,this.ambientEffectCanvas.style.width=`${this.canvas.width}px`,this.ambientEffectCanvas.style.height=`${this.canvas.height}px`),this.showGrid&&this.gridOverlay&&this.updateGridOverlay(),this.updateCanvasSize()}getCanvas(){return this.canvas}getGridSize(){return{cols:this.cols,rows:this.rows}}getCellWidth(){return this.cellWidth}getCellHeight(){return this.cellHeight}getCurrentScale(){return this.currentScale}getBaseDimensions(){return{width:this.cols*this.cellWidth,height:this.rows*this.cellHeight}}setOnResizeCallback(t){this.onResizeCallback=t}clearOnResizeCallback(){this.onResizeCallback=void 0}setScalingMode(t){this.scalingMode!==t&&(this.scalingMode=t,this.updateCanvasSize())}getScalingMode(){return this.scalingMode}setGrid(t){t.enabled?(this.gridOverlay?this.gridOverlay.setStyle({strokeColor:t.color,lineWidth:t.lineWidth}):this.gridOverlay=new R(this.containerDiv,{strokeColor:t.color??"rgba(144, 24, 24, 1)",lineWidth:t.lineWidth??1,zIndex:10}),this.showGrid=!0,this.gridOverlay.setVisible(!0),this.updateGridOverlay()):(this.showGrid=!1,this.gridOverlay&&this.gridOverlay.setVisible(!1))}isGridEnabled(){return this.showGrid}setAmbientEffect(t){typeof t=="boolean"?this.ambientEffectEnabled=t:(this.ambientEffectEnabled=!0,t.blur!==void 0&&(this.ambientEffectBlur=t.blur),t.scale!==void 0&&(this.ambientEffectScale=t.scale)),this.ambientEffectEnabled&&!this.ambientEffectCanvas&&this.createAmbientEffectCanvas(),this.ambientEffectCanvas&&(this.ambientEffectEnabled?(this.ambientEffectCanvas.style.display="block",this.ambientEffectCanvas.style.filter=`blur(${this.ambientEffectBlur}px)`,this.ambientEffectCanvas.style.transform=`scale(${this.ambientEffectScale})`,this.updateAmbientEffect()):this.ambientEffectCanvas.style.display="none")}createAmbientEffectCanvas(){this.ambientEffectCanvas||(this.ambientEffectCanvas=document.createElement("canvas"),this.ambientEffectCanvas.className="terminalgl-ambient-effect-canvas",this.ambientEffectCanvas.width=this.canvas.width,this.ambientEffectCanvas.height=this.canvas.height,this.ambientEffectCanvas.style.cssText=`
117
117
  display: block !important;
118
118
  position: absolute !important;
119
119
  width: ${this.canvas.width}px !important;
@@ -124,7 +124,7 @@ var J=Object.defineProperty;var tt=(C,t,e)=>t in C?J(C,t,{enumerable:!0,configur
124
124
  transform: scale(${this.ambientEffectScale}) !important;
125
125
  pointer-events: none !important;
126
126
  z-index: 0 !important;
127
- `,this.ambientEffectCtx=this.ambientEffectCanvas.getContext("2d",{alpha:!0}),this.containerDiv.insertBefore(this.ambientEffectCanvas,this.canvas),console.warn("[TerminalGL] \u{1F308} ambient effect canvas created dynamically"))}isAmbientEffectEnabled(){return this.ambientEffectEnabled}getAmbientEffectConfig(){return{enabled:this.ambientEffectEnabled,blur:this.ambientEffectBlur,scale:this.ambientEffectScale}}getCols(){return this.cols}getRows(){return this.rows}isReady(){return!!(this.fontLoaded&&this.atlasTexture&&this.program)}destroy(){this.dispose()}dispose(){this.resizeObserver&&this.resizeObserver.disconnect();let t=this.gl;this.program&&t.deleteProgram(this.program),this.positionBuffer&&t.deleteBuffer(this.positionBuffer),this.texCoordBuffer&&t.deleteBuffer(this.texCoordBuffer),this.colorIndexBuffer&&t.deleteBuffer(this.colorIndexBuffer),this.indexBuffer&&t.deleteBuffer(this.indexBuffer),this.instanceDataBuffer&&t.deleteBuffer(this.instanceDataBuffer),this.atlasTexture&&t.deleteTexture(this.atlasTexture),this.paletteTexture&&t.deleteTexture(this.paletteTexture),this.vao&&this.vaoExtension&&this.vaoExtension.deleteVertexArrayOES(this.vao);let e=t.getExtension("WEBGL_lose_context");e&&e.loseContext(),this.atlasCanvas&&(this.atlasCanvas.width=0,this.atlasCanvas.height=0,this.atlasCanvas=void 0),this.containerDiv.parentElement&&this.containerDiv.parentElement.removeChild(this.containerDiv),this.canvas.width=0,this.canvas.height=0,this.ambientEffectCanvas&&(this.ambientEffectCanvas.width=0,this.ambientEffectCanvas.height=0,this.ambientEffectCanvas=null),this.gridOverlay&&(this.gridOverlay.destroy(),this.gridOverlay=void 0),this.renderPositions=new Float32Array(0),this.renderTexCoords=new Float32Array(0),this.renderColorIndices=new Float32Array(0),this.renderIndices=new Uint32Array(0),this.paletteFloat=new Float32Array(0),this.atlasUVs=new Float32Array(0),this.instanceData=new Float32Array(0),this.templateQuadPositions=new Float32Array(0),this.templateQuadIndices=new Uint16Array(0)}};v(U,"TerminalGL");var P=U;var O=class O{constructor(t,e,i,s,r){n(this,"atlases");n(this,"charMap");n(this,"baseCharWidth");n(this,"baseCharHeight");n(this,"baseCellWidth");n(this,"baseCellHeight");n(this,"atlasColumns",16);n(this,"font");n(this,"SCALES",[1,2,4,8]);n(this,"colorCache",new Map);n(this,"MAX_CACHE_SIZE",512);this.font=t,this.baseCharWidth=e,this.baseCharHeight=i,this.baseCellWidth=s??e,this.baseCellHeight=r??i,this.charMap=new Map,this.atlases=new Map,this.generateAtlases()}generateAtlases(){this.atlasColumns=16;let t=0;for(let[e,i]of this.font){let s=t%this.atlasColumns,r=Math.floor(t/this.atlasColumns);this.charMap.set(e,{x:s*this.baseCharWidth,y:r*this.baseCharHeight});for(let a of this.SCALES){let l=this.getOrCreateAtlas(a),o=s*l.charWidth,h=r*l.charHeight;this.renderBitmapToAtlas(l,i,o,h)}t++}}getOrCreateAtlas(t){let e=this.atlases.get(t);if(!e){let i=this.baseCharWidth*t,s=this.baseCharHeight*t,a=Math.ceil(256/this.atlasColumns),l=document.createElement("canvas");l.width=this.atlasColumns*i,l.height=a*s;let o=l.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!o)throw new Error(`Impossible de cr\xE9er le contexte 2D pour l'atlas ${t}x`);o.imageSmoothingEnabled=!1,e={canvas:l,ctx:o,scale:t,charWidth:i,charHeight:s},this.atlases.set(t,e)}return e}renderBitmapToAtlas(t,e,i,s){let r=t.scale,a=t.ctx;a.fillStyle="#ffffff";for(let l=0;l<Math.min(e.length,this.baseCharHeight);l++){let o=e[l];for(let h=0;h<this.baseCharWidth;h++){let c=1<<7-h;o&c&&a.fillRect(i+h*r,s+l*r,r,r)}}}drawChar(t,e,i,s,r,a,l){let o=this.charMap.get(e);if(!o)return;let h=`${e}:${l}`,c=this.colorCache.get(h);if(c)c.lastUsed=performance.now();else{let x=this.createColoredGlyph(e,l,o);if(!x)return;c={canvas:x,lastUsed:performance.now()},this.colorCache.set(h,c),this.colorCache.size>this.MAX_CACHE_SIZE&&this.evictLRU()}let d=r/this.baseCellWidth,f=a/this.baseCellHeight,u=(this.baseCellWidth-this.baseCharWidth)/2*d,m=(this.baseCellHeight-this.baseCharHeight)/2*f,g=this.baseCharWidth*d,p=this.baseCharHeight*f;t.drawImage(c.canvas,i+u,s+m,g,p)}createColoredGlyph(t,e,i){let s=this.atlases.get(1);if(!s)return null;let r=s.ctx.getImageData(i.x,i.y,this.baseCharWidth,this.baseCharHeight),a=r.data,l=this.hexToRgb(e);for(let c=0;c<a.length;c+=4)a[c+3]>0&&(a[c]=l.r,a[c+1]=l.g,a[c+2]=l.b);let o=document.createElement("canvas");o.width=this.baseCharWidth,o.height=this.baseCharHeight;let h=o.getContext("2d",{alpha:!0});return h?(h.imageSmoothingEnabled=!1,h.putImageData(r,0,0),o):null}hexToRgb(t){if(t.startsWith("#")){let r=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;t=t.replace(r,(l,o,h,c)=>o+o+h+h+c+c);let a=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return a?{r:parseInt(a[1],16),g:parseInt(a[2],16),b:parseInt(a[3],16)}:{r:255,g:255,b:255}}let e=/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*[\d.]+)?\)/.exec(t);if(e)return{r:parseInt(e[1],10),g:parseInt(e[2],10),b:parseInt(e[3],10)};let s={white:[255,255,255],black:[0,0,0],red:[255,0,0],green:[0,255,0],blue:[0,0,255],yellow:[255,255,0],cyan:[0,255,255],magenta:[255,0,255]}[t.toLowerCase()];return s?{r:s[0],g:s[1],b:s[2]}:{r:255,g:255,b:255}}evictLRU(){let t=null,e=1/0;for(let[i,s]of this.colorCache)s.lastUsed<e&&(e=s.lastUsed,t=i);if(t){let i=this.colorCache.get(t);i&&(i.canvas.width=0,i.canvas.height=0),this.colorCache.delete(t)}}getAtlasCanvas(t=1){return this.atlases.get(t)?.canvas}getAllAtlases(){return this.atlases}getCharDimensions(){return{width:this.baseCharWidth,height:this.baseCharHeight}}getCharCount(){return this.charMap.size}hasChar(t){return this.charMap.has(t)}getAtlasDimensions(t=1){let e=this.atlases.get(t);if(e)return{width:e.canvas.width,height:e.canvas.height}}toDataURL(t=1,e="image/png"){return this.atlases.get(t)?.canvas.toDataURL(e)}getCacheStats(){return{size:this.colorCache.size,maxSize:this.MAX_CACHE_SIZE}}clearCache(){for(let t of this.colorCache.values())t.canvas.width=0,t.canvas.height=0;this.colorCache.clear()}destroy(){this.charMap.clear();for(let t of this.atlases.values())t.canvas.width=0,t.canvas.height=0;this.atlases.clear(),this.clearCache()}};v(O,"BitmapFontAtlas");var S=O;var k=class k{constructor(t){n(this,"atlasCanvas",null);n(this,"atlasCtx",null);n(this,"atlasImage",null);n(this,"glyphWidth");n(this,"glyphHeight");n(this,"cellWidth");n(this,"cellHeight");n(this,"atlasBlocks");n(this,"atlasColumns");n(this,"maxCharCode");n(this,"isLoaded",!1);n(this,"colorCache",new Map);n(this,"MAX_CACHE_SIZE",1024);this.glyphWidth=t.glyphWidth,this.glyphHeight=t.glyphHeight,this.cellWidth=t.cellWidth??t.glyphWidth,this.cellHeight=t.cellHeight??t.glyphHeight,this.atlasBlocks=t.atlasBlocks,this.atlasColumns=M(t.atlasBlocks),this.maxCharCode=F(t.atlasBlocks)}async loadFromPNG(t){return new Promise((e,i)=>{let s=new Uint8Array(t),r=new Blob([s],{type:"image/png"}),a=URL.createObjectURL(r),l=new Image;l.onload=()=>{URL.revokeObjectURL(a);let o=this.atlasColumns*this.glyphWidth,h=this.atlasColumns*this.glyphHeight;if((l.width!==o||l.height!==h)&&console.warn(`ImageFontAtlas: Image size ${l.width}\xD7${l.height} doesn't match expected ${o}\xD7${h} for ${this.atlasBlocks} block(s) with ${this.glyphWidth}\xD7${this.glyphHeight} glyphs`),this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=l.width,this.atlasCanvas.height=l.height,this.atlasCtx=this.atlasCanvas.getContext("2d",{alpha:!0,willReadFrequently:!0}),!this.atlasCtx){i(new Error("Failed to create 2D context for atlas"));return}this.atlasCtx.imageSmoothingEnabled=!1,this.atlasCtx.drawImage(l,0,0),this.atlasImage=l,this.isLoaded=!0,e()},l.onerror=()=>{URL.revokeObjectURL(a),i(new Error("Failed to load PNG image for atlas"))},l.src=a})}isReady(){return this.isLoaded}getGlyphPosition(t){if(t<0||t>this.maxCharCode)return null;let{col:e,row:i}=D(t,this.atlasBlocks);return{x:e*this.glyphWidth,y:i*this.glyphHeight}}getCharUV(t){if(t<0||t>this.maxCharCode)return null;let{col:e,row:i}=D(t,this.atlasBlocks),s=e/this.atlasColumns,r=i/this.atlasColumns,a=(e+1)/this.atlasColumns,l=(i+1)/this.atlasColumns;return{u1:s,v1:r,u2:a,v2:l}}drawChar(t,e,i,s,r,a,l){if(!this.isLoaded||!this.atlasCanvas)return;let o=this.getGlyphPosition(e);if(!o)return;let h=`${e}:${l}`,c=this.colorCache.get(h);if(c)c.lastUsed=performance.now();else{let f=this.createColoredGlyph(e,l,o);if(!f)return;c={canvas:f,lastUsed:performance.now()},this.colorCache.set(h,c),this.colorCache.size>this.MAX_CACHE_SIZE&&this.evictLRU()}if(t.imageSmoothingEnabled=!1,r===this.cellWidth&&a===this.cellHeight){let f=Math.floor((this.cellWidth-this.glyphWidth)/2),u=Math.floor((this.cellHeight-this.glyphHeight)/2);t.drawImage(c.canvas,Math.floor(i)+f,Math.floor(s)+u)}else{let f=r/this.cellWidth,u=a/this.cellHeight,m=Math.floor((this.cellWidth-this.glyphWidth)/2*f),g=Math.floor((this.cellHeight-this.glyphHeight)/2*u),p=Math.ceil(this.glyphWidth*f),x=Math.ceil(this.glyphHeight*u);t.drawImage(c.canvas,Math.floor(i)+m,Math.floor(s)+g,p,x)}}createColoredGlyph(t,e,i){if(!this.atlasCtx)return null;let s=this.atlasCtx.getImageData(i.x,i.y,this.glyphWidth,this.glyphHeight),r=s.data,a=this.parseColor(e);for(let h=0;h<r.length;h+=4)r[h+3]>0&&(r[h]=a.r,r[h+1]=a.g,r[h+2]=a.b);let l=document.createElement("canvas");l.width=this.glyphWidth,l.height=this.glyphHeight;let o=l.getContext("2d",{alpha:!0});return o?(o.putImageData(s,0,0),l):null}parseColor(t){if(t.startsWith("#")){let i=t.slice(1);return i.length===3&&(i=i[0]+i[0]+i[1]+i[1]+i[2]+i[2]),{r:parseInt(i.slice(0,2),16),g:parseInt(i.slice(2,4),16),b:parseInt(i.slice(4,6),16)}}let e=/rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(t);return e?{r:parseInt(e[1],10),g:parseInt(e[2],10),b:parseInt(e[3],10)}:{r:255,g:255,b:255}}evictLRU(){let t=null,e=1/0;for(let[i,s]of this.colorCache)s.lastUsed<e&&(e=s.lastUsed,t=i);if(t){let i=this.colorCache.get(t);i&&(i.canvas.width=0,i.canvas.height=0),this.colorCache.delete(t)}}getAtlasCanvas(){return this.atlasCanvas}getAtlasImage(){return this.atlasImage}getConfig(){return{glyphWidth:this.glyphWidth,glyphHeight:this.glyphHeight,cellWidth:this.cellWidth,cellHeight:this.cellHeight,atlasBlocks:this.atlasBlocks}}getGlyphDimensions(){return{width:this.glyphWidth,height:this.glyphHeight}}getCellDimensions(){return{width:this.cellWidth,height:this.cellHeight}}getAtlasDimensions(){return{width:this.atlasColumns*this.glyphWidth,height:this.atlasColumns*this.glyphHeight}}getAtlasColumns(){return this.atlasColumns}getMaxCharCode(){return this.maxCharCode}isValidCharCode(t){return t>=0&&t<=this.maxCharCode}clearCache(){for(let t of this.colorCache.values())t.canvas.width=0,t.canvas.height=0;this.colorCache.clear()}getCacheStats(){return{size:this.colorCache.size,maxSize:this.MAX_CACHE_SIZE}}destroy(){this.clearCache(),this.atlasCanvas&&(this.atlasCanvas.width=0,this.atlasCanvas.height=0,this.atlasCanvas=null),this.atlasCtx=null,this.atlasImage=null,this.isLoaded=!1}};v(k,"ImageFontAtlas");var L=k;import{ScalingMode as B}from"@utsp/types";var $=class ${constructor(t,e={}){n(this,"containerDiv");n(this,"canvas");n(this,"ctx");n(this,"parentElement");n(this,"cells");n(this,"cols",0);n(this,"rows",0);n(this,"fontSize");n(this,"fontFamily");n(this,"defaultFgColor");n(this,"defaultBgColor");n(this,"canvasBgColor");n(this,"cellWidth");n(this,"cellHeight");n(this,"offsetX",0);n(this,"offsetY",0);n(this,"fontType","web");n(this,"bitmapFont");n(this,"bitmapAtlas");n(this,"imageAtlas");n(this,"bitmapCharWidth",8);n(this,"bitmapCharHeight",8);n(this,"showDebugGrid");n(this,"debugGridColor");n(this,"gridOverlay");n(this,"fixedGridMode");n(this,"fixedCols");n(this,"fixedRows");n(this,"cellAspectRatio");n(this,"resizeObserver");n(this,"imageDataBuffer");n(this,"useImageDataRendering",!1);n(this,"paletteCache");n(this,"scalingMode",B.None);n(this,"currentScale",1);if(!t)throw new Error("Render: L'\xE9l\xE9ment parent est requis");this.parentElement=t,this.fixedGridMode=!!(e.fixedCols&&e.fixedRows),this.fixedCols=e.fixedCols,this.fixedRows=e.fixedRows,this.cellAspectRatio=e.cellAspectRatio??10/14,this.cellWidth=e.cellWidth??10,this.cellHeight=e.cellHeight??14,this.fontSize=e.fontSize??12,this.fontFamily=e.fontFamily??"monospace",this.defaultFgColor=e.defaultFgColor??"#ffffff",this.defaultBgColor=e.defaultBgColor??"#000000",this.canvasBgColor=e.canvasBgColor!==void 0?e.canvasBgColor:null,this.showDebugGrid=e.showDebugGrid??!1,this.debugGridColor=e.debugGridColor??"rgba(144, 24, 24, 1)",this.scalingMode=e.scalingMode??B.None,window.getComputedStyle(this.parentElement).position==="static"&&(this.parentElement.style.position="relative"),this.containerDiv=document.createElement("div"),this.containerDiv.className="terminal2d-container",this.containerDiv.style.cssText=`
127
+ `,this.ambientEffectCtx=this.ambientEffectCanvas.getContext("2d",{alpha:!0}),this.containerDiv.insertBefore(this.ambientEffectCanvas,this.canvas),console.warn("[TerminalGL] \u{1F308} ambient effect canvas created dynamically"))}isAmbientEffectEnabled(){return this.ambientEffectEnabled}getAmbientEffectConfig(){return{enabled:this.ambientEffectEnabled,blur:this.ambientEffectBlur,scale:this.ambientEffectScale}}getCols(){return this.cols}getRows(){return this.rows}isReady(){return!!(this.fontLoaded&&this.atlasTexture&&this.program)}destroy(){this.dispose()}dispose(){this.resizeObserver&&this.resizeObserver.disconnect();let t=this.gl;this.program&&t.deleteProgram(this.program),this.positionBuffer&&t.deleteBuffer(this.positionBuffer),this.texCoordBuffer&&t.deleteBuffer(this.texCoordBuffer),this.colorIndexBuffer&&t.deleteBuffer(this.colorIndexBuffer),this.indexBuffer&&t.deleteBuffer(this.indexBuffer),this.instanceDataBuffer&&t.deleteBuffer(this.instanceDataBuffer),this.atlasTexture&&t.deleteTexture(this.atlasTexture),this.paletteTexture&&t.deleteTexture(this.paletteTexture),this.vao&&this.vaoExtension&&this.vaoExtension.deleteVertexArrayOES(this.vao);let e=t.getExtension("WEBGL_lose_context");e&&e.loseContext(),this.atlasCanvas&&(this.atlasCanvas.width=0,this.atlasCanvas.height=0,this.atlasCanvas=void 0),this.containerDiv.parentElement&&this.containerDiv.parentElement.removeChild(this.containerDiv),this.canvas.width=0,this.canvas.height=0,this.ambientEffectCanvas&&(this.ambientEffectCanvas.width=0,this.ambientEffectCanvas.height=0,this.ambientEffectCanvas=null),this.gridOverlay&&(this.gridOverlay.destroy(),this.gridOverlay=void 0),this.renderPositions=new Float32Array(0),this.renderTexCoords=new Float32Array(0),this.renderColorIndices=new Float32Array(0),this.renderIndices=new Uint32Array(0),this.paletteFloat=new Float32Array(0),this.atlasUVs=new Float32Array(0),this.instanceData=new Float32Array(0),this.templateQuadPositions=new Float32Array(0),this.templateQuadIndices=new Uint16Array(0)}};v(F,"TerminalGL");var P=F;var O=class O{constructor(t,e,i,s,r){n(this,"atlases");n(this,"charMap");n(this,"baseCharWidth");n(this,"baseCharHeight");n(this,"baseCellWidth");n(this,"baseCellHeight");n(this,"atlasColumns",16);n(this,"font");n(this,"SCALES",[1,2,4,8]);n(this,"colorCache",new Map);n(this,"MAX_CACHE_SIZE",512);this.font=t,this.baseCharWidth=e,this.baseCharHeight=i,this.baseCellWidth=s??e,this.baseCellHeight=r??i,this.charMap=new Map,this.atlases=new Map,this.generateAtlases()}generateAtlases(){this.atlasColumns=16;let t=0;for(let[e,i]of this.font){let s=t%this.atlasColumns,r=Math.floor(t/this.atlasColumns);this.charMap.set(e,{x:s*this.baseCharWidth,y:r*this.baseCharHeight});for(let a of this.SCALES){let l=this.getOrCreateAtlas(a),o=s*l.charWidth,h=r*l.charHeight;this.renderBitmapToAtlas(l,i,o,h)}t++}}getOrCreateAtlas(t){let e=this.atlases.get(t);if(!e){let i=this.baseCharWidth*t,s=this.baseCharHeight*t,a=Math.ceil(256/this.atlasColumns),l=document.createElement("canvas");l.width=this.atlasColumns*i,l.height=a*s;let o=l.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!o)throw new Error(`Impossible de cr\xE9er le contexte 2D pour l'atlas ${t}x`);o.imageSmoothingEnabled=!1,e={canvas:l,ctx:o,scale:t,charWidth:i,charHeight:s},this.atlases.set(t,e)}return e}renderBitmapToAtlas(t,e,i,s){let r=t.scale,a=t.ctx;a.fillStyle="#ffffff";for(let l=0;l<Math.min(e.length,this.baseCharHeight);l++){let o=e[l];for(let h=0;h<this.baseCharWidth;h++){let c=1<<7-h;o&c&&a.fillRect(i+h*r,s+l*r,r,r)}}}drawChar(t,e,i,s,r,a,l){let o=this.charMap.get(e);if(!o)return;let h=`${e}:${l}`,c=this.colorCache.get(h);if(c)c.lastUsed=performance.now();else{let x=this.createColoredGlyph(e,l,o);if(!x)return;c={canvas:x,lastUsed:performance.now()},this.colorCache.set(h,c),this.colorCache.size>this.MAX_CACHE_SIZE&&this.evictLRU()}let d=r/this.baseCellWidth,f=a/this.baseCellHeight,u=(this.baseCellWidth-this.baseCharWidth)/2*d,m=(this.baseCellHeight-this.baseCharHeight)/2*f,g=this.baseCharWidth*d,p=this.baseCharHeight*f;t.drawImage(c.canvas,i+u,s+m,g,p)}createColoredGlyph(t,e,i){let s=this.atlases.get(1);if(!s)return null;let r=s.ctx.getImageData(i.x,i.y,this.baseCharWidth,this.baseCharHeight),a=r.data,l=this.hexToRgb(e);for(let c=0;c<a.length;c+=4)a[c+3]>0&&(a[c]=l.r,a[c+1]=l.g,a[c+2]=l.b);let o=document.createElement("canvas");o.width=this.baseCharWidth,o.height=this.baseCharHeight;let h=o.getContext("2d",{alpha:!0});return h?(h.imageSmoothingEnabled=!1,h.putImageData(r,0,0),o):null}hexToRgb(t){if(t.startsWith("#")){let r=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;t=t.replace(r,(l,o,h,c)=>o+o+h+h+c+c);let a=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return a?{r:parseInt(a[1],16),g:parseInt(a[2],16),b:parseInt(a[3],16)}:{r:255,g:255,b:255}}let e=/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*[\d.]+)?\)/.exec(t);if(e)return{r:parseInt(e[1],10),g:parseInt(e[2],10),b:parseInt(e[3],10)};let s={white:[255,255,255],black:[0,0,0],red:[255,0,0],green:[0,255,0],blue:[0,0,255],yellow:[255,255,0],cyan:[0,255,255],magenta:[255,0,255]}[t.toLowerCase()];return s?{r:s[0],g:s[1],b:s[2]}:{r:255,g:255,b:255}}evictLRU(){let t=null,e=1/0;for(let[i,s]of this.colorCache)s.lastUsed<e&&(e=s.lastUsed,t=i);if(t){let i=this.colorCache.get(t);i&&(i.canvas.width=0,i.canvas.height=0),this.colorCache.delete(t)}}getAtlasCanvas(t=1){return this.atlases.get(t)?.canvas}getAllAtlases(){return this.atlases}getCharDimensions(){return{width:this.baseCharWidth,height:this.baseCharHeight}}getCharCount(){return this.charMap.size}hasChar(t){return this.charMap.has(t)}getAtlasDimensions(t=1){let e=this.atlases.get(t);if(e)return{width:e.canvas.width,height:e.canvas.height}}toDataURL(t=1,e="image/png"){return this.atlases.get(t)?.canvas.toDataURL(e)}getCacheStats(){return{size:this.colorCache.size,maxSize:this.MAX_CACHE_SIZE}}clearCache(){for(let t of this.colorCache.values())t.canvas.width=0,t.canvas.height=0;this.colorCache.clear()}destroy(){this.charMap.clear();for(let t of this.atlases.values())t.canvas.width=0,t.canvas.height=0;this.atlases.clear(),this.clearCache()}};v(O,"BitmapFontAtlas");var U=O;var k=class k{constructor(t){n(this,"atlasCanvas",null);n(this,"atlasCtx",null);n(this,"atlasImage",null);n(this,"glyphWidth");n(this,"glyphHeight");n(this,"cellWidth");n(this,"cellHeight");n(this,"atlasBlocks");n(this,"atlasColumns");n(this,"maxCharCode");n(this,"isLoaded",!1);n(this,"colorCache",new Map);n(this,"MAX_CACHE_SIZE",1024);this.glyphWidth=t.glyphWidth,this.glyphHeight=t.glyphHeight,this.cellWidth=t.cellWidth??t.glyphWidth,this.cellHeight=t.cellHeight??t.glyphHeight,this.atlasBlocks=t.atlasBlocks,this.atlasColumns=S(t.atlasBlocks),this.maxCharCode=M(t.atlasBlocks)}async loadFromPNG(t){return new Promise((e,i)=>{let s=new Uint8Array(t),r=new Blob([s],{type:"image/png"}),a=URL.createObjectURL(r),l=new Image;l.onload=()=>{URL.revokeObjectURL(a);let o=this.atlasColumns*this.glyphWidth,h=this.atlasColumns*this.glyphHeight;if((l.width!==o||l.height!==h)&&console.warn(`ImageFontAtlas: Image size ${l.width}\xD7${l.height} doesn't match expected ${o}\xD7${h} for ${this.atlasBlocks} block(s) with ${this.glyphWidth}\xD7${this.glyphHeight} glyphs`),this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=l.width,this.atlasCanvas.height=l.height,this.atlasCtx=this.atlasCanvas.getContext("2d",{alpha:!0,willReadFrequently:!0}),!this.atlasCtx){i(new Error("Failed to create 2D context for atlas"));return}this.atlasCtx.imageSmoothingEnabled=!1,this.atlasCtx.drawImage(l,0,0),this.atlasImage=l,this.isLoaded=!0,e()},l.onerror=()=>{URL.revokeObjectURL(a),i(new Error("Failed to load PNG image for atlas"))},l.src=a})}isReady(){return this.isLoaded}getGlyphPosition(t){if(t<0||t>this.maxCharCode)return null;let{col:e,row:i}=D(t,this.atlasBlocks);return{x:e*this.glyphWidth,y:i*this.glyphHeight}}getCharUV(t){if(t<0||t>this.maxCharCode)return null;let{col:e,row:i}=D(t,this.atlasBlocks),s=e/this.atlasColumns,r=i/this.atlasColumns,a=(e+1)/this.atlasColumns,l=(i+1)/this.atlasColumns;return{u1:s,v1:r,u2:a,v2:l}}drawChar(t,e,i,s,r,a,l){if(!this.isLoaded||!this.atlasCanvas)return;let o=this.getGlyphPosition(e);if(!o)return;let h=`${e}:${l}`,c=this.colorCache.get(h);if(c)c.lastUsed=performance.now();else{let f=this.createColoredGlyph(e,l,o);if(!f)return;c={canvas:f,lastUsed:performance.now()},this.colorCache.set(h,c),this.colorCache.size>this.MAX_CACHE_SIZE&&this.evictLRU()}if(t.imageSmoothingEnabled=!1,r===this.cellWidth&&a===this.cellHeight){let f=Math.floor((this.cellWidth-this.glyphWidth)/2),u=Math.floor((this.cellHeight-this.glyphHeight)/2);t.drawImage(c.canvas,Math.floor(i)+f,Math.floor(s)+u)}else{let f=r/this.cellWidth,u=a/this.cellHeight,m=Math.floor((this.cellWidth-this.glyphWidth)/2*f),g=Math.floor((this.cellHeight-this.glyphHeight)/2*u),p=Math.ceil(this.glyphWidth*f),x=Math.ceil(this.glyphHeight*u);t.drawImage(c.canvas,Math.floor(i)+m,Math.floor(s)+g,p,x)}}createColoredGlyph(t,e,i){if(!this.atlasCtx)return null;let s=this.atlasCtx.getImageData(i.x,i.y,this.glyphWidth,this.glyphHeight),r=s.data,a=this.parseColor(e);for(let h=0;h<r.length;h+=4)r[h+3]>0&&(r[h]=a.r,r[h+1]=a.g,r[h+2]=a.b);let l=document.createElement("canvas");l.width=this.glyphWidth,l.height=this.glyphHeight;let o=l.getContext("2d",{alpha:!0});return o?(o.putImageData(s,0,0),l):null}parseColor(t){if(t.startsWith("#")){let i=t.slice(1);return i.length===3&&(i=i[0]+i[0]+i[1]+i[1]+i[2]+i[2]),{r:parseInt(i.slice(0,2),16),g:parseInt(i.slice(2,4),16),b:parseInt(i.slice(4,6),16)}}let e=/rgba?\((\d+),\s*(\d+),\s*(\d+)/.exec(t);return e?{r:parseInt(e[1],10),g:parseInt(e[2],10),b:parseInt(e[3],10)}:{r:255,g:255,b:255}}evictLRU(){let t=null,e=1/0;for(let[i,s]of this.colorCache)s.lastUsed<e&&(e=s.lastUsed,t=i);if(t){let i=this.colorCache.get(t);i&&(i.canvas.width=0,i.canvas.height=0),this.colorCache.delete(t)}}getAtlasCanvas(){return this.atlasCanvas}getAtlasImage(){return this.atlasImage}getConfig(){return{glyphWidth:this.glyphWidth,glyphHeight:this.glyphHeight,cellWidth:this.cellWidth,cellHeight:this.cellHeight,atlasBlocks:this.atlasBlocks}}getGlyphDimensions(){return{width:this.glyphWidth,height:this.glyphHeight}}getCellDimensions(){return{width:this.cellWidth,height:this.cellHeight}}getAtlasDimensions(){return{width:this.atlasColumns*this.glyphWidth,height:this.atlasColumns*this.glyphHeight}}getAtlasColumns(){return this.atlasColumns}getMaxCharCode(){return this.maxCharCode}isValidCharCode(t){return t>=0&&t<=this.maxCharCode}clearCache(){for(let t of this.colorCache.values())t.canvas.width=0,t.canvas.height=0;this.colorCache.clear()}getCacheStats(){return{size:this.colorCache.size,maxSize:this.MAX_CACHE_SIZE}}destroy(){this.clearCache(),this.atlasCanvas&&(this.atlasCanvas.width=0,this.atlasCanvas.height=0,this.atlasCanvas=null),this.atlasCtx=null,this.atlasImage=null,this.isLoaded=!1}};v(k,"ImageFontAtlas");var L=k;import{ScalingMode as B}from"@utsp/types";var $=class ${constructor(t,e={}){n(this,"containerDiv");n(this,"canvas");n(this,"ctx");n(this,"parentElement");n(this,"cells");n(this,"cols",0);n(this,"rows",0);n(this,"fontSize");n(this,"fontFamily");n(this,"defaultFgColor");n(this,"defaultBgColor");n(this,"canvasBgColor");n(this,"cellWidth");n(this,"cellHeight");n(this,"offsetX",0);n(this,"offsetY",0);n(this,"fontType","web");n(this,"bitmapFont");n(this,"bitmapAtlas");n(this,"imageAtlas");n(this,"bitmapCharWidth",8);n(this,"bitmapCharHeight",8);n(this,"showDebugGrid");n(this,"debugGridColor");n(this,"gridOverlay");n(this,"fixedGridMode");n(this,"fixedCols");n(this,"fixedRows");n(this,"cellAspectRatio");n(this,"resizeObserver");n(this,"imageDataBuffer");n(this,"useImageDataRendering",!1);n(this,"paletteCache");n(this,"scalingMode",B.None);n(this,"currentScale",1);if(!t)throw new Error("Render: L'\xE9l\xE9ment parent est requis");this.parentElement=t,this.fixedGridMode=!!(e.fixedCols&&e.fixedRows),this.fixedCols=e.fixedCols,this.fixedRows=e.fixedRows,this.cellAspectRatio=e.cellAspectRatio??10/14,this.cellWidth=e.cellWidth??10,this.cellHeight=e.cellHeight??14,this.fontSize=e.fontSize??12,this.fontFamily=e.fontFamily??"monospace",this.defaultFgColor=e.defaultFgColor??"#ffffff",this.defaultBgColor=e.defaultBgColor??"#000000",this.canvasBgColor=e.canvasBgColor!==void 0?e.canvasBgColor:null,this.showDebugGrid=e.showDebugGrid??!1,this.debugGridColor=e.debugGridColor??"rgba(144, 24, 24, 1)",this.scalingMode=e.scalingMode??B.None,window.getComputedStyle(this.parentElement).position==="static"&&(this.parentElement.style.position="relative"),this.containerDiv=document.createElement("div"),this.containerDiv.className="terminal2d-container",this.containerDiv.style.cssText=`
128
128
  position: absolute !important;
129
129
  top: 0 !important;
130
130
  left: 0 !important;
@@ -138,7 +138,7 @@ var J=Object.defineProperty;var tt=(C,t,e)=>t in C?J(C,t,{enumerable:!0,configur
138
138
  justify-content: center !important;
139
139
  align-items: center !important;
140
140
  isolation: isolate !important;
141
- `,this.canvas=document.createElement("canvas"),this.canvas.className="terminal2d-canvas",e.className&&(this.canvas.className+=" "+e.className),e.style&&Object.assign(this.canvas.style,e.style),this.canvas.style.imageRendering="pixelated",this.canvas.style.imageRendering="crisp-edges",this.containerDiv.appendChild(this.canvas),this.parentElement.appendChild(this.containerDiv);let s=this.canvas.getContext("2d",{alpha:!0,desynchronized:!1});if(!s)throw new Error("UTSPRender: Impossible d'obtenir le contexte 2D du canvas");this.ctx=s,this.ctx.imageSmoothingEnabled=!1,this.calculateGridSize(),this.cells=this.createEmptyGrid(),this.showDebugGrid&&(this.gridOverlay=new T(this.parentElement,{strokeColor:this.debugGridColor,lineWidth:1,zIndex:10})),this.enableAutoResize(),this.render()}calculateGridSize(){let t=this.parentElement.clientWidth||800,e=this.parentElement.clientHeight||600,i,s;if(this.fontType==="image"&&this.imageAtlas){let d=this.imageAtlas.getCellDimensions();i=d.width,s=d.height}else this.fontType==="bitmap"?(i=this.bitmapCharWidth,s=this.bitmapCharHeight):(i=Math.round(this.cellWidth)||10,s=Math.round(this.cellHeight)||14);this.cellWidth=Math.round(i),this.cellHeight=Math.round(s),this.fixedGridMode&&this.fixedCols&&this.fixedRows?(this.cols=this.fixedCols,this.rows=this.fixedRows):(this.cols=Math.floor(t/this.cellWidth)||1,this.rows=Math.floor(e/this.cellHeight)||1);let r=this.cols*this.cellWidth,a=this.rows*this.cellHeight,l=t/r,o=e/a,h=Math.min(l,o),c;switch(this.scalingMode){case B.Integer:c=Math.max(1,Math.floor(h));break;case B.Half:c=Math.max(.5,Math.floor(h*2)/2);break;case B.Quarter:c=Math.max(.25,Math.floor(h*4)/4);break;case B.Eighth:c=Math.max(.125,Math.floor(h*8)/8);break;case B.None:default:c=Math.max(.1,h);break}this.currentScale=c,this.canvas.width=r,this.canvas.height=a,this.ctx.imageSmoothingEnabled=!1,this.canvas.style.cssText=`
141
+ `,this.canvas=document.createElement("canvas"),this.canvas.className="terminal2d-canvas",e.className&&(this.canvas.className+=" "+e.className),e.style&&Object.assign(this.canvas.style,e.style),this.canvas.style.imageRendering="pixelated",this.canvas.style.imageRendering="crisp-edges",this.containerDiv.appendChild(this.canvas),this.parentElement.appendChild(this.containerDiv);let s=this.canvas.getContext("2d",{alpha:!0,desynchronized:!1});if(!s)throw new Error("UTSPRender: Impossible d'obtenir le contexte 2D du canvas");this.ctx=s,this.ctx.imageSmoothingEnabled=!1,this.calculateGridSize(),this.cells=this.createEmptyGrid(),this.showDebugGrid&&(this.gridOverlay=new R(this.parentElement,{strokeColor:this.debugGridColor,lineWidth:1,zIndex:10})),this.enableAutoResize(),this.render()}calculateGridSize(){let t=this.parentElement.clientWidth||800,e=this.parentElement.clientHeight||600,i,s;if(this.fontType==="image"&&this.imageAtlas){let d=this.imageAtlas.getCellDimensions();i=d.width,s=d.height}else this.fontType==="bitmap"?(i=this.bitmapCharWidth,s=this.bitmapCharHeight):(i=Math.round(this.cellWidth)||10,s=Math.round(this.cellHeight)||14);this.cellWidth=Math.round(i),this.cellHeight=Math.round(s),this.fixedGridMode&&this.fixedCols&&this.fixedRows?(this.cols=this.fixedCols,this.rows=this.fixedRows):(this.cols=Math.floor(t/this.cellWidth)||1,this.rows=Math.floor(e/this.cellHeight)||1);let r=this.cols*this.cellWidth,a=this.rows*this.cellHeight,l=t/r,o=e/a,h=Math.min(l,o),c;switch(this.scalingMode){case B.Integer:c=Math.max(1,Math.floor(h));break;case B.Half:c=Math.max(.5,Math.floor(h*2)/2);break;case B.Quarter:c=Math.max(.25,Math.floor(h*4)/4);break;case B.Eighth:c=Math.max(.125,Math.floor(h*8)/8);break;case B.None:default:c=Math.max(.1,h);break}this.currentScale=c,this.canvas.width=r,this.canvas.height=a,this.ctx.imageSmoothingEnabled=!1,this.canvas.style.cssText=`
142
142
  flex-shrink: 0 !important;
143
143
  flex-grow: 0 !important;
144
144
  width: ${r}px !important;
@@ -150,7 +150,7 @@ var J=Object.defineProperty;var tt=(C,t,e)=>t in C?J(C,t,{enumerable:!0,configur
150
150
  transform: scale(${c}) !important;
151
151
  will-change: transform !important;
152
152
  backface-visibility: hidden !important;
153
- `,this.fontType==="web"&&(this.fontSize=Math.round(this.cellHeight/14*12)),this.offsetX=0,this.offsetY=0}createEmptyGrid(){let t=[];for(let e=0;e<this.rows;e++){let i=[];for(let s=0;s<this.cols;s++)i.push({char:" ",fgColor:this.defaultFgColor,bgColor:this.defaultBgColor});t.push(i)}return t}enableAutoResize(){this.resizeObserver=new ResizeObserver(()=>{let t=this.cols,e=this.rows;if(this.calculateGridSize(),this.cols!==t||this.rows!==e){let i=this.cells;this.cells=this.createEmptyGrid();let s=Math.min(t,this.cols),r=Math.min(e,this.rows);for(let a=0;a<r;a++)for(let l=0;l<s;l++)this.cells[a][l]=i[a][l]}this.render()}),this.resizeObserver.observe(this.parentElement)}setCell(t,e,i,s,r){if(e<0||e>=this.rows||t<0||t>=this.cols)return;let a=i&&typeof i=="string"?i.charAt(0):" ";this.cells[e][t]={char:a,fgColor:s??this.defaultFgColor,bgColor:r??this.defaultBgColor}}getCell(t,e){return e<0||e>=this.rows||t<0||t>=this.cols?null:this.cells[e][t]}write(t,e,i,s,r){for(let a=0;a<i.length;a++)this.setCell(t+a,e,i[a],s,r)}fillRect(t,e,i,s,r=" ",a,l){for(let o=e;o<e+s;o++)for(let h=t;h<t+i;h++)this.setCell(h,o,r,a,l)}clear(){this.cells=this.createEmptyGrid()}setFromArray(t){let e=t.width*t.height;if(t.cells.length!==e)throw new Error(`Invalid array length: expected ${e} (${t.width}\xD7${t.height}), got ${t.cells.length}`);let i=0;for(let s=0;s<t.height;s++)for(let r=0;r<t.width;r++){let a=t.cells[i];s<this.rows&&r<this.cols&&this.setCell(r,s,a.char,a.fgColor,a.bgColor),i++}}render(){if(this.fontType==="bitmap"&&this.bitmapFont&&this.useImageDataRendering){this.renderWithImageData();return}this.renderClassic()}renderWithImageData(){if(!this.bitmapFont)return;let t=this.cols*this.bitmapCharWidth,e=this.rows*this.bitmapCharHeight;(!this.imageDataBuffer||this.imageDataBuffer.width!==t||this.imageDataBuffer.height!==e)&&(this.imageDataBuffer=this.ctx.createImageData(t,e));let i=this.imageDataBuffer.data;for(let o=0;o<this.rows;o++)for(let h=0;h<this.cols;h++){let c=this.cells[o][h],d=this.parseColorToRGB(c.bgColor),f=this.parseColorToRGB(c.fgColor),u=c.char.charCodeAt(0),m=this.bitmapFont.get(u);for(let g=0;g<this.bitmapCharHeight;g++)for(let p=0;p<this.bitmapCharWidth;p++){let x=h*this.bitmapCharWidth+p,b=((o*this.bitmapCharHeight+g)*t+x)*4,E=!1;if(m&&g<m.length){let A=m[g],y=1<<7-p;E=(A&y)!==0}E?(i[b]=f.r,i[b+1]=f.g,i[b+2]=f.b,i[b+3]=f.a):(i[b]=d.r,i[b+1]=d.g,i[b+2]=d.b,i[b+3]=d.a)}}this.canvasBgColor!==null?(this.ctx.fillStyle=this.canvasBgColor,this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height)):this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.imageSmoothingEnabled=!1,this.canvas.style.imageRendering="pixelated",this.canvas.style.imageRendering="crisp-edges";let s=document.createElement("canvas");s.width=t,s.height=e,s.getContext("2d").putImageData(this.imageDataBuffer,0,0);let a=this.cols*this.cellWidth,l=this.rows*this.cellHeight;this.ctx.drawImage(s,0,0,t,e,this.offsetX,this.offsetY,a,l),this.showDebugGrid&&this.drawDebugGrid()}parseColorToRGB(t){let e=/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/.exec(t);if(e)return{r:parseInt(e[1],10),g:parseInt(e[2],10),b:parseInt(e[3],10),a:e[4]?Math.round(parseFloat(e[4])*255):255};if(t.startsWith("#")){let r=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;t=t.replace(r,(l,o,h,c)=>o+o+h+h+c+c);let a=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(a)return{r:parseInt(a[1],16),g:parseInt(a[2],16),b:parseInt(a[3],16),a:255}}let s={white:[255,255,255],black:[0,0,0],red:[255,0,0],green:[0,255,0],blue:[0,0,255],yellow:[255,255,0],cyan:[0,255,255],magenta:[255,0,255],transparent:[0,0,0]}[t.toLowerCase()];return s?{r:s[0],g:s[1],b:s[2],a:t==="transparent"?0:255}:{r:255,g:255,b:255,a:255}}renderClassic(){this.canvasBgColor!==null?(this.ctx.fillStyle=this.canvasBgColor,this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height)):this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.fontType==="bitmap"||this.fontType==="image"?(this.ctx.imageSmoothingEnabled=!1,this.canvas.style.imageRendering="pixelated",this.canvas.style.imageRendering="crisp-edges"):(this.ctx.imageSmoothingEnabled=!0,this.ctx.imageSmoothingQuality="high",this.canvas.style.imageRendering="auto",this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.ctx.textBaseline="top",this.ctx.textRendering="optimizeLegibility");for(let t=0;t<this.rows;t++)for(let e=0;e<this.cols;e++){let i=this.cells[t][e],s=Math.floor(this.offsetX+e*this.cellWidth),r=Math.floor(this.offsetY+t*this.cellHeight),a=Math.floor(this.offsetX+(e+1)*this.cellWidth),l=Math.floor(this.offsetY+(t+1)*this.cellHeight),o=a-s,h=l-r;if((this.canvasBgColor!==null||i.bgColor!==this.defaultBgColor)&&(this.ctx.fillStyle=i.bgColor,this.ctx.fillRect(s,r,o,h)),i.char!==" ")if(this.fontType==="image"&&this.imageAtlas){let d=i.char.charCodeAt(0);this.imageAtlas.drawChar(this.ctx,d,s,r,o,h,i.fgColor)}else if(this.fontType==="bitmap"&&this.bitmapFont)this.drawBitmapChar(i.char,s,r,o,h,i.fgColor);else{this.ctx.fillStyle=i.fgColor;let d=s+(o-this.ctx.measureText(i.char).width)/2,f=r+(h-this.fontSize)/2;this.ctx.fillText(i.char,d,f)}}this.showDebugGrid&&this.drawDebugGrid()}drawBitmapChar(t,e,i,s,r,a){let l=t.charCodeAt(0);if(this.bitmapAtlas){this.bitmapAtlas.drawChar(this.ctx,l,e,i,s,r,a);return}if(!this.bitmapFont)return;let o=this.bitmapFont.get(l);if(!o)return;let h=s/this.bitmapCharWidth,c=r/this.bitmapCharHeight;this.ctx.fillStyle=a;for(let d=0;d<Math.min(o.length,this.bitmapCharHeight);d++){let f=o[d],u=i+d*c,m=i+(d+1)*c;for(let g=0;g<this.bitmapCharWidth;g++){let p=1<<7-g;if(f&p){let x=e+g*h,w=e+(g+1)*h;this.ctx.fillRect(x,u,w-x,m-u)}}}}drawDebugGrid(){if(!this.gridOverlay)return;let t=this.parentElement.clientWidth||800,e=this.parentElement.clientHeight||600;this.gridOverlay.update(this.cols,this.rows,this.cellWidth,this.cellHeight,t,e,this.offsetX,this.offsetY)}getCanvas(){return this.canvas}getContext(){return this.ctx}getDimensions(){return{cols:this.cols,rows:this.rows}}getCellDimensions(){return{cellWidth:this.cellWidth,cellHeight:this.cellHeight}}getCellWidth(){return this.cellWidth}getCellHeight(){return this.cellHeight}getCurrentScale(){return this.currentScale}getScalingMode(){return this.scalingMode}getOffsets(){return{offsetX:this.offsetX,offsetY:this.offsetY}}setDebugGrid(t){this.showDebugGrid=t,t&&!this.gridOverlay?(this.gridOverlay=new T(this.parentElement,{strokeColor:this.debugGridColor,lineWidth:1,zIndex:10}),this.drawDebugGrid()):!t&&this.gridOverlay?(this.gridOverlay.destroy(),this.gridOverlay=void 0):t&&this.gridOverlay&&this.gridOverlay.setVisible(!0)}setCanvasBackgroundColor(t){this.canvasBgColor=t}getCanvasBackgroundColor(){return this.canvasBgColor}setFixedGrid(t,e,i){this.fixedGridMode=!0,this.fixedCols=t,this.fixedRows=e,i!==void 0&&(this.cellAspectRatio=i);let s=this.cols,r=this.rows,a=this.cells;if(this.calculateGridSize(),this.cols!==s||this.rows!==r){this.cells=this.createEmptyGrid();let l=Math.min(s,this.cols),o=Math.min(r,this.rows);for(let h=0;h<o;h++)for(let c=0;c<l;c++)this.cells[h][c]=a[h][c]}this.render()}setAdaptiveGrid(t,e){this.fixedGridMode=!1,this.fixedCols=void 0,this.fixedRows=void 0,t!==void 0&&(this.cellWidth=t),e!==void 0&&(this.cellHeight=e);let i=this.cols,s=this.rows,r=this.cells;if(this.calculateGridSize(),this.cols!==i||this.rows!==s){this.cells=this.createEmptyGrid();let a=Math.min(i,this.cols),l=Math.min(s,this.rows);for(let o=0;o<l;o++)for(let h=0;h<a;h++)this.cells[o][h]=r[o][h]}this.render()}isFixedGridMode(){return this.fixedGridMode}setDebugGridColor(t){this.debugGridColor=t}isDebugGridEnabled(){return this.showDebugGrid}setImageDataRendering(t){this.useImageDataRendering=t,t&&this.fontType==="bitmap"?console.warn("[Render] ImageData rendering enabled (optimized for benchmarks)"):t&&(console.warn("[Render] ImageData rendering requires bitmap font, keeping classic mode"),this.useImageDataRendering=!1)}isImageDataRenderingEnabled(){return this.useImageDataRendering}setWebFont(t,e){this.fontType="web",this.fontFamily=t,e!==void 0&&(this.fontSize=e),this.bitmapFont=void 0,this.bitmapAtlas=void 0,this.useImageDataRendering=!1,this.calculateGridSize(),this.cells=this.createEmptyGrid()}setBitmapFont(t,e,i,s,r){this.fontType="bitmap",this.bitmapFont=t,this.bitmapCharWidth=e,this.bitmapCharHeight=i,this.bitmapAtlas=new S(t,e,i,s,r),this.cellWidth=s,this.cellHeight=r,this.calculateGridSize(),this.cells=this.createEmptyGrid()}async setImageFont(t,e,i,s,r,a){this.fontType="image",this.imageAtlas=new L({glyphWidth:e,glyphHeight:i,cellWidth:s,cellHeight:r,atlasBlocks:a}),await this.imageAtlas.loadFromPNG(t),this.cellWidth=s,this.cellHeight=r,this.bitmapCharWidth=e,this.bitmapCharHeight=i,this.calculateGridSize(),this.cells=this.createEmptyGrid()}getFontType(){return this.fontType}getBitmapFont(){return this.bitmapFont}getBitmapCharDimensions(){return this.fontType!=="bitmap"?null:{width:this.bitmapCharWidth,height:this.bitmapCharHeight}}setPalette(t){this.paletteCache=t}renderDisplayData(t){if(!t||!t.cells||t.cells.length===0){console.warn("[Terminal2D] Empty display data");return}if(t.width===0||t.height===0){console.warn("[Terminal2D] Invalid display dimensions:",t.width,t.height);return}(t.width!==this.cols||t.height!==this.rows)&&this.setFixedGrid(t.width,t.height,this.cellAspectRatio);let e=this.paletteCache??t.palette;if(!e||e.length===0){console.error("[Terminal2D] No palette available (neither cached nor in display)");return}let i=v(s=>{if(s==null||isNaN(s))return console.warn("[Terminal2D] Invalid palette index (undefined/null/NaN):",s),this.defaultFgColor;if(s===255)return"rgba(0, 0, 0, 0)";if(s<0||s>=e.length)return console.warn(`[Terminal2D] Invalid palette index: ${s}`),this.defaultFgColor;let r=e[s];return!r||typeof r.r!="number"?(console.warn(`[Terminal2D] Corrupted palette entry at index ${s}:`,r),this.defaultFgColor):`rgba(${r.r}, ${r.g}, ${r.b}, ${r.a/255})`},"convertColor");for(let s=0;s<t.height&&s<this.rows;s++)for(let r=0;r<t.width&&r<this.cols;r++){let a=s*t.width+r;if(a>=t.cells.length)break;let l=t.cells[a];if(!l)continue;let o=i(l.fgColorIndex),h=i(l.bgColorIndex);this.setCell(r,s,l.char??" ",o,h)}this.render()}isReady(){return!0}getCols(){return this.cols}getRows(){return this.rows}resize(t,e){this.setFixedGrid(t,e)}destroy(){this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=void 0),this.gridOverlay&&(this.gridOverlay.destroy(),this.gridOverlay=void 0),this.containerDiv.parentElement&&this.containerDiv.parentElement.removeChild(this.containerDiv)}};v($,"Terminal2D");var z=$;var Y=class Y{constructor(t,e={}){n(this,"container");n(this,"overlayDiv",null);n(this,"button",null);n(this,"options");n(this,"started",!1);n(this,"onStartCallback");this.container=t,this.options={buttonText:e.buttonText??"Click to Start",onStart:e.onStart??(()=>{}),backgroundColor:e.backgroundColor??"rgba(0, 0, 0, 0.8)",buttonColor:e.buttonColor??"#4a90d9",buttonHoverColor:e.buttonHoverColor??"#357abd",buttonTextColor:e.buttonTextColor??"#ffffff",zIndex:e.zIndex??1e3},this.onStartCallback=e.onStart,this.createOverlay()}createOverlay(){let t=window.getComputedStyle(this.container).position;t!=="relative"&&t!=="absolute"&&t!=="fixed"&&(this.container.style.position="relative"),this.overlayDiv=document.createElement("div"),this.overlayDiv.className="utsp-autoplay-overlay",this.overlayDiv.style.cssText=`
153
+ `,this.fontType==="web"&&(this.fontSize=Math.round(this.cellHeight/14*12)),this.offsetX=0,this.offsetY=0}createEmptyGrid(){let t=[];for(let e=0;e<this.rows;e++){let i=[];for(let s=0;s<this.cols;s++)i.push({char:" ",fgColor:this.defaultFgColor,bgColor:this.defaultBgColor});t.push(i)}return t}enableAutoResize(){this.resizeObserver=new ResizeObserver(()=>{let t=this.cols,e=this.rows;if(this.calculateGridSize(),this.cols!==t||this.rows!==e){let i=this.cells;this.cells=this.createEmptyGrid();let s=Math.min(t,this.cols),r=Math.min(e,this.rows);for(let a=0;a<r;a++)for(let l=0;l<s;l++)this.cells[a][l]=i[a][l]}this.render()}),this.resizeObserver.observe(this.parentElement)}setCell(t,e,i,s,r){if(e<0||e>=this.rows||t<0||t>=this.cols)return;let a=i&&typeof i=="string"?i.charAt(0):" ";this.cells[e][t]={char:a,fgColor:s??this.defaultFgColor,bgColor:r??this.defaultBgColor}}getCell(t,e){return e<0||e>=this.rows||t<0||t>=this.cols?null:this.cells[e][t]}write(t,e,i,s,r){for(let a=0;a<i.length;a++)this.setCell(t+a,e,i[a],s,r)}fillRect(t,e,i,s,r=" ",a,l){for(let o=e;o<e+s;o++)for(let h=t;h<t+i;h++)this.setCell(h,o,r,a,l)}clear(){this.cells=this.createEmptyGrid()}setFromArray(t){let e=t.width*t.height;if(t.cells.length!==e)throw new Error(`Invalid array length: expected ${e} (${t.width}\xD7${t.height}), got ${t.cells.length}`);let i=0;for(let s=0;s<t.height;s++)for(let r=0;r<t.width;r++){let a=t.cells[i];s<this.rows&&r<this.cols&&this.setCell(r,s,a.char,a.fgColor,a.bgColor),i++}}render(){if(this.fontType==="bitmap"&&this.bitmapFont&&this.useImageDataRendering){this.renderWithImageData();return}this.renderClassic()}renderWithImageData(){if(!this.bitmapFont)return;let t=this.cols*this.bitmapCharWidth,e=this.rows*this.bitmapCharHeight;(!this.imageDataBuffer||this.imageDataBuffer.width!==t||this.imageDataBuffer.height!==e)&&(this.imageDataBuffer=this.ctx.createImageData(t,e));let i=this.imageDataBuffer.data;for(let o=0;o<this.rows;o++)for(let h=0;h<this.cols;h++){let c=this.cells[o][h],d=this.parseColorToRGB(c.bgColor),f=this.parseColorToRGB(c.fgColor),u=c.char.charCodeAt(0),m=this.bitmapFont.get(u);for(let g=0;g<this.bitmapCharHeight;g++)for(let p=0;p<this.bitmapCharWidth;p++){let x=h*this.bitmapCharWidth+p,C=((o*this.bitmapCharHeight+g)*t+x)*4,E=!1;if(m&&g<m.length){let A=m[g],y=1<<7-p;E=(A&y)!==0}E?(i[C]=f.r,i[C+1]=f.g,i[C+2]=f.b,i[C+3]=f.a):(i[C]=d.r,i[C+1]=d.g,i[C+2]=d.b,i[C+3]=d.a)}}this.canvasBgColor!==null?(this.ctx.fillStyle=this.canvasBgColor,this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height)):this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.imageSmoothingEnabled=!1,this.canvas.style.imageRendering="pixelated",this.canvas.style.imageRendering="crisp-edges";let s=document.createElement("canvas");s.width=t,s.height=e,s.getContext("2d").putImageData(this.imageDataBuffer,0,0);let a=this.cols*this.cellWidth,l=this.rows*this.cellHeight;this.ctx.drawImage(s,0,0,t,e,this.offsetX,this.offsetY,a,l),this.showDebugGrid&&this.drawDebugGrid()}parseColorToRGB(t){let e=/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/.exec(t);if(e)return{r:parseInt(e[1],10),g:parseInt(e[2],10),b:parseInt(e[3],10),a:e[4]?Math.round(parseFloat(e[4])*255):255};if(t.startsWith("#")){let r=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;t=t.replace(r,(l,o,h,c)=>o+o+h+h+c+c);let a=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(a)return{r:parseInt(a[1],16),g:parseInt(a[2],16),b:parseInt(a[3],16),a:255}}let s={white:[255,255,255],black:[0,0,0],red:[255,0,0],green:[0,255,0],blue:[0,0,255],yellow:[255,255,0],cyan:[0,255,255],magenta:[255,0,255],transparent:[0,0,0]}[t.toLowerCase()];return s?{r:s[0],g:s[1],b:s[2],a:t==="transparent"?0:255}:{r:255,g:255,b:255,a:255}}renderClassic(){this.canvasBgColor!==null?(this.ctx.fillStyle=this.canvasBgColor,this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height)):this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.fontType==="bitmap"||this.fontType==="image"?(this.ctx.imageSmoothingEnabled=!1,this.canvas.style.imageRendering="pixelated",this.canvas.style.imageRendering="crisp-edges"):(this.ctx.imageSmoothingEnabled=!0,this.ctx.imageSmoothingQuality="high",this.canvas.style.imageRendering="auto",this.ctx.font=`${this.fontSize}px ${this.fontFamily}`,this.ctx.textBaseline="top",this.ctx.textRendering="optimizeLegibility");for(let t=0;t<this.rows;t++)for(let e=0;e<this.cols;e++){let i=this.cells[t][e],s=Math.floor(this.offsetX+e*this.cellWidth),r=Math.floor(this.offsetY+t*this.cellHeight),a=Math.floor(this.offsetX+(e+1)*this.cellWidth),l=Math.floor(this.offsetY+(t+1)*this.cellHeight),o=a-s,h=l-r;if((this.canvasBgColor!==null||i.bgColor!==this.defaultBgColor)&&(this.ctx.fillStyle=i.bgColor,this.ctx.fillRect(s,r,o,h)),i.char!==" ")if(this.fontType==="image"&&this.imageAtlas){let d=i.char.charCodeAt(0);this.imageAtlas.drawChar(this.ctx,d,s,r,o,h,i.fgColor)}else if(this.fontType==="bitmap"&&this.bitmapFont)this.drawBitmapChar(i.char,s,r,o,h,i.fgColor);else{this.ctx.fillStyle=i.fgColor;let d=s+(o-this.ctx.measureText(i.char).width)/2,f=r+(h-this.fontSize)/2;this.ctx.fillText(i.char,d,f)}}this.showDebugGrid&&this.drawDebugGrid()}drawBitmapChar(t,e,i,s,r,a){let l=t.charCodeAt(0);if(this.bitmapAtlas){this.bitmapAtlas.drawChar(this.ctx,l,e,i,s,r,a);return}if(!this.bitmapFont)return;let o=this.bitmapFont.get(l);if(!o)return;let h=s/this.bitmapCharWidth,c=r/this.bitmapCharHeight;this.ctx.fillStyle=a;for(let d=0;d<Math.min(o.length,this.bitmapCharHeight);d++){let f=o[d],u=i+d*c,m=i+(d+1)*c;for(let g=0;g<this.bitmapCharWidth;g++){let p=1<<7-g;if(f&p){let x=e+g*h,w=e+(g+1)*h;this.ctx.fillRect(x,u,w-x,m-u)}}}}drawDebugGrid(){if(!this.gridOverlay)return;let t=this.parentElement.clientWidth||800,e=this.parentElement.clientHeight||600;this.gridOverlay.update(this.cols,this.rows,this.cellWidth,this.cellHeight,t,e,this.offsetX,this.offsetY)}getCanvas(){return this.canvas}getContext(){return this.ctx}getDimensions(){return{cols:this.cols,rows:this.rows}}getCellDimensions(){return{cellWidth:this.cellWidth,cellHeight:this.cellHeight}}getCellWidth(){return this.cellWidth}getCellHeight(){return this.cellHeight}getCurrentScale(){return this.currentScale}getScalingMode(){return this.scalingMode}getOffsets(){return{offsetX:this.offsetX,offsetY:this.offsetY}}setDebugGrid(t){this.showDebugGrid=t,t&&!this.gridOverlay?(this.gridOverlay=new R(this.parentElement,{strokeColor:this.debugGridColor,lineWidth:1,zIndex:10}),this.drawDebugGrid()):!t&&this.gridOverlay?(this.gridOverlay.destroy(),this.gridOverlay=void 0):t&&this.gridOverlay&&this.gridOverlay.setVisible(!0)}setCanvasBackgroundColor(t){this.canvasBgColor=t}getCanvasBackgroundColor(){return this.canvasBgColor}setFixedGrid(t,e,i){this.fixedGridMode=!0,this.fixedCols=t,this.fixedRows=e,i!==void 0&&(this.cellAspectRatio=i);let s=this.cols,r=this.rows,a=this.cells;if(this.calculateGridSize(),this.cols!==s||this.rows!==r){this.cells=this.createEmptyGrid();let l=Math.min(s,this.cols),o=Math.min(r,this.rows);for(let h=0;h<o;h++)for(let c=0;c<l;c++)this.cells[h][c]=a[h][c]}this.render()}setAdaptiveGrid(t,e){this.fixedGridMode=!1,this.fixedCols=void 0,this.fixedRows=void 0,t!==void 0&&(this.cellWidth=t),e!==void 0&&(this.cellHeight=e);let i=this.cols,s=this.rows,r=this.cells;if(this.calculateGridSize(),this.cols!==i||this.rows!==s){this.cells=this.createEmptyGrid();let a=Math.min(i,this.cols),l=Math.min(s,this.rows);for(let o=0;o<l;o++)for(let h=0;h<a;h++)this.cells[o][h]=r[o][h]}this.render()}isFixedGridMode(){return this.fixedGridMode}setDebugGridColor(t){this.debugGridColor=t}isDebugGridEnabled(){return this.showDebugGrid}setImageDataRendering(t){this.useImageDataRendering=t,t&&this.fontType==="bitmap"?console.warn("[Render] ImageData rendering enabled (optimized for benchmarks)"):t&&(console.warn("[Render] ImageData rendering requires bitmap font, keeping classic mode"),this.useImageDataRendering=!1)}isImageDataRenderingEnabled(){return this.useImageDataRendering}setWebFont(t,e){this.fontType="web",this.fontFamily=t,e!==void 0&&(this.fontSize=e),this.bitmapFont=void 0,this.bitmapAtlas=void 0,this.useImageDataRendering=!1,this.calculateGridSize(),this.cells=this.createEmptyGrid()}setBitmapFont(t,e,i,s,r){this.fontType="bitmap",this.bitmapFont=t,this.bitmapCharWidth=e,this.bitmapCharHeight=i,this.bitmapAtlas=new U(t,e,i,s,r),this.cellWidth=s,this.cellHeight=r,this.calculateGridSize(),this.cells=this.createEmptyGrid()}async setImageFont(t,e,i,s,r,a){this.fontType="image",this.imageAtlas=new L({glyphWidth:e,glyphHeight:i,cellWidth:s,cellHeight:r,atlasBlocks:a}),await this.imageAtlas.loadFromPNG(t),this.cellWidth=s,this.cellHeight=r,this.bitmapCharWidth=e,this.bitmapCharHeight=i,this.calculateGridSize(),this.cells=this.createEmptyGrid()}getFontType(){return this.fontType}getBitmapFont(){return this.bitmapFont}getBitmapCharDimensions(){return this.fontType!=="bitmap"?null:{width:this.bitmapCharWidth,height:this.bitmapCharHeight}}setPalette(t){this.paletteCache=t}renderDisplayData(t){if(!t||!t.cells||t.cells.length===0){console.warn("[Terminal2D] Empty display data");return}if(t.width===0||t.height===0){console.warn("[Terminal2D] Invalid display dimensions:",t.width,t.height);return}(t.width!==this.cols||t.height!==this.rows)&&this.setFixedGrid(t.width,t.height,this.cellAspectRatio);let e=this.paletteCache??t.palette;if(!e||e.length===0){console.error("[Terminal2D] No palette available (neither cached nor in display)");return}let i=v(s=>{if(s==null||isNaN(s))return console.warn("[Terminal2D] Invalid palette index (undefined/null/NaN):",s),this.defaultFgColor;if(s===255)return"rgba(0, 0, 0, 0)";if(s<0||s>=e.length)return console.warn(`[Terminal2D] Invalid palette index: ${s}`),this.defaultFgColor;let r=e[s];return!r||typeof r.r!="number"?(console.warn(`[Terminal2D] Corrupted palette entry at index ${s}:`,r),this.defaultFgColor):`rgba(${r.r}, ${r.g}, ${r.b}, ${r.a/255})`},"convertColor");for(let s=0;s<t.height&&s<this.rows;s++)for(let r=0;r<t.width&&r<this.cols;r++){let a=s*t.width+r;if(a>=t.cells.length)break;let l=t.cells[a];if(!l)continue;let o=i(l.fgColorIndex),h=i(l.bgColorIndex);this.setCell(r,s,l.char??" ",o,h)}this.render()}isReady(){return!0}getCols(){return this.cols}getRows(){return this.rows}resize(t,e){this.setFixedGrid(t,e)}destroy(){this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=void 0),this.gridOverlay&&(this.gridOverlay.destroy(),this.gridOverlay=void 0),this.containerDiv.parentElement&&this.containerDiv.parentElement.removeChild(this.containerDiv)}};v($,"Terminal2D");var z=$;var Y=class Y{constructor(t,e={}){n(this,"container");n(this,"overlayDiv",null);n(this,"button",null);n(this,"options");n(this,"started",!1);n(this,"onStartCallback");this.container=t,this.options={buttonText:e.buttonText??"Click to Start",onStart:e.onStart??(()=>{}),backgroundColor:e.backgroundColor??"rgba(0, 0, 0, 0.8)",buttonColor:e.buttonColor??"#4a90d9",buttonHoverColor:e.buttonHoverColor??"#357abd",buttonTextColor:e.buttonTextColor??"#ffffff",zIndex:e.zIndex??1e3},this.onStartCallback=e.onStart,this.createOverlay()}createOverlay(){let t=window.getComputedStyle(this.container).position;t!=="relative"&&t!=="absolute"&&t!=="fixed"&&(this.container.style.position="relative"),this.overlayDiv=document.createElement("div"),this.overlayDiv.className="utsp-autoplay-overlay",this.overlayDiv.style.cssText=`
154
154
  position: absolute !important;
155
155
  top: 0 !important;
156
156
  left: 0 !important;
@@ -174,7 +174,7 @@ var J=Object.defineProperty;var tt=(C,t,e)=>t in C?J(C,t,{enumerable:!0,configur
174
174
  cursor: pointer !important;
175
175
  transition: background-color 0.2s ease, transform 0.1s ease !important;
176
176
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3) !important;
177
- `,this.button.addEventListener("mouseenter",()=>{this.button&&(this.button.style.backgroundColor=`${this.options.buttonHoverColor} !important`,this.button.style.transform="scale(1.05)")}),this.button.addEventListener("mouseleave",()=>{this.button&&(this.button.style.backgroundColor=`${this.options.buttonColor} !important`,this.button.style.transform="scale(1)")}),this.button.addEventListener("click",e=>{e.stopPropagation(),this.start()}),this.overlayDiv.addEventListener("click",()=>{this.start()}),this.overlayDiv.appendChild(this.button),this.container.appendChild(this.overlayDiv)}start(){this.started||(this.started=!0,this.overlayDiv&&(this.overlayDiv.style.transition="opacity 0.3s ease",this.overlayDiv.style.opacity="0",setTimeout(()=>{this.removeOverlay()},300)),this.onStartCallback&&this.onStartCallback())}isStarted(){return this.started}isVisible(){return this.overlayDiv!==null&&!this.started}removeOverlay(){this.overlayDiv&&this.overlayDiv.parentElement&&this.overlayDiv.parentElement.removeChild(this.overlayDiv),this.overlayDiv=null,this.button=null}setButtonText(t){this.options.buttonText=t,this.button&&(this.button.textContent=t)}setOnStart(t){this.onStartCallback=t}destroy(){this.removeOverlay(),this.started=!1}};v(Y,"AutoplayOverlay");var N=Y;import{POST_PROCESS_DEFAULTS as G}from"@utsp/types";var X=class X{constructor(t,e){n(this,"canvas");n(this,"ctx");n(this,"containerDiv");n(this,"parentElement");n(this,"resizeObserver");n(this,"width",0);n(this,"height",0);n(this,"currentConfig",null);n(this,"configHash","");this.parentElement=t,this.containerDiv=document.createElement("div"),this.containerDiv.className="postprocess-container",this.containerDiv.style.cssText=`
177
+ `,this.button.addEventListener("mouseenter",()=>{this.button&&(this.button.style.backgroundColor=`${this.options.buttonHoverColor} !important`,this.button.style.transform="scale(1.05)")}),this.button.addEventListener("mouseleave",()=>{this.button&&(this.button.style.backgroundColor=`${this.options.buttonColor} !important`,this.button.style.transform="scale(1)")}),this.button.addEventListener("click",e=>{e.stopPropagation(),this.start()}),this.overlayDiv.addEventListener("click",()=>{this.start()}),this.overlayDiv.appendChild(this.button),this.container.appendChild(this.overlayDiv)}start(){this.started||(this.started=!0,this.overlayDiv&&(this.overlayDiv.style.transition="opacity 0.3s ease",this.overlayDiv.style.opacity="0",setTimeout(()=>{this.removeOverlay()},300)),this.onStartCallback&&this.onStartCallback())}isStarted(){return this.started}isVisible(){return this.overlayDiv!==null&&!this.started}removeOverlay(){this.overlayDiv&&this.overlayDiv.parentElement&&this.overlayDiv.parentElement.removeChild(this.overlayDiv),this.overlayDiv=null,this.button=null}setButtonText(t){this.options.buttonText=t,this.button&&(this.button.textContent=t)}setOnStart(t){this.onStartCallback=t}destroy(){this.removeOverlay(),this.started=!1}};v(Y,"AutoplayOverlay");var N=Y;import{POST_PROCESS_DEFAULTS as H}from"@utsp/types";var X=class X{constructor(t,e){n(this,"canvas");n(this,"ctx");n(this,"containerDiv");n(this,"parentElement");n(this,"resizeObserver");n(this,"width",0);n(this,"height",0);n(this,"currentConfig",null);n(this,"configHash","");this.parentElement=t,this.containerDiv=document.createElement("div"),this.containerDiv.className="postprocess-container",this.containerDiv.style.cssText=`
178
178
  position: absolute !important;
179
179
  top: 0 !important;
180
180
  left: 0 !important;
@@ -192,4 +192,5 @@ var J=Object.defineProperty;var tt=(C,t,e)=>t in C?J(C,t,{enumerable:!0,configur
192
192
  width: 100% !important;
193
193
  height: 100% !important;
194
194
  pointer-events: none !important;
195
- `;let i=this.canvas.getContext("2d",{alpha:!0});if(!i)throw new Error("PostProcessOverlay: Failed to get 2D context");this.ctx=i,this.containerDiv.appendChild(this.canvas),this.parentElement.appendChild(this.containerDiv),this.resizeObserver=new ResizeObserver(r=>{for(let a of r){let{width:l,height:o}=a.contentRect;l>0&&o>0&&this.handleResize(Math.floor(l),Math.floor(o))}}),this.resizeObserver.observe(this.parentElement);let s=this.parentElement.getBoundingClientRect();s.width>0&&s.height>0&&this.handleResize(Math.floor(s.width),Math.floor(s.height)),this.hide()}handleResize(t,e){this.width===t&&this.height===e||(this.width=t,this.height=e,this.canvas.width=t,this.canvas.height=e,this.currentConfig&&this.isActive()&&this.render())}setConfig(t){let e=this.hashConfig(t);if(e!==this.configHash){if(this.currentConfig=t,this.configHash=e,!t||!this.isActiveConfig(t)){this.clear(),this.hide();return}this.show(),this.render()}}setScanlines(t){t===null?this.setConfig({scanlines:{enabled:!1}}):this.setConfig({scanlines:t})}setScanlinesEnabled(t){if(t){let e=this.currentConfig?.scanlines;this.setScanlines({enabled:!0,opacity:e?.opacity??G.scanlines.opacity,pattern:e?.pattern??"horizontal",spacing:e?.spacing??2,thickness:e?.thickness??1,color:e?.color??{r:0,g:0,b:0}})}else this.setScanlines({enabled:!1})}setScanlinesOpacity(t){let e=Math.max(0,Math.min(1,t)),i=this.currentConfig?.scanlines;this.setScanlines({enabled:i?.enabled??!0,opacity:e,pattern:i?.pattern??"horizontal",spacing:i?.spacing??2,thickness:i?.thickness??1,color:i?.color??{r:0,g:0,b:0}})}setScanlinesPattern(t){let e=this.currentConfig?.scanlines;this.setScanlines({enabled:e?.enabled??!0,opacity:e?.opacity??G.scanlines.opacity,pattern:t,spacing:e?.spacing??2,thickness:e?.thickness??1,color:e?.color??{r:0,g:0,b:0}})}setScanlinesSpacing(t){let e=Math.max(2,Math.round(t)),i=this.currentConfig?.scanlines;this.setScanlines({enabled:i?.enabled??!0,opacity:i?.opacity??G.scanlines.opacity,pattern:i?.pattern??"horizontal",spacing:e,thickness:i?.thickness??1,color:i?.color??{r:0,g:0,b:0}})}getConfig(){return this.currentConfig}isActive(){return this.isActiveConfig(this.currentConfig)}destroy(){this.resizeObserver.disconnect(),this.containerDiv.parentElement&&this.containerDiv.parentElement.removeChild(this.containerDiv)}syncWithRenderer(t){}resize(t,e){}setCellDimensions(t,e){}show(){this.containerDiv.style.display="block"}hide(){this.containerDiv.style.display="none"}clear(){this.ctx.clearRect(0,0,this.width,this.height)}isActiveConfig(t){return t?.scanlines?.enabled??!1}render(){this.clear(),this.currentConfig?.scanlines?.enabled&&this.renderScanlines(this.currentConfig.scanlines)}renderScanlines(t){let e=t.opacity??G.scanlines.opacity,i=t.pattern??"horizontal",s=t.spacing??2,r=t.thickness??1,a=t.color??{r:0,g:0,b:0},l=this.ctx;switch(l.fillStyle=`rgba(${a.r}, ${a.g}, ${a.b}, ${e})`,i){case"horizontal":for(let o=s-1;o<this.height;o+=s)l.fillRect(0,o,this.width,r);break;case"vertical":for(let o=s-1;o<this.width;o+=s)l.fillRect(o,0,r,this.height);break;case"grid":for(let o=s-1;o<this.height;o+=s)l.fillRect(0,o,this.width,r);for(let o=s-1;o<this.width;o+=s)l.fillRect(o,0,r,this.height);break}}hashConfig(t){return t?JSON.stringify(t):"null"}};v(X,"PostProcessOverlay");var V=X;var Ut="0.1.0";export{N as AutoplayOverlay,S as BitmapFontAtlas,H as DEFAULT_PALETTE,T as GridOverlay,L as ImageFontAtlas,V as PostProcessOverlay,R as ScalingMode,z as Terminal2D,P as TerminalGL,it as colorToPaletteIndex,M as getAtlasColumns,D as getCharGridPosition,F as getMaxCharCode,et as paletteIndexToColor,Ut as version};
195
+ `;let i=this.canvas.getContext("2d",{alpha:!0});if(!i)throw new Error("PostProcessOverlay: Failed to get 2D context");this.ctx=i,this.containerDiv.appendChild(this.canvas),this.parentElement.appendChild(this.containerDiv),this.resizeObserver=new ResizeObserver(r=>{for(let a of r){let{width:l,height:o}=a.contentRect;l>0&&o>0&&this.handleResize(Math.floor(l),Math.floor(o))}}),this.resizeObserver.observe(this.parentElement);let s=this.parentElement.getBoundingClientRect();s.width>0&&s.height>0&&this.handleResize(Math.floor(s.width),Math.floor(s.height)),this.hide()}handleResize(t,e){this.width===t&&this.height===e||(this.width=t,this.height=e,this.canvas.width=t,this.canvas.height=e,this.currentConfig&&this.isActive()&&this.render())}setConfig(t){let e=this.hashConfig(t);if(e!==this.configHash){if(this.currentConfig=t,this.configHash=e,!t||!this.isActiveConfig(t)){this.clear(),this.hide();return}this.show(),this.render()}}setScanlines(t){t===null?this.setConfig({scanlines:{enabled:!1}}):this.setConfig({scanlines:t})}setScanlinesEnabled(t){if(t){let e=this.currentConfig?.scanlines;this.setScanlines({enabled:!0,opacity:e?.opacity??H.scanlines.opacity,pattern:e?.pattern??"horizontal",spacing:e?.spacing??2,thickness:e?.thickness??1,color:e?.color??{r:0,g:0,b:0}})}else this.setScanlines({enabled:!1})}setScanlinesOpacity(t){let e=Math.max(0,Math.min(1,t)),i=this.currentConfig?.scanlines;this.setScanlines({enabled:i?.enabled??!0,opacity:e,pattern:i?.pattern??"horizontal",spacing:i?.spacing??2,thickness:i?.thickness??1,color:i?.color??{r:0,g:0,b:0}})}setScanlinesPattern(t){let e=this.currentConfig?.scanlines;this.setScanlines({enabled:e?.enabled??!0,opacity:e?.opacity??H.scanlines.opacity,pattern:t,spacing:e?.spacing??2,thickness:e?.thickness??1,color:e?.color??{r:0,g:0,b:0}})}setScanlinesSpacing(t){let e=Math.max(2,Math.round(t)),i=this.currentConfig?.scanlines;this.setScanlines({enabled:i?.enabled??!0,opacity:i?.opacity??H.scanlines.opacity,pattern:i?.pattern??"horizontal",spacing:e,thickness:i?.thickness??1,color:i?.color??{r:0,g:0,b:0}})}getConfig(){return this.currentConfig}isActive(){return this.isActiveConfig(this.currentConfig)}destroy(){this.resizeObserver.disconnect(),this.containerDiv.parentElement&&this.containerDiv.parentElement.removeChild(this.containerDiv)}syncWithRenderer(t){}resize(t,e){}setCellDimensions(t,e){}show(){this.containerDiv.style.display="block"}hide(){this.containerDiv.style.display="none"}clear(){this.ctx.clearRect(0,0,this.width,this.height)}isActiveConfig(t){return t?.scanlines?.enabled??!1}render(){this.clear(),this.currentConfig?.scanlines?.enabled&&this.renderScanlines(this.currentConfig.scanlines)}renderScanlines(t){let e=t.opacity??H.scanlines.opacity,i=t.pattern??"horizontal",s=t.spacing??2,r=t.thickness??1,a=t.color??{r:0,g:0,b:0},l=this.ctx;switch(l.fillStyle=`rgba(${a.r}, ${a.g}, ${a.b}, ${e})`,i){case"horizontal":for(let o=s-1;o<this.height;o+=s)l.fillRect(0,o,this.width,r);break;case"vertical":for(let o=s-1;o<this.width;o+=s)l.fillRect(o,0,r,this.height);break;case"grid":for(let o=s-1;o<this.height;o+=s)l.fillRect(0,o,this.width,r);for(let o=s-1;o<this.width;o+=s)l.fillRect(o,0,r,this.height);break}}hashConfig(t){return t?JSON.stringify(t):"null"}};v(X,"PostProcessOverlay");var V=X;var q="\x1B[0m",st="\x1B[H",lt="\x1B[2J",rt="\x1B[?25l",ht="\x1B[?25h",ct=`
196
+ `,Q=class Q{constructor(t={}){n(this,"options");n(this,"fgCache",[]);n(this,"bgCache",[]);n(this,"lastPalette",null);this.options={optimizeColors:t.optimizeColors??!0,includeHome:t.includeHome??!0,hideCursor:t.hideCursor??!0,includeNewlines:t.includeNewlines??!0,includeReset:t.includeReset??!0}}buildColorCache(t){if(this.lastPalette!==t){this.fgCache=new Array(t.length),this.bgCache=new Array(t.length);for(let e=0;e<t.length;e++){let i=t[e];this.fgCache[e]=`\x1B[38;2;${i.r};${i.g};${i.b}m`,this.bgCache[e]=`\x1B[48;2;${i.r};${i.g};${i.b}m`}this.lastPalette=t}}render(t){let{width:e,height:i,cells:s,palette:r}=t;this.buildColorCache(r);let a="";this.options.hideCursor&&(a+=rt),this.options.includeHome&&(a+=st);let l=-1,o=-1,h=this.options.optimizeColors,c=this.options.includeNewlines;for(let d=0;d<i;d++){let f=d*e;for(let u=0;u<e;u++){let m=s[f+u],g=m.fgColorIndex,p=m.bgColorIndex;h?(p!==o&&(a+=this.bgCache[p],o=p),g!==l&&(a+=this.fgCache[g],l=g)):(a+=this.bgCache[p],a+=this.fgCache[g]),a+=m.char||" "}c&&d<i-1&&(a+=ct)}return this.options.includeReset&&(a+=q),a}renderRow(t,e){let{width:i,cells:s,palette:r}=t;this.buildColorCache(r);let a=`\x1B[${e+1};1H`,l=-1,o=-1,h=this.options.optimizeColors,c=e*i;for(let d=0;d<i;d++){let f=s[c+d],u=f.fgColorIndex,m=f.bgColorIndex;h?(m!==o&&(a+=this.bgCache[m],o=m),u!==l&&(a+=this.fgCache[u],l=u)):(a+=this.bgCache[m],a+=this.fgCache[u]),a+=f.char||" "}return this.options.includeReset&&(a+=q),a}clear(){return lt+st}showCursor(){return ht}hideCursor(){return rt}reset(){return q}moveTo(t,e){return`\x1B[${t+1};${e+1}H`}};v(Q,"TerminalANSI");var j=Q;function dt(b){let t=b.startsWith("#")?b.slice(1):b,e=t.length===3?t[0]+t[0]+t[1]+t[1]+t[2]+t[2]:t,i=parseInt(e,16);return{r:i>>16&255,g:i>>8&255,b:i&255,a:255}}v(dt,"hexToRGB");function ft(b){let t=b.r.toString(16).padStart(2,"0"),e=b.g.toString(16).padStart(2,"0"),i=b.b.toString(16).padStart(2,"0");return`#${t}${e}${i}`}v(ft,"rgbToHex");function ut(b,t){let e=[{r:0,g:0,b:0,a:255},{r:128,g:0,b:0,a:255},{r:0,g:128,b:0,a:255},{r:128,g:128,b:0,a:255},{r:0,g:0,b:128,a:255},{r:128,g:0,b:128,a:255},{r:0,g:128,b:128,a:255},{r:192,g:192,b:192,a:255},{r:128,g:128,b:128,a:255},{r:255,g:0,b:0,a:255},{r:0,g:255,b:0,a:255},{r:255,g:255,b:0,a:255},{r:0,g:0,b:255,a:255},{r:255,g:0,b:255,a:255},{r:0,g:255,b:255,a:255},{r:255,g:255,b:255,a:255}];for(;e.length<256;)e.push({r:128,g:128,b:128,a:255});let i=[];for(let s=0;s<t;s++)for(let r=0;r<b;r++)i.push({char:String.fromCharCode(65+(r+s)%26),fgColorIndex:15,bgColorIndex:(r+s)%16,fgEmission:0,bgEmission:0});return{width:b,height:t,cells:i,palette:e}}v(ut,"createTestRenderState");var Yt="0.1.0";export{N as AutoplayOverlay,U as BitmapFontAtlas,G as DEFAULT_PALETTE,R as GridOverlay,L as ImageFontAtlas,V as PostProcessOverlay,T as ScalingMode,z as Terminal2D,j as TerminalANSI,P as TerminalGL,ot as colorToPaletteIndex,ut as createTestRenderState,S as getAtlasColumns,D as getCharGridPosition,M as getMaxCharCode,dt as hexToRGB,nt as paletteIndexToColor,ft as rgbToHex,Yt as version};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@utsp/render",
3
- "version": "0.10.0",
4
- "description": "UTSP Render - Browser-based rendering engine for terminal graphics",
3
+ "version": "0.11.0-nightly.20251213232121.8b318c1",
4
+ "description": "UTSP Render - Rendering engine for terminal graphics with WebGL, Canvas 2D, and ANSI terminal support",
5
5
  "author": "THP Software",
6
6
  "license": "MIT",
7
7
  "type": "module",
@@ -13,6 +13,42 @@
13
13
  "types": "./dist/index.d.ts",
14
14
  "import": "./dist/index.mjs",
15
15
  "require": "./dist/index.cjs"
16
+ },
17
+ "./gl": {
18
+ "types": "./dist/gl/index.d.ts",
19
+ "import": "./dist/gl/index.mjs",
20
+ "require": "./dist/gl/index.cjs"
21
+ },
22
+ "./2d": {
23
+ "types": "./dist/2d/index.d.ts",
24
+ "import": "./dist/2d/index.mjs",
25
+ "require": "./dist/2d/index.cjs"
26
+ },
27
+ "./common": {
28
+ "types": "./dist/common/index.d.ts",
29
+ "import": "./dist/common/index.mjs",
30
+ "require": "./dist/common/index.cjs"
31
+ },
32
+ "./ansi": {
33
+ "types": "./dist/ansi/index.d.ts",
34
+ "import": "./dist/ansi/index.mjs",
35
+ "require": "./dist/ansi/index.cjs"
36
+ }
37
+ },
38
+ "typesVersions": {
39
+ "*": {
40
+ "gl": [
41
+ "./dist/gl/index.d.ts"
42
+ ],
43
+ "2d": [
44
+ "./dist/2d/index.d.ts"
45
+ ],
46
+ "common": [
47
+ "./dist/common/index.d.ts"
48
+ ],
49
+ "ansi": [
50
+ "./dist/ansi/index.d.ts"
51
+ ]
16
52
  }
17
53
  },
18
54
  "repository": {
@@ -34,6 +70,7 @@
34
70
  "browser",
35
71
  "text-mode",
36
72
  "ascii",
73
+ "ansi",
37
74
  "graphics"
38
75
  ],
39
76
  "engines": {
@@ -49,7 +86,7 @@
49
86
  "access": "public"
50
87
  },
51
88
  "dependencies": {
52
- "@utsp/types": "0.10.0"
89
+ "@utsp/types": "0.11.0-nightly.20251213232121.8b318c1"
53
90
  },
54
91
  "devDependencies": {
55
92
  "typescript": "^5.6.3"