diff --git a/src/game/96-map/56-webgl.js b/src/game/96-map/56-webgl.js index 981aba4..26fae66 100644 --- a/src/game/96-map/56-webgl.js +++ b/src/game/96-map/56-webgl.js @@ -5,29 +5,46 @@ Two canvases sit over #map, which stays empty: #mapgl, where the card draws the background (57), the tubes and packets (58) and the pictures of cities, labels and markers (59); and #mapfx, a transparent 2D canvas over it for the few things still painted shape by shape (the drag preview, the chaos monkey), cleared only after it was used. - Puzzles, and any browser without WebGL2 or whose context fails or is lost, keep the 2D map. So does WebGL drawn by + Puzzles, and any browser without WebGL2 or whose context fails, keep the 2D map; a lost context, until it is back. So does WebGL drawn by the processor (no usable graphics card: a blocked driver, a virtual machine): there every instance of a line costs microseconds, and a big map took a second and a half a frame where the 2D canvas takes 50 ms. */ -const GLX={want:true,dead:false,gl:null,ctx:null,c:null,f:null,fx:null,key:[],nSeg:0,nPk:0,nHalo:0,shown:false,gpu:''}; +const GLX={want:true,dead:false,lost:false,sleep:false,losses:0,lose:null,gl:null,ctx:null,c:null,f:null,fx:null,key:[],nSeg:0,nPk:0,nHalo:0,shown:false,gpu:''}; try{GLX.want=localStorage.getItem('sot-map')!=='2d';}catch(e){} // Renderers that are the processor pretending to be a graphics card (GLX.soft: use them anyway, for the GPU benchmark). const GL_SOFT=/swiftshader|llvmpipe|softpipe|lavapipe|software|basic render/i; const glOn=()=>GLX.want&&!GLX.dead&&!!S&&!pzOn()&&glInit(); // Switches the WebGL map on or off: the setting keeps the choice in this browser (keep), the GPU benchmark does not. +// Chosen in Settings, Always 2D also lets the card's context go (glSleep()), and Auto takes it back. function mapGl(on,keep=true){GLX.want=!!on;if(keep)try{on?localStorage.removeItem('sot-map'):localStorage.setItem('sot-map','2d');}catch(e){} - if(!on)glShow(false);GLX.key=[];UI.drawnAt=0;return on&&!GLX.dead;} + if(!on){glShow(false);if(keep)glSleep();}else if(GLX.sleep){GLX.sleep=false;try{GLX.lose.restoreContext();}catch(e){}} + GLX.key=[];UI.drawnAt=0;return on&&!GLX.dead;} 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.why=String(why&&why.message||why);GLX.dead=true; const gl=GLX.ctx;GLX.gl=GLX.ctx=null;spritesDrop();glFree(gl);glShow(false);} -/* The card given up for good (not Always 2D, which keeps it for later) still held what was sent to it, the atlas alone +/* The card given up for good (not Always 2D: glSleep()) still held what was sent to it, the atlas alone 64 MB, while the 2D map starts painting its own pictures. So its biggest things are deleted and the context let go (WEBGL_lose_context, where the browser has it), unless the browser already lost it, which freed them. glInit() keeps the context in GLX.ctx from the start, so a setup that fails half-way is let go too. */ function glFree(gl){try{if(gl&&gl.isContextLost()===false){for(const x of [GLS.tex,GLX.tex])if(x)gl.deleteTexture(x);if(GLS.buf)gl.deleteBuffer(GLS.buf); const L=gl.getExtension('WEBGL_lose_context');if(L&&typeof L.loseContext==='function')L.loseContext();}}catch(e){} GLS.tex=GLS.buf=GLS.vao=GLS.prog=null;GLX.tex=null;GLX.land={};GLS_PAD.cv=GLS_PAD.g=null;} +/* A lost context comes back. The browser may lose it (a driver reset; on a phone, sometimes just leaving the app) and + give it back (webglcontextrestored): the 2D map draws meanwhile, and everything on the card is built again on the + same context, as for the first frame. A card lost more than GL_LOSSES times is given up for the session, so a card + that keeps failing does not keep the map switching. Always 2D lets the context go the same way (WEBGL_lose_context) + and Auto asks for it back, so 64 MB of atlas and the rest are not held for a map that is not drawn. */ +const GL_LOSSES=2; +// Forgets what was on the card (the context itself is kept): glInit() builds it all again. +function glForget(){GLX.gl=null;spritesDrop();GLS.tex=GLS.buf=GLS.vao=GLS.prog=null;Object.assign(GLX,{tex:null,land:{},ckey:null,key:[]});glShow(false);UI.drawnAt=0;} +function glLost(e){if(GLX.dead)return;e.preventDefault();if(GLX.lost)return; // let go by Always 2D (glSleep()) + if(++GLX.losses>GL_LOSSES){glKill('the graphics context was lost '+GLX.losses+' times');return;} + GLX.lost=true;glForget();} +function glRestored(){if(GLX.dead)return;GLX.lost=false;glForget();if(!GLX.want)glSleep();} +// Always 2D: lets the context go, unless the browser has it already (its restore then finds Always 2D and lets it go). +function glSleep(){const L=GLX.lose;if(!GLX.ctx||GLX.dead||!L||typeof L.restoreContext!=='function')return; + if(GLX.lost){GLX.sleep=true;return;}glForget();GLX.sleep=GLX.lost=true;try{L.loseContext();}catch(e){GLX.sleep=GLX.lost=false;}} /* A card short of memory may refuse a texture or a buffer without throwing: it only leaves OUT_OF_MEMORY for getError(), and the texture then draws black (every picture a black box) or the buffer draws nothing. So the big uploads (the atlas, the land, the tubes, the cables) read it, and give the card up like any of its errors. Never @@ -47,21 +64,21 @@ function glVao(gl,sizes,div=1,data=null){const v=gl.createVertexArray(),b=gl.cre gl.bindVertexArray(v);gl.bindBuffer(gl.ARRAY_BUFFER,b);if(data)gl.bufferData(gl.ARRAY_BUFFER,data,gl.STATIC_DRAW); let off=0;sizes.forEach((n,i)=>{gl.enableVertexAttribArray(i);gl.vertexAttribPointer(i,n,gl.FLOAT,false,stride,off);gl.vertexAttribDivisor(i,div);off+=n*4;}); gl.bindVertexArray(null);return {v,b};} -function glInit(){if(GLX.gl)return true;if(GLX.dead)return false; +function glInit(){if(GLX.gl)return true;if(GLX.dead||GLX.lost)return false; try{const c=document.getElementById('mapgl'),f=document.getElementById('mapfx');if(!c||!f||!c.getContext)throw new Error('no map layers'); const gl=c.getContext('webgl2',{alpha:true,premultipliedAlpha:true,antialias:false,depth:true,stencil:true,powerPreference:'high-performance'}); if(!gl||typeof gl.createShader!=='function')throw new Error('no WebGL2');GLX.ctx=gl; + if(!GLX.lose){c.addEventListener('webglcontextlost',glLost);c.addEventListener('webglcontextrestored',glRestored);try{GLX.lose=gl.getExtension('WEBGL_lose_context')||{};}catch(e){GLX.lose={};}} try{const x=gl.getExtension('WEBGL_debug_renderer_info');GLX.gpu=String(x?gl.getParameter(x.UNMASKED_RENDERER_WEBGL):gl.getParameter(gl.RENDERER));}catch(e){} if(!GLX.soft&&GL_SOFT.test(GLX.gpu))throw new Error('no graphics card, only '+GLX.gpu); const P=(vs,fs)=>glProg(gl,vs,fs),progs={line:P(GL_LINE_VS,GL_LINE_FS),pk:P(GL_PK_VS,GL_PK_FS),fill:P(FILL_VS,FILL_FS),fan:P(FAN_VS,FAN_FS),ell:P(ELL_VS,ELL_FS),circ:P(CIRC_VS,CIRC_FS)}; // The tubes' points for the packets: floats read with texelFetch, never filtered. const tex=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,tex);for(const k of [gl.TEXTURE_MIN_FILTER,gl.TEXTURE_MAG_FILTER])gl.texParameteri(gl.TEXTURE_2D,k,gl.NEAREST); - c.addEventListener('webglcontextlost',e=>{e.preventDefault();if(GLX.dead)return;glKill('the graphics context was lost');UI.drawnAt=0;}); glsInit(gl); // The overlay is cleared only after something was painted on it: clearing a whole screen of empty canvas every // frame makes the browser send the layer to the screen again, which on a 4K screen cost more than the map itself. const fx=f.getContext('2d'),CP=CanvasRenderingContext2D.prototype; - for(const m of ['fill','stroke','fillRect','strokeRect','fillText','strokeText','drawImage','putImageData']){const fn=CP[m];fx[m]=function(){GLX.fxUsed=true;return fn.apply(this,arguments);};} + if(!fx.__fxw){fx.__fxw=true;for(const m of ['fill','stroke','fillRect','strokeRect','fillText','strokeText','drawImage','putImageData']){const fn=CP[m];fx[m]=function(){GLX.fxUsed=true;return fn.apply(this,arguments);};}} const V=s=>glVao(gl,s); Object.assign(GLX,progs,{gl,c,f,fx,fxUsed:true,tex,land:{},lv:V([4,4,4]),hv:V([4,4,4]),pv:V([4,4]),cb:V([4,4,4]),wv:V([4,4,4]),cl:V([4]),empty:gl.createVertexArray()});return true;} catch(e){glKill(e);return false;}} diff --git a/src/game/96-map/97-diagnostics.js b/src/game/96-map/97-diagnostics.js index b5a427e..d80320f 100644 --- a/src/game/96-map/97-diagnostics.js +++ b/src/game/96-map/97-diagnostics.js @@ -9,7 +9,7 @@ function diagFrame(now){const D=DIAG;if(D.last)D.fr.push(now-D.last);D.last=now; if(D.fr.length>600)D.fr.splice(0,300);if(D.dr.length>600)D.dr.splice(0,300);} // What draws the map, and why it is the 2D canvas when it is. function diagMap(){if(!S)return 'map: none (title screen)';if(pzOn())return 'map: 2D (puzzle)';if(!GLX.want)return 'map: 2D (Always 2D)'; - if(GLX.dead)return 'map: 2D ('+(GLX.why||'no WebGL2')+')';return GLX.gl&&GLX.shown?'map: WebGL2 · '+(GLX.gpu||'unknown GPU'):'map: WebGL2 (starting)';} + if(GLX.dead)return 'map: 2D ('+(GLX.why||'no WebGL2')+')';if(GLX.lost)return 'map: 2D (graphics context lost, waiting for it back)';return GLX.gl&&GLX.shown?'map: WebGL2 · '+(GLX.gpu||'unknown GPU'):'map: WebGL2 (starting)';} // Frames since the last readout: per second, the 95th percentile and the slowest, and draw()'s mean. function diagPerf(){const f=DIAG.fr.splice(0),d=DIAG.dr.splice(0),s=f.slice().sort((a,b)=>a-b),sum=f.reduce((a,x)=>a+x,0), q=x=>s.length?s[Math.min(s.length-1,Math.floor(s.length*x))].toFixed(0):'-',gl=GLX.shown&&!GLX.dead; diff --git a/tests/diagnostic-info.test.js b/tests/diagnostic-info.test.js index 324fcf6..2713149 100644 --- a/tests/diagnostic-info.test.js +++ b/tests/diagnostic-info.test.js @@ -47,7 +47,9 @@ test('it says what draws the map, and why it is the 2D canvas', () => { assert.equal(map(), 'map: 2D (Always 2D)'); ev('mapGl(true,false);glKill(new Error("the graphics card is out of memory (the pictures)"))'); assert.equal(map(), 'map: 2D (the graphics card is out of memory (the pictures))'); - ev('GLX.dead=false;GLX.gl={};GLX.shown=true;GLX.gpu="ANGLE (NVIDIA GeForce GTX 980)"'); + ev('GLX.dead=false;GLX.lost=true'); + assert.equal(map(), 'map: 2D (graphics context lost, waiting for it back)'); + ev('GLX.lost=false;GLX.gl={};GLX.shown=true;GLX.gpu="ANGLE (NVIDIA GeForce GTX 980)"'); assert.equal(map(), 'map: WebGL2 · ANGLE (NVIDIA GeForce GTX 980)'); ev('const s=S;S=null;window.__S=s'); assert.equal(map(), 'map: none (title screen)'); diff --git a/tests/webgl-context-restore.test.js b/tests/webgl-context-restore.test.js new file mode 100644 index 0000000..734fa03 --- /dev/null +++ b/tests/webgl-context-restore.test.js @@ -0,0 +1,145 @@ +// A WebGL context can be lost and given back: a driver reset, or on a phone sometimes just leaving the app. The map +// gave the card up for the session at the first loss, so a phone that went to another app came back to the slower 2D +// map until the page was reloaded. It now draws in 2D while the context is away, and builds everything on the card +// again when the browser gives it back (webglcontextrestored), up to GL_LOSSES times a session. Settings › Map drawing +// › Always 2D lets the context go the same way (WEBGL_lose_context), and Auto asks for it back, so a map drawn in 2D +// does not hold 64 MB of atlas on the card. Switching for the GPU benchmark (mapGl(on,false)) keeps the context. +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'); + +/* A WebGL2 context that compiles everything, as tests/webgl-map.test.js's. It can be lost by the "browser" + (__browserLose(), __browserRestore()) or through WEBGL_lose_context (counted in __LOST and __RESTORE; without it when + window.__noExt). Events come at once, which the real ones do not: the code must not rely on either order. Textures + made are counted (__TEX), so a rebuild shows. */ +const GL = `(()=>{window.CanvasRenderingContext2D=window.CanvasRenderingContext2D||class{};window.__LOST=0;window.__RESTORE=0;window.__TEX=0; + let lost=false;const c=document.getElementById('mapgl'),fire=t=>c.dispatchEvent(new window.Event(t,{cancelable:true})); + window.__browserLose=()=>{lost=true;fire('webglcontextlost');};window.__browserRestore=()=>{lost=false;fire('webglcontextrestored');}; + const ext={loseContext:()=>{__LOST++;if(lost)return;lost=true;fire('webglcontextlost');},restoreContext:()=>{__RESTORE++;if(!lost)return;lost=false;fire('webglcontextrestored');}}; + const gl=new Proxy({},{get(t,k){ + if(typeof k==='string'&&/^[A-Z_0-9]+$/.test(k))return k; + if(k==='getExtension')return (n)=>n==='WEBGL_lose_context'?(window.__noExt?null:ext):{UNMASKED_RENDERER_WEBGL:'REN'}; + if(k==='isContextLost')return ()=>lost; + if(k==='createTexture')return ()=>{__TEX++;return {};}; + if(k==='getParameter')return (p)=>p==='REN'?'Stub GPU':p==='ACTIVE_UNIFORMS'?0:4096; + if(k==='getShaderParameter'||k==='getProgramParameter')return (x,p)=>p==='ACTIVE_UNIFORMS'?0:true; + if(k==='getError')return ()=>0; + return ()=>({});}}); + c.getContext=(t)=>t==='webgl2'?gl:null;})()`; + +function open(storage) { + const h = load({ seed: 777, storage }); + h.ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute(); + window.__T=100000;Object.defineProperty(performance,'now',{value:()=>__T,configurable:true});console.warn=()=>{}; + const h=CITY[S.home];cam.x=h.x;cam.y=h.y;cam.z=1.4;`); + h.ev(GL); + return h; +} +const frame = (ev) => ev('__T+=16;draw(__T);JSON.stringify({gl:!!GLX.gl&&GLX.shown,dead:GLX.dead,lost:GLX.lost,sprs:SPRS.size,sprc:SPRC.size,err:!!UI.tickErr})'); + +test('a context the browser loses draws the map in 2D, then on the card again once it is back', () => { + const { ev, errors } = open(); + assert.equal(JSON.parse(frame(ev)).gl, true, 'drawn on the card'); + ev('UI.tickErr=false;__browserLose();'); + let f = JSON.parse(frame(ev)); + assert.deepEqual([f.gl, f.dead, f.lost, f.err], [false, false, true, false], 'in 2D while it is away, without a glitch'); + assert.equal(f.sprs, 0, 'the card’s pictures are forgotten (its atlas went with the context)'); + assert.ok(f.sprc > 0, 'the 2D map paints its own'); + assert.equal(ev('document.getElementById("mapgl").hidden'), true); + ev('window.__t0=__TEX;window.__built=0;const gb=glBuild;glBuild=function(){__built++;return gb.apply(this,arguments);};__browserRestore();'); + f = JSON.parse(frame(ev)); + assert.deepEqual([f.gl, f.dead, f.lost], [true, false, false], 'back on the card'); + assert.ok(ev('__TEX-__t0') >= 2, 'the atlas and the tubes’ points are made again'); + assert.equal(ev('__built'), 1, 'the tubes are built again'); + assert.ok(f.sprs > 0, 'the pictures are sent again'); + assert.equal(ev('GLX.losses'), 1); + assert.deepEqual(errors, []); +}); + +test(`a card lost more than GL_LOSSES times is given up for the session`, () => { + const { ev, errors } = open(); + frame(ev); + const n = ev('GL_LOSSES'); + for (let i = 0; i < n; i++) { ev('__browserLose()'); frame(ev); ev('__browserRestore()'); assert.equal(JSON.parse(frame(ev)).gl, true, `back after loss ${i + 1}`); } + ev('__browserLose()'); + let f = JSON.parse(frame(ev)); + assert.equal(f.dead, true, 'given up'); + assert.match(ev('GLX.why'), /lost 3 times/); + assert.equal(ev('__LOST'), 0, 'nothing to let go: the browser already did'); + // A late restore does not bring it back. + ev('__browserRestore()'); + f = JSON.parse(frame(ev)); + assert.deepEqual([f.gl, f.dead], [false, true]); + assert.deepEqual(errors, []); +}); + +test('Always 2D lets the context go, Auto takes it back, and neither counts as a loss', () => { + const { ev, errors } = open(); + frame(ev); + ev("ACT.mapSet({v:'2d'})"); + assert.equal(ev('__LOST'), 1, 'the context is let go'); + assert.equal(ev('GLX.gl===null&&GLS.tex===null&&SPRS.size===0'), true, 'nothing on the card is held'); + let f = JSON.parse(frame(ev)); + assert.deepEqual([f.gl, f.dead], [false, false]); + assert.equal(ev('localStorage.getItem("sot-map")'), '2d'); + ev("ACT.mapSet({v:'auto'})"); + assert.equal(ev('__RESTORE'), 1, 'asked back'); + f = JSON.parse(frame(ev)); + assert.deepEqual([f.gl, f.dead, f.lost], [true, false, false], 'on the card again'); + assert.equal(ev('GLX.losses'), 0, 'the player’s choice is not a failure'); + // Back and forth: still fine, still not counted. + for (let i = 0; i < 4; i++) { ev("ACT.mapSet({v:'2d'})"); frame(ev); ev("ACT.mapSet({v:'auto'})"); } + assert.equal(JSON.parse(frame(ev)).gl, true); + assert.equal(ev('GLX.losses'), 0); + assert.deepEqual(errors, []); +}); + +test('a context the browser gives back after the player chose Always 2D is let go again', () => { + const { ev, errors } = open(); + frame(ev); + ev('__browserLose()'); + ev("ACT.mapSet({v:'2d'})"); + assert.equal(ev('__LOST'), 0, 'already lost: nothing to let go yet'); + ev('__browserRestore()'); + assert.equal(ev('__LOST'), 1, 'let go as soon as it is back'); + assert.equal(JSON.parse(frame(ev)).gl, false); + ev("ACT.mapSet({v:'auto'})"); + assert.equal(JSON.parse(frame(ev)).gl, true); + assert.deepEqual(errors, []); +}); + +test('the GPU benchmark switches maps without letting the context go', () => { + const { ev, errors } = open(); + frame(ev); + ev('mapGl(false,false)'); + assert.equal(JSON.parse(frame(ev)).gl, false); + ev('mapGl(true,false)'); + assert.equal(JSON.parse(frame(ev)).gl, true); + assert.equal(ev('__LOST+__RESTORE'), 0); + assert.deepEqual(errors, []); +}); + +test('without WEBGL_lose_context, Always 2D keeps the context, as before', () => { + const { ev, errors } = open(); + ev('window.__noExt=true'); + frame(ev); + ev("ACT.mapSet({v:'2d'})"); + assert.equal(JSON.parse(frame(ev)).gl, false); + assert.equal(ev('!!GLX.gl'), true, 'kept for later'); + ev("ACT.mapSet({v:'auto'})"); + assert.equal(JSON.parse(frame(ev)).gl, true); + assert.deepEqual(errors, []); +}); + +test('a game started with Always 2D never makes a context', () => { + const { ev, errors } = open({ 'sot-map': '2d' }); + ev('window.__made=0;const gc=document.getElementById("mapgl").getContext;document.getElementById("mapgl").getContext=t=>{__made++;return gc(t);};'); + frame(ev); + ev("ACT.settings({})"); + assert.equal(ev('__made'), 0); + assert.deepEqual(errors, []); +}); diff --git a/tests/webgl-out-of-memory.test.js b/tests/webgl-out-of-memory.test.js index b09577c..fb54011 100644 --- a/tests/webgl-out-of-memory.test.js +++ b/tests/webgl-out-of-memory.test.js @@ -135,13 +135,14 @@ test('a setup that fails half-way lets its context go too', () => { assert.deepEqual(errors, []); }); +// A context the browser lost may come back (tests/webgl-context-restore.test.js): it is waited for, not let go. test('a context the browser lost is not let go a second time', () => { const { ev, errors } = open({}); assert.equal(ev('glInit()'), true); ev('__T+=16;draw(__T);'); - ev('window.__lostNow=true;document.getElementById("mapgl").dispatchEvent(new window.Event("webglcontextlost"));'); - assert.equal(ev('GLX.dead'), true); - assert.equal(ev('GLX.why'), 'the graphics context was lost'); + ev('window.__lostNow=true;document.getElementById("mapgl").dispatchEvent(new window.Event("webglcontextlost",{cancelable:true}));'); + assert.equal(ev('GLX.dead'), false, 'waiting for it to come back'); + assert.equal(ev('GLX.lost&&!glOn()'), true, 'the 2D map draws meanwhile'); assert.equal(ev('__LOST'), 0, 'nothing to let go: the browser already did'); ev('__T+=16;draw(__T);'); assert.deepEqual(errors, []);