From d3174600e758242551bf45e3e155e6e79b11d3dd Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Sun, 1 Nov 2026 16:40:38 +0100 Subject: [PATCH] Pie in the Sky: animated 3D globe for Pie Control, with a night view An orthographic Earth on a 2D canvas (sticker look, plus a night view with stars, city lights and terminator) showing a capped sample of each crust's pies, laser links, pie-dish beams and launches. One rAF loop only while open (30 fps cap, DPR <= 2, idle while hidden), nothing left behind once closed. Land comes from LANDS_LL. The world map only gets a pink pie-dish badge at cities with a dish, behind one null check per visible city when there are none. --- site/i18n/de.js | 3 + site/i18n/es.js | 3 + site/i18n/fr.js | 3 + site/i18n/it.js | 3 + site/i18n/pt.js | 3 + src/game/90-actions/98-pie-globe.js | 4 + src/game/95-modals/30-modal-and-names.js | 2 +- src/game/96-map/60-draw.js | 2 +- src/game/96-map/80-cities.js | 9 +- src/game/96-map/89-pie-globe.js | 151 +++++++++++++++++++++++ src/i18n/en.js | 3 + src/styles/38-pie-globe.css | 5 + tests/pie-globe.test.js | 150 ++++++++++++++++++++++ 13 files changed, 338 insertions(+), 3 deletions(-) create mode 100644 src/game/90-actions/98-pie-globe.js create mode 100644 src/game/96-map/89-pie-globe.js create mode 100644 src/styles/38-pie-globe.css create mode 100644 tests/pie-globe.test.js diff --git a/site/i18n/de.js b/site/i18n/de.js index a08d527..1f339e5 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -3497,6 +3497,9 @@ "pie.why_queue_full":"Der Startplan ist voll.", "pie.why_stock":"Braucht {n} Pies; die Fabrik hat {have}.", "pie.would_have":"Hätte gekostet", +"pie_globe.switch_to_day_view":"Zur Tagansicht wechseln", +"pie_globe.switch_to_night_view":"Zur Nachtansicht wechseln", +"pie_globe.your_pies_in_orbit":"Deine Kuchen im Orbit, zum Drehen der Erde ziehen", "pitcairn.uk_grant_mo":"Zuschuss aus UK {mo}/Monat", "pitcairn.uk_grant_mo_once_islanders":"Zuschuss aus UK {mo}/Monat, sobald die Inselbewohner online sind", "pni_all.additional_per_month":"Zusätzliche Kosten pro Monat", diff --git a/site/i18n/es.js b/site/i18n/es.js index f484ba5..e3b4cca 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -3495,6 +3495,9 @@ "pie.why_queue_full":"El calendario de lanzamientos está lleno.", "pie.why_stock":"Necesita {n} tartas; la fábrica tiene {have}.", "pie.would_have":"Habría costado", +"pie_globe.switch_to_day_view":"Cambiar a vista de día", +"pie_globe.switch_to_night_view":"Cambiar a vista nocturna", +"pie_globe.your_pies_in_orbit":"Tus tartas en órbita, arrastra para girar la Tierra", "pitcairn.uk_grant_mo":"Subvención británica {mo}/mes", "pitcairn.uk_grant_mo_once_islanders":"Subvención británica {mo}/mes cuando los isleños estén en línea", "pni_all.additional_per_month":"Coste mensual adicional", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 477ae5a..1ec730a 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -3495,6 +3495,9 @@ "pie.why_queue_full":"Le calendrier des lancements est plein.", "pie.why_stock":"Il faut {n} tartes ; l'usine en a {have}.", "pie.would_have":"Aurait coûté", +"pie_globe.switch_to_day_view":"Passer en vue de jour", +"pie_globe.switch_to_night_view":"Passer en vue de nuit", +"pie_globe.your_pies_in_orbit":"Tes tartes en orbite, fais glisser pour tourner la Terre", "pitcairn.uk_grant_mo":"Subvention britannique {mo}/mois", "pitcairn.uk_grant_mo_once_islanders":"Subvention britannique {mo}/mois une fois les insulaires en ligne", "pni_all.additional_per_month":"Coût mensuel supplémentaire", diff --git a/site/i18n/it.js b/site/i18n/it.js index ff3d410..e99b917 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -3495,6 +3495,9 @@ "pie.why_queue_full":"Il calendario dei lanci è pieno.", "pie.why_stock":"Servono {n} torte; la fabbrica ne ha {have}.", "pie.would_have":"Sarebbe costato", +"pie_globe.switch_to_day_view":"Passa alla vista diurna", +"pie_globe.switch_to_night_view":"Passa alla vista notturna", +"pie_globe.your_pies_in_orbit":"Le tue torte in orbita, trascina per girare la Terra", "pitcairn.uk_grant_mo":"Contributo UK {mo}/mese", "pitcairn.uk_grant_mo_once_islanders":"Contributo UK {mo}/mese quando gli isolani saranno online", "pni_all.additional_per_month":"Costo mensile aggiuntivo", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 83dcde8..3388dad 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -3495,6 +3495,9 @@ "pie.why_queue_full":"O calendário de lançamentos está cheio.", "pie.why_stock":"Precisa de {n} tortas; a fábrica tem {have}.", "pie.would_have":"Teria custado", +"pie_globe.switch_to_day_view":"Mudar para a visão diurna", +"pie_globe.switch_to_night_view":"Mudar para a visão noturna", +"pie_globe.your_pies_in_orbit":"Suas tortas em órbita, arraste para girar a Terra", "pitcairn.uk_grant_mo":"Subsídio do Reino Unido {mo}/mês", "pitcairn.uk_grant_mo_once_islanders":"Subsídio do Reino Unido {mo}/mês quando os ilhéus estiverem online", "pni_all.additional_per_month":"Custo mensal adicional", diff --git a/src/game/90-actions/98-pie-globe.js b/src/game/90-actions/98-pie-globe.js new file mode 100644 index 0000000..281bd31 --- /dev/null +++ b/src/game/90-actions/98-pie-globe.js @@ -0,0 +1,4 @@ +// The Pie Control globe's day/night switch (96-map/89-pie-globe.js). Display only: nothing in the save changes. +Object.assign(ACT,{ + pieGlobeNight:()=>{pieGlobeNight(!PG.night);}, +}); diff --git a/src/game/95-modals/30-modal-and-names.js b/src/game/95-modals/30-modal-and-names.js index bf56ba4..5c9f272 100644 --- a/src/game/95-modals/30-modal-and-names.js +++ b/src/game/95-modals/30-modal-and-names.js @@ -1,7 +1,7 @@ // Keyboard focus moves into the modal, so Enter or Space can't keep pressing a hidden button behind it. // The link check on phones sits above the tab bar and is not modal, so the tabs stay usable. function openModal(html,cls=''){HOOKS.modal?.(true);$('modal').className=cls;$('modalCard').setAttribute('aria-modal',cls==='link-check'&&isPhone()?'false':'true');if($('modal').hidden)markLayer();$('modalCard').innerHTML=html;$('modal').hidden=false;const a=document.activeElement;if(a&&a!==document.body&&!a.closest('#modal')){a.blur();const m=$('modalCard');m.tabIndex=-1;m.focus({preventScroll:true});}} -function closeModal(){if(!$('modal').hidden)markLayer();$('modal').hidden=true;UI.pending=null;HOOKS.modal?.(false);} +function closeModal(){if(!$('modal').hidden)markLayer();pieGlobeClose();$('modal').hidden=true;UI.pending=null;HOOKS.modal?.(false);} const NETWORK_NAMES=[ 'Packet Pals','Shinternet','Post, Telegraph & Tubes','Peering Pressure','Best Effort Telecom', 'Mostly Online','Buffering & Sons','Lord of the Pings','The Ping Dynasty', diff --git a/src/game/96-map/60-draw.js b/src/game/96-map/60-draw.js index 9e29039..ae2dcdf 100644 --- a/src/game/96-map/60-draw.js +++ b/src/game/96-map/60-draw.js @@ -104,7 +104,7 @@ function drawFrame(now){ const farL=lodFar(); // Which cities show an offer bubble (a big one?) or an incident marker, worked out once for all of them. CM.off=new Set();CM.big=new Set();for(const o of S.offers){const big=BIZ_T[o.type].lv>=3||BIZ_T[o.type].event;for(const c of bCities(o)){CM.off.add(c);if(big)CM.big.add(c);}} - CM.inc=new Set(S.inc.filter(i=>i.type!=='leak').map(i=>i.ref));CM.far=farL; + CM.inc=new Set(S.inc.filter(i=>i.type!=='leak').map(i=>i.ref));CM.far=farL;CM.dish=pieDishMap(); // Zoomed in, crowded small cities give way to bigger ones and become dots (75-city-size.js). const csc=cityScale(sc);if(farL)for(const v of vis)v.dem=false;else cityRoom(vis,csc); if(pzOn()&&!farL)for(const v of vis)if(pzQuiet(v.C.id))v.dem=true; diff --git a/src/game/96-map/80-cities.js b/src/game/96-map/80-cities.js index 3c6eb38..44cc489 100644 --- a/src/game/96-map/80-cities.js +++ b/src/game/96-map/80-cities.js @@ -1,5 +1,10 @@ // Label widths by text (city labels by id, link labels and far-view labels by text): measuring text every frame is slow. -const LBLW={},LINKW=new Map(),LBLF=new Map(),FKEY=new Map(),QKEY=new Map(),CM={off:new Set(),big:new Set(),inc:new Set(),far:false}; +const LBLW={},LINKW=new Map(),LBLF=new Map(),FKEY=new Map(),QKEY=new Map(),CM={off:new Set(),big:new Set(),inc:new Set(),far:false,dish:null}; +// Pie dishes (Pie in the Sky): city -> up?, or null without any, so most maps pay one null check per city. +function pieDishMap(){const d=S.pie&&S.pie.dishes;if(!Array.isArray(d)||!d.length)return null;const m=new Map();for(const x of d)if(x&&x.city)m.set(x.city,m.get(x.city)||!(x.down>S.day));return m;} +// Painted once per look and drawn as a sprite, so it shows on the graphics-card map as well. +function dishBadge(x,y,up,k=1){stamp(up?'dish|1':'dish|0',16,16,8,8,k,x,y,()=>dishPaint(0,0,up));} +function dishPaint(x,y,up){ctx.fillStyle=up?'#FF4F9A':'#8A91A8';ctx.strokeStyle='#1E2640';ctx.lineWidth=1.6;ctx.beginPath();ctx.arc(x,y,5.5,0,7);ctx.fill();ctx.stroke();ctx.strokeStyle='#fff';ctx.lineWidth=1.4;ctx.beginPath();ctx.arc(x,y-1,3,0.15*Math.PI,0.85*Math.PI);ctx.moveTo(x,y+2);ctx.lineTo(x+2.6,y-2.6);ctx.stroke();ctx.strokeStyle='#1E2640';} try{document.fonts&&document.fonts.ready.then(()=>{for(const k in LBLW)delete LBLW[k];LINKW.clear();LBLF.clear();FRAME.length=0;spritesReset();});}catch(e){} // A label on a pill: its text and look never change, so it is painted once (spriteEntry) and drawn as a picture. The // centre is x, y; the text sits at y+ty. The pill's box is w×h with corners r; the picture also takes the outline. @@ -21,6 +26,7 @@ function drawCityFar(C,sx,sy,sc,now,lyOverride){ // The key, kept per city and built again only when the picture changes. let m=FKEY.get(C.id);if(!m||m.f!==f||m.t!==t||m.ph!==ph)FKEY.set(C.id,m={f,t,ph,k:'far|'+t+'|'+f+'|'+ph}); stamp(m.k,36,36,18,18,1,sx,sy,()=>cityFarStatic(C,p,down,sel,hov,ph)); + if(CM.dish&&CM.dish.has(C.id))dishBadge(sx+(p?10:6),sy+(p?6:5),CM.dish.get(C.id)); if(lyOverride!==null&&(p||sel||hov)){ctx.font=`800 ${p?12:11}px "Baloo 2", sans-serif`;const t=C.name,wk=C.id+(p?1:0);let tw=LBLF.get(wk);if(tw===undefined)LBLF.set(wk,tw=ctx.measureText(t).width+12);const ly=lyOverride==null?sy+15:lyOverride; pill(t,ctx.font,tw,16,8,p?'#FF4F9A':'#FFFFFF',p?'#FFFFFF':'#1E2640','#1E2640',1.6,sx,ly,1);} } @@ -130,6 +136,7 @@ function drawCity(C,sx,sy,sc,now,lyOverride,dem){ if(ph.gl>=0)dot(sx,sy-6*k,26*k,'rgba(255,77,94,1)',.35+.25*(2*ph.gl/7-1)); blit(spr,sx-spr.ax*r,sy-spr.ay*r,spr.w*r,spr.h*r); cityMoving(C,p,t,cs,k,sx,sy,now,p?18:SKY_H[t],st,hot); + if(CM.dish&&p&&CM.dish.has(C.id))dishBadge(sx,sy-13*k,CM.dish.get(C.id),k); // between the antennas: the corners are taken // label if((cam.z>=0.62||p||sel||hov)&&(lyOverride!==null||hov)){ ctx.font=`800 ${p?13:12}px "Baloo 2", sans-serif`;const t=C.name,tw=LBLW[C.id+(p?1:0)]||(LBLW[C.id+(p?1:0)]=ctx.measureText(t).width+14),ly=lyOverride==null?sy+16*sc+8:lyOverride; diff --git a/src/game/96-map/89-pie-globe.js b/src/game/96-map/89-pie-globe.js new file mode 100644 index 0000000..8aa1add --- /dev/null +++ b/src/game/96-map/89-pie-globe.js @@ -0,0 +1,151 @@ +/* Pie in the Sky globe (Pie Control panel): an orthographic Earth on a 2D canvas with a sample of your pies in their + crusts, laser links, pie-dish beams and launches. Never drawn on the world map. It costs nothing until the panel calls + pieGlobeOpen(canvas,getData): then one rAF loop, at most 30 frames a second, idle while the canvas is hidden; it stops + by itself (pieGlobeClose()) once the canvas leaves the page. Positions come from the clock, so nothing is saved. */ +const PG_D=Math.PI/180,PG_XF=2.6,PG_FPS=30,PG_FULL={short:1584,frozen:520,upper:1200,flaky:2500},PG_CI={short:0,frozen:1,upper:2,flaky:3}; +const PG_ST={ + day:{sea:'#57C4E5',sea2:'#3AA6CF',land:'#9BDA6C',ink:'#1E2640',grid:'rgba(255,255,255,.35)',sat:['#FFFFFF','#FFD23F','#FF4F9A','#B9A6FF'],laser:'#FF4F9A',beam:['#FF8A3D','#FFD23F'],dish:'#FF4F9A',off:'#8A91A8'}, + night:{bg:'#0B1030',sea:'#14234F',sea2:'#0B1638',land:'#24396F',ink:'#3E5BB0',grid:'rgba(120,150,255,.10)',sat:['#7DF9FF','#FFD23F','#FF7AC0','#C9B8FF'],laser:'rgba(255,79,154,.75)',beam:['rgba(255,210,63,.65)','rgba(255,138,61,.5)'],dish:'#FFD23F',off:'#4A5378'}}; +// The whole state of the globe. cv is null whenever it is closed, and then nothing below runs. +const PG={cv:null,ctx:null,get:null,raf:0,last:0,t:0,yaw:-20,tilt:18,vy:0,drag:null,night:null,anim:true,dirty:true, + data:null,dAt:-1e9,sig:'',sm:[],dish:[],pads:[],lch:[],on:null,g:null,frames:0,m:new Float64Array(9)}; +let PG_LAND=null,PG_GRID=null,PG_LIGHT=null,PG_STAR=null; +const pgNightPref=()=>{if(PG.night===null){try{PG.night=localStorage.getItem('sot-globe')==='night';}catch(e){PG.night=false;}}return PG.night;}; +// Unit vectors for the land rings (LANDS_LL), the graticule, city lights and stars: worked out once, on first open. +function pgUnit(lo,la,a,i){const b=la*PG_D,c=Math.cos(b),o=lo*PG_D;a[i]=c*Math.cos(o);a[i+1]=c*Math.sin(o);a[i+2]=Math.sin(b);} +function pgVecs(){if(PG_LAND)return; + PG_LAND=LANDS_LL.map(l=>{const a=new Float32Array(l.ll.length*3);l.ll.forEach((q,i)=>pgUnit(q[0],q[1],a,i*3));return a;}); + PG_GRID=[];for(let lo=-180;lo<180;lo+=30){const a=new Float32Array(31*3);for(let j=0;j<=30;j++)pgUnit(lo,-90+j*6,a,j*3);PG_GRID.push(a);} + for(let la=-60;la<=60;la+=30){const a=new Float32Array(61*3);for(let j=0;j<=60;j++)pgUnit(-180+j*6,la,a,j*3);PG_GRID.push(a);} + const cs=CITIES.filter(c=>isFinite(c.lat)&&isFinite(c.lon));PG_LIGHT={v:new Float32Array(cs.length*3),r:cs.map(c=>1.1+Math.min(1.6,(c.P||0)/400))};cs.forEach((c,i)=>pgUnit(c.lon,c.lat,PG_LIGHT.v,i*3)); + let s=7;const r=()=>(s=(s*16807)%2147483647)/2147483647;PG_STAR=[];for(let i=0;i<140;i++)PG_STAR.push([r(),r(),r()*9]);} +// Camera: yaw about the poles, then tilt towards the viewer. Out: d (towards the viewer), h (right), v (up). +function pgCam(){const m=PG.m,cy=Math.cos(PG.yaw*PG_D),sy=Math.sin(PG.yaw*PG_D),ct=Math.cos(PG.tilt*PG_D),st=Math.sin(PG.tilt*PG_D); + m[0]=cy*ct;m[1]=-sy*ct;m[2]=st;m[3]=sy;m[4]=cy;m[5]=0;m[6]=-cy*st;m[7]=sy*st;m[8]=ct;} +function pgRot(src,dst,n){const m=PG.m;for(let i=0;i(PG.buf&&PG.buf.length>=n*3)?PG.buf:(PG.buf=new Float32Array(Math.max(n*3,4096))); +// Data from the panel, read once a second, never trusted: bad entries are dropped, not drawn. +const pgNum=(x,d)=>typeof x==='number'&&isFinite(x)?x:d,pgArr=x=>Array.isArray(x)?x:[]; +function pgPlace(list,cap){const out=[];for(const o of pgArr(list)){if(out.length>=cap)break;if(!o)continue;const C=o.city&&typeof CITY!=='undefined'?CITY[o.city]:null; + const lat=pgNum(o.lat,C?C.lat:NaN),lon=pgNum(o.lon,C?C.lon:NaN);if(!isFinite(lat)||!isFinite(lon))continue;const v=new Float32Array(3);pgUnit(lon,lat,v,0);out.push({v,up:o.up!==false});}return out;} +function pgRefresh(now){PG.dAt=now;let d=null;try{d=PG.get?PG.get():null;}catch(e){d=null;}d=d&&typeof d==='object'?d:{}; + const cr=pgArr(d.crusts).filter(c=>c&&pgNum(c.n,0)>0).slice(0,8),ph=isPhone(),cap=ph?80:160; + const sig=ph+'|'+cr.map(c=>[c.id,c.n,c.alt,c.inc,!!c.las].join(':')).join(','); + if(sig!==PG.sig){PG.sig=sig;PG.sm=cr.map((c,j)=>{const n=Math.floor(pgNum(c.n,0)),full=PG_FULL[c.id]||1000,alt=Math.max(200,Math.min(2000,pgNum(c.alt,550))); + // A sample, not every pie: more dots as the crust fills, up to the cap. + const cnt=Math.min(n,Math.max(Math.min(n,6),Math.round(cap*Math.min(1,n/full)))),inc=Math.max(0,Math.min(180,pgNum(c.inc,53))),polar=inc>=80; + const P=Math.max(1,Math.round(polar?Math.sqrt(cnt/2):Math.sqrt(cnt*1.2))),K=Math.ceil(cnt/P),span=polar?Math.PI:2*Math.PI; + const co=new Float32Array(P),so=new Float32Array(P);for(let p=0;pa[i]<0&&a[i+1]*a[i+1]+a[i+2]*a[i+2]<1; +function pgFrame(now,force){ + const cv=PG.cv;if(!cv)return false; + if(!cv.isConnected){pieGlobeClose();return false;} + let W=cv.clientWidth,H=cv.clientHeight;if((!W||!H)&&force){W=300;H=300;} + if(!W||!H||document.hidden)return false; + if(!force&&now-PG.last<1000/PG_FPS-2)return false; + const dt=Math.min(0.1,Math.max(0,(now-(PG.last||now))/1000));PG.last=now; + if(now-PG.dAt>1000)pgRefresh(now); + if(PG.drag){}else if(Math.abs(PG.vy)>0.01){PG.yaw+=PG.vy*dt;PG.vy*=Math.pow(0.04,dt);PG.dirty=true;}else if(PG.anim){PG.yaw+=4*dt;} + if(PG.anim)PG.t+=dt;else if(!PG.dirty&&!force)return false; + PG.dirty=false;PG.frames++; + const ctx=PG.ctx,dpr=Math.min(2,window.devicePixelRatio||1),pw=Math.round(W*dpr),ph=Math.round(H*dpr); + if(cv.width!==pw||cv.height!==ph){cv.width=pw;cv.height=ph;} + ctx.setTransform(dpr,0,0,dpr,0,0);pgDraw(ctx,W,H);return true;} +function pgDraw(ctx,W,H){ + const night=!!PG.night,st=night?PG_ST.night:PG_ST.day,t=PG.t;pgCam();pgSats(); + let mr=1;for(const c of PG.sm)if(c.rr>mr)mr=c.rr; + const cx=W/2,cy=H/2,R=Math.min(W,H)*0.47/(mr+0.04),P=(a,i)=>[cx+R*a[i+1],cy-R*a[i+2]]; + const gk=W+'|'+H+'|'+R+'|'+night;if(!PG.g||PG.g.k!==gk){const sea=ctx.createRadialGradient(cx-R*.35,cy-R*.35,R*.1,cx,cy,R);sea.addColorStop(0,st.sea);sea.addColorStop(1,st.sea2); + let sh;if(night){sh=ctx.createRadialGradient(cx-R*.7,cy-R*.35,R*.2,cx-R*.7,cy-R*.35,R*2);sh.addColorStop(0,'rgba(0,0,20,0)');sh.addColorStop(.45,'rgba(0,0,20,0)');sh.addColorStop(1,'rgba(0,0,20,.62)');} + else{sh=ctx.createRadialGradient(cx-R*.45,cy-R*.5,0,cx-R*.45,cy-R*.5,R*.6);sh.addColorStop(0,'rgba(255,255,255,.35)');sh.addColorStop(1,'rgba(255,255,255,0)');} + PG.g={k:gk,sea,sh};} + ctx.clearRect(0,0,W,H); + if(night){ctx.fillStyle=st.bg;ctx.fillRect(0,0,W,H); + // Twinkling stars, in four brightness steps: four fills instead of one per star. + for(let b=0;b<4;b++){ctx.beginPath();for(const s of PG_STAR){const a=Math.abs(Math.sin(t*0.7+s[2]));if(Math.min(3,a*4|0)===b)ctx.rect(s[0]*W,s[1]*H,1.4,1.4);}ctx.fillStyle=`rgba(255,255,255,${.25+b*.2})`;ctx.fill();}} + const sats=(front)=>{for(const c of PG.sm){const a=c.pos,col=st.sat[c.col%4],r=front?3.2:2.2;let any=false; + if(night){ctx.beginPath();for(let i=0;i=0)!==front||pgHid(a,i))continue;const x=cx+R*a[i+1],y=cy-R*a[i+2];ctx.moveTo(x+r*2.4,y);ctx.arc(x,y,r*2.4,0,7);any=true;} + if(!any)continue;ctx.fillStyle=col;ctx.globalAlpha=front?.25:.1;ctx.fill(); + ctx.beginPath();for(let i=0;i=0)!==front||pgHid(a,i))continue;const x=cx+R*a[i+1],y=cy-R*a[i+2];ctx.moveTo(x+r*.8,y);ctx.arc(x,y,r*.8,0,7);}ctx.globalAlpha=front?1:.45;ctx.fill();ctx.globalAlpha=1;} + else{ctx.beginPath();for(let i=0;i=0)!==front||pgHid(a,i))continue;const x=cx+R*a[i+1],y=cy-R*a[i+2];ctx.moveTo(x+r,y);ctx.arc(x,y,r,0,7);any=true;} + if(!any)continue;ctx.globalAlpha=front?1:.45;ctx.fillStyle=col;ctx.fill();ctx.lineWidth=front?1.4:1;ctx.strokeStyle=st.ink;ctx.stroke();ctx.globalAlpha=1;}}}; + sats(false); + // The Earth: offset ink shadow, sea, graticule, land, then light and shade. + if(!night){ctx.beginPath();ctx.arc(cx+6,cy+6,R,0,7);ctx.fillStyle=st.ink;ctx.fill();} + ctx.beginPath();ctx.arc(cx,cy,R,0,7);ctx.fillStyle=PG.g.sea;ctx.fill(); + ctx.save();ctx.beginPath();ctx.arc(cx,cy,R,0,7);ctx.clip(); + const buf=pgBuf(61);ctx.beginPath();for(const g of PG_GRID){const n=g.length/3;pgRot(g,buf,n);let on=false; + for(let i=0;i=0){any=true;break;}if(!any)continue; + for(let i=0;i0.08)ds.push(d);} + ctx.beginPath();let nb=0;for(const d of ds){if(!d.up)continue;const g=d.s;let best=-1,bc=null,bd=0.3; + for(const c of PG.sm){const a=c.pos;for(let i=0;i=0){ctx.moveTo(cx+R*g[1],cy-R*g[2]);ctx.lineTo(cx+R*bc[best+1],cy-R*bc[best+2]);nb++;}} + if(nb){ctx.lineWidth=1.6;ctx.setLineDash([3,3]);ctx.lineDashOffset=-t*8;ctx.strokeStyle=st.beam[0];ctx.stroke();ctx.lineDashOffset=-t*8+3;ctx.strokeStyle=st.beam[1];ctx.stroke();ctx.setLineDash([]);ctx.lineDashOffset=0;} + // Laser links between neighbouring pies, along the plane and to the next plane, near side only. + for(const c of PG.sm){if(!c.las||c.cnt<2)continue;const a=c.pos,K=c.K,n=c.cnt;ctx.beginPath(); + for(let i=0;i=0){ctx.moveTo(x,y);ctx.lineTo(cx+R*a[j*3+1],cy-R*a[j*3+2]);} + const q=((p+1)%c.P)*K+k;if(i%2===0&&q=0){ctx.moveTo(x,y);ctx.lineTo(cx+R*a[q*3+1],cy-R*a[q*3+2]);}} + ctx.strokeStyle=st.laser;ctx.lineWidth=1.2;ctx.globalAlpha=.55;ctx.stroke();ctx.globalAlpha=1;} + for(const up of [true,false]){ctx.beginPath();let any=false;for(const d of ds){if(d.up!==up)continue;const [x,y]=P(d.s,0);ctx.moveTo(x+4.5,y);ctx.arc(x,y,4.5,0,7);any=true;} + if(any){ctx.fillStyle=up?st.dish:st.off;ctx.fill();ctx.lineWidth=1.5;ctx.strokeStyle=night?'#0B1030':st.ink;ctx.stroke();}} + sats(true); + // Launch pads, and a rocket climbing from each launch every five seconds, staggered. + ctx.beginPath();let np=0;for(const d of PG.pads){const b=pgRot(d.v,d.s||(d.s=new Float32Array(3)),1);if(b[0]<0.05)continue;const [x,y]=P(b,0);ctx.moveTo(x-4,y+3);ctx.lineTo(x,y-5);ctx.lineTo(x+4,y+3);ctx.closePath();np++;} + if(np){ctx.fillStyle='#FF8A3D';ctx.fill();ctx.lineWidth=1.3;ctx.strokeStyle=night?'#0B1030':st.ink;ctx.stroke();} + const tv=new Float32Array(33),tp=new Float32Array(33); + PG.lch.forEach((L,li)=>{const ph=((t+li*2.3)%5)/2.6;if(ph>1)return;const b=pgRot(L.v,tp,1);if(b[0]<0.05)return; + // Climb and lean east: the trail is the launch's path so far. + const la=Math.asin(L.v[2])/PG_D,lo=Math.atan2(L.v[1],L.v[0])/PG_D;for(let s=0;s<=10;s++){const f=ph*s/10,r=1+f*f*0.7;pgUnit(lo+f*f*28,la+f*6,tv,s*3);tv[s*3]*=r;tv[s*3+1]*=r;tv[s*3+2]*=r;} + pgRot(tv,tp,11);ctx.beginPath();for(let s=0;s<=10;s++){const x=cx+R*tp[s*3+1],y=cy-R*tp[s*3+2];if(s)ctx.lineTo(x,y);else ctx.moveTo(x,y);} + ctx.lineCap='round';ctx.lineWidth=4;ctx.strokeStyle='rgba(255,138,61,.85)';ctx.stroke();ctx.lineWidth=1.5;ctx.strokeStyle='#FFD23F';ctx.stroke();ctx.lineCap='butt'; + ctx.beginPath();ctx.arc(cx+R*tp[31],cy-R*tp[32],3.5,0,7);ctx.fillStyle='#FFFFFF';ctx.fill();ctx.strokeStyle=night?'#0B1030':st.ink;ctx.lineWidth=1.2;ctx.stroke();});} +function pgLoop(now){PG.raf=0;if(!PG.cv)return;pgFrame(now,false);if(PG.cv)PG.raf=requestAnimationFrame(pgLoop);} +// Drag to turn the Earth; it keeps turning a little after you let go. +function pgDown(e){const cv=PG.cv;if(!cv)return;PG.drag={x:e.clientX,y:e.clientY,yaw:PG.yaw,tilt:PG.tilt,lx:e.clientX,lt:performance.now(),v:0};PG.vy=0;try{cv.setPointerCapture(e.pointerId);}catch(_){}cv.style.cursor='grabbing';} +function pgMove(e){const d=PG.drag;if(!d)return;PG.yaw=d.yaw+(e.clientX-d.x)*0.4;PG.tilt=Math.max(-60,Math.min(60,d.tilt+(e.clientY-d.y)*0.3)); + const now=performance.now(),dt=(now-d.lt)/1000;if(dt>0.008){d.v=(e.clientX-d.lx)*0.4/dt;d.lx=e.clientX;d.lt=now;}PG.dirty=true;} +function pgUp(){const d=PG.drag;if(!d)return;PG.drag=null;PG.vy=performance.now()-d.lt<120?Math.max(-240,Math.min(240,d.v)):0;if(PG.cv)PG.cv.style.cursor='grab';} +function pieGlobeOpen(canvas,getData){ + if(!canvas||!canvas.getContext)return false; + if(PG.cv===canvas){PG.get=getData||null;return true;} + if(PG.cv)pieGlobeClose(); + const ctx=canvas.getContext('2d');if(!ctx)return false; + pgVecs();pgNightPref(); + Object.assign(PG,{cv:canvas,ctx,get:getData||null,last:0,dAt:-1e9,sig:'',sm:[],dish:[],pads:[],lch:[],g:null,dirty:true,drag:null,vy:0,anim:animOn()}); + PG.on=[['pointerdown',pgDown],['pointermove',pgMove],['pointerup',pgUp],['pointercancel',pgUp],['lostpointercapture',pgUp]]; + for(const [k,f] of PG.on)canvas.addEventListener(k,f); + canvas.style.touchAction='none';canvas.style.cursor='grab'; + PG.raf=requestAnimationFrame(pgLoop);return true;} +function pieGlobeClose(){ + if(PG.raf)cancelAnimationFrame(PG.raf);PG.raf=0; + const cv=PG.cv;if(cv&&PG.on)for(const [k,f] of PG.on)cv.removeEventListener(k,f); + Object.assign(PG,{cv:null,ctx:null,get:null,on:null,drag:null,sm:[],dish:[],pads:[],lch:[],g:null,sig:'',buf:null});} +// Night view: a per-device preference, like the other display settings. +function pieGlobeNight(on){PG.night=!!on;PG.g=null;PG.dirty=true;try{localStorage.setItem('sot-globe',PG.night?'night':'day');}catch(e){} + for(const b of document.querySelectorAll('.pgnight')){b.setAttribute('aria-pressed',String(PG.night));b.setAttribute('aria-label',pgNightLbl());b.textContent=PG.night?'☀️':'🌙';} + return PG.night;} +const pgNightLbl=()=>pgNightPref()?tr('pie_globe.switch_to_day_view'):tr('pie_globe.switch_to_night_view'); +const pieGlobeBtn=()=>``; +// What the panel puts where the globe goes; then it calls pieGlobeOpen(that canvas, pieGlobeData). +const pieGlobeHtml=()=>`
${pieGlobeBtn()}
`; diff --git a/src/i18n/en.js b/src/i18n/en.js index a775d26..415d2c8 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -3496,6 +3496,9 @@ "pie.why_queue_full":"The launch schedule is full.", "pie.why_stock":"Needs {n} pies; the factory has {have}.", "pie.would_have":"Would have cost", +"pie_globe.switch_to_day_view":"Switch to day view", +"pie_globe.switch_to_night_view":"Switch to night view", +"pie_globe.your_pies_in_orbit":"Your pies in orbit, drag to turn the Earth", "pitcairn.uk_grant_mo":"UK grant {mo}/mo", "pitcairn.uk_grant_mo_once_islanders":"UK grant {mo}/mo once the islanders are online", "pni_all.additional_per_month":"Additional monthly cost", diff --git a/src/styles/38-pie-globe.css b/src/styles/38-pie-globe.css new file mode 100644 index 0000000..b3c1735 --- /dev/null +++ b/src/styles/38-pie-globe.css @@ -0,0 +1,5 @@ +/* Pie Control globe (96-map/89-pie-globe.js): square, as wide as the panel, never wider than the screen allows. */ +.pglobe{position:relative;width:100%;max-width:420px;margin:6px auto;aspect-ratio:1/1} +.pglobe .pgcv{display:block;width:100%;height:100%;touch-action:none;cursor:grab;border-radius:16px} +.pglobe .pgnight{position:absolute;top:6px;right:6px;min-width:36px;min-height:36px} +@media (max-width:420px){.pglobe{max-width:min(100%,62vh)}} diff --git a/tests/pie-globe.test.js b/tests/pie-globe.test.js new file mode 100644 index 0000000..84ec773 --- /dev/null +++ b/tests/pie-globe.test.js @@ -0,0 +1,150 @@ +// Pie in the Sky globe (src/game/96-map/89-pie-globe.js): a loop only while open, nothing left behind once closed, +// a capped sample of pies, the night view, and no surprises from empty or broken data. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +const DATA = `({crusts:[{id:'short',alt:550,inc:53,n:1584,las:true},{id:'frozen',alt:560,inc:97.6,n:260,las:false},{id:'upper',alt:1100,inc:60,n:5000,las:true},{id:'flaky',alt:340,inc:42,n:3,las:false}], + dishes:[{city:'fra',up:true},{city:'nyc',up:false},{city:'sin',lat:1.3,lon:103.8,up:true},{city:'nowhere'}], + pads:[{city:'mia'},{city:'nowhere'}],launches:[{city:'mia',at:1}]})`; + +// A page with a canvas in the document, rAF and listeners counted. +const open = []; +test.afterEach(() => { for (const p of open.splice(0)) { try { p.ev('pieGlobeClose()'); } catch (e) {} p.dom.window.close(); } }); +function page(opts) { + const p = load(opts); + open.push(p); + p.ev(`window.__raf=0;window.__caf=0;const _r=requestAnimationFrame,_c=cancelAnimationFrame; + window.requestAnimationFrame=f=>{__raf++;return _r(f);};window.cancelAnimationFrame=i=>{__caf++;return _c(i);}; + const cvs=document.createElement('canvas');cvs.id='pgTest';document.body.appendChild(cvs);window.__ls=0; + const a=cvs.addEventListener.bind(cvs),r=cvs.removeEventListener.bind(cvs);cvs.addEventListener=(k,f)=>{__ls++;a(k,f);};cvs.removeEventListener=(k,f)=>{__ls--;r(k,f);}; + window.__pgData=()=>${DATA};`); + return p; +} +const wait = (ms) => new Promise((r) => setTimeout(r, ms)); + +test('opening starts one loop, closing stops it and removes every listener', async () => { + const { ev, errors } = page(); + assert.equal(ev('PG.raf'), 0, 'nothing runs before it is opened'); + assert.equal(ev("pieGlobeOpen($('pgTest'),__pgData)"), true); + assert.ok(ev('PG.raf') > 0); + assert.ok(ev('__ls') >= 4, 'pointer listeners on the canvas'); + assert.equal(ev("$('pgTest').style.touchAction"), 'none'); + ev("pieGlobeOpen($('pgTest'),__pgData)"); // opening twice keeps one loop + assert.ok(ev('__ls') >= 4 && ev('__ls') <= 5); + await wait(120); + assert.ok(ev('__raf') >= 2, 'the loop keeps itself going while open'); + ev('pieGlobeClose()'); + assert.equal(ev('PG.raf'), 0); + assert.equal(ev('PG.cv'), null); + assert.equal(ev('__ls'), 0, 'every listener removed'); + const n = ev('__raf'); + await wait(120); + assert.equal(ev('__raf'), n, 'no frame is requested once closed'); + ev('pieGlobeClose()'); // closing twice is fine + assert.deepEqual(errors, []); +}); + +test('it draws a capped sample of every crust, beams, lasers and launches', () => { + const { ev, errors } = page(); + ev("pieGlobeOpen($('pgTest'),__pgData);PG.anim=true"); + assert.equal(ev('pgFrame(1000,true)'), true); + assert.ok(ev("$('pgTest').__ctx.calls.n") > 50, 'the frame really drew'); + const cnt = ev('JSON.stringify(PG.sm.map(c=>c.cnt))'); + const c = JSON.parse(cnt); + assert.equal(c.length, 4); + assert.equal(c[0], 160, 'a full Shortcrust shows the desktop cap'); + assert.equal(c[2], 160, 'more pies than a full crust: still the cap'); + assert.ok(c[1] > 6 && c[1] < 160, 'half a frozen crust shows a share of the cap'); + assert.equal(c[3], 3, 'never more dots than pies'); + assert.equal(ev('PG.dish.length'), 3, 'a dish at an unknown city is dropped'); + assert.equal(ev('PG.pads.length'), 1); + // Satellites stay in their crust: radius 1 + alt/6371 x 2.6. + const r = ev('const a=PG.sm[0].pos;Math.hypot(a[0],a[1],a[2])'); + assert.ok(Math.abs(r - (1 + 550 / 6371 * 2.6)) < 1e-4); + for (let i = 1; i < 5; i++) ev(`pgFrame(${1000 + i * 40},true)`); + ev('pieGlobeClose()'); + assert.deepEqual(errors, []); +}); + +test('fewer dots on phones', () => { + const { ev, errors } = page(); + ev('window.innerWidth=390'); + ev("pieGlobeOpen($('pgTest'),__pgData);pgFrame(1000,true)"); + const c = JSON.parse(ev('JSON.stringify(PG.sm.map(c=>c.cnt))')); + assert.ok(Math.max(...c) <= 80, 'at most 80 per crust on a phone: ' + c); + assert.equal(c[0], 80); + ev('pieGlobeClose()'); + assert.deepEqual(errors, []); +}); + +test('night view toggles, updates its button and is remembered on this device', () => { + const { dom, ev, errors } = page(); + ev('ACT.start({})'); // the click delegate only runs game actions in a game + ev("document.body.insertAdjacentHTML('beforeend',pieGlobeHtml())"); + const b = dom.window.document.querySelector('.pgnight'); + assert.equal(b.getAttribute('aria-pressed'), 'false'); + assert.equal(b.getAttribute('aria-label'), ev("tr('pie_globe.switch_to_night_view')")); + ev("pieGlobeOpen(document.querySelector('.pgcv'),__pgData)"); + b.click(); + assert.equal(ev('PG.night'), true); + assert.equal(b.getAttribute('aria-pressed'), 'true'); + assert.equal(b.getAttribute('aria-label'), ev("tr('pie_globe.switch_to_day_view')")); + assert.equal(ev("localStorage.getItem('sot-globe')"), 'night'); + assert.equal(ev('pgFrame(2000,true)'), true, 'draws at night'); + ev('pieGlobeNight(false)'); + assert.equal(ev('PG.night'), false); + assert.equal(ev('pgFrame(2100,true)'), true); + ev('pieGlobeClose()'); + assert.deepEqual(errors, []); +}); + +test('empty, missing or broken data never throws', () => { + const { ev, errors } = page(); + for (const d of ['null', '{}', '({crusts:[],dishes:[],pads:[],launches:[]})', '({crusts:[null,{id:"x",n:"lots"},{n:NaN},{id:"short",n:-5}],dishes:[null,{}],pads:7,launches:"x"})', '(()=>{throw new Error("boom")})()']) { + ev(`pieGlobeOpen($('pgTest'),()=>${d})`); + assert.equal(ev('pgFrame(1000,true)'), true, d); + assert.equal(ev('PG.sm.length'), 0, d); + ev('pieGlobeClose()'); + } + ev("pieGlobeOpen($('pgTest'))"); + assert.equal(ev('pgFrame(1000,true)'), true); + ev('pieGlobeClose()'); + assert.equal(ev('pieGlobeOpen(null,()=>({}))'), false); + assert.equal(ev('PG.raf'), 0); + assert.deepEqual(errors, []); +}); + +test('closed, it does no work at all; a canvas that leaves the page closes it', async () => { + const { ev, errors } = page(); + ev("pieGlobeOpen($('pgTest'),__pgData);pgFrame(1000,true)"); + ev('pieGlobeClose()'); + const calls = ev("$('pgTest').__ctx.calls.n"); + assert.equal(ev('pgFrame(5000,true)'), false, 'a stray frame after closing draws nothing'); + await wait(80); + assert.equal(ev("$('pgTest').__ctx.calls.n"), calls); + // The panel was rebuilt and the canvas thrown away without a close: the next frame cleans up. + ev("pieGlobeOpen($('pgTest'),__pgData);$('pgTest').remove()"); + assert.equal(ev('pgFrame(6000,true)'), false); + assert.equal(ev('PG.cv'), null); + assert.equal(ev('PG.raf'), 0); + assert.equal(ev('__ls'), 0); + // A hidden tab draws nothing. + ev("const c2=document.createElement('canvas');c2.id='pg2';document.body.appendChild(c2);pieGlobeOpen(c2,__pgData);Object.defineProperty(document,'hidden',{configurable:true,get:()=>true})"); + assert.equal(ev('pgFrame(7000,true)'), false); + ev('pieGlobeClose()'); + assert.deepEqual(errors, []); +}); + +test('the map shows a pie dish badge only where there is one, and never satellites', () => { + const { ev, errors } = page(); + ev("ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})"); + ev("const C=CITY.fra;cam.x=C.x;cam.y=C.y;cam.z=1.5;draw(0)"); + assert.equal(ev('CM.dish'), null, 'no pies: no lookup table at all'); + ev("S.pie={dishes:[{id:1,city:'fra',ant:2,down:0},{id:2,city:'ams',ant:1,down:S.day+5}]};draw(0)"); + assert.equal(ev("CM.dish.get('fra')"), true); + assert.equal(ev("CM.dish.get('ams')"), false, 'a dish that is down shows grey'); + assert.equal(ev('PG.raf'), 0, 'the map never starts the globe'); + ev('S.pie=null;draw(0)'); + assert.deepEqual(errors, []); +});