@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.mjs CHANGED
@@ -1,11 +1,11 @@
1
- var F=Object.defineProperty;var O=(u,t,e)=>t in u?F(u,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):u[t]=e;var f=(u,t)=>F(u,"name",{value:t,configurable:!0});var h=(u,t,e)=>(O(u,typeof t!="symbol"?t+"":t,e),e);var E=class E{constructor(t,e,i,s,n){h(this,"atlases");h(this,"charMap");h(this,"baseCharWidth");h(this,"baseCharHeight");h(this,"baseCellWidth");h(this,"baseCellHeight");h(this,"atlasColumns",16);h(this,"font");h(this,"SCALES",[1,2,4,8]);h(this,"colorCache",new Map);h(this,"MAX_CACHE_SIZE",512);this.font=t,this.baseCharWidth=e,this.baseCharHeight=i,this.baseCellWidth=s??e,this.baseCellHeight=n??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,n=Math.floor(t/this.atlasColumns);this.charMap.set(e,{x:s*this.baseCharWidth,y:n*this.baseCharHeight});for(let r of this.SCALES){let a=this.getOrCreateAtlas(r),l=s*a.charWidth,o=n*a.charHeight;this.renderBitmapToAtlas(a,i,l,o)}t++}}getOrCreateAtlas(t){let e=this.atlases.get(t);if(!e){let i=this.baseCharWidth*t,s=this.baseCharHeight*t,r=Math.ceil(256/this.atlasColumns),a=document.createElement("canvas");a.width=this.atlasColumns*i,a.height=r*s;let l=a.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!l)throw new Error(`Impossible de cr\xE9er le contexte 2D pour l'atlas ${t}x`);l.imageSmoothingEnabled=!1,e={canvas:a,ctx:l,scale:t,charWidth:i,charHeight:s},this.atlases.set(t,e)}return e}renderBitmapToAtlas(t,e,i,s){let n=t.scale,r=t.ctx;r.fillStyle="#ffffff";for(let a=0;a<Math.min(e.length,this.baseCharHeight);a++){let l=e[a];for(let o=0;o<this.baseCharWidth;o++){let c=1<<7-o;l&c&&r.fillRect(i+o*n,s+a*n,n,n)}}}drawChar(t,e,i,s,n,r,a){let l=this.charMap.get(e);if(!l)return;let o=`${e}:${a}`,c=this.colorCache.get(o);if(c)c.lastUsed=performance.now();else{let p=this.createColoredGlyph(e,a,l);if(!p)return;c={canvas:p,lastUsed:performance.now()},this.colorCache.set(o,c),this.colorCache.size>this.MAX_CACHE_SIZE&&this.evictLRU()}let d=n/this.baseCellWidth,m=r/this.baseCellHeight,g=(this.baseCellWidth-this.baseCharWidth)/2*d,w=(this.baseCellHeight-this.baseCharHeight)/2*m,b=this.baseCharWidth*d,C=this.baseCharHeight*m;t.drawImage(c.canvas,i+g,s+w,b,C)}createColoredGlyph(t,e,i){let s=this.atlases.get(1);if(!s)return null;let n=s.ctx.getImageData(i.x,i.y,this.baseCharWidth,this.baseCharHeight),r=n.data,a=this.hexToRgb(e);for(let c=0;c<r.length;c+=4)r[c+3]>0&&(r[c]=a.r,r[c+1]=a.g,r[c+2]=a.b);let l=document.createElement("canvas");l.width=this.baseCharWidth,l.height=this.baseCharHeight;let o=l.getContext("2d",{alpha:!0});return o?(o.imageSmoothingEnabled=!1,o.putImageData(n,0,0),l):null}hexToRgb(t){if(t.startsWith("#")){let n=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;t=t.replace(n,(a,l,o,c)=>l+l+o+o+c+c);let r=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return r?{r:parseInt(r[1],16),g:parseInt(r[2],16),b:parseInt(r[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()}};f(E,"BitmapFontAtlas");var M=E;function D(u){return Math.sqrt(u)*16}f(D,"getAtlasColumns");function A(u){return u*256-1}f(A,"getMaxCharCode");function W(u,t){let e=Math.floor(u/256),i=u%256,s=Math.sqrt(t),n=e%s,r=Math.floor(e/s),a=i%16,l=Math.floor(i/16);return{col:n*16+a,row:r*16+l}}f(W,"getCharGridPosition");var I=class I{constructor(t){h(this,"atlasCanvas",null);h(this,"atlasCtx",null);h(this,"atlasImage",null);h(this,"glyphWidth");h(this,"glyphHeight");h(this,"cellWidth");h(this,"cellHeight");h(this,"atlasBlocks");h(this,"atlasColumns");h(this,"maxCharCode");h(this,"isLoaded",!1);h(this,"colorCache",new Map);h(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=D(t.atlasBlocks),this.maxCharCode=A(t.atlasBlocks)}async loadFromPNG(t){return new Promise((e,i)=>{let s=new Uint8Array(t),n=new Blob([s],{type:"image/png"}),r=URL.createObjectURL(n),a=new Image;a.onload=()=>{URL.revokeObjectURL(r);let l=this.atlasColumns*this.glyphWidth,o=this.atlasColumns*this.glyphHeight;if((a.width!==l||a.height!==o)&&console.warn(`ImageFontAtlas: Image size ${a.width}\xD7${a.height} doesn't match expected ${l}\xD7${o} for ${this.atlasBlocks} block(s) with ${this.glyphWidth}\xD7${this.glyphHeight} glyphs`),this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=a.width,this.atlasCanvas.height=a.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(a,0,0),this.atlasImage=a,this.isLoaded=!0,e()},a.onerror=()=>{URL.revokeObjectURL(r),i(new Error("Failed to load PNG image for atlas"))},a.src=r})}isReady(){return this.isLoaded}getGlyphPosition(t){if(t<0||t>this.maxCharCode)return null;let{col:e,row:i}=W(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}=W(t,this.atlasBlocks),s=e/this.atlasColumns,n=i/this.atlasColumns,r=(e+1)/this.atlasColumns,a=(i+1)/this.atlasColumns;return{u1:s,v1:n,u2:r,v2:a}}drawChar(t,e,i,s,n,r,a){if(!this.isLoaded||!this.atlasCanvas)return;let l=this.getGlyphPosition(e);if(!l)return;let o=`${e}:${a}`,c=this.colorCache.get(o);if(c)c.lastUsed=performance.now();else{let m=this.createColoredGlyph(e,a,l);if(!m)return;c={canvas:m,lastUsed:performance.now()},this.colorCache.set(o,c),this.colorCache.size>this.MAX_CACHE_SIZE&&this.evictLRU()}if(t.imageSmoothingEnabled=!1,n===this.cellWidth&&r===this.cellHeight){let m=Math.floor((this.cellWidth-this.glyphWidth)/2),g=Math.floor((this.cellHeight-this.glyphHeight)/2);t.drawImage(c.canvas,Math.floor(i)+m,Math.floor(s)+g)}else{let m=n/this.cellWidth,g=r/this.cellHeight,w=Math.floor((this.cellWidth-this.glyphWidth)/2*m),b=Math.floor((this.cellHeight-this.glyphHeight)/2*g),C=Math.ceil(this.glyphWidth*m),p=Math.ceil(this.glyphHeight*g);t.drawImage(c.canvas,Math.floor(i)+w,Math.floor(s)+b,C,p)}}createColoredGlyph(t,e,i){if(!this.atlasCtx)return null;let s=this.atlasCtx.getImageData(i.x,i.y,this.glyphWidth,this.glyphHeight),n=s.data,r=this.parseColor(e);for(let o=0;o<n.length;o+=4)n[o+3]>0&&(n[o]=r.r,n[o+1]=r.g,n[o+2]=r.b);let a=document.createElement("canvas");a.width=this.glyphWidth,a.height=this.glyphHeight;let l=a.getContext("2d",{alpha:!0});return l?(l.putImageData(s,0,0),a):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}};f(I,"ImageFontAtlas");var H=I;var S=class S{constructor(t,e){h(this,"canvas");h(this,"ctx");h(this,"container");h(this,"cols",0);h(this,"rows",0);h(this,"cellWidth",0);h(this,"cellHeight",0);h(this,"offsetX",0);h(this,"offsetY",0);h(this,"strokeColor","rgba(80, 80, 80, 0.4)");h(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 E=Object.defineProperty;var B=(g,t,e)=>t in g?E(g,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):g[t]=e;var u=(g,t)=>E(g,"name",{value:t,configurable:!0});var h=(g,t,e)=>(B(g,typeof t!="symbol"?t+"":t,e),e);function w(g){return Math.sqrt(g)*16}u(w,"getAtlasColumns");function x(g){return g*256-1}u(x,"getMaxCharCode");function b(g,t){let e=Math.floor(g/256),i=g%256,s=Math.sqrt(t),n=e%s,l=Math.floor(e/s),r=i%16,a=Math.floor(i/16);return{col:n*16+r,row:l*16+a}}u(b,"getCharGridPosition");var y=class y{constructor(t){h(this,"atlasCanvas",null);h(this,"atlasCtx",null);h(this,"atlasImage",null);h(this,"glyphWidth");h(this,"glyphHeight");h(this,"cellWidth");h(this,"cellHeight");h(this,"atlasBlocks");h(this,"atlasColumns");h(this,"maxCharCode");h(this,"isLoaded",!1);h(this,"colorCache",new Map);h(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=w(t.atlasBlocks),this.maxCharCode=x(t.atlasBlocks)}getCanvas(){return this.atlasCanvas}getGlyphWidth(){return this.glyphWidth}getGlyphHeight(){return this.glyphHeight}prepare(){let t=this.atlasColumns*this.glyphWidth,e=this.atlasColumns*this.glyphHeight;this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=t,this.atlasCanvas.height=e,this.atlasCtx=this.atlasCanvas.getContext("2d",{alpha:!0,willReadFrequently:!0}),this.atlasCtx&&(this.atlasCtx.imageSmoothingEnabled=!1,this.atlasCtx.clearRect(0,0,t,e)),this.isLoaded=!0}async loadBlock(t,e){return(!this.atlasCanvas||!this.atlasCtx)&&this.prepare(),new Promise((i,s)=>{let n=new Uint8Array(e),l=new Blob([n],{type:"image/png"}),r=URL.createObjectURL(l),a=new Image;a.onload=()=>{URL.revokeObjectURL(r);let o=Math.sqrt(this.atlasBlocks),c=t%o,d=Math.floor(t/o),m=c*16*this.glyphWidth,f=d*16*this.glyphHeight;this.atlasCtx.drawImage(a,m,f),this.colorCache.clear(),i()},a.onerror=()=>{URL.revokeObjectURL(r),s(new Error(`Failed to load PNG for block ${t}`))},a.src=r})}async loadFromPNG(t){return new Promise((e,i)=>{let s=new Uint8Array(t),n=new Blob([s],{type:"image/png"}),l=URL.createObjectURL(n),r=new Image;r.onload=()=>{URL.revokeObjectURL(l);let a=this.atlasColumns*this.glyphWidth,o=this.atlasColumns*this.glyphHeight;if((r.width!==a||r.height!==o)&&console.warn(`ImageFontAtlas: Image size ${r.width}\xD7${r.height} doesn't match expected ${a}\xD7${o} for ${this.atlasBlocks} block(s) with ${this.glyphWidth}\xD7${this.glyphHeight} glyphs`),this.atlasCanvas=document.createElement("canvas"),this.atlasCanvas.width=r.width,this.atlasCanvas.height=r.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(r,0,0),this.atlasImage=r,this.isLoaded=!0,e()},r.onerror=()=>{URL.revokeObjectURL(l),i(new Error("Failed to load PNG image for atlas"))},r.src=l})}isReady(){return this.isLoaded}getGlyphPosition(t){if(t<0||t>this.maxCharCode)return null;let{col:e,row:i}=b(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}=b(t,this.atlasBlocks),s=e/this.atlasColumns,n=i/this.atlasColumns,l=(e+1)/this.atlasColumns,r=(i+1)/this.atlasColumns;return{u1:s,v1:n,u2:l,v2:r}}drawChar(t,e,i,s,n,l,r){if(!this.isLoaded||!this.atlasCanvas)return;let a=this.getGlyphPosition(e);if(!a)return;let o=`${e}:${r}`,c=this.colorCache.get(o);if(c)c.lastUsed=performance.now();else{let m=this.createColoredGlyph(e,r,a);if(!m)return;c={canvas:m,lastUsed:performance.now()},this.colorCache.set(o,c),this.colorCache.size>this.MAX_CACHE_SIZE&&this.evictLRU()}if(t.imageSmoothingEnabled=!1,n===this.cellWidth&&l===this.cellHeight){let m=Math.floor((this.cellWidth-this.glyphWidth)/2),f=Math.floor((this.cellHeight-this.glyphHeight)/2);t.drawImage(c.canvas,Math.floor(i)+m,Math.floor(s)+f)}else{let m=n/this.cellWidth,f=l/this.cellHeight,G=Math.floor((this.cellWidth-this.glyphWidth)/2*m),A=Math.floor((this.cellHeight-this.glyphHeight)/2*f),k=Math.ceil(this.glyphWidth*m),D=Math.ceil(this.glyphHeight*f);t.drawImage(c.canvas,Math.floor(i)+G,Math.floor(s)+A,k,D)}}createColoredGlyph(t,e,i){if(!this.atlasCtx)return null;let s=this.atlasCtx.getImageData(i.x,i.y,this.glyphWidth,this.glyphHeight),n=s.data,l=this.parseColor(e);for(let o=0;o<n.length;o+=4)n[o+3]>0&&(n[o]=n[o]*l.r/255,n[o+1]=n[o+1]*l.g/255,n[o+2]=n[o+2]*l.b/255);let r=document.createElement("canvas");r.width=this.glyphWidth,r.height=this.glyphHeight;let a=r.getContext("2d",{alpha:!0});return a?(a.putImageData(s,0,0),r):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}};u(y,"ImageFontAtlas");var C=y;var M=class M{constructor(t,e){h(this,"canvas");h(this,"ctx");h(this,"container");h(this,"cols",0);h(this,"rows",0);h(this,"cellWidth",0);h(this,"cellHeight",0);h(this,"offsetX",0);h(this,"offsetY",0);h(this,"strokeColor","rgba(80, 80, 80, 0.4)");h(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,n=0,r=0){this.cols=t,this.rows=e,this.cellWidth=i,this.cellHeight=s,this.offsetX=n,this.offsetY=r}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,n){let r=s.left-n.left,a=s.top-n.top,l=s.width,o=s.height;(this.canvas.width!==l||this.canvas.height!==o)&&(this.canvas.width=l,this.canvas.height=o);let c=this.canvas.style;c.width=`${l}px`,c.height=`${o}px`,c.left=`${r}px`,c.top=`${a}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,n=Math.min(i,s),r=this.cellWidth*n,a=this.cellHeight*n,l=this.cols*r,o=this.rows*a,c=this.offsetX*n,d=this.offsetY*n;if(!(l===0||o===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*n),this.ctx.beginPath();for(let m=0;m<=this.cols;m++){let g=c+m*r+.5;this.ctx.moveTo(g,d),this.ctx.lineTo(g,d+o)}for(let m=0;m<=this.rows;m++){let g=d+m*a+.5;this.ctx.moveTo(c,g),this.ctx.lineTo(c+l,g)}this.ctx.stroke()}}update(t,e,i,s,n,r,a=0,l=0){this.setDimensions(t,e,i,s,a,l),this.setCanvasSize(n,r),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}};f(S,"GridOverlay");var y=S;import{ScalingMode as v}from"@utsp/types";var T=class T{constructor(t,e={}){h(this,"containerDiv");h(this,"canvas");h(this,"ctx");h(this,"parentElement");h(this,"cells");h(this,"cols",0);h(this,"rows",0);h(this,"fontSize");h(this,"fontFamily");h(this,"defaultFgColor");h(this,"defaultBgColor");h(this,"canvasBgColor");h(this,"cellWidth");h(this,"cellHeight");h(this,"offsetX",0);h(this,"offsetY",0);h(this,"fontType","web");h(this,"bitmapFont");h(this,"bitmapAtlas");h(this,"imageAtlas");h(this,"bitmapCharWidth",8);h(this,"bitmapCharHeight",8);h(this,"showDebugGrid");h(this,"debugGridColor");h(this,"gridOverlay");h(this,"fixedGridMode");h(this,"fixedCols");h(this,"fixedRows");h(this,"cellAspectRatio");h(this,"resizeObserver");h(this,"imageDataBuffer");h(this,"useImageDataRendering",!1);h(this,"paletteCache");h(this,"scalingMode",v.None);h(this,"currentScale",1);h(this,"customCellSize",!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??1,this.cellWidth=e.cellWidth??8,this.cellHeight=e.cellHeight??8,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??v.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=`
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,n=0,l=0){this.cols=t,this.rows=e,this.cellWidth=i,this.cellHeight=s,this.offsetX=n,this.offsetY=l}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,n){let l=s.left-n.left,r=s.top-n.top,a=s.width,o=s.height;(this.canvas.width!==a||this.canvas.height!==o)&&(this.canvas.width=a,this.canvas.height=o);let c=this.canvas.style;c.width=`${a}px`,c.height=`${o}px`,c.left=`${l}px`,c.top=`${r}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,n=Math.min(i,s),l=this.cellWidth*n,r=this.cellHeight*n,a=this.cols*l,o=this.rows*r,c=this.offsetX*n,d=this.offsetY*n;if(!(a===0||o===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*n),this.ctx.beginPath();for(let m=0;m<=this.cols;m++){let f=c+m*l+.5;this.ctx.moveTo(f,d),this.ctx.lineTo(f,d+o)}for(let m=0;m<=this.rows;m++){let f=d+m*r+.5;this.ctx.moveTo(c,f),this.ctx.lineTo(c+a,f)}this.ctx.stroke()}}update(t,e,i,s,n,l,r=0,a=0){this.setDimensions(t,e,i,s,r,a),this.setCanvasSize(n,l),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}};u(M,"GridOverlay");var v=M;import{ScalingMode as p}from"@utsp/types";var W=class W{constructor(t,e={}){h(this,"containerDiv");h(this,"canvas");h(this,"ctx");h(this,"parentElement");h(this,"cells");h(this,"cols",0);h(this,"rows",0);h(this,"defaultFgColor");h(this,"defaultBgColor");h(this,"canvasBgColor");h(this,"cellWidth");h(this,"cellHeight");h(this,"offsetX",0);h(this,"offsetY",0);h(this,"imageAtlas");h(this,"showDebugGrid");h(this,"debugGridColor");h(this,"gridOverlay");h(this,"fixedGridMode");h(this,"fixedCols");h(this,"fixedRows");h(this,"cellAspectRatio");h(this,"resizeObserver");h(this,"paletteCache");h(this,"scalingMode",p.None);h(this,"currentScale",1);h(this,"customCellSize",!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??1,this.cellWidth=e.cellWidth??8,this.cellHeight=e.cellHeight??8,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??p.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=`
9
9
  position: absolute !important;
10
10
  top: 0 !important;
11
11
  left: 0 !important;
@@ -20,7 +20,7 @@ var F=Object.defineProperty;var O=(u,t,e)=>t in u?F(u,t,{enumerable:!0,configura
20
20
  align-items: center !important;
21
21
  isolation: isolate !important;
22
22
  pointer-events: none !important;
23
- `,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 y(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;if(!this.customCellSize){let o,c;if(this.fontType==="image"&&this.imageAtlas){let d=this.imageAtlas.getCellDimensions();o=d.width,c=d.height}else this.fontType==="bitmap"?(o=this.bitmapCharWidth,c=this.bitmapCharHeight):(o=Math.round(this.cellWidth)||10,c=Math.round(this.cellHeight)||14);this.cellWidth=Math.round(o),this.cellHeight=Math.round(c)}this.scalingMode===v.Responsive?(this.cols=Math.floor(t/this.cellWidth)||1,this.rows=Math.floor(e/this.cellHeight)||1):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 i=this.cols*this.cellWidth,s=this.rows*this.cellHeight,n=t/i,r=e/s,a=Math.min(n,r),l;switch(this.scalingMode){case v.Integer:l=Math.max(1,Math.floor(a));break;case v.Half:l=Math.max(.5,Math.floor(a*2)/2);break;case v.Quarter:l=Math.max(.25,Math.floor(a*4)/4);break;case v.Eighth:l=Math.max(.125,Math.floor(a*8)/8);break;case v.Responsive:l=1;break;case v.None:default:l=Math.max(.1,a);break}this.currentScale=l,this.canvas.width=i,this.canvas.height=s,this.ctx.imageSmoothingEnabled=!1,this.canvas.style.cssText=`
23
+ `,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 v(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;if(!this.customCellSize){let o,c;if(this.imageAtlas){let d=this.imageAtlas.getCellDimensions();o=d.width,c=d.height}else o=this.cellWidth,c=this.cellHeight;this.cellWidth=Math.round(o),this.cellHeight=Math.round(c)}this.scalingMode===p.Responsive?(this.cols=Math.floor(t/this.cellWidth)||1,this.rows=Math.floor(e/this.cellHeight)||1):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 i=this.cols*this.cellWidth,s=this.rows*this.cellHeight,n=t/i,l=e/s,r=Math.min(n,l),a;switch(this.scalingMode){case p.Integer:a=Math.max(1,Math.floor(r));break;case p.Half:a=Math.max(.5,Math.floor(r*2)/2);break;case p.Quarter:a=Math.max(.25,Math.floor(r*4)/4);break;case p.Eighth:a=Math.max(.125,Math.floor(r*8)/8);break;case p.Responsive:a=1;break;case p.None:default:a=Math.max(.1,r);break}this.currentScale=a,this.canvas.width=i,this.canvas.height=s,this.ctx.imageSmoothingEnabled=!1,this.canvas.style.cssText=`
24
24
  flex-shrink: 0 !important;
25
25
  flex-grow: 0 !important;
26
26
  width: ${i}px !important;
@@ -29,9 +29,9 @@ var F=Object.defineProperty;var O=(u,t,e)=>t in u?F(u,t,{enumerable:!0,configura
29
29
  image-rendering: crisp-edges !important;
30
30
  -ms-interpolation-mode: nearest-neighbor !important;
31
31
  transform-origin: center center !important;
32
- transform: scale(${l}) !important;
32
+ transform: scale(${a}) !important;
33
33
  will-change: transform !important;
34
34
  backface-visibility: hidden !important;
35
35
  pointer-events: auto !important;
36
36
  touch-action: none !important;
37
- `,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),n=Math.min(e,this.rows);for(let r=0;r<n;r++)for(let a=0;a<s;a++)this.cells[r][a]=i[r][a]}this.render()}),this.resizeObserver.observe(this.parentElement)}setCell(t,e,i,s,n){if(e<0||e>=this.rows||t<0||t>=this.cols)return;let r=i&&typeof i=="string"?i.charAt(0):" ";this.cells[e][t]={char:r,fgColor:s??this.defaultFgColor,bgColor:n??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,n){for(let r=0;r<i.length;r++)this.setCell(t+r,e,i[r],s,n)}fillRect(t,e,i,s,n=" ",r,a){for(let l=e;l<e+s;l++)for(let o=t;o<t+i;o++)this.setCell(o,l,n,r,a)}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 n=0;n<t.width;n++){let r=t.cells[i];s<this.rows&&n<this.cols&&this.setCell(n,s,r.char,r.fgColor,r.bgColor),i++}}render(t=!0){if(this.fontType==="bitmap"&&this.bitmapFont&&this.useImageDataRendering){this.renderWithImageData(t);return}this.renderClassic(t)}renderWithImageData(t=!0){if(!this.bitmapFont)return;let e=this.cols*this.bitmapCharWidth,i=this.rows*this.bitmapCharHeight;(!this.imageDataBuffer||this.imageDataBuffer.width!==e||this.imageDataBuffer.height!==i)&&(this.imageDataBuffer=this.ctx.createImageData(e,i));let s=this.imageDataBuffer.data;for(let o=0;o<this.rows;o++)for(let c=0;c<this.cols;c++){let d=this.cells[o][c],m=this.parseColorToRGB(d.bgColor),g=this.parseColorToRGB(d.fgColor),w=d.char.charCodeAt(0),b=this.bitmapFont.get(w);for(let C=0;C<this.bitmapCharHeight;C++)for(let p=0;p<this.bitmapCharWidth;p++){let R=c*this.bitmapCharWidth+p,x=((o*this.bitmapCharHeight+C)*e+R)*4,k=!1;if(b&&C<b.length){let z=b[C],L=1<<7-p;k=(z&L)!==0}k?(s[x]=g.r,s[x+1]=g.g,s[x+2]=g.b,s[x+3]=g.a):(s[x]=m.r,s[x+1]=m.g,s[x+2]=m.b,s[x+3]=m.a)}}t&&(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 n=document.createElement("canvas");n.width=e,n.height=i,n.getContext("2d").putImageData(this.imageDataBuffer,0,0);let a=this.cols*this.cellWidth,l=this.rows*this.cellHeight;this.ctx.drawImage(n,0,0,e,i,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 n=/^#?([a-f\d])([a-f\d])([a-f\d])$/i;t=t.replace(n,(a,l,o,c)=>l+l+o+o+c+c);let r=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(r)return{r:parseInt(r[1],16),g:parseInt(r[2],16),b:parseInt(r[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(t=!0){t&&(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 e=0;e<this.rows;e++)for(let i=0;i<this.cols;i++){let s=this.cells[e][i],n=Math.floor(this.offsetX+i*this.cellWidth),r=Math.floor(this.offsetY+e*this.cellHeight),a=Math.floor(this.offsetX+(i+1)*this.cellWidth),l=Math.floor(this.offsetY+(e+1)*this.cellHeight),o=a-n,c=l-r;if((this.canvasBgColor!==null||s.bgColor!==this.defaultBgColor)&&(this.ctx.fillStyle=s.bgColor,this.ctx.fillRect(n,r,o,c)),s.char!==" ")if(this.fontType==="image"&&this.imageAtlas){let m=s.char.charCodeAt(0);this.imageAtlas.drawChar(this.ctx,m,n,r,o,c,s.fgColor)}else if(this.fontType==="bitmap"&&this.bitmapFont)this.drawBitmapChar(s.char,n,r,o,c,s.fgColor);else{this.ctx.fillStyle=s.fgColor;let m=n+(o-this.ctx.measureText(s.char).width)/2,g=r+(c-this.fontSize)/2;this.ctx.fillText(s.char,m,g)}}this.showDebugGrid&&this.drawDebugGrid()}drawBitmapChar(t,e,i,s,n,r){let a=t.charCodeAt(0);if(this.bitmapAtlas){this.bitmapAtlas.drawChar(this.ctx,a,e,i,s,n,r);return}if(!this.bitmapFont)return;let l=this.bitmapFont.get(a);if(!l)return;let o=s/this.bitmapCharWidth,c=n/this.bitmapCharHeight;this.ctx.fillStyle=r;for(let d=0;d<Math.min(l.length,this.bitmapCharHeight);d++){let m=l[d],g=i+d*c,w=i+(d+1)*c;for(let b=0;b<this.bitmapCharWidth;b++){let C=1<<7-b;if(m&C){let p=e+b*o,R=e+(b+1)*o;this.ctx.fillRect(p,g,R-p,w-g)}}}}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 y(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,n=this.rows,r=this.cells;if(this.calculateGridSize(),this.cols!==s||this.rows!==n){this.cells=this.createEmptyGrid();let a=Math.min(s,this.cols),l=Math.min(n,this.rows);for(let o=0;o<l;o++)for(let c=0;c<a;c++)this.cells[o][c]=r[o][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,n=this.cells;if(this.calculateGridSize(),this.cols!==i||this.rows!==s){this.cells=this.createEmptyGrid();let r=Math.min(i,this.cols),a=Math.min(s,this.rows);for(let l=0;l<a;l++)for(let o=0;o<r;o++)this.cells[l][o]=n[l][o]}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,n){this.fontType="bitmap",this.bitmapFont=t,this.bitmapCharWidth=e,this.bitmapCharHeight=i,this.bitmapAtlas=new M(t,e,i,s,n),this.cellWidth=s,this.cellHeight=n,this.calculateGridSize(),this.cells=this.createEmptyGrid()}async setImageFont(t,e,i,s,n,r){this.fontType="image",this.imageAtlas=new H({glyphWidth:e,glyphHeight:i,cellWidth:s,cellHeight:n,atlasBlocks:r}),await this.imageAtlas.loadFromPNG(t),this.cellWidth=s,this.cellHeight=n,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}convertColor(t,e){if(t==null||isNaN(t))return this.defaultFgColor;if(t===255)return"rgba(0, 0, 0, 0)";if(t<0||t>=e.length)return this.defaultFgColor;let i=e[t];return!i||typeof i.r!="number"?this.defaultFgColor:`rgba(${i.r}, ${i.g}, ${i.b}, ${i.a/255})`}renderDirect(t,e,i,s,n){for(let r=0;r<e&&r<this.rows;r++)for(let a=0;a<t&&a<this.cols;a++){let l=r*t+a;if(l>=i.length)break;let o=i[l];if(!o)continue;let c=this.convertColor(o.fgColorIndex,s),d=this.convertColor(o.bgColorIndex,s);this.setCell(a,r,o.char??" ",c,d)}this.render(n)}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}if(t.passes&&t.passes.length>0)for(let i=0;i<t.passes.length;i++){let s=t.passes[i];this.renderDirect(t.width,t.height,s.cells,e,i===0)}else this.renderDirect(t.width,t.height,t.cells,e,!0)}isReady(){return!0}getCols(){return this.cols}getRows(){return this.rows}resize(t,e){this.setFixedGrid(t,e)}setScalingMode(t){if(this.scalingMode===t)return;let e=this.cols,i=this.rows;if(this.scalingMode=t,this.calculateGridSize(),this.cols!==e||this.rows!==i){let s=this.cells;if(this.cells=this.createEmptyGrid(),s&&s.length>0){let n=Math.min(e,this.cols),r=Math.min(i,this.rows);for(let a=0;a<r;a++)for(let l=0;l<n;l++)s[a]&&s[a][l]&&(this.cells[a][l]=s[a][l])}}this.render()}setCellSize(t,e){let i=Math.max(1,Math.min(255,Math.round(t))),s=Math.max(1,Math.min(255,Math.round(e)));if(this.cellWidth===i&&this.cellHeight===s)return;let n=this.cols,r=this.rows;if(this.cellWidth=i,this.cellHeight=s,this.customCellSize=!0,this.calculateGridSize(),this.cols!==n||this.rows!==r){let a=this.cells;if(this.cells=this.createEmptyGrid(),a&&a.length>0){let l=Math.min(n,this.cols),o=Math.min(r,this.rows);for(let c=0;c<o;c++)for(let d=0;d<l;d++)a[c]&&a[c][d]&&(this.cells[c][d]=a[c][d])}}this.render()}getCellSize(){return{cellWidth:this.cellWidth,cellHeight:this.cellHeight}}getAvailableSize(){return{width:this.parentElement.clientWidth,height:this.parentElement.clientHeight}}getMaxCells(){return 65536}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)}};f(T,"Terminal2D");var B=T;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 U(u,t=G){return u<0||u>=t.length?"#ff00ff":t[u]}f(U,"paletteIndexToColor");function $(u,t=G){let e=t.indexOf(u.toLowerCase());return e>=0?e:0}f($,"colorToPaletteIndex");import{ScalingMode as bt}from"@utsp/types";export{M as BitmapFontAtlas,G as DEFAULT_PALETTE,y as GridOverlay,H as ImageFontAtlas,bt as ScalingMode,B as Terminal2D,$ as colorToPaletteIndex,D as getAtlasColumns,W as getCharGridPosition,A as getMaxCharCode,U as paletteIndexToColor};
37
+ `,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),n=Math.min(e,this.rows);for(let l=0;l<n;l++)for(let r=0;r<s;r++)this.cells[l][r]=i[l][r]}this.render()}),this.resizeObserver.observe(this.parentElement)}setCell(t,e,i,s,n){if(e<0||e>=this.rows||t<0||t>=this.cols)return;let l=i&&typeof i=="string"?i.charAt(0):" ";this.cells[e][t]={char:l,fgColor:s??this.defaultFgColor,bgColor:n??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,n){for(let l=0;l<i.length;l++)this.setCell(t+l,e,i[l],s,n)}fillRect(t,e,i,s,n=" ",l,r){for(let a=e;a<e+s;a++)for(let o=t;o<t+i;o++)this.setCell(o,a,n,l,r)}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 n=0;n<t.width;n++){let l=t.cells[i];s<this.rows&&n<this.cols&&this.setCell(n,s,l.char,l.fgColor,l.bgColor),i++}}render(t=!0){this.renderClassic(t)}renderClassic(t=!0){t&&(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";for(let e=0;e<this.rows;e++)for(let i=0;i<this.cols;i++){let s=this.cells[e][i],n=Math.floor(this.offsetX+i*this.cellWidth),l=Math.floor(this.offsetY+e*this.cellHeight),r=Math.floor(this.offsetX+(i+1)*this.cellWidth),a=Math.floor(this.offsetY+(e+1)*this.cellHeight),o=r-n,c=a-l;if((this.canvasBgColor!==null||s.bgColor!==this.defaultBgColor)&&(this.ctx.fillStyle=s.bgColor,this.ctx.fillRect(n,l,o,c)),s.char!==" "&&this.imageAtlas){let m=s.char.charCodeAt(0);this.imageAtlas.drawChar(this.ctx,m,n,l,o,c,s.fgColor)}}this.showDebugGrid&&this.drawDebugGrid()}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 v(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,n=this.rows,l=this.cells;if(this.calculateGridSize(),this.cols!==s||this.rows!==n){this.cells=this.createEmptyGrid();let r=Math.min(s,this.cols),a=Math.min(n,this.rows);for(let o=0;o<a;o++)for(let c=0;c<r;c++)this.cells[o][c]=l[o][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,n=this.cells;if(this.calculateGridSize(),this.cols!==i||this.rows!==s){this.cells=this.createEmptyGrid();let l=Math.min(i,this.cols),r=Math.min(s,this.rows);for(let a=0;a<r;a++)for(let o=0;o<l;o++)this.cells[a][o]=n[a][o]}this.render()}isFixedGridMode(){return this.fixedGridMode}setDebugGridColor(t){this.debugGridColor=t}isDebugGridEnabled(){return this.showDebugGrid}async setImageFont(t,e,i,s,n,l){this.imageAtlas=new C({glyphWidth:e,glyphHeight:i,cellWidth:s,cellHeight:n,atlasBlocks:l}),await this.imageAtlas.loadFromPNG(t),this.cellWidth=s,this.cellHeight=n,this.calculateGridSize(),this.fixedGridMode||(this.calculateGridSize(),this.cells=this.createEmptyGrid()),this.render()}async setImageFontStructure(t,e,i,s,n){let l=this.imageAtlas;if(this.imageAtlas=new C({glyphWidth:t,glyphHeight:e,cellWidth:i,cellHeight:s,atlasBlocks:n}),this.imageAtlas.prepare(),l){let r=l.getCanvas();if(r&&l.getGlyphWidth()===t&&l.getGlyphHeight()===e){let o=this.imageAtlas.getCanvas()?.getContext("2d");if(o){let c=16*t,d=16*e;r.width>=c&&r.height>=d&&o.drawImage(r,0,0,c,d,0,0,c,d)}}}this.cellWidth=i,this.cellHeight=s,this.fixedGridMode||(this.calculateGridSize(),this.cells=this.createEmptyGrid())}async setImageFontBlock(t,e){if(!this.imageAtlas){console.warn("[Terminal2D] Cannot load block: no atlas initialized");return}await this.imageAtlas.loadBlock(t,e),this.render()}setPalette(t){this.paletteCache=t}convertColor(t,e){if(t==null||isNaN(t))return this.defaultFgColor;if(t===255)return"rgba(0, 0, 0, 0)";if(t<0||t>=e.length)return this.defaultFgColor;let i=e[t];return!i||typeof i.r!="number"?this.defaultFgColor:`rgba(${i.r}, ${i.g}, ${i.b}, ${i.a/255})`}renderDirect(t,e,i,s,n){for(let l=0;l<e&&l<this.rows;l++)for(let r=0;r<t&&r<this.cols;r++){let a=l*t+r;if(a>=i.length)break;let o=i[a];if(!o)continue;let c=this.convertColor(o.fgColorIndex,s),d=this.convertColor(o.bgColorIndex,s);this.setCell(r,l,o.char??" ",c,d)}this.render(n)}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}if(t.passes&&t.passes.length>0)for(let i=0;i<t.passes.length;i++){let s=t.passes[i];this.renderDirect(t.width,t.height,s.cells,e,i===0)}else this.renderDirect(t.width,t.height,t.cells,e,!0)}isReady(){return!0}getCols(){return this.cols}getRows(){return this.rows}resize(t,e){this.setFixedGrid(t,e)}setScalingMode(t){if(this.scalingMode===t)return;let e=this.cols,i=this.rows;if(this.scalingMode=t,this.calculateGridSize(),this.cols!==e||this.rows!==i){let s=this.cells;if(this.cells=this.createEmptyGrid(),s&&s.length>0){let n=Math.min(e,this.cols),l=Math.min(i,this.rows);for(let r=0;r<l;r++)for(let a=0;a<n;a++)s[r]&&s[r][a]&&(this.cells[r][a]=s[r][a])}}this.render()}setCellSize(t,e){let i=Math.max(1,Math.min(255,Math.round(t))),s=Math.max(1,Math.min(255,Math.round(e)));if(this.cellWidth===i&&this.cellHeight===s)return;let n=this.cols,l=this.rows;if(this.cellWidth=i,this.cellHeight=s,this.customCellSize=!0,this.calculateGridSize(),this.cols!==n||this.rows!==l){let r=this.cells;if(this.cells=this.createEmptyGrid(),r&&r.length>0){let a=Math.min(n,this.cols),o=Math.min(l,this.rows);for(let c=0;c<o;c++)for(let d=0;d<a;d++)r[c]&&r[c][d]&&(this.cells[c][d]=r[c][d])}}this.render()}getCellSize(){return{cellWidth:this.cellWidth,cellHeight:this.cellHeight}}getAvailableSize(){return{width:this.parentElement.clientWidth,height:this.parentElement.clientHeight}}getMaxCells(){return 65536}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)}};u(W,"Terminal2D");var H=W;var R=["#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 S(g,t=R){return g<0||g>=t.length?"#ff00ff":t[g]}u(S,"paletteIndexToColor");function I(g,t=R){let e=t.indexOf(g.toLowerCase());return e>=0?e:0}u(I,"colorToPaletteIndex");import{ScalingMode as rt}from"@utsp/types";export{R as DEFAULT_PALETTE,v as GridOverlay,C as ImageFontAtlas,rt as ScalingMode,H as Terminal2D,I as colorToPaletteIndex,w as getAtlasColumns,b as getCharGridPosition,x as getMaxCharCode,S as paletteIndexToColor};
package/dist/gl/index.cjs CHANGED
@@ -1,11 +1,11 @@
1
- "use strict";var y=Object.defineProperty;var Y=Object.getOwnPropertyDescriptor;var k=Object.getOwnPropertyNames;var z=Object.prototype.hasOwnProperty;var N=(f,e,t)=>e in f?y(f,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):f[e]=t;var C=(f,e)=>y(f,"name",{value:e,configurable:!0});var X=(f,e)=>{for(var t in e)y(f,t,{get:e[t],enumerable:!0})},q=(f,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of k(e))!z.call(f,i)&&i!==t&&y(f,i,{get:()=>e[i],enumerable:!(s=Y(e,i))||s.enumerable});return f};var j=f=>q(y({},"__esModule",{value:!0}),f);var r=(f,e,t)=>(N(f,typeof e!="symbol"?e+"":e,t),t);var Q={};X(Q,{DEFAULT_PALETTE:()=>D,GridOverlay:()=>I,ScalingMode:()=>x.ScalingMode,TerminalGL:()=>_,colorToPaletteIndex:()=>V,getAtlasColumns:()=>B,getCharGridPosition:()=>L,getMaxCharCode:()=>F,paletteIndexToColor:()=>$});module.exports=j(Q);var M=class M{constructor(e,t){r(this,"canvas");r(this,"ctx");r(this,"container");r(this,"cols",0);r(this,"rows",0);r(this,"cellWidth",0);r(this,"cellHeight",0);r(this,"offsetX",0);r(this,"offsetY",0);r(this,"strokeColor","rgba(80, 80, 80, 0.4)");r(this,"lineWidth",1);this.container=e,this.canvas=document.createElement("canvas"),this.canvas.className="grid-overlay-canvas";let s=t?.zIndex??10;this.canvas.style.cssText=`
1
+ "use strict";var U=Object.defineProperty;var Y=Object.getOwnPropertyDescriptor;var k=Object.getOwnPropertyNames;var z=Object.prototype.hasOwnProperty;var V=(u,e,t)=>e in u?U(u,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):u[e]=t;var p=(u,e)=>U(u,"name",{value:e,configurable:!0});var X=(u,e)=>{for(var t in e)U(u,t,{get:e[t],enumerable:!0})},q=(u,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of k(e))!z.call(u,s)&&s!==t&&U(u,s,{get:()=>e[s],enumerable:!(i=Y(e,s))||i.enumerable});return u};var Q=u=>q(U({},"__esModule",{value:!0}),u);var a=(u,e,t)=>(V(u,typeof e!="symbol"?e+"":e,t),t);var j={};X(j,{DEFAULT_PALETTE:()=>D,GridOverlay:()=>I,ScalingMode:()=>v.ScalingMode,TerminalGL:()=>L,colorToPaletteIndex:()=>N,getAtlasColumns:()=>w,getCharGridPosition:()=>_,getMaxCharCode:()=>B,paletteIndexToColor:()=>$});module.exports=Q(j);var M=class M{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: ${s} !important;
8
- `,this.container.appendChild(this.canvas);let i=this.canvas.getContext("2d");if(!i)throw new Error("[GridOverlay] Impossible de cr\xE9er le contexte 2D");this.ctx=i,t&&(t.strokeColor&&(this.strokeColor=t.strokeColor),t.lineWidth!==void 0&&(this.lineWidth=t.lineWidth))}setDimensions(e,t,s,i,n=0,a=0){this.cols=e,this.rows=t,this.cellWidth=s,this.cellHeight=i,this.offsetX=n,this.offsetY=a}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,s,i,n){let a=i.left-n.left,l=i.top-n.top,o=i.width,c=i.height;(this.canvas.width!==o||this.canvas.height!==c)&&(this.canvas.width=o,this.canvas.height=c);let d=this.canvas.style;d.width=`${o}px`,d.height=`${c}px`,d.left=`${a}px`,d.top=`${l}px`}render(){if(!this.ctx)return;let e=this.cols*this.cellWidth,t=this.rows*this.cellHeight,s=e>0?this.canvas.width/e:1,i=t>0?this.canvas.height/t:1,n=Math.min(s,i),a=this.cellWidth*n,l=this.cellHeight*n,o=this.cols*a,c=this.rows*l,d=this.offsetX*n,h=this.offsetY*n;if(!(o===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*n),this.ctx.beginPath();for(let m=0;m<=this.cols;m++){let b=d+m*a+.5;this.ctx.moveTo(b,h),this.ctx.lineTo(b,h+c)}for(let m=0;m<=this.rows;m++){let b=h+m*l+.5;this.ctx.moveTo(d,b),this.ctx.lineTo(d+o,b)}this.ctx.stroke()}}update(e,t,s,i,n,a,l=0,o=0){this.setDimensions(e,t,s,i,l,o),this.setCanvasSize(n,a),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}};C(M,"GridOverlay");var I=M;function B(f){return Math.sqrt(f)*16}C(B,"getAtlasColumns");function F(f){return f*256-1}C(F,"getMaxCharCode");function L(f,e){let t=Math.floor(f/256),s=f%256,i=Math.sqrt(e),n=t%i,a=Math.floor(t/i),l=s%16,o=Math.floor(s/16);return{col:n*16+l,row:a*16+o}}C(L,"getCharGridPosition");var x=require("@utsp/types");var U=class U{constructor(e,t){r(this,"canvas");r(this,"gl");r(this,"parentElement");r(this,"containerDiv");r(this,"cols");r(this,"rows");r(this,"charWidth");r(this,"charHeight");r(this,"cellWidth",8);r(this,"cellHeight",8);r(this,"glyphOffsetX",0);r(this,"glyphOffsetY",0);r(this,"canvasBgColor");r(this,"showGrid");r(this,"supportsUint32Indices",!1);r(this,"useUint16Indices",!1);r(this,"gridOverlay");r(this,"bitmapFont");r(this,"atlasTexture",null);r(this,"atlasCanvas");r(this,"atlasColumns",0);r(this,"fontLoaded",!1);r(this,"paletteTexture",null);r(this,"program",null);r(this,"positionBuffer",null);r(this,"texCoordBuffer",null);r(this,"colorIndexBuffer",null);r(this,"indexBuffer",null);r(this,"aPosition");r(this,"aTexCoord");r(this,"aColorIndex");r(this,"uResolution",null);r(this,"uTexture",null);r(this,"uPalette",null);r(this,"resizeObserver");r(this,"charCodeToAtlasIndex",new Uint16Array(65536).fill(65535));r(this,"atlasUVs",new Float32Array(0));r(this,"cachedAtlasWidth",0);r(this,"cachedAtlasHeight",0);r(this,"paletteFloat",new Float32Array(256*4));r(this,"maxCells",0);r(this,"renderPositions",new Float32Array(0));r(this,"renderTexCoords",new Float32Array(0));r(this,"renderColorIndices",new Float32Array(0));r(this,"renderIndices",new Uint32Array(0));r(this,"cachedResolution",[0,0]);r(this,"cachedTextureUnit",-1);r(this,"cachedPaletteUnit",-1);r(this,"cachedTextureUniform",!1);r(this,"cachedPaletteUniform",!1);r(this,"paletteHash",0);r(this,"currentScale",1);r(this,"scalingMode",x.ScalingMode.None);r(this,"ambientEffectEnabled",!1);r(this,"ambientEffectCanvas",null);r(this,"ambientEffectCtx",null);r(this,"ambientEffectBlur",x.POST_PROCESS_DEFAULTS.ambientEffect.blur);r(this,"ambientEffectScale",x.POST_PROCESS_DEFAULTS.ambientEffect.scale);r(this,"ambientEffectOpacity",.7);r(this,"onResizeCallback");r(this,"staticPositionsInitialized",!1);r(this,"vaoExtension",null);r(this,"vao",null);r(this,"instancedExtension",null);r(this,"useInstancing",!1);r(this,"instanceDataBuffer",null);r(this,"instanceData",new Float32Array(0));r(this,"templateQuadPositions",new Float32Array(0));r(this,"templateQuadIndices",new Uint16Array(0));r(this,"aInstanceOffset",-1);r(this,"aInstanceUVs",-1);r(this,"aInstanceColors",-1);r(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 s=t.cols*t.rows,i=U.checkCompatibility();if(i.errors.length>0)throw new Error(`TerminalGL: WebGL incompatible - ${i.errors.join(", ")}`);let n=t.forceUint16??!1;if(n&&s>i.maxCellsUint16)throw new Error(`TerminalGL: Terminal size ${t.cols}\xD7${t.rows} (${s} cells) exceeds Uint16 limit of ${i.maxCellsUint16} cells. Maximum size with Uint16: ${Math.floor(Math.sqrt(i.maxCellsUint16))}\xD7${Math.floor(Math.sqrt(i.maxCellsUint16))} (or smaller rectangles like 127\xD764)`);if(!i.uint32Indices&&s>i.maxCellsUint16)throw new Error(`TerminalGL: Terminal size ${t.cols}\xD7${t.rows} (${s} cells) exceeds device limit of ${i.maxCellsUint16} cells (OES_element_index_uint not supported). Maximum size: ${Math.floor(Math.sqrt(i.maxCellsUint16))}\xD7${Math.floor(Math.sqrt(i.maxCellsUint16))}`);s>i.recommendedMaxCells&&console.warn(`[TerminalGL] \u26A0\uFE0F Large terminal size ${t.cols}\xD7${t.rows} (${s} cells) exceeds recommended limit of ${i.recommendedMaxCells} cells. Performance may be impacted.`),i.warnings.length>0&&console.warn("[TerminalGL] WebGL Compatibility Warnings:",i.warnings);let a=t.charWidth??8,l=t.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=e,this.cols=t.cols,this.rows=t.rows,this.charWidth=a,this.charHeight=l,this.canvasBgColor=t.canvasBgColor!==void 0?t.canvasBgColor:null,this.showGrid=t.showGrid??!1,this.scalingMode=t.scalingMode??x.ScalingMode.None,t.ambientEffect&&(this.ambientEffectEnabled=!0,typeof t.ambientEffect=="object"&&(this.ambientEffectBlur=t.ambientEffect.blur??x.POST_PROCESS_DEFAULTS.ambientEffect.blur,this.ambientEffectScale=t.ambientEffect.scale??x.POST_PROCESS_DEFAULTS.ambientEffect.scale,this.ambientEffectOpacity=t.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=`
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 m=0;m<=this.cols;m++){let b=h+m*l+.5;this.ctx.moveTo(b,d),this.ctx.lineTo(b,d+c)}for(let m=0;m<=this.rows;m++){let b=d+m*o+.5;this.ctx.moveTo(h,b),this.ctx.lineTo(h+n,b)}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}};p(M,"GridOverlay");var I=M;function w(u){return Math.sqrt(u)*16}p(w,"getAtlasColumns");function B(u){return u*256-1}p(B,"getMaxCharCode");function _(u,e){let t=Math.floor(u/256),i=u%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}}p(_,"getCharGridPosition");var v=require("@utsp/types");var F=class F{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",v.ScalingMode.None);a(this,"ambientEffectEnabled",!1);a(this,"ambientEffectCanvas",null);a(this,"ambientEffectCtx",null);a(this,"ambientEffectBlur",v.POST_PROCESS_DEFAULTS.ambientEffect.blur);a(this,"ambientEffectScale",v.POST_PROCESS_DEFAULTS.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=F.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??v.ScalingMode.None,t.ambientEffect&&(this.ambientEffectEnabled=!0,typeof t.ambientEffect=="object"&&(this.ambientEffectBlur=t.ambientEffect.blur??v.POST_PROCESS_DEFAULTS.ambientEffect.blur,this.ambientEffectScale=t.ambientEffect.scale??v.POST_PROCESS_DEFAULTS.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 @@
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=n||!this.supportsUint32Indices,this.useUint16Indices?console.warn(`[TerminalGL] \u{1F4CA} Using Uint16 indices (max ${i.maxCellsUint16} cells)`):console.warn(`[TerminalGL] \u{1F4CA} Using Uint32 indices (max ${i.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(d){throw console.error("[TerminalGL] \u274C Failed to initialize WebGL:",d),d}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"),s=t.getContext("webgl")||t.getContext("experimental-webgl");if(!s||!(s instanceof WebGLRenderingContext))return e.errors.push("\u274C WebGL 1.0 not supported by this browser/device"),e;let i=s;e.webgl1=!0;try{e.maxTextureSize=i.getParameter(i.MAX_TEXTURE_SIZE);let o=i.getParameter(i.MAX_VIEWPORT_DIMS);e.maxViewportDims=[o[0],o[1]]}catch(o){return e.errors.push(`\u274C Failed to query WebGL parameters: ${o}`),e}let n=i.getExtension("OES_element_index_uint");e.uint32Indices=!!n;let a=8;if(e.maxCellsUint16=Math.floor(65535/a),e.uint32Indices){let o=Math.floor(e.maxTextureSize*e.maxTextureSize/64);e.maxCellsUint32=Math.min(o,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]}`),i.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,s=this.glyphOffsetX,i=this.glyphOffsetY,n=this.charWidth,a=this.charHeight,l=0,o=0,c=0;for(let h=0;h<this.rows;h++){let m=Math.round(h*t),b=Math.round(m+t);for(let v=0;v<this.cols;v++){let u=Math.round(v*e),g=Math.round(u+e);this.renderPositions[l++]=u,this.renderPositions[l++]=m,this.renderPositions[l++]=g,this.renderPositions[l++]=m,this.renderPositions[l++]=u,this.renderPositions[l++]=b,this.renderPositions[l++]=g,this.renderPositions[l++]=b,this.renderIndices[o++]=c,this.renderIndices[o++]=c+1,this.renderIndices[o++]=c+2,this.renderIndices[o++]=c+2,this.renderIndices[o++]=c+1,this.renderIndices[o++]=c+3,c+=4;let E=Math.round(u+s),p=Math.round(m+i),w=Math.round(E+n),A=Math.round(p+a);this.renderPositions[l++]=E,this.renderPositions[l++]=p,this.renderPositions[l++]=w,this.renderPositions[l++]=p,this.renderPositions[l++]=E,this.renderPositions[l++]=A,this.renderPositions[l++]=w,this.renderPositions[l++]=A,this.renderIndices[o++]=c,this.renderIndices[o++]=c+1,this.renderIndices[o++]=c+2,this.renderIndices[o++]=c+2,this.renderIndices[o++]=c+1,this.renderIndices[o++]=c+3,c+=4}}let d=this.gl;d.bindBuffer(d.ARRAY_BUFFER,this.positionBuffer),d.bufferSubData(d.ARRAY_BUFFER,0,this.renderPositions),d.bindBuffer(d.ELEMENT_ARRAY_BUFFER,this.indexBuffer),d.bufferSubData(d.ELEMENT_ARRAY_BUFFER,0,this.renderIndices),this.staticPositionsInitialized=!0}initWebGL(){let e=this.gl,t;this.useInstancing?t=`
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 m=Math.round(d*t),b=Math.round(m+t);for(let x=0;x<this.cols;x++){let f=Math.round(x*e),E=Math.round(f+e);this.renderPositions[o++]=f,this.renderPositions[o++]=m,this.renderPositions[o++]=E,this.renderPositions[o++]=m,this.renderPositions[o++]=f,this.renderPositions[o++]=b,this.renderPositions[o++]=E,this.renderPositions[o++]=b,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 C=Math.round(f+i),g=Math.round(m+s),y=Math.round(C+r),A=Math.round(g+l);this.renderPositions[o++]=C,this.renderPositions[o++]=g,this.renderPositions[o++]=y,this.renderPositions[o++]=g,this.renderPositions[o++]=C,this.renderPositions[o++]=A,this.renderPositions[o++]=y,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 @@
96
96
  float paletteU = (aColorIndex + 0.5) / 256.0;
97
97
  vColor = texture2D(uPalette, vec2(paletteU, 0.5));
98
98
  }
99
- `;let s=`
99
+ `;let i=`
100
100
  precision mediump float;
101
101
 
102
102
  uniform sampler2D uTexture;
@@ -116,7 +116,7 @@
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=B(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(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(l,e),d=(o*this.charWidth+n)/s,h=(c*this.charHeight+a)/i,m=((o+1)*this.charWidth-n)/s,b=((c+1)*this.charHeight-a)/i,v=l*4;this.atlasUVs[v]=d,this.atlasUVs[v+1]=h,this.atlasUVs[v+2]=m,this.atlasUVs[v+3]=b}}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),m=d*this.charWidth,b=h*this.charHeight;for(let v=0;v<Math.min(c.length,this.charHeight);v++){let u=c[v];for(let g=0;g<this.charWidth;g++){let E=1<<7-g;u&E&&a.fillRect(m+g,b+v,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,m=((o+1)*this.charHeight-n)/s,b=a*4;this.atlasUVs[b]=c,this.atlasUVs[b+1]=d,this.atlasUVs[b+2]=h,this.atlasUVs[b+3]=m}}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 x.ScalingMode.Integer:o=Math.max(1,Math.floor(l));break;case x.ScalingMode.Half:o=Math.max(1,Math.floor(l*2)/2);break;case x.ScalingMode.Quarter:o=Math.max(1,Math.floor(l*4)/4);break;case x.ScalingMode.Eighth:o=Math.max(1,Math.floor(l*8)/8);break;case x.ScalingMode.Responsive:o=1;break;case x.ScalingMode.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,m=d.fgColorIndex,b=this.canvasBgColor!==null&&h===255,v=d.char===" "||m===255;if(!b){if(i>=n){console.error(`[TerminalGL] \u274C Instance buffer overflow! instanceIdx=${i}, max=${n}`);break}let u=i*8;this.instanceData[u]=c,this.instanceData[u+1]=o,this.instanceData[u+2]=0,this.instanceData[u+3]=0,this.instanceData[u+4]=0,this.instanceData[u+5]=0,this.instanceData[u+6]=h,this.instanceData[u+7]=0,i++}if(!v){let u=d.char.charCodeAt(0),g=this.charCodeToAtlasIndex[u];if(g!==65535){if(i>=n){console.error(`[TerminalGL] \u274C Instance buffer overflow! instanceIdx=${i}, max=${n}`);break}let E=g*4,p=i*8;this.instanceData[p]=c,this.instanceData[p+1]=o,this.instanceData[p+2]=this.atlasUVs[E],this.instanceData[p+3]=this.atlasUVs[E+1],this.instanceData[p+4]=this.atlasUVs[E+2],this.instanceData[p+5]=this.atlasUVs[E+3],this.instanceData[p+6]=0,this.instanceData[p+7]=m,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 v=0;v<o;v++){let u=l[v],g=u.bgColorIndex,p=this.canvasBgColor!==null&&g===255?255:g,w=0;for(let T=0;T<4;T++)this.renderTexCoords[n++]=w,this.renderTexCoords[n++]=w,this.renderColorIndices[a++]=p;let A=u.fgColorIndex,S=u.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 m=e.width*e.height*2*6,b=this.useUint16Indices?t.UNSIGNED_SHORT:t.UNSIGNED_INT;t.drawElements(t.TRIANGLES,m,b,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=U.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 u=this.gl;u.bindBuffer(u.ARRAY_BUFFER,this.instanceDataBuffer),u.bufferData(u.ARRAY_BUFFER,this.instanceData.byteLength,u.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 m=o?"\u{1F4C8} Growing":"\u{1F4C9} Shrinking",b=d*160/1048576,v=this.maxCells*160/1048576;console.warn(`[TerminalGL] ${m} buffers: ${b.toFixed(2)}MB \u2192 ${v.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,m=h*this.charHeight;for(let b=0;b<this.charHeight&&!(b>=n.length);b++){let x=n[b];for(let f=0;f<this.charWidth;f++){let E=1<<7-f;x&E&&(r.fillStyle="#FFFFFF",r.fillRect(d+f,m+b,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=w(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=w(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=w(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}=_(o,e),h=(n*this.charWidth+r)/i,d=(c*this.charHeight+l)/s,m=((n+1)*this.charWidth-r)/i,b=((c+1)*this.charHeight-l)/s,x=o*4;this.atlasUVs[x]=h,this.atlasUVs[x+1]=d,this.atlasUVs[x+2]=m,this.atlasUVs[x+3]=b}}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 v.ScalingMode.Integer:n=Math.max(1,Math.floor(o));break;case v.ScalingMode.Half:n=Math.max(1,Math.floor(o*2)/2);break;case v.ScalingMode.Quarter:n=Math.max(1,Math.floor(o*4)/4);break;case v.ScalingMode.Eighth:n=Math.max(1,Math.floor(o*8)/8);break;case v.ScalingMode.Responsive:n=1;break;case v.ScalingMode.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,m=h.fgColorIndex,b=this.canvasBgColor!==null&&d===255,x=h.char===" "||m===255;if(!b){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),E=this.charCodeToAtlasIndex[f];if(E!==65535){if(s>=r){console.error(`[TerminalGL] \u274C Instance buffer overflow! instanceIdx=${s}, max=${r}`);break}let C=E*4,g=s*8;this.instanceData[g]=c,this.instanceData[g+1]=n,this.instanceData[g+2]=this.atlasUVs[C],this.instanceData[g+3]=this.atlasUVs[C+1],this.instanceData[g+4]=this.atlasUVs[C+2],this.instanceData[g+5]=this.atlasUVs[C+3],this.instanceData[g+6]=0,this.instanceData[g+7]=m,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],E=f.bgColorIndex,g=this.canvasBgColor!==null&&E===255?255:E,y=0;for(let T=0;T<4;T++)this.renderTexCoords[r++]=y,this.renderTexCoords[r++]=y,this.renderColorIndices[l++]=g;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 m=e.width*e.height*2*6,b=this.useUint16Indices?t.UNSIGNED_SHORT:t.UNSIGNED_INT;t.drawElements(t.TRIANGLES,m,b,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=F.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 m=n?"\u{1F4C8} Growing":"\u{1F4C9} Shrinking",b=h*160/1048576,x=this.maxCells*160/1048576;console.warn(`[TerminalGL] ${m} buffers: ${b.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 @@
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)}};C(U,"TerminalGL");var _=U;var D=["#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 $(f,e=D){return f<0||f>=e.length?"#ff00ff":e[f]}C($,"paletteIndexToColor");function V(f,e=D){let t=e.indexOf(f.toLowerCase());return t>=0?t:0}C(V,"colorToPaletteIndex");
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)}};p(F,"TerminalGL");var L=F;var D=["#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 $(u,e=D){return u<0||u>=e.length?"#ff00ff":e[u]}p($,"paletteIndexToColor");function N(u,e=D){let t=e.indexOf(u.toLowerCase());return t>=0?t:0}p(N,"colorToPaletteIndex");
@@ -51,13 +51,6 @@ declare function getCharGridPosition(charCode: number, blocks: AtlasBlocks): {
51
51
  row: number;
52
52
  };
53
53
 
54
- /**
55
- * Police bitmap matricielle
56
- * Map qui associe un code de caractère (charCode) à une représentation bitmap 8x8
57
- * Chaque Uint8Array contient 8 octets, un par ligne de pixels
58
- */
59
- type BitmapFont = Map<number, Uint8Array>;
60
-
61
54
  /**
62
55
  * WebGL compatibility report
63
56
  */
@@ -285,34 +278,22 @@ declare class TerminalGL implements IRenderer {
285
278
  * @param font - Bitmap font mapping (charCode → byte array)
286
279
  * @param charWidth - Width of each character in pixels
287
280
  * @param charHeight - Height of each character in pixels
288
- * @param cellWidth - Width of each cell in pixels
289
- * @param cellHeight - Height of each cell in pixels
290
- * @throws {Error} If atlas generation fails
291
- *
292
- * @example
293
- * ```typescript
294
- * // ❌ DON'T: Call setBitmapFont directly
295
- * renderer.setBitmapFont(font, 8, 16, 8, 16);
296
- *
297
- * // ✅ DO: Use Core's loadBitmapFontById (triggers event automatically)
298
- * core.loadBitmapFontById(1, {
299
- * charWidth: 8, charHeight: 16,
300
- * cellWidth: 8, cellHeight: 16,
301
- * glyphs: new Map([[65, new Uint8Array([...])]])
302
- * });
303
- * ```
304
281
  */
305
- setBitmapFont(font: BitmapFont, charWidth: number, charHeight: number, cellWidth: number, cellHeight: number): void;
282
+ setBitmapFont(font: Map<number, Uint8Array>, charWidth: number, charHeight: number, cellWidth?: number, cellHeight?: number): void;
306
283
  /**
307
- * Set image font (PNG atlas) for extended character rendering
308
- * Supports 1, 4, or 16 blocks (256, 1024, or 4096 characters)
309
- *
310
- * @param imageData - PNG image data as Uint8Array
311
- * @param glyphWidth - Glyph width in pixels
312
- * @param glyphHeight - Glyph height in pixels
313
- * @param cellWidth - Cell width in pixels
314
- * @param cellHeight - Cell height in pixels
315
- * @param atlasBlocks - Number of 256-char blocks (1, 4, or 16)
284
+ * Convertit la police Bitmap en texture Atlas
285
+ */
286
+ private generateAtlas;
287
+ /**
288
+ * Initialize ImageFont structure (allocate texture)
289
+ */
290
+ setImageFontStructure(glyphWidth: number, glyphHeight: number, cellWidth: number, cellHeight: number, atlasBlocks: AtlasBlocks): Promise<void>;
291
+ /**
292
+ * Upload an image block to the atlas
293
+ */
294
+ setImageFontBlock(blockIndex: number, data: Uint8Array): Promise<void>;
295
+ /**
296
+ * Set image font (legacy/full)
316
297
  */
317
298
  setImageFont(imageData: Uint8Array, glyphWidth: number, glyphHeight: number, cellWidth: number, cellHeight: number, atlasBlocks: AtlasBlocks): Promise<void>;
318
299
  /**
@@ -337,21 +318,11 @@ declare class TerminalGL implements IRenderer {
337
318
  */
338
319
  private precomputeImageFontUVs;
339
320
  /**
340
- * Generate texture atlas from bitmap font
341
- */
342
- private generateAtlas;
343
- /**
344
- * 🚀 OPTIMIZED: Build charCode → atlas index using direct array lookup
345
- */
346
- private buildCharCodeMap;
347
- /**
348
- * 🚀 MEGA OPTIMIZATION: Pre-compute ALL atlas UVs
349
- * Called once after atlas generation - UVs never change!
350
- * Eliminates per-frame division and modulo operations
321
+ * Create WebGL texture from atlas (Empty allocation)
351
322
  */
352
- private precomputeAtlasUVs;
323
+ private allocateAtlasTexture;
353
324
  /**
354
- * Create WebGL texture from atlas
325
+ * Create WebGL texture from atlas (Legacy canvas based)
355
326
  */
356
327
  private createAtlasTexture;
357
328
  /**
@@ -417,9 +388,9 @@ declare class TerminalGL implements IRenderer {
417
388
  * @example
418
389
  * ```typescript
419
390
  * // ✅ Normal usage: Core handles this automatically
420
- * core.loadPalette([...]);
421
- * // → Core emits event
422
- * // → ClientRuntime receives event
391
+ * core.loadPaletteToSlot(0, [...]);
392
+ * display.switchPalette(0);
393
+ * // → ClientRuntime applies slot palette
423
394
  * // → renderer.setPalette() called automatically
424
395
  *
425
396
  * // ⚠️ Manual usage (advanced):
@@ -848,4 +819,4 @@ declare function paletteIndexToColor(index: number, palette?: readonly string[])
848
819
  declare function colorToPaletteIndex(color: string, palette?: readonly string[]): number;
849
820
 
850
821
  export { DEFAULT_PALETTE, GridOverlay, TerminalGL, colorToPaletteIndex, getAtlasColumns, getCharGridPosition, getMaxCharCode, paletteIndexToColor };
851
- export type { AtlasBlocks, BitmapFont, TerminalGLOptions, WebGLCompatibilityReport };
822
+ export type { AtlasBlocks, TerminalGLOptions, WebGLCompatibilityReport };