diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f268f8..2640db8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ All notable changes to this project are documented here. The project follows - Puzzles are easier to read, above all on phones: the three stars are now three goals in plain words, and the one you are working on says what is wrong and what to do, with a Show me button. The map marks it too: a red ring around a city that still needs traffic, and a pulsing ✂ on a link whose cut would hurt. On phones the sheet starts small so the map gets the screen; swipe it up for the rest. Cities far from the puzzle are left off the map, and stepping stones you are not using are small dots without a name until you tap one, build there or zoom in. - The map is now drawn by the graphics card wherever the browser can, so panning, zooming and fast play stay smooth on big networks and big screens. The map looks the same; Settings › Map drawing › Always 2D keeps the old drawing, and browsers without WebGL2 or without a usable graphics card keep it on their own, as does a game whose graphics card fails while you play. - Cities, labels, building cones, ships, offer bubbles and money pop-ups are painted once and then reused, so the usual map also draws far fewer shapes each frame. +- Long zooms stay on the graphics card: the pictures of cities and labels are painted on one shared canvas instead of each keeping its own, so the browser no longer runs out of room for them and switches to the slower drawing. ## [2.9.1] — 2026-11-04 diff --git a/src/game/96-map/56-webgl.js b/src/game/96-map/56-webgl.js index d6be4f4..2819c7d 100644 --- a/src/game/96-map/56-webgl.js +++ b/src/game/96-map/56-webgl.js @@ -19,7 +19,7 @@ function mapGl(on,keep=true){GLX.want=!!on;if(keep)try{on?localStorage.removeIte function glShow(on){on=!!on;if(GLX.shown===on)return;GLX.shown=on;const e=document.getElementById('mapgl'),fx=document.getElementById('mapfx');if(e)e.hidden=!on;if(fx)fx.hidden=!on;} // Marks an error as the card's own, so draw() falls back to 2D instead of trying WebGL again every frame. function glErr(e){const x=e instanceof Error?e:new Error(String(e));x.glErr=true;return x;} -function glKill(why){console.warn('[tubes] the map stays 2D:',why&&why.message||why);GLX.dead=true;GLX.gl=null;glShow(false);} +function glKill(why){console.warn('[tubes] the map stays 2D:',why&&why.message||why);GLX.dead=true;GLX.gl=null;spritesDrop();glShow(false);} const GL_HEAD='#version 300 es\nprecision highp float;precision highp int;\n'; // Clip space from CSS px (the shaders work in CSS px, as the 2D map does, and use uDpr only for anti-aliasing). const GL_CLIP='vec4 clip(vec2 p,vec2 v,float z){return vec4(p.x/v.x*2.-1.,1.-p.y/v.y*2.,z,1.);}\n'; diff --git a/src/game/96-map/59-gl-sprites.js b/src/game/96-map/59-gl-sprites.js index 87eeee6..234cf94 100644 --- a/src/game/96-map/59-gl-sprites.js +++ b/src/game/96-map/59-gl-sprites.js @@ -26,30 +26,46 @@ function glsInit(gl){GLS.prog=glProg(gl,SPR_VS,SPR_FS);const {v,b}=glVao(gl,[4,4 GLS.shx=GLS.shy=GLS.shh=0;} // Forgets every picture and starts the atlas again, after the pictures already queued are drawn (they point into it). function spritesReset(){glsDrawNow();SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;} +// The card given up: its pictures go (they have no canvas to be drawn from in 2D) and the atlas is forgotten. +function spritesDrop(){GLS.n=0;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0;} +/* The card's pictures are painted on one canvas, reused, and each goes into the atlas as soon as it is painted: a + canvas kept per picture made the browser hold thousands of them while you zoomed, until it lost the graphics context + and the map fell back to 2D. The 2D map, and a picture too big for the atlas, keep their own canvas. */ +const GLS_PAD={cv:null,g:null}; +function glsPad(pw,ph){const P=GLS_PAD;if(!P.cv){P.cv=document.createElement('canvas');P.cv.width=P.cv.height=256;} + if(P.cv.width=SPR_MAX)spritesReset(); - const cv=document.createElement('canvas');cv.width=Math.ceil(w*DPR);cv.height=Math.ceil(h*DPR); - const g=cv.getContext('2d'),saved=ctx;ctx=g; - try{g.setTransform(DPR,0,0,DPR,0,0);paint(g);}finally{ctx=saved;} - e={cv,w,h,ax,ay,up:false,u0:0,v0:0,u1:1,v1:1};SPRS.set(key,e);return e;} -// Puts a picture into the atlas (once), shelf by shelf. A full atlas starts again; this picture then waits a frame. -function glsEnsure(e){if(e.up)return true;const gl=GLX.gl;if(!gl||!GLS.prog)return false; - try{return glsPut(gl,e);}catch(x){throw glErr(x);}} -function glsPut(gl,e){const pw=e.cv.width,ph=e.cv.height,A=GLS.size;if(pw>A||ph>A)return false; + const pw=Math.ceil(w*DPR),ph=Math.ceil(h*DPR),saved=ctx; + e={cv:null,pw,ph,w,h,ax,ay,up:false,u0:0,v0:0,u1:1,v1:1}; + if(gpu&&pw<=GLS.size&&ph<=GLS.size){const P=glsPad(pw,ph),g=P.g; + g.save();g.setTransform(1,0,0,1,0,0);g.clearRect(0,0,pw,ph);ctx=g; + try{g.setTransform(DPR,0,0,DPR,0,0);paint(g);}finally{ctx=saved;g.restore();} + // A full atlas starts again (glsPut), and the picture goes into the empty one at once: the pad is reused next. + try{if(!glsPut(GLX.gl,e,P.cv))glsPut(GLX.gl,e,P.cv);}catch(x){throw glErr(x);} + }else{const cv=document.createElement('canvas');cv.width=pw;cv.height=ph;const g=cv.getContext('2d');ctx=g; + try{g.setTransform(DPR,0,0,DPR,0,0);paint(g);}finally{ctx=saved;}e.cv=cv;} + SPRS.set(key,e);return e;} +// Puts a picture with its own canvas into the atlas (once), shelf by shelf. A full atlas starts again; this picture then waits a frame. +function glsEnsure(e){if(e.up)return true;const gl=GLX.gl;if(!gl||!GLS.prog||!e.cv)return false; + try{return glsPut(gl,e,e.cv);}catch(x){throw glErr(x);}} +function glsPut(gl,e,src){const pw=e.pw,ph=e.ph,A=GLS.size;if(pw>A||ph>A)return false; if(GLS.shx+pw>A){GLS.shx=0;GLS.shy+=GLS.shh;GLS.shh=0;} if(GLS.shy+ph>A){spritesReset();return false;} const x=GLS.shx,y=GLS.shy;GLS.shx+=pw;GLS.shh=Math.max(GLS.shh,ph); gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,GLS.tex);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,true); - gl.texSubImage2D(gl.TEXTURE_2D,0,x,y,gl.RGBA,gl.UNSIGNED_BYTE,e.cv);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,false); + // Only the picture's corner of the source: the pad is bigger than most pictures. + gl.texSubImage2D(gl.TEXTURE_2D,0,x,y,pw,ph,gl.RGBA,gl.UNSIGNED_BYTE,src);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,false); Object.assign(e,{up:true,u0:x/A,v0:y/A,u1:(x+pw)/A,v1:(y+ph)/A});return true;} // The next record in GLS.data, which grows as needed: take it before reading GLS.data, which it may replace. function glsNext(){if((GLS.n+1)*SPR_STRIDE>GLS.data.length){const nd=new Float32Array(GLS.data.length*2);nd.set(GLS.data);GLS.data=nd;}return GLS.n++*SPR_STRIDE;} // Draws a picture at (x,y) of w×h CSS px, on the card for a frame drawn there, else with the 2D canvas. function blit(e,x,y,w,h){if(GLS.frame&&glsEnsure(e)){const o=glsNext(),d=GLS.data; d[o]=x;d[o+1]=y;d[o+2]=w;d[o+3]=h;d[o+4]=e.u0;d[o+5]=e.v0;d[o+6]=e.u1;d[o+7]=e.v1;d[o+8]=d[o+9]=d[o+10]=0;d[o+11]=ctx.globalAlpha;d[o+12]=0;} - else ctx.drawImage(e.cv,x,y,w,h);} + else if(e.cv)ctx.drawImage(e.cv,x,y,w,h);} // A round dot of radius r at (x,y), in colour col (CSS colour string) at opacity a, on the card or the 2D canvas. function dot(x,y,r,col,a){if(GLS.frame){const c=glColor(col),o=glsNext(),d=GLS.data; d[o]=x;d[o+1]=y;d[o+2]=r;d[o+3]=d[o+4]=d[o+5]=d[o+6]=d[o+7]=0;d[o+8]=c[0];d[o+9]=c[1];d[o+10]=c[2];d[o+11]=(a===undefined?ctx.globalAlpha:a)*c[3];d[o+12]=1;} diff --git a/tests/webgl-sprites.test.js b/tests/webgl-sprites.test.js new file mode 100644 index 0000000..e5d765c --- /dev/null +++ b/tests/webgl-sprites.test.js @@ -0,0 +1,102 @@ +// The card's pictures (src/game/96-map/59-gl-sprites.js): painted on one reused canvas and sent to the atlas at once, so +// a long zoom does not leave the browser holding a canvas per picture (it lost the graphics context and fell back to 2D). +// The 2D map keeps a canvas per picture. jsdom has no WebGL: a stand-in context records what would go to the card. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { load } = require('./harness'); + +const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); + +function open() { + const h = load({ seed: 777 }); + h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.nextFail=S.day+999;S.nextEvent=S.day+999;compute();`); + return h; +} + +const STUB = `(()=>{const calls=[];const gl=new Proxy({calls},{get(t,k){if(k in t)return t[k];if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k; + return (...a)=>{calls.push([k,...a]);return {};};}}); + const c=document.getElementById('mapgl'),f=document.getElementById('mapfx'); + const P=()=>({p:{},u:{}}),B=()=>({v:{},b:{}}); + Object.assign(GLX,{want:true,dead:false,gl,c,f,fx:f.getContext('2d'),line:P(),pk:P(),fill:P(),fan:P(),ell:P(),land:{},circ:P(),tex:{},lv:B(),hv:B(),pv:B(),cb:B(),wv:B(),cl:B(),empty:{},key:[],gpu:'stub'}); + GLS.prog=P();GLS.vao={};GLS.buf={};GLS.tex={};GLS.size=4096;SPRS.clear();GLS.shx=GLS.shy=GLS.shh=0; + // Counts the canvases the page makes from here on. + const ce=document.createElement.bind(document);window.__canvases=0;document.createElement=function(t){if(String(t).toLowerCase()==='canvas')__canvases++;return ce.apply(document,arguments);}; + return gl;})()`; + +// Frames over a zoom from far to near and back, as a player pinching would. +const ZOOM = `(()=>{const h=CITY[S.home];cam.x=h.x;cam.y=h.y;for(let i=0;i<=40;i++){cam.z=0.5*Math.pow(9,(1-Math.cos(i/40*Math.PI*2))/2);draw(1000+i*16);}})()`; + +test('on the card, pictures are painted on one canvas and each goes into the atlas as it is painted', () => { + const { ev, errors } = open(); + ev(STUB); + ev(ZOOM); + const r = JSON.parse(ev(`(()=>{const subs=GLX.gl.calls.filter(c=>c[0]==='texSubImage2D'),es=[...SPRS.values()]; + return JSON.stringify({canvases:__canvases,subs:subs.length,sprites:es.length,mine:es.filter(e=>e.cv).length, + allUp:es.every(e=>e.up),rect:subs.every(c=>c.length===10&&c[9]===GLS_PAD.cv&&c[5]>0&&c[6]>0), + fit:subs.every(c=>c[5]<=GLS_PAD.cv.width&&c[6]<=GLS_PAD.cv.height),keys:es.length?[...SPRS.keys()].every(k=>k[0]==='g'):false});})()`)); + assert.ok(r.sprites > 50, `a zoom paints many pictures (${r.sprites})`); + assert.ok(r.canvases <= 1, `one canvas for all of them, not one each (${r.canvases} made)`); + assert.equal(r.mine, 0, 'no picture keeps a canvas of its own'); + assert.equal(r.allUp, true, 'every picture is in the atlas'); + assert.ok(r.subs >= r.sprites, 'each was sent once, when painted'); + assert.equal(r.rect, true, 'only its corner of the pad, from the pad'); + assert.equal(r.fit, true); + assert.equal(r.keys, true, 'kept apart from the 2D map’s pictures'); + assert.deepEqual(errors, []); +}); + +test('a full atlas starts again and the picture that did not fit goes into the new one at once', () => { + const { ev, errors } = open(); + ev(STUB); + const r = JSON.parse(ev(`(()=>{GLS.frame=true;GLS.n=0;ctx=GLX.fx;GLS.shy=GLS.size-4;GLS.shx=GLS.size-2;GLS.shh=4; + const before=SPRS.size;let draws=0;const gd=glsDraw;glsDraw=function(){draws++;}; + const e=spriteEntry('big',40,40,20,20,g=>{g.fillRect(0,0,40,40);});blit(e,10,10,40,40); + glsDraw=gd;const r={up:e.up,u0:e.u0,v0:e.v0,kept:SPRS.get('g'+DPR+'|big')===e,size:SPRS.size,n:GLS.n,cv:!!e.cv,shy:GLS.shy};GLS.frame=false;GLS.n=0;ctx=CTX0;return JSON.stringify(r);})()`)); + assert.equal(r.up, true, 'the picture is in the atlas'); + assert.equal(r.u0, 0); assert.equal(r.v0, 0); + assert.equal(r.kept, true, 'and kept under its key after the restart'); + assert.equal(r.size, 1, 'the old pictures are gone'); + assert.equal(r.n, 1, 'drawn this frame'); + assert.equal(r.cv, false); + assert.deepEqual(errors, []); +}); + +test('the 2D map keeps a canvas per picture, and its pictures are not the card’s', () => { + const { ev, errors } = open(); + ev(`mapGl(false);const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;draw(1000);`); + const r = JSON.parse(ev(`(()=>{const es=[...SPRS.entries()];return JSON.stringify({n:es.length,cv:es.every(([k,e])=>k[0]==='c'&&e.cv&&e.cv.width===e.pw&&e.cv.height===e.ph),up:es.some(([,e])=>e.up)});})()`)); + assert.ok(r.n > 10); + assert.equal(r.cv, true, 'each with its own canvas, at its size'); + assert.equal(r.up, false, 'nothing went to a card'); + assert.deepEqual(errors, []); +}); + +test('giving the card up drops its pictures; the 2D map paints its own', () => { + const { ev, errors } = open(); + ev(STUB); + ev(`const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;draw(1000);`); + assert.ok(ev('SPRS.size') > 10); + ev(`window.__warn=0;console.warn=function(){__warn++;};glKill('test')`); + assert.equal(ev('SPRS.size'), 0, 'no picture without a canvas is left behind'); + assert.equal(ev('GLS.shx+GLS.shy+GLS.shh'), 0, 'the atlas is forgotten'); + ev('draw(1016)'); + assert.ok(ev('SPRS.size') > 10); + assert.equal(ev(`[...SPRS.values()].every(e=>e.cv)`), true, 'the 2D map’s pictures have their canvas'); + assert.ok(ev('ctx===CTX0')); + assert.deepEqual(errors, []); +}); + +test('a picture too big for the atlas keeps its own canvas and is painted on the overlay', () => { + const { ev, errors } = open(); + ev(STUB); + const r = JSON.parse(ev(`(()=>{GLS.frame=true;GLS.n=0;ctx=GLX.fx;GLS.size=64;const n0=GLX.fx.calls.n; + const e=spriteEntry('huge',200,30,100,15,g=>{g.fillRect(0,0,200,30);});blit(e,0,0,200,30); + const r={cv:!!e.cv,up:e.up,n:GLS.n,fx:GLX.fx.calls.n-n0};GLS.frame=false;GLS.n=0;ctx=CTX0;GLS.size=4096;return JSON.stringify(r);})()`)); + assert.equal(r.cv, true); + assert.equal(r.up, false); + assert.equal(r.n, 0, 'not queued for the card'); + assert.ok(r.fx >= 1, 'drawn on the overlay instead'); + assert.deepEqual(errors, []); +});