@utsp/render 0.16.1 → 0.17.0-nightly.20260120215017.712755a
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/2d/index.cjs +5 -5
- package/dist/2d/index.d.ts +31 -226
- package/dist/2d/index.mjs +5 -5
- package/dist/gl/index.cjs +7 -7
- package/dist/gl/index.d.ts +21 -50
- package/dist/gl/index.mjs +7 -7
- package/dist/index.cjs +10 -10
- package/dist/index.d.ts +799 -1017
- package/dist/index.mjs +10 -10
- package/package.json +2 -2
package/dist/gl/index.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var $=Object.defineProperty;var
|
|
1
|
+
var $=Object.defineProperty;var N=(b,e,t)=>e in b?$(b,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):b[e]=t;var g=(b,e)=>$(b,"name",{value:e,configurable:!0});var a=(b,e,t)=>(N(b,typeof e!="symbol"?e+"":e,t),t);var _=class _{constructor(e,t){a(this,"canvas");a(this,"ctx");a(this,"container");a(this,"cols",0);a(this,"rows",0);a(this,"cellWidth",0);a(this,"cellHeight",0);a(this,"offsetX",0);a(this,"offsetY",0);a(this,"strokeColor","rgba(80, 80, 80, 0.4)");a(this,"lineWidth",1);this.container=e,this.canvas=document.createElement("canvas"),this.canvas.className="grid-overlay-canvas";let i=t?.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
|
-
z-index: ${
|
|
8
|
-
`,this.container.appendChild(this.canvas);let
|
|
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,t&&(t.strokeColor&&(this.strokeColor=t.strokeColor),t.lineWidth!==void 0&&(this.lineWidth=t.lineWidth))}setDimensions(e,t,i,s,r=0,l=0){this.cols=e,this.rows=t,this.cellWidth=i,this.cellHeight=s,this.offsetX=r,this.offsetY=l}setCanvasSize(e,t){this.canvas.width=e,this.canvas.height=t,this.ctx.setTransform(1,0,0,1,0,0)}setStyle(e){e.strokeColor&&(this.strokeColor=e.strokeColor),e.lineWidth!==void 0&&(this.lineWidth=e.lineWidth)}setTransform(e,t,i,s,r){let l=s.left-r.left,o=s.top-r.top,n=s.width,c=s.height;(this.canvas.width!==n||this.canvas.height!==c)&&(this.canvas.width=n,this.canvas.height=c);let h=this.canvas.style;h.width=`${n}px`,h.height=`${c}px`,h.left=`${l}px`,h.top=`${o}px`}render(){if(!this.ctx)return;let e=this.cols*this.cellWidth,t=this.rows*this.cellHeight,i=e>0?this.canvas.width/e:1,s=t>0?this.canvas.height/t:1,r=Math.min(i,s),l=this.cellWidth*r,o=this.cellHeight*r,n=this.cols*l,c=this.rows*o,h=this.offsetX*r,d=this.offsetY*r;if(!(n===0||c===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 u=0;u<=this.cols;u++){let m=h+u*l+.5;this.ctx.moveTo(m,d),this.ctx.lineTo(m,d+c)}for(let u=0;u<=this.rows;u++){let m=d+u*o+.5;this.ctx.moveTo(h,m),this.ctx.lineTo(h+n,m)}this.ctx.stroke()}}update(e,t,i,s,r,l,o=0,n=0){this.setDimensions(e,t,i,s,o,n),this.setCanvasSize(r,l),this.render()}setVisible(e){this.canvas.style.display=e?"block":"none"}destroy(){this.canvas.parentElement&&this.canvas.parentElement.removeChild(this.canvas)}getCanvas(){return this.canvas}};g(_,"GridOverlay");var I=_;function y(b){return Math.sqrt(b)*16}g(y,"getAtlasColumns");function B(b){return b*256-1}g(B,"getMaxCharCode");function L(b,e){let t=Math.floor(b/256),i=b%256,s=Math.sqrt(e),r=t%s,l=Math.floor(t/s),o=i%16,n=Math.floor(i/16);return{col:r*16+o,row:l*16+n}}g(L,"getCharGridPosition");import{POST_PROCESS_DEFAULTS as F,ScalingMode as C}from"@utsp/types";var U=class U{constructor(e,t){a(this,"canvas");a(this,"gl");a(this,"parentElement");a(this,"containerDiv");a(this,"cols");a(this,"rows");a(this,"charWidth");a(this,"charHeight");a(this,"cellWidth",8);a(this,"cellHeight",8);a(this,"glyphOffsetX",0);a(this,"glyphOffsetY",0);a(this,"canvasBgColor");a(this,"showGrid");a(this,"supportsUint32Indices",!1);a(this,"useUint16Indices",!1);a(this,"gridOverlay");a(this,"bitmapFont");a(this,"atlasTexture",null);a(this,"atlasCanvas");a(this,"atlasColumns",0);a(this,"fontLoaded",!1);a(this,"paletteTexture",null);a(this,"program",null);a(this,"positionBuffer",null);a(this,"texCoordBuffer",null);a(this,"colorIndexBuffer",null);a(this,"indexBuffer",null);a(this,"aPosition");a(this,"aTexCoord");a(this,"aColorIndex");a(this,"uResolution",null);a(this,"uTexture",null);a(this,"uPalette",null);a(this,"resizeObserver");a(this,"charCodeToAtlasIndex",new Uint16Array(65536).fill(65535));a(this,"atlasUVs",new Float32Array(0));a(this,"cachedAtlasWidth",0);a(this,"cachedAtlasHeight",0);a(this,"paletteFloat",new Float32Array(256*4));a(this,"maxCells",0);a(this,"renderPositions",new Float32Array(0));a(this,"renderTexCoords",new Float32Array(0));a(this,"renderColorIndices",new Float32Array(0));a(this,"renderIndices",new Uint32Array(0));a(this,"cachedResolution",[0,0]);a(this,"cachedTextureUnit",-1);a(this,"cachedPaletteUnit",-1);a(this,"cachedTextureUniform",!1);a(this,"cachedPaletteUniform",!1);a(this,"paletteHash",0);a(this,"currentScale",1);a(this,"scalingMode",C.None);a(this,"ambientEffectEnabled",!1);a(this,"ambientEffectCanvas",null);a(this,"ambientEffectCtx",null);a(this,"ambientEffectBlur",F.ambientEffect.blur);a(this,"ambientEffectScale",F.ambientEffect.scale);a(this,"ambientEffectOpacity",.7);a(this,"onResizeCallback");a(this,"staticPositionsInitialized",!1);a(this,"vaoExtension",null);a(this,"vao",null);a(this,"instancedExtension",null);a(this,"useInstancing",!1);a(this,"instanceDataBuffer",null);a(this,"instanceData",new Float32Array(0));a(this,"templateQuadPositions",new Float32Array(0));a(this,"templateQuadIndices",new Uint16Array(0));a(this,"aInstanceOffset",-1);a(this,"aInstanceUVs",-1);a(this,"aInstanceColors",-1);a(this,"uCellSize",null);if(!e)throw new Error("TerminalGL: Parent element is required");if(!Number.isInteger(t.cols)||t.cols<=0)throw new Error(`TerminalGL: Invalid cols: ${t.cols}. Must be a positive integer.`);if(!Number.isInteger(t.rows)||t.rows<=0)throw new Error(`TerminalGL: Invalid rows: ${t.rows}. Must be a positive integer.`);let i=t.cols*t.rows,s=U.checkCompatibility();if(s.errors.length>0)throw new Error(`TerminalGL: WebGL incompatible - ${s.errors.join(", ")}`);let r=t.forceUint16??!1;if(r&&i>s.maxCellsUint16)throw new Error(`TerminalGL: Terminal size ${t.cols}\xD7${t.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 ${t.cols}\xD7${t.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 ${t.cols}\xD7${t.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 l=t.charWidth??8,o=t.charHeight??8;if(!Number.isFinite(l)||l<=0)throw new Error(`TerminalGL: Invalid charWidth: ${l}. Must be a positive number.`);if(!Number.isFinite(o)||o<=0)throw new Error(`TerminalGL: Invalid charHeight: ${o}. Must be a positive number.`);for(this.parentElement=e,this.cols=t.cols,this.rows=t.rows,this.charWidth=l,this.charHeight=o,this.canvasBgColor=t.canvasBgColor!==void 0?t.canvasBgColor:null,this.showGrid=t.showGrid??!1,this.scalingMode=t.scalingMode??C.None,t.ambientEffect&&(this.ambientEffectEnabled=!0,typeof t.ambientEffect=="object"&&(this.ambientEffectBlur=t.ambientEffect.blur??F.ambientEffect.blur,this.ambientEffectScale=t.ambientEffect.scale??F.ambientEffect.scale,this.ambientEffectOpacity=t.ambientEffect.opacity??.7));this.parentElement.firstChild;)this.parentElement.removeChild(this.parentElement.firstChild);let n=window.getComputedStyle(this.parentElement).position;n!=="relative"&&n!=="absolute"&&n!=="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;
|
|
@@ -35,7 +35,7 @@ var $=Object.defineProperty;var V=(v,e,t)=>e in v?$(v,e,{enumerable:!0,configura
|
|
|
35
35
|
z-index: 1 !important;
|
|
36
36
|
pointer-events: auto !important;
|
|
37
37
|
touch-action: none !important;
|
|
38
|
-
`;let c=this.canvas.getContext("webgl",{alpha:this.canvasBgColor===null,premultipliedAlpha:!1});if(!c)throw new Error("TerminalGL: WebGL not supported");this.gl=c,this.supportsUint32Indices=!!c.getExtension("OES_element_index_uint"),this.useUint16Indices=
|
|
38
|
+
`;let c=this.canvas.getContext("webgl",{alpha:this.canvasBgColor===null,premultipliedAlpha:!1});if(!c)throw new Error("TerminalGL: WebGL not supported");this.gl=c,this.supportsUint32Indices=!!c.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=c.getExtension("OES_vertex_array_object"),this.vaoExtension&&console.warn("[TerminalGL] \u2705 VAO extension enabled (faster attribute binding)"),this.instancedExtension=c.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(h){throw console.error("[TerminalGL] \u274C Failed to initialize WebGL:",h),h}this.showGrid&&this.initGridOverlay(),this.setupResizeObserver()}static checkCompatibility(){let e={webgl1:!1,uint32Indices:!1,maxTextureSize:0,maxViewportDims:[0,0],maxCellsUint16:0,maxCellsUint32:0,recommendedMaxCells:0,warnings:[],errors:[]},t=document.createElement("canvas"),i=t.getContext("webgl")||t.getContext("experimental-webgl");if(!i||!(i instanceof WebGLRenderingContext))return e.errors.push("\u274C WebGL 1.0 not supported by this browser/device"),e;let s=i;e.webgl1=!0;try{e.maxTextureSize=s.getParameter(s.MAX_TEXTURE_SIZE);let n=s.getParameter(s.MAX_VIEWPORT_DIMS);e.maxViewportDims=[n[0],n[1]]}catch(n){return e.errors.push(`\u274C Failed to query WebGL parameters: ${n}`),e}let r=s.getExtension("OES_element_index_uint");e.uint32Indices=!!r;let l=8;if(e.maxCellsUint16=Math.floor(65535/l),e.uint32Indices){let n=Math.floor(e.maxTextureSize*e.maxTextureSize/64);e.maxCellsUint32=Math.min(n,262144)}else e.maxCellsUint32=e.maxCellsUint16,e.warnings.push(`\u26A0\uFE0F OES_element_index_uint not supported - limited to ${e.maxCellsUint16} cells (e.g., 90\xD790 or 127\xD764)`);return e.recommendedMaxCells=Math.floor((e.uint32Indices?e.maxCellsUint32:e.maxCellsUint16)*.8),e.maxTextureSize<256?e.errors.push(`\u274C MAX_TEXTURE_SIZE too small: ${e.maxTextureSize} (minimum 256 required for font atlas)`):e.maxTextureSize<2048&&e.warnings.push(`\u26A0\uFE0F Small MAX_TEXTURE_SIZE: ${e.maxTextureSize} (may limit font atlas)`),(e.maxViewportDims[0]<1024||e.maxViewportDims[1]<768)&&e.warnings.push(`\u26A0\uFE0F Small MAX_VIEWPORT_DIMS: ${e.maxViewportDims[0]}\xD7${e.maxViewportDims[1]}`),s.getExtension("WEBGL_lose_context")||e.warnings.push("\u26A0\uFE0F WEBGL_lose_context not supported - may cause memory leaks"),e}initInstancedBuffers(){let e=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]),e.bindBuffer(e.ARRAY_BUFFER,this.positionBuffer),e.bufferData(e.ARRAY_BUFFER,this.templateQuadPositions,e.STATIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.templateQuadIndices,e.STATIC_DRAW),this.instanceData=new Float32Array(this.maxCells*8),console.warn(`[TerminalGL] \u{1F680} initInstancedBuffers: maxCells=${this.maxCells}, instanceData.length=${this.instanceData.length}`),e.bindBuffer(e.ARRAY_BUFFER,this.instanceDataBuffer),e.bufferData(e.ARRAY_BUFFER,this.instanceData.byteLength,e.DYNAMIC_DRAW)}initRenderBuffers(){let e=this.cols*this.rows*2;this.maxCells=Math.ceil(e*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 e=this.cellWidth,t=this.cellHeight,i=this.glyphOffsetX,s=this.glyphOffsetY,r=this.charWidth,l=this.charHeight,o=0,n=0,c=0;for(let d=0;d<this.rows;d++){let u=Math.round(d*t),m=Math.round(u+t);for(let x=0;x<this.cols;x++){let f=Math.round(x*e),p=Math.round(f+e);this.renderPositions[o++]=f,this.renderPositions[o++]=u,this.renderPositions[o++]=p,this.renderPositions[o++]=u,this.renderPositions[o++]=f,this.renderPositions[o++]=m,this.renderPositions[o++]=p,this.renderPositions[o++]=m,this.renderIndices[n++]=c,this.renderIndices[n++]=c+1,this.renderIndices[n++]=c+2,this.renderIndices[n++]=c+2,this.renderIndices[n++]=c+1,this.renderIndices[n++]=c+3,c+=4;let E=Math.round(f+i),v=Math.round(u+s),w=Math.round(E+r),A=Math.round(v+l);this.renderPositions[o++]=E,this.renderPositions[o++]=v,this.renderPositions[o++]=w,this.renderPositions[o++]=v,this.renderPositions[o++]=E,this.renderPositions[o++]=A,this.renderPositions[o++]=w,this.renderPositions[o++]=A,this.renderIndices[n++]=c,this.renderIndices[n++]=c+1,this.renderIndices[n++]=c+2,this.renderIndices[n++]=c+2,this.renderIndices[n++]=c+1,this.renderIndices[n++]=c+3,c+=4}}let h=this.gl;h.bindBuffer(h.ARRAY_BUFFER,this.positionBuffer),h.bufferSubData(h.ARRAY_BUFFER,0,this.renderPositions),h.bindBuffer(h.ELEMENT_ARRAY_BUFFER,this.indexBuffer),h.bufferSubData(h.ELEMENT_ARRAY_BUFFER,0,this.renderIndices),this.staticPositionsInitialized=!0}initWebGL(){let e=this.gl,t;this.useInstancing?t=`
|
|
39
39
|
// Per-vertex attributes (template quad)
|
|
40
40
|
attribute vec2 aPosition; // Local quad position (0,0 to cellW,cellH)
|
|
41
41
|
|
|
@@ -96,7 +96,7 @@ var $=Object.defineProperty;var V=(v,e,t)=>e in v?$(v,e,{enumerable:!0,configura
|
|
|
96
96
|
float paletteU = (aColorIndex + 0.5) / 256.0;
|
|
97
97
|
vColor = texture2D(uPalette, vec2(paletteU, 0.5));
|
|
98
98
|
}
|
|
99
|
-
`;let
|
|
99
|
+
`;let i=`
|
|
100
100
|
precision mediump float;
|
|
101
101
|
|
|
102
102
|
uniform sampler2D uTexture;
|
|
@@ -116,7 +116,7 @@ var $=Object.defineProperty;var V=(v,e,t)=>e in v?$(v,e,{enumerable:!0,configura
|
|
|
116
116
|
gl_FragColor = vec4(texColor.rgb * vColor.rgb, texColor.a);
|
|
117
117
|
}
|
|
118
118
|
}
|
|
119
|
-
`,i=this.compileShader(e.VERTEX_SHADER,t),n=this.compileShader(e.FRAGMENT_SHADER,s);if(!i||!n)throw new Error("Shader compilation error");let a=e.createProgram();if(!a)throw new Error("Unable to create WebGL program");if(e.attachShader(a,i),e.attachShader(a,n),e.linkProgram(a),!e.getProgramParameter(a,e.LINK_STATUS)){let l=e.getProgramInfoLog(a);throw new Error("Program linking error: "+l)}this.program=a,this.cachedTextureUniform=!1,this.cachedPaletteUniform=!1,this.aPosition=e.getAttribLocation(a,"aPosition"),this.useInstancing?(this.aInstanceOffset=e.getAttribLocation(a,"aInstanceOffset"),this.aInstanceUVs=e.getAttribLocation(a,"aInstanceUVs"),this.aInstanceColors=e.getAttribLocation(a,"aInstanceColors"),this.uCellSize=e.getUniformLocation(a,"uCellSize"),this.instanceDataBuffer=e.createBuffer(),this.aTexCoord=this.aInstanceOffset,this.aColorIndex=this.aInstanceUVs):(this.aTexCoord=e.getAttribLocation(a,"aTexCoord"),this.aColorIndex=e.getAttribLocation(a,"aColorIndex")),this.uResolution=e.getUniformLocation(a,"uResolution"),this.uTexture=e.getUniformLocation(a,"uTexture"),this.uPalette=e.getUniformLocation(a,"uPalette"),this.positionBuffer=e.createBuffer(),this.texCoordBuffer=e.createBuffer(),this.colorIndexBuffer=e.createBuffer(),this.indexBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.positionBuffer),e.bufferData(e.ARRAY_BUFFER,this.renderPositions.byteLength,e.DYNAMIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this.texCoordBuffer),e.bufferData(e.ARRAY_BUFFER,this.renderTexCoords.byteLength,e.DYNAMIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this.colorIndexBuffer),e.bufferData(e.ARRAY_BUFFER,this.renderColorIndices.byteLength,e.DYNAMIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.renderIndices.byteLength,e.DYNAMIC_DRAW),this.vaoExtension&&(this.vao=this.vaoExtension.createVertexArrayOES(),this.vao&&(this.vaoExtension.bindVertexArrayOES(this.vao),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.enableVertexAttribArray(this.aTexCoord),e.vertexAttribPointer(this.aTexCoord,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this.colorIndexBuffer),e.enableVertexAttribArray(this.aColorIndex),e.vertexAttribPointer(this.aColorIndex,1,e.FLOAT,!1,0,0),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer),this.vaoExtension.bindVertexArrayOES(null))),e.enable(e.BLEND),e.blendFunc(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA),e.viewport(0,0,this.canvas.width,this.canvas.height)}compileShader(e,t){let s=this.gl,i=s.createShader(e);return i?(s.shaderSource(i,t),s.compileShader(i),s.getShaderParameter(i,s.COMPILE_STATUS)?i:(console.error("Shader compilation error:",s.getShaderInfoLog(i)),s.deleteShader(i),null)):null}initGridOverlay(){this.gridOverlay=new I(this.containerDiv,{strokeColor:"rgba(144, 24, 24, 1)",lineWidth:1,zIndex:10}),this.updateGridOverlay()}updateGridOverlay(){if(!this.gridOverlay)return;let e=this.cols*this.cellWidth,t=this.rows*this.cellHeight,s=this.canvas.getBoundingClientRect(),i=this.containerDiv.getBoundingClientRect();this.gridOverlay.setDimensions(this.cols,this.rows,this.cellWidth,this.cellHeight,0,0),this.gridOverlay.setTransform(this.currentScale,e,t,s,i),this.gridOverlay.render()}setBitmapFont(e,t,s,i,n){this.bitmapFont=e,this.fontLoaded=!0,this.charWidth=Math.round(t),this.charHeight=Math.round(s),this.cellWidth=Math.round(i),this.cellHeight=Math.round(n),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(e,t,s,i,n,a){this.fontLoaded=!0,this.charWidth=Math.round(t),this.charHeight=Math.round(s),this.cellWidth=Math.round(i),this.cellHeight=Math.round(n),this.atlasColumns=F(a);let l=L(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(e),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(e){return new Promise((t,s)=>{let i=new Uint8Array(e),n=new Blob([i],{type:"image/png"}),a=URL.createObjectURL(n),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){s(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(),t()},l.onerror=()=>{URL.revokeObjectURL(a),s(new Error("Failed to load PNG image for ImageFont atlas"))},l.src=a})}precomputeImageFontUVs(e){let t=e*256;this.atlasUVs=new Float32Array(t*4);let s=this.cachedAtlasWidth,i=this.cachedAtlasHeight,n=.5/s,a=.5/i;for(let l=0;l<t;l++){let{col:o,row:c}=_(l,e),d=(o*this.charWidth+n)/s,h=(c*this.charHeight+a)/i,u=((o+1)*this.charWidth-n)/s,m=((c+1)*this.charHeight-a)/i,b=l*4;this.atlasUVs[b]=d,this.atlasUVs[b+1]=h,this.atlasUVs[b+2]=u,this.atlasUVs[b+3]=m}}generateAtlas(){if(!this.bitmapFont)return;let e=Array.from(this.bitmapFont.keys()).sort((o,c)=>o-c),t=e.length;this.atlasColumns=Math.ceil(Math.sqrt(t));let s=Math.ceil(t/this.atlasColumns),i=this.atlasColumns*this.charWidth,n=s*this.charHeight;this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=i,this.atlasCanvas.height=n;let a=this.atlasCanvas.getContext("2d");if(!a)throw new Error("Unable to create 2D context for atlas");a.clearRect(0,0,i,n),a.fillStyle="#ffffff";let l=0;for(let o of e){let c=this.bitmapFont.get(o);if(!c)continue;let d=l%this.atlasColumns,h=Math.floor(l/this.atlasColumns),u=d*this.charWidth,m=h*this.charHeight;for(let b=0;b<Math.min(c.length,this.charHeight);b++){let f=c[b];for(let p=0;p<this.charWidth;p++){let g=1<<7-p;f&g&&a.fillRect(u+p,m+b,1,1)}}l++}this.createAtlasTexture()}buildCharCodeMap(){if(!this.bitmapFont)return;this.charCodeToAtlasIndex.fill(65535);let e=Array.from(this.bitmapFont.keys()).sort((t,s)=>t-s);for(let t=0;t<e.length;t++)this.charCodeToAtlasIndex[e[t]]=t}precomputeAtlasUVs(){if(!this.bitmapFont)return;let e=this.bitmapFont.size;this.atlasUVs=new Float32Array(e*4),this.cachedAtlasWidth=this.atlasColumns*this.charWidth,this.cachedAtlasHeight=Math.ceil(e/this.atlasColumns)*this.charHeight;let t=this.cachedAtlasWidth,s=this.cachedAtlasHeight,i=.5/t,n=.5/s;for(let a=0;a<e;a++){let l=a%this.atlasColumns,o=Math.floor(a/this.atlasColumns),c=(l*this.charWidth+i)/t,d=(o*this.charHeight+n)/s,h=((l+1)*this.charWidth-i)/t,u=((o+1)*this.charHeight-n)/s,m=a*4;this.atlasUVs[m]=c,this.atlasUVs[m+1]=d,this.atlasUVs[m+2]=h,this.atlasUVs[m+3]=u}}createAtlasTexture(){if(this.atlasCanvas)try{let e=this.gl,t=e.createTexture();if(!t)throw new Error("Unable to create texture");e.bindTexture(e.TEXTURE_2D,t),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.atlasCanvas),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),this.atlasTexture=t}catch(e){throw console.error("[TerminalGL] \u274C Failed to create atlas texture:",e),e}}clear(){let e=this.gl;e&&e.clear(e.COLOR_BUFFER_BIT)}parseColor(e){if(e.startsWith("#")){let t=e.slice(1),s=0,i=0,n=0;return t.length===3?(s=parseInt(t[0]+t[0],16),i=parseInt(t[1]+t[1],16),n=parseInt(t[2]+t[2],16)):t.length===6&&(s=parseInt(t.slice(0,2),16),i=parseInt(t.slice(2,4),16),n=parseInt(t.slice(4,6),16)),[s/255,i/255,n/255,1]}if(e.startsWith("rgb")){let t=e.match(/rgba?\(([^)]+)\)/);if(t){let s=t[1].split(",").map(i=>parseFloat(i.trim()));return[s[0]/255,s[1]/255,s[2]/255,s[3]!==void 0?s[3]:1]}}return[1,1,1,1]}setupResizeObserver(){if(!(typeof ResizeObserver>"u"))try{this.resizeObserver=new ResizeObserver(()=>{try{this.updateCanvasSize()}catch(e){console.error("[TerminalGL] \u274C Error in resize callback:",e)}}),this.resizeObserver.observe(this.parentElement),this.updateCanvasSize()}catch(e){console.error("[TerminalGL] \u274C Failed to setup ResizeObserver:",e)}}updateCanvasSize(){let e=this.parentElement.clientWidth,t=this.parentElement.clientHeight;if(e===0||t===0)return;let s=this.cols*this.cellWidth,i=this.rows*this.cellHeight;if(s===0||i===0)return;let n=e/s,a=t/i,l=Math.min(n,a),o;switch(this.scalingMode){case C.Integer:o=Math.max(1,Math.floor(l));break;case C.Half:o=Math.max(1,Math.floor(l*2)/2);break;case C.Quarter:o=Math.max(1,Math.floor(l*4)/4);break;case C.Eighth:o=Math.max(1,Math.floor(l*8)/8);break;case C.Responsive:o=1;break;case C.None:default:o=Math.max(.1,l);break}if(this.canvas.style.transform=`scale(${o})`,this.ambientEffectEnabled&&this.ambientEffectCanvas){let c=o*this.ambientEffectScale;this.ambientEffectCanvas.style.transform=`scale(${c})`}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(e){let t=0;for(let s=0;s<Math.min(e.length,256);s++){let i=e[s];t=(t<<5)-t+i.r,t=(t<<5)-t+i.g,t=(t<<5)-t+i.b,t=(t<<5)-t+i.a,t=t|0}if(t!==this.paletteHash){this.paletteHash=t;for(let s=0;s<e.length&&s<256;s++){let i=e[s],n=s*4;this.paletteFloat[n]=i.r/255,this.paletteFloat[n+1]=i.g/255,this.paletteFloat[n+2]=i.b/255,this.paletteFloat[n+3]=i.a/255}this.updatePaletteTexture()}}updatePaletteTexture(){try{let e=this.gl;this.paletteTexture||(this.paletteTexture=e.createTexture()),e.bindTexture(e.TEXTURE_2D,this.paletteTexture);let t=new Uint8Array(256*4);for(let s=0;s<256;s++){let i=s*4;t[i]=this.paletteFloat[i]*255,t[i+1]=this.paletteFloat[i+1]*255,t[i+2]=this.paletteFloat[i+2]*255,t[i+3]=this.paletteFloat[i+3]*255}e.texImage2D(e.TEXTURE_2D,0,e.RGBA,256,1,0,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null)}catch(e){throw console.error("[TerminalGL] \u274C Failed to update palette texture:",e),e}}renderDisplayData(e){try{if(!this.isReady()){console.warn("[TerminalGL] \u26A0\uFE0F Not ready: font not loaded yet");return}(e.width!==this.cols||e.height!==this.rows)&&this.resize(e.width,e.height),e.passes&&e.passes.length>0?this.renderMultiPass(e,e.passes):this.renderDirect(e),this.ambientEffectEnabled&&this.ambientEffectCanvas&&this.ambientEffectCtx&&this.updateAmbientEffect()}catch(t){console.error("[TerminalGL] \u274C Error rendering display data:",t)}}renderMultiPass(e,t){for(let s=0;s<t.length;s++){let i=t[s],n={id:e.id,width:e.width,height:e.height,palette:e.palette,cells:i.cells};this.renderDirect(n,s===0)}}renderDirect(e,t=!0){let s=this.gl;if(!this.staticPositionsInitialized&&!this.useInstancing&&this.precomputeStaticPositions(),t){if(this.canvasBgColor!==null){let i=this.parseColor(this.canvasBgColor);s.clearColor(i[0],i[1],i[2],i[3])}else s.clearColor(0,0,0,0);s.clear(s.COLOR_BUFFER_BIT)}this.useInstancing?this.renderInstanced(e):this.renderDirectBuffers(e)}renderInstanced(e){let t=this.gl,s=this.instancedExtension;if(!this.instanceData||this.instanceData.length===0){console.warn("[TerminalGL] \u26A0\uFE0F Instance data not initialized, falling back to standard rendering"),this.renderDirectBuffers(e);return}let i=0,n=this.instanceData.length/8,a=e.width*e.height*2;if(a>n){console.error(`[TerminalGL] \u274C Instance buffer too small! Need ${a}, have ${n}. Display size: ${e.width}\xD7${e.height}, buffer was sized for smaller terminal.`),this.renderDirectBuffers(e);return}for(let o=0;o<e.height;o++)for(let c=0;c<e.width;c++){let d=e.cells[o*e.width+c],h=d.bgColorIndex,u=d.fgColorIndex,m=this.canvasBgColor!==null&&h===255,b=d.char===" "||u===255;if(!m){if(i>=n){console.error(`[TerminalGL] \u274C Instance buffer overflow! instanceIdx=${i}, max=${n}`);break}let f=i*8;this.instanceData[f]=c,this.instanceData[f+1]=o,this.instanceData[f+2]=0,this.instanceData[f+3]=0,this.instanceData[f+4]=0,this.instanceData[f+5]=0,this.instanceData[f+6]=h,this.instanceData[f+7]=0,i++}if(!b){let f=d.char.charCodeAt(0),p=this.charCodeToAtlasIndex[f];if(p!==65535){if(i>=n){console.error(`[TerminalGL] \u274C Instance buffer overflow! instanceIdx=${i}, max=${n}`);break}let g=p*4,x=i*8;this.instanceData[x]=c,this.instanceData[x+1]=o,this.instanceData[x+2]=this.atlasUVs[g],this.instanceData[x+3]=this.atlasUVs[g+1],this.instanceData[x+4]=this.atlasUVs[g+2],this.instanceData[x+5]=this.atlasUVs[g+3],this.instanceData[x+6]=0,this.instanceData[x+7]=u,i++}}}if(i===0){console.warn("[TerminalGL] \u26A0\uFE0F No instances to draw (all cells skipped)");return}t.bindBuffer(t.ARRAY_BUFFER,this.instanceDataBuffer),t.bufferSubData(t.ARRAY_BUFFER,0,this.instanceData.subarray(0,i*8)),t.useProgram(this.program),t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.enableVertexAttribArray(this.aPosition),t.vertexAttribPointer(this.aPosition,2,t.FLOAT,!1,0,0),s.vertexAttribDivisorANGLE(this.aPosition,0),t.bindBuffer(t.ARRAY_BUFFER,this.instanceDataBuffer);let l=8*Float32Array.BYTES_PER_ELEMENT;t.enableVertexAttribArray(this.aInstanceOffset),t.vertexAttribPointer(this.aInstanceOffset,2,t.FLOAT,!1,l,0),s.vertexAttribDivisorANGLE(this.aInstanceOffset,1),t.enableVertexAttribArray(this.aInstanceUVs),t.vertexAttribPointer(this.aInstanceUVs,4,t.FLOAT,!1,l,2*Float32Array.BYTES_PER_ELEMENT),s.vertexAttribDivisorANGLE(this.aInstanceUVs,1),t.enableVertexAttribArray(this.aInstanceColors),t.vertexAttribPointer(this.aInstanceColors,2,t.FLOAT,!1,l,6*Float32Array.BYTES_PER_ELEMENT),s.vertexAttribDivisorANGLE(this.aInstanceColors,1),t.uniform2f(this.uResolution,this.canvas.width,this.canvas.height),t.uniform2f(this.uCellSize,this.cellWidth,this.cellHeight),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.atlasTexture),t.uniform1i(this.uTexture,0),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this.paletteTexture),t.uniform1i(this.uPalette,1),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),s.drawElementsInstancedANGLE(t.TRIANGLES,6,t.UNSIGNED_SHORT,0,i),s.vertexAttribDivisorANGLE(this.aPosition,0),s.vertexAttribDivisorANGLE(this.aInstanceOffset,0),s.vertexAttribDivisorANGLE(this.aInstanceUVs,0),s.vertexAttribDivisorANGLE(this.aInstanceColors,0)}renderDirectBuffers(e){let t=this.gl,s=e.width*e.height,i=s*2;if(i>this.maxCells){console.error(`[TerminalGL] \u274C Buffer overflow detected! Trying to render ${i} quads but buffer capacity is ${this.maxCells}. This should not happen - resize() should have reallocated.`);return}let n=0,a=0,l=e.cells,o=s;for(let b=0;b<o;b++){let f=l[b],p=f.bgColorIndex,x=this.canvasBgColor!==null&&p===255?255:p,w=0;for(let T=0;T<4;T++)this.renderTexCoords[n++]=w,this.renderTexCoords[n++]=w,this.renderColorIndices[a++]=x;let A=f.fgColorIndex,S=f.char;if(S===" "||A===255)for(let T=0;T<4;T++)this.renderTexCoords[n++]=0,this.renderTexCoords[n++]=0,this.renderColorIndices[a++]=255;else{let T=S.charCodeAt(0),P=this.charCodeToAtlasIndex[T];if(P!==65535){let R=P*4,G=this.atlasUVs[R],W=this.atlasUVs[R+1],O=this.atlasUVs[R+2],H=this.atlasUVs[R+3];this.renderTexCoords[n++]=G,this.renderTexCoords[n++]=W,this.renderColorIndices[a++]=A,this.renderTexCoords[n++]=O,this.renderTexCoords[n++]=W,this.renderColorIndices[a++]=A,this.renderTexCoords[n++]=G,this.renderTexCoords[n++]=H,this.renderColorIndices[a++]=A,this.renderTexCoords[n++]=O,this.renderTexCoords[n++]=H,this.renderColorIndices[a++]=A}else for(let R=0;R<4;R++)this.renderTexCoords[n++]=0,this.renderTexCoords[n++]=0,this.renderColorIndices[a++]=255}}(n!==o*2*4*2||a!==o*2*4)&&console.error("[TerminalGL] \u274C Buffer index mismatch!",{texIdx:n,colorIdx:a,expected:o*2*4}),t.useProgram(this.program),this.vao&&this.vaoExtension?(this.vaoExtension.bindVertexArrayOES(this.vao),t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferSubData(t.ARRAY_BUFFER,0,this.renderTexCoords.subarray(0,n)),t.bindBuffer(t.ARRAY_BUFFER,this.colorIndexBuffer),t.bufferSubData(t.ARRAY_BUFFER,0,this.renderColorIndices.subarray(0,a))):(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.bufferSubData(t.ARRAY_BUFFER,0,this.renderTexCoords.subarray(0,n)),t.enableVertexAttribArray(this.aTexCoord),t.vertexAttribPointer(this.aTexCoord,2,t.FLOAT,!1,0,0),t.bindBuffer(t.ARRAY_BUFFER,this.colorIndexBuffer),t.bufferSubData(t.ARRAY_BUFFER,0,this.renderColorIndices.subarray(0,a)),t.enableVertexAttribArray(this.aColorIndex),t.vertexAttribPointer(this.aColorIndex,1,t.FLOAT,!1,0,0));let c=this.canvas.width,d=this.canvas.height;(this.cachedResolution[0]!==c||this.cachedResolution[1]!==d)&&(t.uniform2f(this.uResolution,c,d),this.cachedResolution[0]=c,this.cachedResolution[1]=d),this.cachedTextureUnit!==0&&(t.activeTexture(t.TEXTURE0),this.cachedTextureUnit=0),t.bindTexture(t.TEXTURE_2D,this.atlasTexture),this.cachedTextureUniform||(t.uniform1i(this.uTexture,0),this.cachedTextureUniform=!0),this.cachedPaletteUnit!==1&&(t.activeTexture(t.TEXTURE1),this.cachedPaletteUnit=1),t.bindTexture(t.TEXTURE_2D,this.paletteTexture),this.cachedPaletteUniform||(t.uniform1i(this.uPalette,1),this.cachedPaletteUniform=!0),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer);let u=e.width*e.height*2*6,m=this.useUint16Indices?t.UNSIGNED_SHORT:t.UNSIGNED_INT;t.drawElements(t.TRIANGLES,u,m,0)}resize(e,t){if(!Number.isInteger(e)||e<=0){console.error(`[TerminalGL] \u274C Invalid cols: ${e}. Must be positive integer.`);return}if(!Number.isInteger(t)||t<=0){console.error(`[TerminalGL] \u274C Invalid rows: ${t}. Must be positive integer.`);return}if(e===this.cols&&t===this.rows)return;let s=e*t,i=this.useInstancing?262144:this.useUint16Indices?8191:262144;if(s>i){let d=Math.floor(Math.sqrt(i));console.error(`[TerminalGL] \u274C Cannot resize to ${e}\xD7${t} (${s} cells). Device limit: ${i} cells (max ~${d}\xD7${d}). ${!this.useInstancing&&this.useUint16Indices?"Device lacks OES_element_index_uint extension.":""}`);return}let n=y.checkCompatibility();s>n.recommendedMaxCells&&console.warn(`[TerminalGL] \u26A0\uFE0F Resizing to ${e}\xD7${t} (${s} cells) exceeds recommended limit (${n.recommendedMaxCells} cells). Performance may degrade.`),this.cols=e,this.rows=t,this.staticPositionsInitialized=!1;let a=this.cols*this.rows*2,l=Math.ceil(a*1.5),o=a>this.maxCells,c=this.maxCells>l*4;if(console.warn(`[TerminalGL] \u{1F4D0} resize check: cols=${e}, rows=${t}, newMaxCells=${a}, this.maxCells=${this.maxCells}, needGrow=${o}, needShrink=${c}`),o||c){let d=this.maxCells;if(this.maxCells=l,console.warn(`[TerminalGL] \u{1F4D0} resize realloc: ${d} \u2192 ${this.maxCells} (needGrow=${o}, needShrink=${c})`),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.useInstancing&&this.instanceDataBuffer){this.instanceData=new Float32Array(this.maxCells*8);let f=this.gl;f.bindBuffer(f.ARRAY_BUFFER,this.instanceDataBuffer),f.bufferData(f.ARRAY_BUFFER,this.instanceData.byteLength,f.DYNAMIC_DRAW)}let h=this.gl;this.useInstancing||(h.bindBuffer(h.ARRAY_BUFFER,this.positionBuffer),h.bufferData(h.ARRAY_BUFFER,this.renderPositions.byteLength,h.DYNAMIC_DRAW)),h.bindBuffer(h.ARRAY_BUFFER,this.texCoordBuffer),h.bufferData(h.ARRAY_BUFFER,this.renderTexCoords.byteLength,h.DYNAMIC_DRAW),h.bindBuffer(h.ARRAY_BUFFER,this.colorIndexBuffer),h.bufferData(h.ARRAY_BUFFER,this.renderColorIndices.byteLength,h.DYNAMIC_DRAW),this.useInstancing||(h.bindBuffer(h.ELEMENT_ARRAY_BUFFER,this.indexBuffer),h.bufferData(h.ELEMENT_ARRAY_BUFFER,this.renderIndices.byteLength,h.DYNAMIC_DRAW)),this.vaoExtension&&this.vao&&(this.vaoExtension.deleteVertexArrayOES(this.vao),this.vao=this.vaoExtension.createVertexArrayOES(),this.vao&&(this.vaoExtension.bindVertexArrayOES(this.vao),h.bindBuffer(h.ARRAY_BUFFER,this.positionBuffer),h.enableVertexAttribArray(this.aPosition),h.vertexAttribPointer(this.aPosition,2,h.FLOAT,!1,0,0),h.bindBuffer(h.ARRAY_BUFFER,this.texCoordBuffer),h.enableVertexAttribArray(this.aTexCoord),h.vertexAttribPointer(this.aTexCoord,2,h.FLOAT,!1,0,0),h.bindBuffer(h.ARRAY_BUFFER,this.colorIndexBuffer),h.enableVertexAttribArray(this.aColorIndex),h.vertexAttribPointer(this.aColorIndex,1,h.FLOAT,!1,0,0),h.bindBuffer(h.ELEMENT_ARRAY_BUFFER,this.indexBuffer),this.vaoExtension.bindVertexArrayOES(null)));let u=o?"\u{1F4C8} Growing":"\u{1F4C9} Shrinking",m=d*160/1048576,b=this.maxCells*160/1048576;console.warn(`[TerminalGL] ${u} buffers: ${m.toFixed(2)}MB \u2192 ${b.toFixed(2)}MB (${d} \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.canvas.style.width=`${this.canvas.width}px`,this.canvas.style.height=`${this.canvas.height}px`,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(e){this.onResizeCallback=e}clearOnResizeCallback(){this.onResizeCallback=void 0}getAvailableSize(){return{width:this.parentElement.clientWidth,height:this.parentElement.clientHeight}}setScalingMode(e){this.scalingMode!==e&&(this.scalingMode=e,this.updateCanvasSize())}getScalingMode(){return this.scalingMode}setCellSize(e,t){let s=Math.max(1,Math.min(255,Math.round(e))),i=Math.max(1,Math.min(255,Math.round(t)));this.cellWidth===s&&this.cellHeight===i||(this.cellWidth=s,this.cellHeight=i,this.charWidth=s,this.charHeight=i,this.glyphOffsetX=Math.round((this.cellWidth-this.charWidth)/2),this.glyphOffsetY=Math.round((this.cellHeight-this.charHeight)/2),this.fontLoaded&&this.generateAtlas(),this.useInstancing&&this.initInstancedBuffers(),this.updateCanvasSize())}getCellSize(){return{cellWidth:this.cellWidth,cellHeight:this.cellHeight}}getMaxCells(){return this.useInstancing?262144:this.useUint16Indices?8191:262144}setGrid(e){e.enabled?(this.gridOverlay?this.gridOverlay.setStyle({strokeColor:e.color,lineWidth:e.lineWidth}):this.gridOverlay=new I(this.containerDiv,{strokeColor:e.color??"rgba(144, 24, 24, 1)",lineWidth:e.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(e){typeof e=="boolean"?this.ambientEffectEnabled=e:(this.ambientEffectEnabled=!0,e.blur!==void 0&&(this.ambientEffectBlur=e.blur),e.scale!==void 0&&(this.ambientEffectScale=e.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=`
|
|
119
|
+
`,s=this.compileShader(e.VERTEX_SHADER,t),r=this.compileShader(e.FRAGMENT_SHADER,i);if(!s||!r)throw new Error("Shader compilation error");let l=e.createProgram();if(!l)throw new Error("Unable to create WebGL program");if(e.attachShader(l,s),e.attachShader(l,r),e.linkProgram(l),!e.getProgramParameter(l,e.LINK_STATUS)){let o=e.getProgramInfoLog(l);throw new Error("Program linking error: "+o)}this.program=l,this.cachedTextureUniform=!1,this.cachedPaletteUniform=!1,this.aPosition=e.getAttribLocation(l,"aPosition"),this.useInstancing?(this.aInstanceOffset=e.getAttribLocation(l,"aInstanceOffset"),this.aInstanceUVs=e.getAttribLocation(l,"aInstanceUVs"),this.aInstanceColors=e.getAttribLocation(l,"aInstanceColors"),this.uCellSize=e.getUniformLocation(l,"uCellSize"),this.instanceDataBuffer=e.createBuffer(),this.aTexCoord=this.aInstanceOffset,this.aColorIndex=this.aInstanceUVs):(this.aTexCoord=e.getAttribLocation(l,"aTexCoord"),this.aColorIndex=e.getAttribLocation(l,"aColorIndex")),this.uResolution=e.getUniformLocation(l,"uResolution"),this.uTexture=e.getUniformLocation(l,"uTexture"),this.uPalette=e.getUniformLocation(l,"uPalette"),this.positionBuffer=e.createBuffer(),this.texCoordBuffer=e.createBuffer(),this.colorIndexBuffer=e.createBuffer(),this.indexBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this.positionBuffer),e.bufferData(e.ARRAY_BUFFER,this.renderPositions.byteLength,e.DYNAMIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this.texCoordBuffer),e.bufferData(e.ARRAY_BUFFER,this.renderTexCoords.byteLength,e.DYNAMIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this.colorIndexBuffer),e.bufferData(e.ARRAY_BUFFER,this.renderColorIndices.byteLength,e.DYNAMIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.renderIndices.byteLength,e.DYNAMIC_DRAW),this.vaoExtension&&(this.vao=this.vaoExtension.createVertexArrayOES(),this.vao&&(this.vaoExtension.bindVertexArrayOES(this.vao),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.enableVertexAttribArray(this.aTexCoord),e.vertexAttribPointer(this.aTexCoord,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this.colorIndexBuffer),e.enableVertexAttribArray(this.aColorIndex),e.vertexAttribPointer(this.aColorIndex,1,e.FLOAT,!1,0,0),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer),this.vaoExtension.bindVertexArrayOES(null))),e.enable(e.BLEND),e.blendFunc(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA),e.viewport(0,0,this.canvas.width,this.canvas.height)}compileShader(e,t){let i=this.gl,s=i.createShader(e);return s?(i.shaderSource(s,t),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 I(this.containerDiv,{strokeColor:"rgba(144, 24, 24, 1)",lineWidth:1,zIndex:10}),this.updateGridOverlay()}updateGridOverlay(){if(!this.gridOverlay)return;let e=this.cols*this.cellWidth,t=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,e,t,i,s),this.gridOverlay.render()}setBitmapFont(e,t,i,s=t,r=i){this.bitmapFont=e,this.fontLoaded=!0,this.charWidth=t,this.charHeight=i,this.cellWidth=s,this.cellHeight=r,this.glyphOffsetX=Math.round((this.cellWidth-this.charWidth)/2),this.glyphOffsetY=Math.round((this.cellHeight-this.charHeight)/2),this.useInstancing&&this.initInstancedBuffers(),this.generateAtlas(),this.updateCanvasSize()}generateAtlas(){if(!this.bitmapFont)return;this.atlasColumns=16;let e=256,t=this.atlasColumns*this.charWidth,s=Math.ceil(e/this.atlasColumns)*this.charHeight;this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=t,this.atlasCanvas.height=s;let r=this.atlasCanvas.getContext("2d",{willReadFrequently:!0});if(!r)return;r.clearRect(0,0,t,s);let l=Array.from(this.bitmapFont.keys());for(let o of l){let n=this.bitmapFont.get(o);if(!n)continue;let c=o%this.atlasColumns,h=Math.floor(o/this.atlasColumns),d=c*this.charWidth,u=h*this.charHeight;for(let m=0;m<this.charHeight&&!(m>=n.length);m++){let x=n[m];for(let f=0;f<this.charWidth;f++){let p=1<<7-f;x&p&&(r.fillStyle="#FFFFFF",r.fillRect(d+f,u+m,1,1))}}}this.cachedAtlasWidth=t,this.cachedAtlasHeight=s,this.createAtlasTexture(),this.charCodeToAtlasIndex.fill(65535);for(let o=0;o<e;o++)this.charCodeToAtlasIndex[o]=o}async setImageFontStructure(e,t,i,s,r){let l=this.atlasCanvas&&this.fontLoaded&&this.charWidth===Math.round(e)&&this.charHeight===Math.round(t),o=this.atlasCanvas;this.fontLoaded=!0,this.charWidth=Math.round(e),this.charHeight=Math.round(t),this.cellWidth=Math.round(i),this.cellHeight=Math.round(s),this.atlasColumns=y(r);let n=B(r);this.glyphOffsetX=Math.round((this.cellWidth-this.charWidth)/2),this.glyphOffsetY=Math.round((this.cellHeight-this.charHeight)/2),this.useInstancing&&this.initInstancedBuffers();let c=y(r);if(this.cachedAtlasWidth=c*this.charWidth,this.cachedAtlasHeight=c*this.charHeight,this.allocateAtlasTexture(this.cachedAtlasWidth,this.cachedAtlasHeight),l&&o){console.warn("[TerminalGL] \u267B\uFE0F Preserving existing BitmapFont as Block 0");let h=this.gl;h.bindTexture(h.TEXTURE_2D,this.atlasTexture),h.texSubImage2D(h.TEXTURE_2D,0,0,0,h.RGBA,h.UNSIGNED_BYTE,o)}this.charCodeToAtlasIndex.fill(65535);for(let h=0;h<=n;h++)this.charCodeToAtlasIndex[h]=h;this.precomputeImageFontUVs(r),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()}async setImageFontBlock(e,t){let i=this.gl;if(!this.atlasTexture)return;let s=new Blob([t],{type:"image/png"}),r=await createImageBitmap(s),l=this.atlasColumns/16,o=e%l,n=Math.floor(e/l),c=o*16*this.charWidth,h=n*16*this.charHeight;i.bindTexture(i.TEXTURE_2D,this.atlasTexture),i.texSubImage2D(i.TEXTURE_2D,0,c,h,i.RGBA,i.UNSIGNED_BYTE,r),r.close()}async setImageFont(e,t,i,s,r,l){this.fontLoaded=!0,this.charWidth=Math.round(t),this.charHeight=Math.round(i),this.cellWidth=Math.round(s),this.cellHeight=Math.round(r),this.atlasColumns=y(l);let o=B(l);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(e),this.charCodeToAtlasIndex.fill(65535);for(let n=0;n<=o;n++)this.charCodeToAtlasIndex[n]=n;this.precomputeImageFontUVs(l),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(e){return new Promise((t,i)=>{let s=new Uint8Array(e),r=new Blob([s],{type:"image/png"}),l=URL.createObjectURL(r),o=new Image;o.onload=()=>{URL.revokeObjectURL(l),this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=o.width,this.atlasCanvas.height=o.height;let n=this.atlasCanvas.getContext("2d");if(!n){i(new Error("Failed to create 2D context for atlas"));return}n.drawImage(o,0,0),this.cachedAtlasWidth=o.width,this.cachedAtlasHeight=o.height,this.createAtlasTexture(),t()},o.onerror=()=>{URL.revokeObjectURL(l),i(new Error("Failed to load PNG image for ImageFont atlas"))},o.src=l})}precomputeImageFontUVs(e){let t=e*256;this.atlasUVs=new Float32Array(t*4);let i=this.cachedAtlasWidth,s=this.cachedAtlasHeight,r=.5/i,l=.5/s;for(let o=0;o<t;o++){let{col:n,row:c}=L(o,e),h=(n*this.charWidth+r)/i,d=(c*this.charHeight+l)/s,u=((n+1)*this.charWidth-r)/i,m=((c+1)*this.charHeight-l)/s,x=o*4;this.atlasUVs[x]=h,this.atlasUVs[x+1]=d,this.atlasUVs[x+2]=u,this.atlasUVs[x+3]=m}}allocateAtlasTexture(e,t){try{let i=this.gl,s=i.createTexture();if(!s)throw new Error("Unable to create texture");i.bindTexture(i.TEXTURE_2D,s),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,e,t,0,i.RGBA,i.UNSIGNED_BYTE,null),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),this.atlasTexture=s}catch(i){throw console.error("[TerminalGL] \u274C Failed to create atlas texture:",i),i}}createAtlasTexture(){if(this.atlasCanvas)try{let e=this.gl,t=e.createTexture();if(!t)throw new Error("Unable to create texture");e.bindTexture(e.TEXTURE_2D,t),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.atlasCanvas),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),this.atlasTexture=t}catch(e){throw console.error("[TerminalGL] \u274C Failed to create atlas texture:",e),e}}clear(){let e=this.gl;e&&e.clear(e.COLOR_BUFFER_BIT)}parseColor(e){if(e.startsWith("#")){let t=e.slice(1),i=0,s=0,r=0;return t.length===3?(i=parseInt(t[0]+t[0],16),s=parseInt(t[1]+t[1],16),r=parseInt(t[2]+t[2],16)):t.length===6&&(i=parseInt(t.slice(0,2),16),s=parseInt(t.slice(2,4),16),r=parseInt(t.slice(4,6),16)),[i/255,s/255,r/255,1]}if(e.startsWith("rgb")){let t=e.match(/rgba?\(([^)]+)\)/);if(t){let i=t[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(e){console.error("[TerminalGL] \u274C Error in resize callback:",e)}}),this.resizeObserver.observe(this.parentElement),this.updateCanvasSize()}catch(e){console.error("[TerminalGL] \u274C Failed to setup ResizeObserver:",e)}}updateCanvasSize(){let e=this.parentElement.clientWidth,t=this.parentElement.clientHeight;if(e===0||t===0)return;let i=this.cols*this.cellWidth,s=this.rows*this.cellHeight;if(i===0||s===0)return;let r=e/i,l=t/s,o=Math.min(r,l),n;switch(this.scalingMode){case C.Integer:n=Math.max(1,Math.floor(o));break;case C.Half:n=Math.max(1,Math.floor(o*2)/2);break;case C.Quarter:n=Math.max(1,Math.floor(o*4)/4);break;case C.Eighth:n=Math.max(1,Math.floor(o*8)/8);break;case C.Responsive:n=1;break;case C.None:default:n=Math.max(.1,o);break}if(this.canvas.style.transform=`scale(${n})`,this.ambientEffectEnabled&&this.ambientEffectCanvas){let c=n*this.ambientEffectScale;this.ambientEffectCanvas.style.transform=`scale(${c})`}this.currentScale=n,this.onResizeCallback&&this.onResizeCallback(),this.showGrid&&this.gridOverlay&&this.updateGridOverlay()}updateAmbientEffect(){!this.ambientEffectCanvas||!this.ambientEffectCtx||this.ambientEffectCtx.drawImage(this.canvas,0,0)}setPalette(e){let t=0;for(let i=0;i<Math.min(e.length,256);i++){let s=e[i];t=(t<<5)-t+s.r,t=(t<<5)-t+s.g,t=(t<<5)-t+s.b,t=(t<<5)-t+s.a,t=t|0}if(t!==this.paletteHash){this.paletteHash=t;for(let i=0;i<e.length&&i<256;i++){let s=e[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 e=this.gl;this.paletteTexture||(this.paletteTexture=e.createTexture()),e.bindTexture(e.TEXTURE_2D,this.paletteTexture);let t=new Uint8Array(256*4);for(let i=0;i<256;i++){let s=i*4;t[s]=this.paletteFloat[s]*255,t[s+1]=this.paletteFloat[s+1]*255,t[s+2]=this.paletteFloat[s+2]*255,t[s+3]=this.paletteFloat[s+3]*255}e.texImage2D(e.TEXTURE_2D,0,e.RGBA,256,1,0,e.RGBA,e.UNSIGNED_BYTE,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null)}catch(e){throw console.error("[TerminalGL] \u274C Failed to update palette texture:",e),e}}renderDisplayData(e){try{if(!this.isReady()){console.warn("[TerminalGL] \u26A0\uFE0F Not ready: font not loaded yet");return}(e.width!==this.cols||e.height!==this.rows)&&this.resize(e.width,e.height),e.passes&&e.passes.length>0?this.renderMultiPass(e,e.passes):this.renderDirect(e),this.ambientEffectEnabled&&this.ambientEffectCanvas&&this.ambientEffectCtx&&this.updateAmbientEffect()}catch(t){console.error("[TerminalGL] \u274C Error rendering display data:",t)}}renderMultiPass(e,t){for(let i=0;i<t.length;i++){let s=t[i],r={id:e.id,width:e.width,height:e.height,palette:e.palette,cells:s.cells};this.renderDirect(r,i===0)}}renderDirect(e,t=!0){let i=this.gl;if(!this.staticPositionsInitialized&&!this.useInstancing&&this.precomputeStaticPositions(),t){if(this.canvasBgColor!==null){let s=this.parseColor(this.canvasBgColor);i.clearColor(s[0],s[1],s[2],s[3])}else i.clearColor(0,0,0,0);i.clear(i.COLOR_BUFFER_BIT)}this.useInstancing?this.renderInstanced(e):this.renderDirectBuffers(e)}renderInstanced(e){let t=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.renderDirectBuffers(e);return}let s=0,r=this.instanceData.length/8,l=e.width*e.height*2;if(l>r){console.error(`[TerminalGL] \u274C Instance buffer too small! Need ${l}, have ${r}. Display size: ${e.width}\xD7${e.height}, buffer was sized for smaller terminal.`),this.renderDirectBuffers(e);return}for(let n=0;n<e.height;n++)for(let c=0;c<e.width;c++){let h=e.cells[n*e.width+c],d=h.bgColorIndex,u=h.fgColorIndex,m=this.canvasBgColor!==null&&d===255,x=h.char===" "||u===255;if(!m){if(s>=r){console.error(`[TerminalGL] \u274C Instance buffer overflow! instanceIdx=${s}, max=${r}`);break}let f=s*8;this.instanceData[f]=c,this.instanceData[f+1]=n,this.instanceData[f+2]=0,this.instanceData[f+3]=0,this.instanceData[f+4]=0,this.instanceData[f+5]=0,this.instanceData[f+6]=d,this.instanceData[f+7]=0,s++}if(!x){let f=h.char.charCodeAt(0),p=this.charCodeToAtlasIndex[f];if(p!==65535){if(s>=r){console.error(`[TerminalGL] \u274C Instance buffer overflow! instanceIdx=${s}, max=${r}`);break}let E=p*4,v=s*8;this.instanceData[v]=c,this.instanceData[v+1]=n,this.instanceData[v+2]=this.atlasUVs[E],this.instanceData[v+3]=this.atlasUVs[E+1],this.instanceData[v+4]=this.atlasUVs[E+2],this.instanceData[v+5]=this.atlasUVs[E+3],this.instanceData[v+6]=0,this.instanceData[v+7]=u,s++}}}if(s===0){console.warn("[TerminalGL] \u26A0\uFE0F No instances to draw (all cells skipped)");return}t.bindBuffer(t.ARRAY_BUFFER,this.instanceDataBuffer),t.bufferSubData(t.ARRAY_BUFFER,0,this.instanceData.subarray(0,s*8)),t.useProgram(this.program),t.bindBuffer(t.ARRAY_BUFFER,this.positionBuffer),t.enableVertexAttribArray(this.aPosition),t.vertexAttribPointer(this.aPosition,2,t.FLOAT,!1,0,0),i.vertexAttribDivisorANGLE(this.aPosition,0),t.bindBuffer(t.ARRAY_BUFFER,this.instanceDataBuffer);let o=8*Float32Array.BYTES_PER_ELEMENT;t.enableVertexAttribArray(this.aInstanceOffset),t.vertexAttribPointer(this.aInstanceOffset,2,t.FLOAT,!1,o,0),i.vertexAttribDivisorANGLE(this.aInstanceOffset,1),t.enableVertexAttribArray(this.aInstanceUVs),t.vertexAttribPointer(this.aInstanceUVs,4,t.FLOAT,!1,o,2*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisorANGLE(this.aInstanceUVs,1),t.enableVertexAttribArray(this.aInstanceColors),t.vertexAttribPointer(this.aInstanceColors,2,t.FLOAT,!1,o,6*Float32Array.BYTES_PER_ELEMENT),i.vertexAttribDivisorANGLE(this.aInstanceColors,1),t.uniform2f(this.uResolution,this.canvas.width,this.canvas.height),t.uniform2f(this.uCellSize,this.cellWidth,this.cellHeight),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.atlasTexture),t.uniform1i(this.uTexture,0),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this.paletteTexture),t.uniform1i(this.uPalette,1),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),i.drawElementsInstancedANGLE(t.TRIANGLES,6,t.UNSIGNED_SHORT,0,s),i.vertexAttribDivisorANGLE(this.aPosition,0),i.vertexAttribDivisorANGLE(this.aInstanceOffset,0),i.vertexAttribDivisorANGLE(this.aInstanceUVs,0),i.vertexAttribDivisorANGLE(this.aInstanceColors,0)}renderDirectBuffers(e){let t=this.gl,i=e.width*e.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,l=0,o=e.cells,n=i;for(let x=0;x<n;x++){let f=o[x],p=f.bgColorIndex,v=this.canvasBgColor!==null&&p===255?255:p,w=0;for(let T=0;T<4;T++)this.renderTexCoords[r++]=w,this.renderTexCoords[r++]=w,this.renderColorIndices[l++]=v;let A=f.fgColorIndex,S=f.char;if(S===" "||A===255)for(let T=0;T<4;T++)this.renderTexCoords[r++]=0,this.renderTexCoords[r++]=0,this.renderColorIndices[l++]=255;else{let T=S.charCodeAt(0),P=this.charCodeToAtlasIndex[T];if(P!==65535){let R=P*4,G=this.atlasUVs[R],W=this.atlasUVs[R+1],O=this.atlasUVs[R+2],H=this.atlasUVs[R+3];this.renderTexCoords[r++]=G,this.renderTexCoords[r++]=W,this.renderColorIndices[l++]=A,this.renderTexCoords[r++]=O,this.renderTexCoords[r++]=W,this.renderColorIndices[l++]=A,this.renderTexCoords[r++]=G,this.renderTexCoords[r++]=H,this.renderColorIndices[l++]=A,this.renderTexCoords[r++]=O,this.renderTexCoords[r++]=H,this.renderColorIndices[l++]=A}else for(let R=0;R<4;R++)this.renderTexCoords[r++]=0,this.renderTexCoords[r++]=0,this.renderColorIndices[l++]=255}}(r!==n*2*4*2||l!==n*2*4)&&console.error("[TerminalGL] \u274C Buffer index mismatch!",{texIdx:r,colorIdx:l,expected:n*2*4}),t.useProgram(this.program),this.vao&&this.vaoExtension?(this.vaoExtension.bindVertexArrayOES(this.vao),t.bindBuffer(t.ARRAY_BUFFER,this.texCoordBuffer),t.bufferSubData(t.ARRAY_BUFFER,0,this.renderTexCoords.subarray(0,r)),t.bindBuffer(t.ARRAY_BUFFER,this.colorIndexBuffer),t.bufferSubData(t.ARRAY_BUFFER,0,this.renderColorIndices.subarray(0,l))):(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.bufferSubData(t.ARRAY_BUFFER,0,this.renderTexCoords.subarray(0,r)),t.enableVertexAttribArray(this.aTexCoord),t.vertexAttribPointer(this.aTexCoord,2,t.FLOAT,!1,0,0),t.bindBuffer(t.ARRAY_BUFFER,this.colorIndexBuffer),t.bufferSubData(t.ARRAY_BUFFER,0,this.renderColorIndices.subarray(0,l)),t.enableVertexAttribArray(this.aColorIndex),t.vertexAttribPointer(this.aColorIndex,1,t.FLOAT,!1,0,0));let c=this.canvas.width,h=this.canvas.height;(this.cachedResolution[0]!==c||this.cachedResolution[1]!==h)&&(t.uniform2f(this.uResolution,c,h),this.cachedResolution[0]=c,this.cachedResolution[1]=h),this.cachedTextureUnit!==0&&(t.activeTexture(t.TEXTURE0),this.cachedTextureUnit=0),t.bindTexture(t.TEXTURE_2D,this.atlasTexture),this.cachedTextureUniform||(t.uniform1i(this.uTexture,0),this.cachedTextureUniform=!0),this.cachedPaletteUnit!==1&&(t.activeTexture(t.TEXTURE1),this.cachedPaletteUnit=1),t.bindTexture(t.TEXTURE_2D,this.paletteTexture),this.cachedPaletteUniform||(t.uniform1i(this.uPalette,1),this.cachedPaletteUniform=!0),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer);let u=e.width*e.height*2*6,m=this.useUint16Indices?t.UNSIGNED_SHORT:t.UNSIGNED_INT;t.drawElements(t.TRIANGLES,u,m,0)}resize(e,t){if(!Number.isInteger(e)||e<=0){console.error(`[TerminalGL] \u274C Invalid cols: ${e}. Must be positive integer.`);return}if(!Number.isInteger(t)||t<=0){console.error(`[TerminalGL] \u274C Invalid rows: ${t}. Must be positive integer.`);return}if(e===this.cols&&t===this.rows)return;let i=e*t,s=this.useInstancing?262144:this.useUint16Indices?8191:262144;if(i>s){let h=Math.floor(Math.sqrt(s));console.error(`[TerminalGL] \u274C Cannot resize to ${e}\xD7${t} (${i} cells). Device limit: ${s} cells (max ~${h}\xD7${h}). ${!this.useInstancing&&this.useUint16Indices?"Device lacks OES_element_index_uint extension.":""}`);return}let r=U.checkCompatibility();i>r.recommendedMaxCells&&console.warn(`[TerminalGL] \u26A0\uFE0F Resizing to ${e}\xD7${t} (${i} cells) exceeds recommended limit (${r.recommendedMaxCells} cells). Performance may degrade.`),this.cols=e,this.rows=t,this.staticPositionsInitialized=!1;let l=this.cols*this.rows*2,o=Math.ceil(l*1.5),n=l>this.maxCells,c=this.maxCells>o*4;if(console.warn(`[TerminalGL] \u{1F4D0} resize check: cols=${e}, rows=${t}, newMaxCells=${l}, this.maxCells=${this.maxCells}, needGrow=${n}, needShrink=${c}`),n||c){let h=this.maxCells;if(this.maxCells=o,console.warn(`[TerminalGL] \u{1F4D0} resize realloc: ${h} \u2192 ${this.maxCells} (needGrow=${n}, needShrink=${c})`),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.useInstancing&&this.instanceDataBuffer){this.instanceData=new Float32Array(this.maxCells*8);let f=this.gl;f.bindBuffer(f.ARRAY_BUFFER,this.instanceDataBuffer),f.bufferData(f.ARRAY_BUFFER,this.instanceData.byteLength,f.DYNAMIC_DRAW)}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),this.useInstancing||(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 u=n?"\u{1F4C8} Growing":"\u{1F4C9} Shrinking",m=h*160/1048576,x=this.maxCells*160/1048576;console.warn(`[TerminalGL] ${u} buffers: ${m.toFixed(2)}MB \u2192 ${x.toFixed(2)}MB (${h} \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.canvas.style.width=`${this.canvas.width}px`,this.canvas.style.height=`${this.canvas.height}px`,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(e){this.onResizeCallback=e}clearOnResizeCallback(){this.onResizeCallback=void 0}getAvailableSize(){return{width:this.parentElement.clientWidth,height:this.parentElement.clientHeight}}setScalingMode(e){this.scalingMode!==e&&(this.scalingMode=e,this.updateCanvasSize())}getScalingMode(){return this.scalingMode}setCellSize(e,t){let i=Math.max(1,Math.min(255,Math.round(e))),s=Math.max(1,Math.min(255,Math.round(t)));this.cellWidth===i&&this.cellHeight===s||(this.cellWidth=i,this.cellHeight=s,this.charWidth=i,this.charHeight=s,this.glyphOffsetX=Math.round((this.cellWidth-this.charWidth)/2),this.glyphOffsetY=Math.round((this.cellHeight-this.charHeight)/2),this.useInstancing&&this.initInstancedBuffers(),this.updateCanvasSize())}getCellSize(){return{cellWidth:this.cellWidth,cellHeight:this.cellHeight}}getMaxCells(){return this.useInstancing?262144:this.useUint16Indices?8191:262144}setGrid(e){e.enabled?(this.gridOverlay?this.gridOverlay.setStyle({strokeColor:e.color,lineWidth:e.lineWidth}):this.gridOverlay=new I(this.containerDiv,{strokeColor:e.color??"rgba(144, 24, 24, 1)",lineWidth:e.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(e){typeof e=="boolean"?this.ambientEffectEnabled=e:(this.ambientEffectEnabled=!0,e.blur!==void 0&&(this.ambientEffectBlur=e.blur),e.scale!==void 0&&(this.ambientEffectScale=e.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=`
|
|
120
120
|
display: block !important;
|
|
121
121
|
position: absolute !important;
|
|
122
122
|
width: ${this.canvas.width}px !important;
|
|
@@ -127,4 +127,4 @@ var $=Object.defineProperty;var V=(v,e,t)=>e in v?$(v,e,{enumerable:!0,configura
|
|
|
127
127
|
transform: scale(${this.ambientEffectScale}) !important;
|
|
128
128
|
pointer-events: none !important;
|
|
129
129
|
z-index: 0 !important;
|
|
130
|
-
`,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 e=this.gl;this.program&&e.deleteProgram(this.program),this.positionBuffer&&e.deleteBuffer(this.positionBuffer),this.texCoordBuffer&&e.deleteBuffer(this.texCoordBuffer),this.colorIndexBuffer&&e.deleteBuffer(this.colorIndexBuffer),this.indexBuffer&&e.deleteBuffer(this.indexBuffer),this.instanceDataBuffer&&e.deleteBuffer(this.instanceDataBuffer),this.atlasTexture&&e.deleteTexture(this.atlasTexture),this.paletteTexture&&e.deleteTexture(this.paletteTexture),this.vao&&this.vaoExtension&&this.vaoExtension.deleteVertexArrayOES(this.vao);let t=e.getExtension("WEBGL_lose_context");t&&t.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)}};
|
|
130
|
+
`,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 e=this.gl;this.program&&e.deleteProgram(this.program),this.positionBuffer&&e.deleteBuffer(this.positionBuffer),this.texCoordBuffer&&e.deleteBuffer(this.texCoordBuffer),this.colorIndexBuffer&&e.deleteBuffer(this.colorIndexBuffer),this.indexBuffer&&e.deleteBuffer(this.indexBuffer),this.instanceDataBuffer&&e.deleteBuffer(this.instanceDataBuffer),this.atlasTexture&&e.deleteTexture(this.atlasTexture),this.paletteTexture&&e.deleteTexture(this.paletteTexture),this.vao&&this.vaoExtension&&this.vaoExtension.deleteVertexArrayOES(this.vao);let t=e.getExtension("WEBGL_lose_context");t&&t.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)}};g(U,"TerminalGL");var D=U;var M=["#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 Y(b,e=M){return b<0||b>=e.length?"#ff00ff":e[b]}g(Y,"paletteIndexToColor");function k(b,e=M){let t=e.indexOf(b.toLowerCase());return t>=0?t:0}g(k,"colorToPaletteIndex");export{M as DEFAULT_PALETTE,I as GridOverlay,C as ScalingMode,D as TerminalGL,k as colorToPaletteIndex,y as getAtlasColumns,L as getCharGridPosition,B as getMaxCharCode,Y as paletteIndexToColor};
|