diff --git a/CHANGELOG.md b/CHANGELOG.md index c8aefcd..d55b120 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ All notable changes to this project are documented here. The project follows - Your traffic to home internet providers now starts where their customers live: a New York POP talks a lot to Comecast and little to Doitsche Telekomm, Frankfurt the other way round. Peering with a big eyeball network in the cities its users are in now takes that traffic off your backbone, while peering in only two cities means hauling it there from everywhere else (#48). - Giant AI circuits now come from campuses in more than 30 metros, from Oregon and Wyoming to Atlanta, Querétaro and Québec, and less often from cities already crowded with them. Ashburn stays a little busier than the rest, but no longer has to carry the whole late game with four other cities (#61). - RouteScript can spill early onto detours within a latency budget: `spill at 80% within 10 ms` keeps a hot link at 80% and moves the rest onto the fastest detour that adds at most 10 ms and is itself under 80%. Stack them (`spill at 90% within 20 ms`) to spill further as links get hotter (#136). +- You can now move a network to another device with QR codes or a link, without an account or a file: open the menu, pick Send to another device, and scan the codes with the other device's camera, or send yourself the link. Nothing is uploaded anywhere, as the codes and the link carry the network itself, and to keep the codes few they leave out your charts and news, which start fresh on the other device; on the other device, open the link or paste it under From another device on the title screen (#263). - From customer level 7, low-latency wholesale routes call: 1.6 or 3.2 Tbps between two of your cities with a strict latency limit, paying about three times what a hyperscaler pays per Gbps on the same route. Every day over the limit (after the first 15) you pay back a day's fee as an SLA credit and they lose patience twice as fast as a trading link over its limit, so keep a fast path and a fast backup. They never grow past 3.2 Tbps, so one contract cannot carry a whole level (#137). - From customer level 2, you can save up to three POP standards (micro POP, medium POP, regional hub), each a router model and a number of routers, and mark which POP is which. One button in a POP's Infra tab brings it up to its standard, and Utilities brings every POP of a kind up at once with the price shown first. A POP is never stepped down to a smaller model, and a busy POP with one router gets its second router before the swap, so the upgrade rolls instead of taking the POP down (#315). - Utilities can now install the redundancy kit at every POP still missing part of it in one go, at one price shown on the button, from customer level 2. With a NOC intern you can also put the kit in the intern's new-POP template from there (#317). diff --git a/site/i18n/de.js b/site/i18n/de.js index 9f0a6f8..b3d0893 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -4849,6 +4849,30 @@ "traceroute.this_one_is_set_to_mode":"; dieser steht auf {mode}", "traceroute.transit_is_the_last_resort":"Transit ist der letzte Ausweg", "traceroute.your_traffic_follows_the_metrics_this":"Dein Internetverkehr folgt den Metriken. Dies ist der Weg, den eine Kundenleitung auf „{mode}“ nehmen würde.", +"transfer.code_i_of_n":"Code {i} von {n}", +"transfer.copy_the_link":"Link kopieren", +"transfer.could_not_copy_the_link_here":"Der Link ließ sich hier nicht kopieren. Exportiere stattdessen deinen Spielstand.", +"transfer.from_another_device":"Von einem anderen Gerät", +"transfer.have_of_n_codes_are_here":"{have} von {n} Codes sind da", +"transfer.its_charts_and_news_start_fresh":"Seine Diagramme und Meldungen fangen hier neu an.", +"transfer.link_copied_open_it_on_your":"Link kopiert. Öffne ihn auf deinem anderen Gerät.", +"transfer.moving_a_network_here":"Netzwerk hierher holen", +"transfer.next_code":"Nächster Code", +"transfer.nothing_is_uploaded_anywhere_the_codes":"Nichts wird irgendwo hochgeladen: Codes und Link tragen das Netzwerk selbst. Wer sie öffnet, bekommt eine Kopie, also behalte sie für dich.", +"transfer.on_the_other_device_open_the":"Öffne auf dem Gerät mit deinem Netzwerk das Menü und wähle Auf ein anderes Gerät senden. Scanne den Code mit der Kamera dieses Geräts oder füge den Link hier ein.", +"transfer.on_your_other_device_open_the":"Richte die Kamera deines anderen Geräts auf diesen Code und öffne den Link.", +"transfer.on_your_other_device_open_the_many":"Richte die Kamera deines anderen Geräts auf diesen Code und öffne den Link, dann komm für den nächsten zurück. Die Reihenfolge ist egal.", +"transfer.paste_a_transfer_link":"Transfer-Link einfügen", +"transfer.qr_code_i_of_n":"QR-Code {i} von {n}", +"transfer.scan_the_next_code_on_your":"Scanne den nächsten Code auf deinem anderen Gerät und öffne den Link. Dein Netzwerk lädt, sobald der letzte da ist.", +"transfer.send_the_link":"Link senden", +"transfer.send_to_another_device":"Auf ein anderes Gerät senden", +"transfer.start_over":"Neu anfangen", +"transfer.that_is_not_a_transfer_link":"Das ist kein Transfer-Link.", +"transfer.that_link_is_incomplete_or_damaged":"Der Link ist unvollständig oder beschädigt. Kopier ihn noch mal, komplett.", +"transfer.the_codes_leave_out_your_charts":"Damit es wenige Codes bleiben, fehlen darin deine Diagramme und Meldungen; der Link enthält alles.", +"transfer.this_browser_cannot_pack_networks_into":"Dieser Browser kann Netzwerke nicht in Links packen. Exportiere stattdessen deinen Spielstand.", +"transfer.this_network_is_too_big_for":"Dieses Netzwerk ist zu groß für Codes. Schick stattdessen den Link oder exportiere deinen Spielstand.", "tutorial.businesses_pop_up_as_bubbles_on":"Unternehmen tauchen als $-Blasen auf der Karte auf. Öffne Deals und gewinne deinen ersten Kunden.", "tutorial.grow_drag_from_your_pink_router":"Wachse: Zieh von deiner Stadt zu einer Stadt in der Nähe, um Glasfaser zu verlegen und einen zweiten POP zu eröffnen.", "tutorial.start_the_clock_with_1_and":"Starte die Uhr mit 1× und sieh zu, wie Traffic und Geld fließen. Du kannst jederzeit pausieren.", diff --git a/site/i18n/es.js b/site/i18n/es.js index 8c6aded..2c4c333 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -4847,6 +4847,30 @@ "traceroute.this_one_is_set_to_mode":"; esta está en {mode}", "traceroute.transit_is_the_last_resort":"el tránsito es el último recurso", "traceroute.your_traffic_follows_the_metrics_this":"Tu tráfico de internet sigue las métricas. Este es el camino que tomaría un circuito de cliente en «{mode}».", +"transfer.code_i_of_n":"Código {i} de {n}", +"transfer.copy_the_link":"Copiar el enlace", +"transfer.could_not_copy_the_link_here":"No se pudo copiar el enlace aquí. Exporta un archivo de partida.", +"transfer.from_another_device":"Desde otro dispositivo", +"transfer.have_of_n_codes_are_here":"Han llegado {have} de {n} códigos", +"transfer.its_charts_and_news_start_fresh":"Sus gráficos y noticias empiezan de cero aquí.", +"transfer.link_copied_open_it_on_your":"Enlace copiado. Ábrelo en tu otro dispositivo.", +"transfer.moving_a_network_here":"Traer una red aquí", +"transfer.next_code":"Siguiente código", +"transfer.nothing_is_uploaded_anywhere_the_codes":"No se sube nada a ningún sitio: los códigos y el enlace llevan la red misma. Quien los abra obtiene una copia, así que guárdalos para ti.", +"transfer.on_the_other_device_open_the":"En el dispositivo con tu red, abre el menú y elige Enviar a otro dispositivo. Escanea su código con la cámara de este dispositivo o pega aquí su enlace.", +"transfer.on_your_other_device_open_the":"En tu otro dispositivo, apunta la cámara a este código y abre el enlace.", +"transfer.on_your_other_device_open_the_many":"En tu otro dispositivo, apunta la cámara a este código y abre el enlace; luego vuelve aquí por el siguiente. Pueden llegar en cualquier orden.", +"transfer.paste_a_transfer_link":"Pega un enlace de traspaso", +"transfer.qr_code_i_of_n":"Código QR {i} de {n}", +"transfer.scan_the_next_code_on_your":"Escanea el siguiente código en tu otro dispositivo y abre su enlace. Tu red se carga en cuanto llegue el último.", +"transfer.send_the_link":"Enviar el enlace", +"transfer.send_to_another_device":"Enviar a otro dispositivo", +"transfer.start_over":"Empezar de nuevo", +"transfer.that_is_not_a_transfer_link":"Eso no es un enlace de traspaso.", +"transfer.that_link_is_incomplete_or_damaged":"Ese enlace está incompleto o dañado. Cópialo otra vez, entero.", +"transfer.the_codes_leave_out_your_charts":"Para que sean pocos códigos, dejan fuera tus gráficos y noticias; el enlace lo lleva todo.", +"transfer.this_browser_cannot_pack_networks_into":"Este navegador no puede meter redes en enlaces. Usa un archivo de partida.", +"transfer.this_network_is_too_big_for":"Esta red es demasiado grande para códigos. Envía el enlace o exporta un archivo de partida.", "tutorial.businesses_pop_up_as_bubbles_on":"Las empresas aparecen como burbujas de $ en el mapa. Abre Tratos y firma a tu primer cliente.", "tutorial.grow_drag_from_your_pink_router":"Crece: arrastra desde tu router rosa hasta una ciudad cercana para tender fibra y abrir un segundo POP.", "tutorial.start_the_clock_with_1_and":"Pon el reloj en marcha con 1× y mira cómo fluyen el tráfico y el dinero. Puedes pausar cuando quieras.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index e7a6640..8b3467c 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -4847,6 +4847,30 @@ "traceroute.this_one_is_set_to_mode":" ; celle-ci est réglée sur {mode}", "traceroute.transit_is_the_last_resort":"le transit est le dernier recours", "traceroute.your_traffic_follows_the_metrics_this":"Ton trafic internet suit les métriques. Voici le chemin que prendrait un circuit client en « {mode} ».", +"transfer.code_i_of_n":"Code {i} sur {n}", +"transfer.copy_the_link":"Copier le lien", +"transfer.could_not_copy_the_link_here":"Impossible de copier le lien ici. Exporte plutôt un fichier de sauvegarde.", +"transfer.from_another_device":"Depuis un autre appareil", +"transfer.have_of_n_codes_are_here":"{have} codes sur {n} sont arrivés", +"transfer.its_charts_and_news_start_fresh":"Ses graphiques et son fil d'infos repartent de zéro ici.", +"transfer.link_copied_open_it_on_your":"Lien copié. Ouvre-le sur ton autre appareil.", +"transfer.moving_a_network_here":"Amener un réseau ici", +"transfer.next_code":"Code suivant", +"transfer.nothing_is_uploaded_anywhere_the_codes":"Rien n'est envoyé nulle part : les codes et le lien contiennent le réseau lui-même. Qui les ouvre en obtient une copie, alors garde-les pour toi.", +"transfer.on_the_other_device_open_the":"Sur l'appareil qui a ton réseau, ouvre le menu et choisis Envoyer vers un autre appareil. Scanne son code avec l'appareil photo de cet appareil, ou colle son lien ici.", +"transfer.on_your_other_device_open_the":"Sur ton autre appareil, vise ce code avec l'appareil photo et ouvre le lien.", +"transfer.on_your_other_device_open_the_many":"Sur ton autre appareil, vise ce code avec l'appareil photo et ouvre le lien, puis reviens ici pour le suivant. L'ordre n'a pas d'importance.", +"transfer.paste_a_transfer_link":"Colle un lien de transfert", +"transfer.qr_code_i_of_n":"QR code {i} sur {n}", +"transfer.scan_the_next_code_on_your":"Scanne le code suivant sur ton autre appareil et ouvre son lien. Ton réseau se charge dès que le dernier arrive.", +"transfer.send_the_link":"Envoyer le lien", +"transfer.send_to_another_device":"Envoyer vers un autre appareil", +"transfer.start_over":"Recommencer", +"transfer.that_is_not_a_transfer_link":"Ce n'est pas un lien de transfert.", +"transfer.that_link_is_incomplete_or_damaged":"Ce lien est incomplet ou abîmé. Copie-le à nouveau, en entier.", +"transfer.the_codes_leave_out_your_charts":"Pour garder peu de codes, ils laissent de côté tes graphiques et ton fil d'infos ; le lien contient tout.", +"transfer.this_browser_cannot_pack_networks_into":"Ce navigateur ne sait pas mettre un réseau dans un lien. Utilise plutôt un fichier de sauvegarde.", +"transfer.this_network_is_too_big_for":"Ce réseau est trop gros pour des codes. Envoie plutôt le lien, ou exporte un fichier de sauvegarde.", "tutorial.businesses_pop_up_as_bubbles_on":"Les entreprises apparaissent sous forme de bulles $ sur la carte. Ouvre Offres et signe ton premier client.", "tutorial.grow_drag_from_your_pink_router":"Grandis : fais glisser depuis ton routeur rose vers une ville proche pour poser de la fibre et ouvrir un deuxième POP.", "tutorial.start_the_clock_with_1_and":"Lance le temps en 1× et regarde le trafic et l’argent couler. Tu peux mettre en pause à tout moment.", diff --git a/site/i18n/it.js b/site/i18n/it.js index afdf926..954d9c3 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -4847,6 +4847,30 @@ "traceroute.this_one_is_set_to_mode":"; questa è impostata su {mode}", "traceroute.transit_is_the_last_resort":"il transit è l’ultima spiaggia", "traceroute.your_traffic_follows_the_metrics_this":"Il tuo traffico internet segue le metriche. Questo è il percorso che prenderebbe un circuito cliente su «{mode}».", +"transfer.code_i_of_n":"Codice {i} di {n}", +"transfer.copy_the_link":"Copia il link", +"transfer.could_not_copy_the_link_here":"Non riesco a copiare il link qui. Esporta un file di salvataggio.", +"transfer.from_another_device":"Da un altro dispositivo", +"transfer.have_of_n_codes_are_here":"Sono arrivati {have} codici su {n}", +"transfer.its_charts_and_news_start_fresh":"I suoi grafici e le notizie ripartono da zero qui.", +"transfer.link_copied_open_it_on_your":"Link copiato. Aprilo sull'altro dispositivo.", +"transfer.moving_a_network_here":"Porta qui una rete", +"transfer.next_code":"Codice successivo", +"transfer.nothing_is_uploaded_anywhere_the_codes":"Non viene caricato nulla da nessuna parte: i codici e il link contengono la rete stessa. Chi li apre ne riceve una copia, quindi tienili per te.", +"transfer.on_the_other_device_open_the":"Sul dispositivo con la tua rete, apri il menu e scegli Invia a un altro dispositivo. Scansiona il codice con la fotocamera di questo dispositivo, oppure incolla qui il link.", +"transfer.on_your_other_device_open_the":"Sull'altro dispositivo, inquadra questo codice con la fotocamera e apri il link.", +"transfer.on_your_other_device_open_the_many":"Sull'altro dispositivo, inquadra questo codice con la fotocamera e apri il link, poi torna qui per il prossimo. L'ordine non conta.", +"transfer.paste_a_transfer_link":"Incolla un link di trasferimento", +"transfer.qr_code_i_of_n":"Codice QR {i} di {n}", +"transfer.scan_the_next_code_on_your":"Scansiona il prossimo codice sull'altro dispositivo e apri il link. La tua rete si carica appena arriva l'ultimo.", +"transfer.send_the_link":"Invia il link", +"transfer.send_to_another_device":"Invia a un altro dispositivo", +"transfer.start_over":"Ricomincia", +"transfer.that_is_not_a_transfer_link":"Questo non è un link di trasferimento.", +"transfer.that_link_is_incomplete_or_damaged":"Il link è incompleto o danneggiato. Copialo di nuovo, tutto intero.", +"transfer.the_codes_leave_out_your_charts":"Per restare pochi, i codici lasciano fuori i grafici e le notizie; il link contiene tutto.", +"transfer.this_browser_cannot_pack_networks_into":"Questo browser non riesce a mettere una rete in un link. Usa un file di salvataggio.", +"transfer.this_network_is_too_big_for":"Questa rete è troppo grande per i codici. Invia il link, oppure esporta un file di salvataggio.", "tutorial.businesses_pop_up_as_bubbles_on":"Le aziende spuntano come bolle $ sulla mappa. Apri Offerte e firma il tuo primo cliente.", "tutorial.grow_drag_from_your_pink_router":"Cresci: trascina dal tuo router rosa su una città vicina per posare fibra e aprire un secondo POP.", "tutorial.start_the_clock_with_1_and":"Fai partire il tempo con 1× e guarda scorrere traffico e soldi. Puoi mettere in pausa quando vuoi.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 9278519..e05fcd3 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -4847,6 +4847,30 @@ "traceroute.this_one_is_set_to_mode":"; esta está configurada como {mode}", "traceroute.transit_is_the_last_resort":"transit é o último recurso", "traceroute.your_traffic_follows_the_metrics_this":"O teu tráfego de internet segue as métricas. Este é o caminho que um circuito de cliente em «{mode}» tomaria.", +"transfer.code_i_of_n":"Código {i} de {n}", +"transfer.copy_the_link":"Copiar o link", +"transfer.could_not_copy_the_link_here":"Não deu para copiar o link aqui. Exporte um arquivo de save.", +"transfer.from_another_device":"De outro dispositivo", +"transfer.have_of_n_codes_are_here":"Chegaram {have} de {n} códigos", +"transfer.its_charts_and_news_start_fresh":"Os gráficos e notícias dela recomeçam do zero aqui.", +"transfer.link_copied_open_it_on_your":"Link copiado. Abra-o no outro dispositivo.", +"transfer.moving_a_network_here":"Trazer uma rede para cá", +"transfer.next_code":"Próximo código", +"transfer.nothing_is_uploaded_anywhere_the_codes":"Nada é enviado para lugar nenhum: os códigos e o link carregam a própria rede. Quem os abrir recebe uma cópia, então guarde-os para você.", +"transfer.on_the_other_device_open_the":"No dispositivo com a sua rede, abra o menu e escolha Enviar para outro dispositivo. Escaneie o código com a câmera deste dispositivo ou cole o link aqui.", +"transfer.on_your_other_device_open_the":"No outro dispositivo, aponte a câmera para este código e abra o link.", +"transfer.on_your_other_device_open_the_many":"No outro dispositivo, aponte a câmera para este código e abra o link, depois volte aqui para o próximo. A ordem não importa.", +"transfer.paste_a_transfer_link":"Cole um link de transferência", +"transfer.qr_code_i_of_n":"Código QR {i} de {n}", +"transfer.scan_the_next_code_on_your":"Escaneie o próximo código no outro dispositivo e abra o link. Sua rede carrega assim que o último chegar.", +"transfer.send_the_link":"Enviar o link", +"transfer.send_to_another_device":"Enviar para outro dispositivo", +"transfer.start_over":"Recomeçar", +"transfer.that_is_not_a_transfer_link":"Isso não é um link de transferência.", +"transfer.that_link_is_incomplete_or_damaged":"Esse link está incompleto ou danificado. Copie de novo, inteiro.", +"transfer.the_codes_leave_out_your_charts":"Para serem poucos códigos, eles deixam de fora seus gráficos e notícias; o link leva tudo.", +"transfer.this_browser_cannot_pack_networks_into":"Este navegador não consegue colocar redes em links. Use um arquivo de save.", +"transfer.this_network_is_too_big_for":"Esta rede é grande demais para códigos. Envie o link ou exporte um arquivo de save.", "tutorial.businesses_pop_up_as_bubbles_on":"Empresas aparecem como bolhas de $ no mapa. Abra Negócios e feche seu primeiro cliente.", "tutorial.grow_drag_from_your_pink_router":"Cresça: arraste do seu router rosa até uma cidade próxima para lançar fibra e abrir um segundo POP.", "tutorial.start_the_clock_with_1_and":"Comece o relógio em 1× e veja o tráfego e o dinheiro fluírem. Dá pra pausar a qualquer momento.", diff --git a/src/agent/20-commands.js b/src/agent/20-commands.js index 84d404a..0928dea 100644 --- a/src/agent/20-commands.js +++ b/src/agent/20-commands.js @@ -637,8 +637,8 @@ const API_WHY={ const API_DENY={ speed:'time',phonePlay:'time',phoneSpeed:'time', start:'start',newgame:'start',cont:'start',toTitle:'start',resetAsk:'start', - exportSave:'files',importGo:'files',importPick:'files',slotExport:'files', + exportSave:'files',importGo:'files',importPick:'files',slotExport:'files',xfer:'files',xferFile:'files',xferPage:'files',xferPaste:'files',xferRecv:'files',xferReset:'files', slotBack:'slots',slotDel:'slots',slotDelGo:'slots',slotMenu:'slots',slotRetry:'slots',slotSpace:'slots',slotSwitch:'slots',slotTake:'slots', animSet:'prefs',langSet:'prefs',mapSet:'prefs',menu:'prefs',mute:'prefs',prefSet:'prefs',settings:'prefs',settingsClose:'prefs',soundSet:'prefs',vpSet:'prefs', - install:'browser',share:'browser',shareDl:'browser',shareGo:'browser',traceCopy:'browser',updateLater:'browser',updateNow:'browser',wsShare:'browser',pzShare:'browser', + install:'browser',share:'browser',shareDl:'browser',shareGo:'browser',traceCopy:'browser',updateLater:'browser',updateNow:'browser',wsShare:'browser',pzShare:'browser',xferLink:'browser', }; diff --git a/src/game/60-features/61-qr-code.js b/src/game/60-features/61-qr-code.js new file mode 100644 index 0000000..d8ad571 --- /dev/null +++ b/src/game/60-features/61-qr-code.js @@ -0,0 +1,59 @@ +/* ---------- QR codes (#263) ---------- + A small QR encoder: byte mode, error correction L or M, versions 1 to 40, the standard mask penalty. The game has no + dependencies and no server, so moving a network to a phone is codes the phone's own camera app can open. + Follows ISO/IEC 18004 (and Project Nayuki's reference implementation, MIT). */ +const QR_ECC={L:[1,[7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25]], + M:[0,[10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49]]}; +const qrRaw=v=>{let r=(16*v+128)*v+64;if(v>=2){const n=Math.floor(v/7)+2;r-=(25*n-10)*n-55;if(v>=7)r-=36;}return r;}; +const qrDataCw=(v,e)=>Math.floor(qrRaw(v)/8)-QR_ECC[e][1][v-1]*QR_ECC[e][2][v-1]; +// The most bytes one code of this version holds (byte mode). +const qrCap=(v,e='L')=>qrDataCw(v,e)-(v<10?2:3); +function qrMul(x,y){let z=0;for(let i=7;i>=0;i--){z=(z<<1)^((z>>>7)*0x11D);z^=((y>>>i)&1)*x;}return z;} +function qrRs(data,n){const d=new Array(n).fill(0);d[n-1]=1;let root=1; + for(let i=0;i{if(v===1)return [];const n=Math.floor(v/7)+2,step=v===32?26:Math.ceil((v*4+4)/(n*2-2))*2,r=[6]; + for(let p=v*4+10;r.length(x+y)%2===0,(x,y)=>y%2===0,(x,y)=>x%3===0,(x,y)=>(x+y)%3===0,(x,y)=>(Math.floor(x/3)+Math.floor(y/2))%2===0, + (x,y)=>x*y%2+x*y%3===0,(x,y)=>(x*y%2+x*y%3)%2===0,(x,y)=>((x+y)%2+x*y%3)%2===0]; +/* bytes (Uint8Array or array) → {size, m: rows of booleans (true = dark)}, or null when it does not fit in version 40. + o.ecc 'L' (default) or 'M'; o.mask 0-7 to force one (tests); o.min/o.max bound the version. */ +function qrEncode(bytes,o={}){const e=o.ecc||'L',len=bytes.length;let v=o.min||1; + while(v<=(o.max||40)&&len>qrCap(v,e))v++;if(v>(o.max||40))return null; + const cap=qrDataCw(v,e),bits=[],put=(x,n)=>{for(let i=n-1;i>=0;i--)bits.push((x>>>i)&1);}; + put(4,4);put(len,v<10?8:16);for(const b of bytes)put(b,8); + put(0,Math.min(4,cap*8-bits.length));put(0,(8-bits.length%8)%8);for(let p=0xEC;bits.length=ns)cw.push(blocks[j][i]); + const n=v*4+17,m=[],fn=[];for(let y=0;y{m[y][x]=d;fn[y][x]=true;}; + for(let i=0;i=0&&x=0&&y{const d=QR_ECC[e][0]<<3|mk;let r=d;for(let i=0;i<10;i++)r=(r<<1)^((r>>>9)*0x537);const b=(d<<10|r)^0x5412,bit=i=>((b>>>i)&1)===1; + for(let i=0;i<=5;i++)set(8,i,bit(i));set(8,7,bit(6));set(8,8,bit(7));set(7,8,bit(8));for(let i=9;i<15;i++)set(14-i,8,bit(i)); + for(let i=0;i<8;i++)set(n-1-i,8,bit(i));for(let i=8;i<15;i++)set(8,n-15+i,bit(i));set(8,n-8,true);}; + fmt(0); + if(v>=7){let r=v;for(let i=0;i<12;i++)r=(r<<1)^((r>>>11)*0x1F25);const b=v<<12|r;for(let i=0;i<18;i++){const d=((b>>>i)&1)===1,a=n-11+i%3,c=Math.floor(i/3);set(a,c,d);set(c,a,d);}} + for(let i=0,r=n-1;r>=1;r-=2){if(r===6)r=5;for(let vt=0;vt>>3]>>>(7-(i&7)))&1)===1;i++;}}} + const flip=mk=>{const f=QR_MASK[mk];for(let y=0;yrow?m[a][b]:m[b][a]; + for(const row of [true,false])for(let a=0;a=5)p+=run-2;run=1;}} + for(let b=0;b+7<=n;b++){let hit=true;for(let k=0;k<7;k++)if(at(a,b+k,row)!==(k!==1&&k!==5)){hit=false;break;}if(!hit)continue; + let l=true,r=true;for(let k=1;k<=4;k++){if(b-k>=0&&at(a,b-k,row))l=false;if(b+6+k`;} diff --git a/src/game/60-features/62-device-transfer.js b/src/game/60-features/62-device-transfer.js new file mode 100644 index 0000000..3f4173e --- /dev/null +++ b/src/game/60-features/62-device-transfer.js @@ -0,0 +1,49 @@ +/* ---------- moving a network to another device (#263) ---------- + No server, no account: the network itself travels, gzipped, in the fragment of a link (#sot1....), + which browsers never send to any server. One link carries all of it, to copy or share; QR codes carry it in parts a + phone's own camera app opens one after another. The receiving page collects the parts in its storage, in any order, + and imports the network like a save file once they are all there. */ +const XFER_K='sot-xfer',XFER_RE=/sot1\.([a-z0-9]{3,8})\.(\d{1,3})\.(\d{1,3})\.([A-Za-z0-9_-]+)/,XFER_CHUNK=900,XFER_MAX=200,XFER_DAY=864e5; +// Taken out of the address bar before anything else can read it (the stats counter only loads after this script): +// a network in a link belongs to the player, and a reload must not import it again. +const XFER_HASH=(()=>{try{const h=location.hash||'';if(!h.startsWith('#sot1.'))return '';history.replaceState(null,'',location.pathname+location.search);return h.slice(1);}catch(e){return '';}})(); +const b64u=u=>b64(u).replace(/\+/g,'-').replace(/\//g,'_').replace(/=+$/,''); +const unb64u=t=>unb64(t.replace(/-/g,'+').replace(/_/g,'/')+'==='.slice((t.length+3)%4)); +const xferBase=()=>/^https?:$/.test(location.protocol)?location.origin+location.pathname:'https://seriesoftub.es/'; +// A network's save text: the one playing now (saved first), or any other straight from storage. +function xferText(id){if(id===UI.slot&&S&&!pzOn()){save(true);return Promise.resolve(JSON.stringify(packSave(S)));} + const raw=slotRaw(id);if(raw==null)return Promise.reject(new Error('no save'));return raw.startsWith(GZ)?gunzip(raw):Promise.resolve(raw);} +/* The link carries everything. The codes leave out the charts' history and the news log: more than half of a played + network, and only ever shown, never played with (the traffic odometer keeps its own count). A year-old network + takes 3 codes instead of 9; its charts start again on the other device, and the import says so. */ +const xferGz=async(t,lean)=>b64u(await gzPipe(new TextEncoder().encode(`{"app":"series-of-tubes","version":${JSON.stringify(APP_VERSION)},${lean?'"lean":1,':''}"S":${t}}`),new CompressionStream('gzip'))); +async function xferPack(id){const e=slotIdx().find(x=>x.id===id),t=await xferText(id),o=JSON.parse(t); + const d=await xferGz(t),c=await xferGz(JSON.stringify({...o,hist:[],log:[]}),true); + const k=Math.floor(Math.random()*36**5).toString(36).padStart(5,'0'),n=Math.ceil(c.length/XFER_CHUNK),base=xferBase()+'#sot1.'; + // Codes and link are two transfers: a code never completes a set with a piece of the link. + const parts=n>XFER_MAX?[]:Array.from({length:n},(_,i)=>`${base}${k}.${i}.${n}.${c.slice(i*XFER_CHUNK,(i+1)*XFER_CHUNK)}`); + return {name:e?e.name:o.name,link:`${base}${k}.0.1.${d}`,parts};} +// Parts that arrived so far (one transfer at a time; a day old, they are forgotten). +function xferStore(){let s=null;try{s=JSON.parse(localStorage.getItem(XFER_K)||'null');}catch(e){} + if(!s||typeof s!=='object'||typeof s.id!=='string'||!(s.n>1&&s.n<=999)||!s.p||typeof s.p!=='object'||!(Date.now()-s.at=0&&+k=1&&is.p[k]).join(''));return true;} + try{localStorage.setItem(XFER_K,JSON.stringify(s));}catch(e){} + openModal(xferWaitHtml(s));sfx('click');return true;} +function xferOpen(d){if(!gzOk()){toast(tr('transfer.this_browser_cannot_pack_networks_into'),'bad');return;} + let u=null;try{u=unb64u(d);}catch(e){} + const bad=()=>{toast(tr('transfer.that_link_is_incomplete_or_damaged'),'bad');sfx('err');};if(!u){bad();return;} + gzPipe(u,new DecompressionStream('gzip')).then(b=>{const r=parseSave(new TextDecoder().decode(b)); + if(r.err){toast(tr('save.import_failed_err',{err:esc(r.err)}),'bad');sfx('err');return;}importAsk(r);track('xfer_in');},bad);} +// Another window got a part (or finished): the one showing the progress follows. +addEventListener('storage',e=>{if(e.key!==XFER_K||!$('xferWait'))return;const s=xferStore();if(s)openModal(xferWaitHtml(s));else ACT.helpClose();}); +addEventListener('hashchange',()=>{const h=location.hash||'';if(!h.startsWith('#sot1.'))return;try{history.replaceState(null,'',location.pathname+location.search);}catch(e){}xferTake(h.slice(1));}); +// After boot: a page opened from a transfer link takes its part. +function xferBoot(){if(XFER_HASH)xferTake(XFER_HASH);} diff --git a/src/game/90-actions/89-game-and-settings.js b/src/game/90-actions/89-game-and-settings.js index a1671dc..9b14de0 100644 --- a/src/game/90-actions/89-game-and-settings.js +++ b/src/game/90-actions/89-game-and-settings.js @@ -30,7 +30,7 @@ Object.assign(ACT,{ ${btn(tr('common.back_to_the_map'),'closeModal',{},'pink big')}${saveFailing()?btn(tr('common.export_save'),'exportSave',{},'pink'):''}${saveFailing()&&UI.saveFail.full&&slotOthers().length?btn(tr('slots.free_up_space'),'slotSpace',{},'pink'):''} - + `);}, settings:()=>{UI.setOpen=true;openModal(settingsHtml());}, settingsClose:()=>{UI.setOpen=false;if(!S||!UI.started)showTitle();else closeModal();}, diff --git a/src/game/90-actions/92-transfer.js b/src/game/90-actions/92-transfer.js new file mode 100644 index 0000000..6d71136 --- /dev/null +++ b/src/game/90-actions/92-transfer.js @@ -0,0 +1,14 @@ +// Moving a network to another device (#263): codes and a link out, a pasted link in. +Object.assign(ACT,{ + xfer:({id}={})=>{const sid=slotOkId(id)?id:UI.slot;if(!sid||!slotIdx().some(e=>e.id===sid))return; + if(!gzOk()){toast(tr('transfer.this_browser_cannot_pack_networks_into'),'bad');return;} + xferPack(sid).then(x=>{UI.xfer={...x,id:sid,i:0};openModal(xferHtml());track('xfer_open');},()=>toast(tr('loop.your_saved_game_could_not_be'),'bad'));}, + xferPage:({i})=>{const x=UI.xfer;if(!x||!(i>=0&&i{const x=UI.xfer;if(!x)return;const t=x.link,no=()=>toast(tr('transfer.could_not_copy_the_link_here'),'bad'); + if(navigator.share&&isPhone()){navigator.share({title:'Series of Tubes',url:t}).catch(()=>{});return;} + try{navigator.clipboard.writeText(t).then(()=>toast(tr('transfer.link_copied_open_it_on_your'),'good'),no);}catch(e){no();}}, + xferFile:()=>{const x=UI.xfer;if(x)exportSlot(x.id);}, + xferRecv:()=>openModal(xferRecvHtml()), + xferPaste:()=>{const el=$('xferIn');if(el)xferTake(el.value.trim());}, + xferReset:()=>{xferClear();ACT.helpClose();}, +}); diff --git a/src/game/91-save.js b/src/game/91-save.js index f407d76..d5c71ab 100644 --- a/src/game/91-save.js +++ b/src/game/91-save.js @@ -81,11 +81,13 @@ function parseSave(txt){if(typeof txt!=='string')return {err:tr('save.that_file_ if(!s||typeof s!=='object'||s.v!==1||typeof s.day!=='number'||typeof s.cash!=='number'||!s.pops||typeof s.pops!=='object'||!Array.isArray(s.links))return {err:tr('save.that_does_not_look_like_a')}; if(s.lost)return {err:tr('save.that_network_went_bankrupt_it_cannot')}; for(const c of Object.keys(s.pops))if(!isCity(c))return {err:tr('save.that_save_has_a_pop_in',{city:esc(String(c).slice(0,12))})}; - return {s,ver:j.version||'?',name:String(s.name||tr('common.unnamed_network'))};} + return {s,ver:j.version||'?',name:String(s.name||tr('common.unnamed_network')),lean:!!(j.lean&&j.S)};} function importFile(file){if(!file)return;if(file.size>64e6){toast(tr('save.that_file_is_too_big_to'),'bad');return;} const rd=new FileReader();rd.onload=()=>{const r=parseSave(String(rd.result));if(r.err){toast(tr('save.import_failed_err',{err:esc(r.err)}),'bad');sfx('err');return;} - UI.importing=r.s;openModal(`
${tr('common.import_a_save')}

${tr('save.load_name',{name:esc(r.name)})}

${esc(dateStr(r.s.day))} · ${tr('save.cash_in_the_bank',{cash:fmt$(r.s.cash)})} · ${trn('save.n_pop',Object.keys(r.s.pops).length)} · ${tr('save.saved_by_v_ver',{ver:esc(r.ver)})}

${tr('slots.it_joins_your_networks_on_this')}

${btn(tr('save.load_this_network'),'importGo',{},'pink big')}${btn(tr('common.cancel'),UI.started?'closeModal':'helpClose',{},'ghost big')}
`);}; + importAsk(r);}; rd.readAsText(file);} +// A save from a file or a transfer link (#263), checked by parseSave(): what it is, and whether to load it. +function importAsk(r){UI.importing=r.s;openModal(`
${tr('common.import_a_save')}

${tr('save.load_name',{name:esc(r.name)})}

${esc(dateStr(r.s.day))} · ${tr('save.cash_in_the_bank',{cash:fmt$(r.s.cash)})} · ${trn('save.n_pop',Object.keys(r.s.pops).length)} · ${tr('save.saved_by_v_ver',{ver:esc(r.ver)})}

${tr('slots.it_joins_your_networks_on_this')}${r.lean?' '+tr('transfer.its_charts_and_news_start_fresh'):''}

${btn(tr('save.load_this_network'),'importGo',{},'pink big')}${btn(tr('common.cancel'),UI.started?'closeModal':'helpClose',{},'ghost big')}
`);} // This window's network, read synchronously (a compressed one was unpacked before boot). UI.loadBad: there, but unreadable. function loadSave(){UI.loadBad=false;const raw=slotRaw(UI.slot);if(raw==null)return null; try{const t=raw.startsWith(GZ)?raw===UI.gzRaw?UI.gzText:null:raw;if(t){const s=JSON.parse(t);if(s&&s.v===1){if(!s.lost)return s;return null;}}}catch(e){} diff --git a/src/game/95-modals/40-title.js b/src/game/95-modals/40-title.js index 54b3867..37a51ee 100644 --- a/src/game/95-modals/40-title.js +++ b/src/game/95-modals/40-title.js @@ -24,7 +24,7 @@ function showTitle(){
${doorsHtml()} ${homePick()}

${homeWhat()}

-
${btn(list.length?tr('common.start_a_new_network'):tr('common.start_building'),'start',{},'big')}${btn(tr('common.how_to_play'),'help',{},'ghost')}${btn(tr('common.import_a_save'),'importPick',{},'ghost')}${btn(tr('common.settings'),'settings',{},'ghost')}

v${APP_VERSION} · ${tr('title.source_on_github')} · ${tr('title.chat_on_signal')} · ${tr('title.cookieless_stats_no_tracking')}

`); +
${btn(list.length?tr('common.start_a_new_network'):tr('common.start_building'),'start',{},'big')}${btn(tr('common.how_to_play'),'help',{},'ghost')}${btn(tr('common.import_a_save'),'importPick',{},'ghost')}${btn(tr('transfer.from_another_device'),'xferRecv',{},'ghost')}${btn(tr('common.settings'),'settings',{},'ghost')}

v${APP_VERSION} · ${tr('title.source_on_github')} · ${tr('title.chat_on_signal')} · ${tr('title.cookieless_stats_no_tracking')}

`); $('nmIn').addEventListener('input',e=>{UI.nm=e.target.value;}); $('asnIn').addEventListener('input',e=>{UI.asnTxt=e.target.value.replace(/\D/g,'').slice(0,10);if(e.target.value!==UI.asnTxt)e.target.value=UI.asnTxt;e.target.classList.toggle('bad',!!UI.asnTxt&&!asnOk(+UI.asnTxt));}); } diff --git a/src/game/95-modals/45-slots.js b/src/game/95-modals/45-slots.js index 047c54d..c8dff9b 100644 --- a/src/game/95-modals/45-slots.js +++ b/src/game/95-modals/45-slots.js @@ -19,7 +19,7 @@ function slotRefresh(){const el=$('slotList');if(!el||UI.started)return;const h= function slotMenuHtml(id){const e=slotIdx().find(x=>x.id===id);if(!e)return '';const nm=esc(e.name||tr('common.unnamed_network')); return `
${slotIcon(e)} ${slotLine(e)}

${nm}

${e.at?tr('slots.last_played_ago',{ago:slotAgo(e.at)}):''}${e.size?' · '+tr('slots.size_on_this_device',{size:slotSize(e.size)}):''}

- `;} + `;} const slotSize=n=>n>=1e6?(n/1e6).toFixed(1)+' MB':Math.max(1,Math.round(n/1e3))+' kB'; function slotBusyModal(id){const e=slotIdx().find(x=>x.id===id),nm=esc(e&&e.name||tr('common.unnamed_network')); openModal(`
🪟 ${tr('slots.two_windows_one_network')}

${tr('slots.name_is_open_in_another_window',{name:nm})}

diff --git a/src/game/95-modals/46-transfer.js b/src/game/95-modals/46-transfer.js new file mode 100644 index 0000000..5b7c78d --- /dev/null +++ b/src/game/95-modals/46-transfer.js @@ -0,0 +1,17 @@ +/* Moving a network to another device (#263): the codes to scan and the link, and on the other side, where to paste it. */ +function xferHtml(){const x=UI.xfer,n=x.parts.length,i=Math.min(x.i,n-1),nm=esc(x.name||tr('common.unnamed_network')); + const q=n?qrEncode(new TextEncoder().encode(x.parts[i])):null; + return `
📲 ${tr('transfer.send_to_another_device')}

${nm}

+ ${q?`

${n>1?tr('transfer.on_your_other_device_open_the_many'):tr('transfer.on_your_other_device_open_the')}

${qrSvg(q,tr('transfer.qr_code_i_of_n',{i:i+1,n}))} + ${n>1?`
${btn('‹','xferPage',{i:i-1},'ghost',i===0)}${tr('transfer.code_i_of_n',{i:i+1,n})}${btn(tr('transfer.next_code'),'xferPage',{i:i+1},'pink',i===n-1)}
`:''}` + :`

${tr('transfer.this_network_is_too_big_for')}

`} +
${btn(navigator.share&&isPhone()?tr('transfer.send_the_link'):tr('transfer.copy_the_link'),'xferLink',{},n?'':'pink')}${btn(tr('common.export_save'),'xferFile',{},'ghost')}
+

${n?tr('transfer.the_codes_leave_out_your_charts')+' ':''}${tr('transfer.nothing_is_uploaded_anywhere_the_codes')}

`;} +function xferRecvHtml(){return `
📲 ${tr('transfer.from_another_device')}

${tr('transfer.moving_a_network_here')}

+

${tr('transfer.on_the_other_device_open_the')}

+ +
${btn(tr('common.open'),'xferPaste',{},'pink big')}${btn(tr('common.import_a_save'),'importPick',{},'ghost')}
`;} +function xferWaitHtml(s){const have=Object.keys(s.p).length; + return `
📲 ${tr('transfer.moving_a_network_here')}

${tr('transfer.have_of_n_codes_are_here',{have,n:s.n})}

+
+

${tr('transfer.scan_the_next_code_on_your')}

${btn(tr('common.close'),'helpClose',{},'pink big')}${btn(tr('transfer.start_over'),'xferReset',{},'ghost')}
`;} diff --git a/src/game/95-modals/60-help.js b/src/game/95-modals/60-help.js index e3fd9c2..169e48c 100644 --- a/src/game/95-modals/60-help.js +++ b/src/game/95-modals/60-help.js @@ -18,7 +18,7 @@ function showHelp(){
${tr('common.waves')}
${tr('help.your_fiber_links_are_leased_waves')}
${tr('common.95th_percentile')}
${tr('help.transit_bills_sample_your_usage')}
${tr('common.routers')}
${tr('help.each_pop_s_router_model_caps')}
${tr('common.dark_fiber')}
${tr('help.lease_an_iru_or_build_your')}
${tr('common.subsea_cables')}
${tr('help.subsea_waves_can_only_follow_cable')}
${tr('common.latency')}
${tr('help.every_link_has_latency_high')}
${tr('common.noc_dashboard')}
${tr('help.the_chart_button_at_the_top')}
${tr('common.asia')}
${tr('help.a_weird_underserved_market_transit')}
${tr('common.russia')}
${tr('help.moscow_needs_a_mandatory_government')}
${tr('help.events_chains_and_wholesale')}
${tr('help.event_networks_a_final_a_festival')}
${tr('common.bank')}
${tr('help.tap_your_cash_to_open_the')}
${tr('common.lags')}
${tr('help.out_of_port_speed_bundle_up')}
${tr('common.traffic_engineering')}
${tr('help.tap_a_link_to_see_which')}
${tr('common.china')}
${tr('help.mainland_china_needs_a_license_and')}
${tr('common.weird_requirements')}
${tr('help.some_customers_come_with_conditions')}
${tr('common.customer_levels')}
${tr('help.as_your_peak_traffic_and_footprint')}
${tr('help.l2vpn_ddos_protection')}
${tr('help.businesses_may_want_a_private')}
${tr('common.ddos_attack')}
${tr('help.ddos_a_flood_comes_from')}
${tr('common.scrubbing_centers')}
${tr('help.scrubbing_a_center_pulls_floods')}
${tr('common.nni_fabrics')}
${tr('help.megapork_pocketfabric_and')}
${tr('common.conferences')}
${tr('help.nanog_ripe_denog_and_friends_come')}
${tr('common.modes')}
${tr('help.one_game_four_doors_and_the')}
${tr('common.traceroute')}
${tr('help.tap_traceroute_on_any_of_your')}
${tr('common.badges')}
${tr('help.below_your_goals_sits_a_wall')}
${tr('common.the_giants')}
${tr('help.at_customer_level_3_and_4')}
RouteScript
${tr('help.once_auto_te_is_installed_you')}
Auto-TE
${tr('help.traffic_follows_the_shortest_path_by')}
${tr('common.metro_diversity')}
${tr('help.a_pop_is_one_building_until')}
${tr('common.wave_markets')}
${tr('help.what_a_wave_costs_depends_on')}
${tr('common.regional_quirks')}
${tr('help.in_the_gulf_saudi_pops_need')}
${tr('common.boot_times')}
${tr('help.some_routers_take_forever_to_boot')}
${tr('common.failures')}
${tr('help.things_break_all_the_time_fiber')}
RouteScript
${tr('help.rules_for_your_auto_te_controller')}
-

${tr('help.want_to_know_how_it_really')}

${plugHtml(true)}${chatHtml()}${issueHtml()}
${btn(UI.started?tr('common.back_to_the_map'):tr('common.got_it'),'helpClose',{},'big')}${RELEASE_NOTES.length?btn(tr('common.what_s_new_in_v',{v:esc(APP_VERSION)}),'whatsNewShow',{},'ghost'):''}${UI.started&&S&&!S.lost?btn(tr('common.start_a_new_network'),'resetAsk',{},'ghost sm'):''}
${UI.started&&S&&!S.lost?btn(tr('common.export_save'),'exportSave',{},'ghost sm'):''}${btn(tr('common.import_a_save'),'importPick',{},'ghost sm')}${btn(tr('common.settings'),'settings',{},'ghost sm')}${isPhone()?'':btn(tr('keys.keyboard_shortcuts'),'keys',{},'ghost sm')}
`); +

${tr('help.want_to_know_how_it_really')}

${plugHtml(true)}${chatHtml()}${issueHtml()}
${btn(UI.started?tr('common.back_to_the_map'):tr('common.got_it'),'helpClose',{},'big')}${RELEASE_NOTES.length?btn(tr('common.what_s_new_in_v',{v:esc(APP_VERSION)}),'whatsNewShow',{},'ghost'):''}${UI.started&&S&&!S.lost?btn(tr('common.start_a_new_network'),'resetAsk',{},'ghost sm'):''}
${UI.started&&S&&!S.lost?btn(tr('common.export_save'),'exportSave',{},'ghost sm'):''}${btn(tr('common.import_a_save'),'importPick',{},'ghost sm')}${btn(tr('transfer.from_another_device'),'xferRecv',{},'ghost sm')}${btn(tr('common.settings'),'settings',{},'ghost sm')}${isPhone()?'':btn(tr('keys.keyboard_shortcuts'),'keys',{},'ghost sm')}
`); } function showWin(){setTimeout(()=>{const m=$('modalCard');if(m&&!m.querySelector('[data-act=share]'))m.insertAdjacentHTML('beforeend',`
${btn(tr('help.share_my_network'),'share',{},'pink')}

${tr('help.you_built_a_cartoon_internet_now')}

${plugHtml(true)}`);},0);openModal(`

${tr('help.you_re_a_tier_1')}

${tr('help.name_as_asn_is_transit_free',{name:esc(S.name),asn:S.asn,days:S.day,n:S.stats.incidents})}

${btn(tr('common.keep_building'),'keepPlaying',{},'pink big')}`);sfx('coin');} function showLose(){openModal(`

${tr('common.bankrupt')}

${tr('help.the_bank_repossessed_your_routers',{name:esc(S.name),days:S.day,peak:fmtG(S.stats.peak)})}

${btn(tr('common.try_again'),'newgame',{},'pink big')}`);if(UI.slot){const id=UI.slot;slotDrop(id);slotFree(id);}} diff --git a/src/game/96-map/95-clicks.js b/src/game/96-map/95-clicks.js index c10b794..9919023 100644 --- a/src/game/96-map/95-clicks.js +++ b/src/game/96-map/95-clicks.js @@ -11,5 +11,5 @@ let PD={t:0,b:null}; document.addEventListener('pointerdown',e=>{PD={t:performance.now(),b:e.target.closest('[data-act]')};},true); function tapOk(e,b){if(!e.isTrusted||!PD.t||e.detail===0)return true;const now=performance.now();if(now-PD.t>4000)return true; if(PD.b!==b)return false;if((UI.layerAt||0)>PD.t)return false;const ts=b.closest('.toast');if(ts&&PD.t-(+ts.dataset.born||0)<500)return false;return true;} -document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','keys','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','mapSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','pzArStart','pzWeekly','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip','slotMenu','slotExport','slotDel','slotDelGo','slotBack','slotSwitch','slotTake','slotSpace','toTitle'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);}); +document.addEventListener('click',e=>{const b=e.target.closest('[data-act]');if(!b||b.disabled)return;if(!$('modal').hidden&&!b.closest('#modal'))return;if(!tapOk(e,b))return;audioInit();const fn=ACT[b.dataset.act];if(!fn)return;if(!S&&!['start','keys','randomName','pickStart','cont','help','helpClose','newgame','mute','animSet','mapSet','soundSet','langSet','closeModal','speed','bankClose','whatsNewShow','updateNow','updateLater','importPick','importGo','modeSet','presetSet','chaosSet','puzzleDoor','puzzleMenu','pzStart','pzArStart','pzWeekly','scenarios','startScn','startWeekly','settings','settingsClose','prefSet','vpSet','install','pitchSkip','slotMenu','slotExport','slotDel','slotDelGo','slotBack','slotSwitch','slotTake','slotSpace','toTitle','xfer','xferPage','xferLink','xferFile','xferRecv','xferPaste','xferReset'].includes(b.dataset.act))return;let a={};try{a=JSON.parse(b.dataset.args||'{}');}catch(_){}fn(a);}); diff --git a/src/game/99-loop.js b/src/game/99-loop.js index 03f7aaa..bbb8114 100644 --- a/src/game/99-loop.js +++ b/src/game/99-loop.js @@ -68,7 +68,7 @@ function boot(data){ // A save that cannot be loaded stays where it is, marked damaged: it can still be exported, or deleted. else if(UI.slot&&(sv||UI.loadBad))slotBroke(UI.slot); else{showTitle();if(UI.bootBusy)slotBusyModal(UI.bootBusy);else whatsNew(false);if(UI.bootBroken)toast(tr('loop.your_saved_game_could_not_be'),'bad');}} - renderHUD();renderLeft(); + renderHUD();renderLeft();xferBoot(); window.claude?.hot?.snapshot?.(()=>({S:S&&JSON.parse(JSON.stringify(S)),cam:{...cam}})); if(!window.__TUBES_TEST__){requestAnimationFrame(frame);setTimeout(checkUpdate,4000);setInterval(checkUpdate,10*60*1000);} } diff --git a/src/i18n/en.js b/src/i18n/en.js index 8ace98f..d0a2a0e 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -4848,6 +4848,30 @@ "traceroute.this_one_is_set_to_mode":"; this one is set to {mode}", "traceroute.transit_is_the_last_resort":"transit is the last resort", "traceroute.your_traffic_follows_the_metrics_this":"Your internet traffic follows the metrics. This is the path a customer circuit on “{mode}” would take.", +"transfer.code_i_of_n":"Code {i} of {n}", +"transfer.copy_the_link":"Copy the link", +"transfer.could_not_copy_the_link_here":"Could not copy the link here. Export a save file instead.", +"transfer.from_another_device":"From another device", +"transfer.have_of_n_codes_are_here":"{have} of {n} codes are here", +"transfer.its_charts_and_news_start_fresh":"Its charts and news start fresh here.", +"transfer.link_copied_open_it_on_your":"Link copied. Open it on your other device.", +"transfer.moving_a_network_here":"Move a network here", +"transfer.next_code":"Next code", +"transfer.nothing_is_uploaded_anywhere_the_codes":"Nothing is uploaded anywhere: the codes and the link carry the network itself. Whoever opens them gets a copy, so keep them to yourself.", +"transfer.on_the_other_device_open_the":"On the device with your network, open the menu and pick Send to another device. Scan its code with this device's camera, or paste its link here.", +"transfer.on_your_other_device_open_the":"On your other device, point the camera at this code and open the link.", +"transfer.on_your_other_device_open_the_many":"On your other device, point the camera at this code and open the link, then come back here for the next one. They can arrive in any order.", +"transfer.paste_a_transfer_link":"Paste a transfer link", +"transfer.qr_code_i_of_n":"QR code {i} of {n}", +"transfer.scan_the_next_code_on_your":"Scan the next code on your other device and open its link. Your network loads as soon as the last one arrives.", +"transfer.send_the_link":"Send the link", +"transfer.send_to_another_device":"Send to another device", +"transfer.start_over":"Start over", +"transfer.that_is_not_a_transfer_link":"That is not a transfer link.", +"transfer.that_link_is_incomplete_or_damaged":"That link is incomplete or damaged. Copy it again, all of it.", +"transfer.the_codes_leave_out_your_charts":"To keep the codes few, they leave out your charts and news; the link carries everything.", +"transfer.this_browser_cannot_pack_networks_into":"This browser cannot pack networks into links. Use a save file instead.", +"transfer.this_network_is_too_big_for":"This network is too big for codes. Send the link instead, or export a save file.", "tutorial.businesses_pop_up_as_bubbles_on":"Businesses pop up as $ bubbles on the map. Open Deals and sign your first customer.", "tutorial.grow_drag_from_your_pink_router":"Grow: drag from your pink router onto a nearby city to lay fiber and open a second POP.", "tutorial.start_the_clock_with_1_and":"Start the clock with 1× and watch traffic and money flow. You can pause any time.", diff --git a/src/styles/40-modal.css b/src/styles/40-modal.css index 4c1884e..d431cd1 100644 --- a/src/styles/40-modal.css +++ b/src/styles/40-modal.css @@ -229,3 +229,8 @@ h2 .rn{font-size:18px;vertical-align:middle;padding:2px 4px} .cmroute{align-items:flex-start} .tag.cmhot{background:#FFE1D6;color:#B43A12} .tag.cmcool{background:#DDF1FB;color:#1E6A8C} +/* Moving a network to another device (#263). A code stays dark on white in dark mode too: cameras need the contrast. */ +svg.qr{display:block;width:100%;max-width:300px;height:auto;margin:10px auto 6px;border:3px solid var(--ink);border-radius:12px;background:#fff;box-sizing:border-box} +.xfer-nav{display:flex;align-items:center;justify-content:space-between;gap:8px;max-width:300px;margin:0 auto}.xfer-nav b{font:800 14px var(--display)} +textarea.xfer-in{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radius:12px;padding:8px 10px;font:13px/1.35 ui-monospace,monospace;background:var(--soft);color:var(--ink);resize:vertical;word-break:break-all} +.xfer-dots{display:flex;flex-wrap:wrap;gap:5px;margin:10px 0}.xfer-dots i{width:12px;height:12px;border-radius:50%;border:2px solid var(--ink);background:var(--soft)}.xfer-dots i.on{background:var(--ok)} diff --git a/tests/device-transfer.test.js b/tests/device-transfer.test.js new file mode 100644 index 0000000..e6d49fa --- /dev/null +++ b/tests/device-transfer.test.js @@ -0,0 +1,164 @@ +// Moving a network to another device with QR codes or a link (#263): no server, the network travels in the link. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const crypto = require('node:crypto'); +const { load } = require('./harness'); +const { until } = require('./net'); + +const settle = async (ev, cond, what) => assert.ok(await until(() => ev(cond)), what || cond); +const hash = (rows) => crypto.createHash('sha256').update(rows).digest('hex').slice(0, 16); + +// Module matrices from Project Nayuki's reference encoder (qrcodegen), byte mode, one per mask. +const REF = [ + ['https://seriesoftub.es/#sot1.ab12c.0.3.HELLO-world_42', 'L', 3, ['30728883c56ec1b1', '18174c37d6786fa7', 'a981f41d89cceb7e', 'e28c29324d50ad09', 'd05a240976233180', 'd7ad281bfed61f9e', '083a4137b252f78f', 'a82468785d358d89']], + ['x'.repeat(200), 'M', 10, ['750d745db4aee09b', '9ff2474eb4806262', 'c8294f9a437b1546', '1bf4d13e40b47c5f', 'fdce0323024df963', '87c3d49925e75834', 'b719f9e8d1b0dd89', '342f8ed986243039']], + ['Series of Tubes '.repeat(40), 'L', 17, ['6d81d73a8426ecea', 'c36740777a080ce2', '79556df75d596a27', 'c4999ca1f4c7cdff', '23185df5abef3f74', '5b2fc9fa8d26aac0', '88b5814b383833f3', '298a1c7f2a08b6ae']], + ['AS64512 '.repeat(120), 'L', 22, ['f8229058824f8960', '0c473ae025a4c779', '58c3ab340313be0a', 'd4fa9891688a1ccc', 'eaac167548e8e5f3', '3f14beb40d1dc4cf', 'a29dee8e6e34fd04', 'b0c682d9933fe28a']], + ['peering '.repeat(360), 'L', 40, ['6efd1b3513f437d0', 'c18c188947dc52bc', 'cd93f7d4626a657f', 'a596a01654473a8d', '33fa5bbfe6b4915a', 'c547ade997387b9e', 'ed333919d660b05a', '44f32c8d979821a8']], +]; + +test('the QR encoder draws exactly the reference codes, for every mask, from version 3 to 40', () => { + const { ev, errors } = load(); + for (const [s, ecc, v, masks] of REF) { + masks.forEach((h, mask) => { + const q = JSON.parse(ev(`(()=>{const q=qrEncode(new TextEncoder().encode(${JSON.stringify(s)}),{ecc:'${ecc}',mask:${mask}});return JSON.stringify({v:q.v,size:q.size,m:q.m.map(r=>r.map(b=>b?1:0).join('')).join('')});})()`)); + assert.equal(q.v, v, `${s.slice(0, 12)}… version`); + assert.equal(q.size, v * 4 + 17); + assert.equal(hash(q.m), h, `${s.slice(0, 12)}… ${ecc} mask ${mask}`); + }); + // Left to choose, it picks one of the eight valid masks. + const auto = JSON.parse(ev(`(()=>{const q=qrEncode(new TextEncoder().encode(${JSON.stringify(s)}),{ecc:'${ecc}'});return JSON.stringify({v:q.v,m:q.m.map(r=>r.map(b=>b?1:0).join('')).join(''),mask:q.mask});})()`)); + assert.equal(auto.v, v); + assert.equal(hash(auto.m), masks[auto.mask]); + } + assert.equal(ev("qrEncode(new Uint8Array(2954))"), null, 'more than version 40 holds'); + assert.match(ev("qrSvg(qrEncode(new TextEncoder().encode('hi')),'x')"), /^ { + const a = await sender(); + const link = a.ev('UI.xfer.link'), want = a.ev("JSON.stringify({day:S.day,cash:S.cash,pops:Object.keys(S.pops),links:S.links.length,biz:S.biz.length,name:S.name})"); + assert.ok(link.startsWith('https://tests.invalid/#sot1.'), link.slice(0, 40)); + assert.ok(a.ev('UI.xfer.parts.length') > 1, 'a played network takes several codes'); + assert.ok(a.ev('UI.xfer.parts.every(p=>p.length<=qrCap(22))'), 'every code is small enough to scan from a phone screen'); + + const b = load({ gzip: true, url: link }); + assert.equal(b.ev('location.hash'), '', 'the network is taken out of the address bar at once'); + await settle(b.ev, '!!UI.importing', 'it asks before loading'); + assert.match(b.ev("$('modalCard').textContent"), /Tube Mover/); + assert.doesNotMatch(b.ev("$('modalCard').textContent"), /start fresh/, 'the link carries everything'); + const hist = a.ev('JSON.stringify(S.hist)'), log = a.ev('S.log.length'); + b.ev('ACT.importGo()'); + assert.equal(b.ev("JSON.stringify({day:S.day,cash:S.cash,pops:Object.keys(S.pops),links:S.links.length,biz:S.biz.length,name:S.name})"), want); + assert.equal(b.ev('JSON.stringify(S.hist)'), hist, 'the charts came along'); + assert.equal(b.ev('S.log.length'), log + 1, 'the news came along (plus the welcome)'); + assert.equal(b.ev('slotIdx().length'), 1, 'it joins the networks on that device'); + assert.deepEqual(a.errors, []); + assert.deepEqual(b.errors, []); +}); + +test('the codes arrive one by one, in any order; the network loads when the last one is in', async () => { + const a = await sender(); + const parts = JSON.parse(a.ev('JSON.stringify(UI.xfer.parts)')), n = parts.length; + // Paging through the codes on the sending device. + a.ev('ACT.xferPage({i:1})'); + assert.match(a.ev("$('modalCard').textContent"), new RegExp(`Code 2 of ${n}`)); + + const b = load({ gzip: true }); + const order = parts.map((p, i) => i).reverse(); + for (const [k, i] of order.entries()) { + b.ev(`xferTake(${JSON.stringify(parts[i])})`); + if (k < n - 1) { + assert.match(b.ev("$('modalCard').textContent"), new RegExp(`${k + 1} of ${n} codes are here`)); + assert.equal(b.ev('document.querySelectorAll(".xfer-dots i.on").length'), k + 1); + // The same code twice changes nothing. + b.ev(`xferTake(${JSON.stringify(parts[i])})`); + assert.equal(b.ev('Object.keys(xferStore().p).length'), k + 1); + } + } + await settle(b.ev, '!!UI.importing', 'the last code opens the network'); + assert.equal(b.ev("localStorage.getItem('sot-xfer')"), null, 'the parts are cleaned up'); + assert.match(b.ev("$('modalCard').textContent"), /charts and news start fresh/, 'it says what the codes left out'); + const vol = a.ev('S.vol'); + b.ev('ACT.importGo()'); + assert.equal(b.ev('S.name'), 'Tube Mover'); + assert.equal(b.ev('S.cash'), a.ev('S.cash')); + assert.equal(b.ev('S.day'), a.ev('S.day')); + assert.equal(b.ev('S.vol'), vol, 'the traffic odometer keeps its count'); + assert.equal(b.ev('S.hist.length'), 0, 'only charts and news were left out'); + assert.equal(b.ev('S.log.length'), 1, 'the news starts with the welcome'); + b.ev('for(let i=0;i<3;i++)dayTick()'); + assert.equal(b.ev('S.hist.length'), 3, 'the charts start again'); + assert.deepEqual(b.errors, []); +}); + +test('a code from another transfer starts over, and bad or cut links say so and load nothing', async () => { + const a = await sender(); + const parts = JSON.parse(a.ev('JSON.stringify(UI.xfer.parts)')), link = a.ev('UI.xfer.link'); + const b = load({ gzip: true }); + b.ev(`xferTake(${JSON.stringify(parts[0])})`); + b.ev(`xferTake(${JSON.stringify(parts[1].replace(/#sot1\.[a-z0-9]+\./, '#sot1.zzzzz.'))})`); + assert.equal(b.ev("xferStore().id"), 'zzzzz'); + assert.equal(b.ev('Object.keys(xferStore().p).length'), 1); + b.ev('ACT.xferReset()'); + assert.equal(b.ev("localStorage.getItem('sot-xfer')"), null); + + b.ev("xferTake('https://example.com/nothing-here')"); + assert.match(b.ev("$('toasts')?$('toasts').textContent:document.body.textContent"), /not a transfer link/); + b.ev(`xferTake(${JSON.stringify(link.slice(0, -40))})`); + await settle(b.ev, "/incomplete or damaged/.test(document.body.textContent)", 'a cut link is reported'); + assert.equal(b.ev('!!UI.importing'), false); + assert.equal(b.ev('S'), null, 'nothing was loaded'); + + // Pasted into the box on the title screen, the whole link works too. + b.ev('ACT.xferRecv()'); + b.ev(`$('xferIn').value=${JSON.stringify(' ' + link + '\n')};ACT.xferPaste()`); + await settle(b.ev, '!!UI.importing'); + assert.deepEqual(b.errors, []); +}); + +test('any network on the title screen can be sent, and the codes fit a 360 px phone', async () => { + const a = await sender(); + a.ev("ACT.toTitle()"); + const id = a.ev('slotIdx()[0].id'); + a.ev(`ACT.slotMenu({id:'${id}'})`); + assert.ok(a.ev(`!!document.querySelector('#modalCard [data-act="xfer"]')`), 'the network menu offers it'); + a.ev('window.innerWidth=360;UI.xfer=null'); + a.ev(`document.querySelector('#modalCard [data-act="xfer"]').click()`); + await settle(a.ev, '!!UI.xfer&&!!document.querySelector("#modalCard svg.qr")', 'sent from storage, without loading it'); + assert.equal(a.ev('UI.xfer.name'), 'Tube Mover'); + assert.ok(a.ev("!!document.querySelector('#modalCard .xfer-nav')")); + const css = a.ev("[...document.styleSheets].flatMap(s=>[...s.cssRules]).map(r=>r.cssText).join('\\n')"); + assert.match(css, /svg\.qr\s*\{[^}]*max-width:\s*300px/, 'the code never gets wider than a small phone'); + assert.ok(a.ev(`!!document.querySelector('#modalCard [data-act="xferLink"]')`)); + assert.deepEqual(a.errors, []); +}); + +test('a year-old network takes a handful of codes, because the codes leave out charts and news', async () => { + const a = load({ gzip: true }); + a.ev("ACT.start({});for(let i=0;i<365;i++)dayTick();save(true);ACT.xfer({})"); + await settle(a.ev, '!!UI.xfer'); + const n = a.ev('UI.xfer.parts.length'), full = Math.ceil(a.ev("UI.xfer.link.split('.').pop().length") / 900); + assert.ok(n <= 4, `${n} codes`); + assert.ok(full >= 2 * n, `the whole network would take ${full}`); + assert.match(a.ev("$('modalCard').textContent"), /leave out your charts and news/); + assert.deepEqual(a.errors, []); +}); + +test('without compression in the browser it says so instead of failing', () => { + const { ev, errors } = load(); + ev("ACT.start({});save(true);ACT.xfer({})"); + assert.equal(ev('UI.xfer'), undefined); + assert.match(ev('document.body.textContent'), /cannot pack networks into links/); + assert.deepEqual(errors, []); +});