Skip to content

Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.

NumPlay Studio: your calculator's real space, big games in every language, a light calculator

Mason3638509188e25ed
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 69322ae0..75f3b4a1 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -56,7 +56,7 @@ Then:
A **small game inside NumPlay** follows Block Blast's pattern (`games/blockblast`): built with `-DNP_MODULE=1`, it draws with the launcher's `gfx_*` functions and fonts and saves with `np_file_read` and `np_file_write`, so it costs only its rules and its screen. On its own it compiles those files in. `tools/new_game.py "My Game" --numplay` starts one this way.
-A **big game** builds as its own `.nwa` (like `games/finalearth2`), with a build for your computer to test it.
+A **big game** builds as its own `.nwa` (like `games/finalearth2`), with a build for your computer to test it. It's built with `-DEPSILON_XL=1`, so in a NumPlay that goes past the calculator's app area (Nwagra) it still finds its saves.
## What every game needs
diff --git a/Makefile b/Makefile
index 8a851a84..42567ab1 100644
--- a/Makefile
+++ b/Makefile
@@ -30,12 +30,22 @@ RAM_LIMIT = 148928
# its own (their big buffers are on the stack, 32 KB apart from that RAM, or in the RAM the software has left)
CUSTOM_RAM = 133652
BIG_APPS = Celeste HollowKnight Undertale ChampionIsland FinalEarth2 NumPowder NumBlocks NumDrive SubwaySurfers FiveNightsAtFreddys Doom BindingOfIsaac HillClimbRacing PlantsVsZombies SonicTheHedgehog CookieClicker LevelDevil JetpackJoyride StickmanHook DonkeyKong Dune
-# the calculator's space for installed apps (0x90200000 to 0x903F0000 in its flash)
+# the calculator's space for installed apps: from the end of its software (64 KiB aligned) to 64 KiB before the
+# end of its 4 MiB slot of flash, 0x903F0000. The software's size sets the start: 0x90200000 is the latest a
+# NumPlay counts on (1.94 MB, APP_SPACE); Epsilon 26.4 on an N0120 ends at 0x90180000 (2.44 MB, the
+# installer's 2496 KB)
+APP_START = 0x90200000
+APP_START_26 = 0x90180000
+APP_END = 0x903F0000
APP_SPACE = 2031616
# with Enlarged Extra Apps (nwagyu's Nwagra), the app loader is told the space goes on to the end of the
# external flash (0x90800000), over the second copy of the calculator's software: a NumPlay of the big
-# games (games.json "xl", made with the customizer website from `make kit`) is for that
+# games (games.json "xl", made with the customizer website from `make kit`) is for that: 6 MB, or 6.5 MB
+# from 0x90180000 (the installer's 6656 KB)
+XL_END = 0x90800000
XL_APP_SPACE = 6291456
+# the spaces the customizer website offers (kit.json "spaces"; tools/kit.py links a NumPlay at each)
+SPACES = std:$(APP_START):$(APP_END) e26:$(APP_START_26):$(APP_END) xl:$(APP_START):$(XL_END) xl26:$(APP_START_26):$(XL_END)
# Upsilon, the N0110 and N0115's custom software, gives .nwa apps less RAM: NumPlay-Upsilon.nwa has
# the games that fit it (NumPlay draws their text there: see launcher/src/compat.c)
UPSILON_RAM = 107674
@@ -114,6 +124,14 @@ $(B)/modules/%.o: FORCE | $(B)
$(PY) tools/npmodule.py $(B)/modules/$*.2.o $@ --game $* --index $(INDEX_$*) \
--entry $(or $(ENTRY_$*),$(ENTRY)) --json $(B)/modules/$*.json
+# A language's tree (make kit-langs) takes the big games' modules from the English build (XL_FROM) as they are:
+# they're in English, and call nothing of NumPlay's but the launcher (KIT_API)
+ifneq ($(XL_FROM),)
+$(foreach g,$(XL_GAMES),$(B)/modules/$(g).o): $(B)/modules/%.o: $(XL_FROM)/$(B)/modules/%.o | $(B)
+ cp $< $@
+ cp $(XL_FROM)/$(B)/modules/$*.json $(B)/modules/$*.json
+endif
+
# games in the standard layout (see tools/games_mk.py)
$(foreach g,$(STD_GAMES),$(eval MOD_$(g) = $(if $(filter $(g),$(GAMES_REDIRECT)),$(B)/games/$(g)/module.o,games/$(g)/output/module.o))$(eval SIM_$(g) = $(if $(filter $(g),$(GAMES_REDIRECT)),$(B)/games/$(g)/sim-module.o,games/$(g)/output/sim-module.o)))
@@ -197,18 +215,21 @@ kit: $(KIT)/base.o $(B)/arm/arena.o $(KIT_GAMES) $(B)/NumPlay.nwa \
$(foreach v,$(VARIANTS),$(B)/variant/$(v)-name.o $(B)/variant/$(v)-icon.o)
$(PY) tools/kit.py games/games.json $(B) $(B)/site-kit --version $(VERSION) --variants "$(VARIANTS)" \
--default "$(GAMES)" --upsilon "$(UPSILON_GAMES)" --app-space $(APP_SPACE) --xl-app-space $(XL_APP_SPACE) \
- --ram $(CUSTOM_RAM) --ram-limit $(RAM_LIMIT) --upsilon-ram $(UPSILON_RAM) --nwlink "$(NWLINK)" --langs "$(LANGS)" \
- --alone "$(foreach g,$(XL_GAMES),$(g)=$(APP_$(g)))"
+ --spaces "$(SPACES)" --ram $(CUSTOM_RAM) --ram-limit $(RAM_LIMIT) --upsilon-ram $(UPSILON_RAM) --nwlink "$(NWLINK)" \
+ --langs "$(LANGS)" --alone "$(foreach g,$(XL_GAMES),$(g)=$(if $(XL_FROM),$(XL_FROM)/)$(APP_$(g)))" \
+ $(if $(XL_FROM),--english "$(XL_FROM)/$(B)/site-kit")
-# ...and in French and Chinese, from each language's tree (make lang), in site-kit/<code> (without the big
-# games, which are in English: the website uses them in English NumPlays)
+# ...and in French and Chinese, from each language's tree (make lang), in site-kit/<code>. The big games stay in
+# English: their modules come from this build (XL_FROM), their names, taglines and screenshots from the tree
kit-langs: kit
@for l in $(LANGS); do \
[ -d $(B)/lang/$$l ] || $(PY) tools/lang.py tree $$l $(B)/lang/$$l || exit 1; \
- $(MAKE) -C $(B)/lang/$$l kit XL_GAMES= NWLINK="$(NWLINK)" || exit 1; \
+ cp Makefile $(B)/lang/$$l/ && cp tools/*.py tools/*.ld $(B)/lang/$$l/tools/ || exit 1; \
+ $(MAKE) -C $(B)/lang/$$l kit XL_FROM="$(CURDIR)" NWLINK="$(NWLINK)" || exit 1; \
rm -rf $(B)/site-kit/$$l && mkdir -p $(B)/site-kit/$$l && \
cp -R $(B)/lang/$$l/$(B)/site-kit/kit.json $(B)/lang/$$l/$(B)/site-kit/base.o.gz \
$(B)/lang/$$l/$(B)/site-kit/arena.o.gz $(B)/lang/$$l/$(B)/site-kit/games $(B)/site-kit/$$l/ || exit 1; \
+ cp $(B)/lang/$$l/$(B)/site-kit/apps/* $(B)/site-kit/apps/ 2>/dev/null; \
done
check: nwa apps
diff --git a/customize/app.css b/customize/app.css
index e52efe4b..b374ee4b 100644
--- a/customize/app.css
+++ b/customize/app.css
@@ -250,18 +250,22 @@ body.dragging .drop-hint { display: flex; }
.segctl.col button[aria-checked="true"] { background: #eceef1; box-shadow: none; }
.tick { display: flex; align-items: center; gap: 5px; font-size: 13px; color: var(--mute); white-space: nowrap; }
-/* ---- 1.94 MB or 6 MB */
-.cap { display: flex; gap: 2px; background: var(--track); border-radius: 999px; padding: 2px; flex-shrink: 0; }
-.cap button { border: 0; background: transparent; padding: 4px 10px; border-radius: 999px; cursor: pointer; font-size: 12px; font-weight: 650; color: var(--mute); white-space: nowrap; }
-.cap button[aria-checked="true"] { background: var(--card); color: var(--ink); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1); }
-#xl-pop { width: 360px; gap: 10px; }
-.xl-title { font-size: 16px; }
-.xl-text, .xl-warn { margin: 0; font-size: 13px; line-height: 1.45; color: #3a3d42; }
-.xl-warn { color: #8a4b00; background: #fff4e0; border-radius: 10px; padding: 8px 10px; }
+/* ---- your calculator's space for apps: it depends on its software, and on Nwagra */
+.space-chip {
+ display: flex; align-items: center; gap: 6px; height: 30px; padding: 0 10px 0 12px; border: 0; border-radius: 15px; flex-shrink: 0;
+ background: var(--card); box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08); cursor: pointer; white-space: nowrap;
+ font-size: 13px; font-weight: 700; font-variant-numeric: tabular-nums;
+}
+.space-chip .caret { color: var(--mute); }
+.space-chip:hover { background: #fafafa; }
+.space-pop { width: 310px; gap: 8px; padding: 12px 8px 8px; }
+.pop-title { font-size: 13px; font-weight: 650; color: var(--mute); padding: 0 12px; }
+.spaces button { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; }
+.spaces button b { font-weight: 700; font-variant-numeric: tabular-nums; }
+.nwagra { display: flex; flex-direction: column; gap: 8px; padding: 4px 8px 4px; }
+.nwagra a { color: #0060c0; font-weight: 650; text-decoration: none; }
+.xl-warn { margin: 0; font-size: 13px; line-height: 1.45; color: #8a4b00; background: #fff4e0; border-radius: 10px; padding: 8px 10px; }
.xl-steps { margin: 0; padding-left: 20px; font-size: 13px; line-height: 1.6; color: #3a3d42; }
-.xl-buttons { display: flex; align-items: center; justify-content: space-between; margin-top: 4px; }
-.xl-guide { font-size: 13px; font-weight: 650; color: #0060c0; text-decoration: none; }
-.xl-ok { padding: 10px 20px; font-size: 14px; }
/* ---- Retro-Go: your own games, as cartridges */
.retro { display: flex; flex-direction: column; gap: 12px; margin-top: 10px; }
@@ -350,6 +354,24 @@ body.dragging .drop-hint { display: flex; }
.foot a:hover { color: var(--ink); }
.noscript { text-align: center; padding: 0 16px; }
+/* ---- the light calculator, for slow computers and phones (app.js, buildFlat): the same photo, flat. OK and Back
+ are cut from it, over a gap that shows round them as they go in; the sticker is drawn once, as the 3D one
+ looks from the front */
+html.flat .device { perspective: none; }
+html.flat .calc { transform: none; transform-style: flat; }
+html.flat .calc-img { clip-path: none; -webkit-mask: none; mask: none; }
+html.flat .well { transform: none; }
+html.flat .well-img, html.flat .body3d { display: none; }
+.fkey { position: absolute; border-radius: 50%; background: radial-gradient(closest-side, #858589 92%, #b9b9bd 100%); }
+.ftop { position: absolute; inset: 0; border-radius: 50%; overflow: hidden; display: block; transition: transform 90ms var(--ease); }
+.ftop img { position: absolute; max-width: none; pointer-events: none; user-select: none; }
+.fkey:has(> .ok-key:hover) .ftop, .fkey:has(> .dl:hover) .ftop { transform: scale(0.985); }
+.fkey:has(> .ok-key:active) .ftop, .fkey:has(> .dl:active) .ftop, .fkey.down .ftop { transform: scale(0.94); }
+html.flat .sticker canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
+
+/* ---- on a phone, the keys under your thumb once the calculator is scrolled away (app.js, dock) */
+.dock { display: none; }
+
/* ---- the intro: the games flying into the calculator */
.flyer { position: fixed; left: 0; top: 0; z-index: 70; pointer-events: none; will-change: transform, opacity; }
.flyer img { display: block; width: 100%; aspect-ratio: 55 / 56; filter: drop-shadow(0 10px 14px rgba(0, 0, 0, 0.22)); }
@@ -369,9 +391,28 @@ html.intro-wait main { opacity: 0; }
.head { padding: 24px 16px 0; }
.games { padding: 8px 16px 0; }
.side { padding: 22px 16px 24px; }
- .device { position: relative; height: calc(var(--cw) * 1.1 + 30px); margin: 8px auto 0; width: calc(var(--cw) + 40px); perspective-origin: 50% 20%; }
+ /* (the calculator down to just above its first row of keys, fading out there) */
+ .device {
+ position: relative; height: calc(var(--cw) * 1.066 + 30px); margin: 8px auto 0; width: min(calc(var(--cw) + 40px), 100%); perspective-origin: 50% 20%;
+ -webkit-mask: linear-gradient(#000 calc(100% - 18px), transparent); mask: linear-gradient(#000 calc(100% - 18px), transparent);
+ }
.meter { display: none; }
.foot { justify-content: center; }
+ .dock {
+ position: fixed; left: 12px; right: 12px; bottom: 12px; z-index: 30; max-width: 520px; margin: 0 auto;
+ display: flex; align-items: center; gap: 8px; padding: 6px 6px 6px 20px; border-radius: 999px;
+ background: var(--card); box-shadow: 0 10px 30px rgba(0, 0, 0, 0.18), 0 0 0 1px rgba(0, 0, 0, 0.05);
+ transform: translateY(calc(100% + 16px)); visibility: hidden; transition: transform 220ms var(--ease), visibility 0s 220ms;
+ }
+ .dock.show { transform: none; visibility: visible; transition: transform 220ms var(--ease); }
+ .dock-used { flex: 1; min-width: 0; font-size: 15px; font-weight: 700; font-variant-numeric: tabular-nums; white-space: nowrap; }
+ .dock.over .dock-used { color: #d70015; }
+ .dock-dl { width: 48px; height: 48px; flex-shrink: 0; border: 0; border-radius: 24px; background: var(--track); cursor: pointer; display: flex; align-items: center; justify-content: center; }
+ .dock-install { height: 48px; padding: 0 28px; flex-shrink: 0; }
+ .dock button.busy { cursor: progress; opacity: 0.6; }
+ body.docked .toast { bottom: 82px; }
+ .side { padding-bottom: 92px; } /* (room for it under the footer) */
+ .space-chip { height: 40px; padding: 0 14px 0 16px; border-radius: 20px; font-size: 14px; }
}
@media (max-width: 520px) {
.head { grid-template-columns: 1fr; }
diff --git a/customize/app.js b/customize/app.js
index 11453251..18003586 100644
--- a/customize/app.js
+++ b/customize/app.js
@@ -7,10 +7,10 @@
const KIT = 'kit/';
const MEDIA = '../docs/media/'; // the games' clips (kit.json: previews/ or gallery/)
const MiB = 1048576;
- // Enlarged Extra Apps (nwagyu's Nwagra): it moves the end of the app area from the end of
- // Epsilon's slot to the end of the 8 MB flash, so apps go from 0x90200000 to 0x90800000
- const XL_SPACE = 6 * MiB;
- const NWAGRA = 'https://nwagyu.org/guide/help/enlarge-your-memory.html';
+ // The calculator's space for apps (kit.json "spaces"): from where its software ends, 0x90200000 or, on Epsilon 26,
+ // 0x90180000, to 0x903F0000; with Enlarged Extra Apps (nwagyu's Nwagra) on to the end of the flash, 0x90800000
+ const SPACES = { std: 'Every NumWorks', e26: 'Epsilon 26', xl: 'Nwagra', xl26: 'Nwagra on Epsilon 26' };
+ const XL_SPACE = 6 * MiB; // (kits from before kit.json had spaces)
const SYS = {
1: { tag: 'GB', name: 'Game Boy', color: '#6d8a0c', shell: '#c9c9cf' },
2: { tag: 'GBC', name: 'Game Boy Color', color: '#6a3fb5', shell: '#b9a6d8' },
@@ -54,24 +54,43 @@
let romKey = 0;
// ------------------------------------------------------------------ sizes
- const capacity = () => st.cap === 'xl' ? XL_SPACE : kit.appSpace;
+ const spaces = () => kit.spaces && kit.spaces.length ? kit.spaces :
+ [{ id: 'std', size: kit.appSpace }, { id: 'xl', size: kit.xlAppSpace || XL_SPACE }];
+ const space = () => spaces().find((s) => s.id === st.cap) || spaces()[0];
+ const capacity = () => space().size;
+ const nwagra = () => st.cap.startsWith('xl');
+ const mb = (b) => +(b / MiB).toFixed(2) + ' MB';
const langKit = () => kits[st.lang] || kit;
- const flash = (id) => ((langKit().byId || {})[id] || byId[id]).flash;
+ const game = (id) => (langKit().byId || {})[id] || byId[id]; // (as the app's language has it)
+ const flash = (id) => game(id).flash;
const romBytes = (r) => ROM_ENTRY + align4(r.bytes.length);
const iconUrl = () => st.app.icon === 'custom' && custom ? custom.url : KIT + 'variants/' + st.app.icon + '.png';
const ordered = () => st.order.filter((id) => st.picked.has(id));
- // a big game too big to go beside the launcher in 1.94 MB (kit.json "alone") goes on its own there,
+ // NumPlay's own bytes: with the library functions NumPlay's games call, or only the launcher when it has big
+ // games only (they bring their own)
+ const own = (ids, roms) => {
+ const k = langKit();
+ return ids.some((id) => !byId[id].xl) || (rg && roms.length) ? k.base : k.baseAlone || k.base;
+ };
+ // what a NumPlay of these games (and Game Boy, NES and Sega games) takes
+ function total(ids, roms = st.roms) {
+ let n = own(ids, roms);
+ for (const id of ids) n += flash(id);
+ if (rg && roms.length) n += flash(rg.id) + ROM_HEAD + roms.reduce((a, r) => a + romBytes(r), 0);
+ return n;
+ }
+ // a big game too big to go beside the launcher in this space (kit.json "alone") goes on its own there,
// as its own app: as if you installed just that game
- const alone = (id) => st.cap === 'std' && !!byId[id].alone;
+ const alone = (id) => !!game(id).alone && own([id], []) + flash(id) > capacity();
const solo = () => ordered().find(alone) || null;
let before = null; // your games while one of those is picked, back when it's taken out
function items() {
const s = solo();
if (s) {
const g = byId[s];
- return [{ key: s, id: s, name: g.title, bytes: g.alone.size, color: hex(g.top), icon: g.icon ? KIT + 'icons/' + s + '.png' : null }];
+ return [{ key: s, id: s, name: g.title, bytes: game(s).alone.size, color: hex(g.top), icon: g.icon ? KIT + 'icons/' + s + '.png' : null }];
}
- const out = [{ key: '_core', name: st.app.name.trim() || 'NumPlay', bytes: langKit().base, color: '#3a3a3c', icon: iconUrl() }];
+ const out = [{ key: '_core', name: st.app.name.trim() || 'NumPlay', bytes: own(ordered(), st.roms), color: '#3a3a3c', icon: iconUrl() }];
for (const id of ordered()) {
const g = byId[id];
out.push({ key: id, id, name: g.title, bytes: flash(id), color: hex(g.top), icon: g.icon ? KIT + 'icons/' + id + '.png' : null });
@@ -198,25 +217,31 @@
$('#battery').style.width = 'calc(' + Math.min(100, 100 * used / cap) + '% - 2px)';
// the icons, in the order they go in the launcher
+ const s0 = solo(), picks = ordered();
for (const [id, b] of buttons) {
- const g = byId[id], on = st.picked.has(id), english = !g.xl || st.lang === 'en' || alone(id);
- const fits = english && (alone(id) || used + flash(id) <= cap);
+ const g = byId[id], on = st.picked.has(id);
+ const fits = alone(id) || (!s0 && total(picks.concat([id])) <= cap);
b.classList.toggle('on', on);
b.classList.toggle('off', !on && fits);
b.classList.toggle('nofit', !on && !fits);
b.setAttribute('aria-pressed', on);
- b.dataset.tip = g.title + '|' + (alone(id) ? size(g.alone.size) + ', on its own' : english ? size(flash(id)) + ' · drag to move' : 'in English NumPlays only');
+ b.dataset.tip = g.title + '|' + (alone(id) ? size(game(id).alone.size) + ', on its own' : size(flash(id)) +
+ (g.xl && st.lang !== 'en' ? ' · in English' : '') + ' · drag to move');
}
for (const box of [$('#small'), $('#big')]) {
const want2 = st.order.map((id) => buttons.get(id)).filter((b) => b && b.parentNode === box);
if ([...box.children].some((c, i) => c !== want2[i])) for (const b of want2) box.appendChild(b);
}
- for (const b of document.querySelectorAll('.cap button')) b.setAttribute('aria-checked', b.dataset.cap === st.cap);
+ $('#space-chip-label').textContent = mb(cap);
+ $('#space-chip').dataset.tip = SPACES[space().id] + '|your calculator\'s space for apps';
+ $('#dock-used').textContent = (used / MiB).toFixed(2) + ' of ' + mb(cap);
+ $('#dock').classList.toggle('over', over);
// (a game on its own has its own icon, name and language)
- const s = solo(), file = s ? byId[s].alone.file : 'NumPlay.nwa';
+ const s = solo(), file = s ? game(s).alone.file : 'NumPlay.nwa';
for (const c of [$('#app-chip'), $('#lang-chip')]) c.disabled = !!s;
$('#download').setAttribute('aria-label', 'Download ' + file);
$('#download').dataset.tip = 'Download ' + file;
+ $('#dock-download').setAttribute('aria-label', 'Download ' + file);
$('#app-chip-icon').src = iconUrl();
$('#app-chip-icon').classList.toggle('custom', st.app.icon === 'custom');
$('#app-chip').dataset.tip = (s ? byId[s].title : st.app.name.trim() || 'No name') + '|its icon and name on your calculator, and how it opens';
@@ -281,7 +306,7 @@
b.addEventListener('animationend', () => b.classList.remove(cls), { once: true });
}
function overflow(bytes) {
- toast("That doesn't fit: " + size(bytes) + ' too much' + (st.cap === 'std' ? '. 6 MB can take more' : ''));
+ toast("That doesn't fit: " + size(bytes) + ' too much' + (st.cap === 'std' ? '. Epsilon 26 and Nwagra give more space' : ''));
$('#screen').classList.add('over');
setTimeout(() => render(), 500);
}
@@ -301,8 +326,7 @@
}
} else {
if (s) { if (!quiet) { bump(b, 'shake'); toast(byId[s].title + ' takes the whole calculator. Pick it again to take it out'); } return; }
- if (byId[id].xl && st.lang !== 'en') { bump(b, 'shake'); toast('The big games are in English: pick English to add them'); return; }
- const over = usedBytes() + flash(id) - capacity();
+ const over = total(ordered().concat([id])) - capacity();
if (over > 0) { if (!quiet) { bump(b, 'shake'); overflow(over); } return; }
st.picked.add(id);
bump(b, 'pop-on');
@@ -322,8 +346,7 @@
}
const bytes = new Uint8Array(await f.arrayBuffer());
const r = { key: ++romKey, sys, bytes, name: romName(f.name) };
- const extra = (st.roms.length ? 0 : flash(rg.id) + ROM_HEAD) + romBytes(r);
- const over = usedBytes() + extra - capacity();
+ const over = total(ordered(), st.roms.concat([r])) - capacity();
if (over > 0) { bump($('#drop'), 'shake'); overflow(over); continue; }
st.roms.push(r);
fetchObj(objPath(rg.id)).catch(() => {});
@@ -440,7 +463,7 @@
function save() {
const a = st.app, p = new URLSearchParams();
p.set('games', ordered().join(','));
- if (st.cap === 'xl') p.set('space', 'xl');
+ if (st.cap !== 'std') p.set('space', st.cap);
if (st.lang !== 'en') p.set('lang', st.lang);
if (a.icon !== 'NumPlay') p.set('icon', a.icon);
if (a.name !== (PRESETS[a.icon] || [0, 'NumPlay'])[1]) p.set('name', a.name);
@@ -460,7 +483,7 @@
// the order: the link's picks first, in its order, then the rest as last time, then the kit's
st.order = [...new Set([...(linked || []), ...saved, ...known])];
st.picked = new Set(linked || kit.games.filter((g) => g.default).map((g) => g.id));
- st.cap = p.get('space') === 'xl' ? 'xl' : 'std';
+ st.cap = spaces().some((x) => x.id === p.get('space')) ? p.get('space') : 'std';
st.lang = LANGS[p.get('lang')] && kit.langs.includes(p.get('lang')) ? p.get('lang') : 'en';
const icon = p.get('icon');
st.app.icon = PRESETS[icon] ? icon : icon === 'custom' && custom ? 'custom' : 'NumPlay';
@@ -469,7 +492,6 @@
st.app.open = open[0] === 'matrices' ? 'matrices' : 'numplay';
st.app.secret = Math.min(SECRETS.length - 1, Math.max(0, parseInt(open[1], 10) || 0));
st.app.hint = !open.includes('nohint');
- if (st.lang !== 'en') for (const id of [...st.picked]) if (byId[id].xl && !alone(id)) st.picked.delete(id); // (English only)
if (solo()) st.picked = new Set([solo()]);
// a pick that no longer fits the calculator (the kit grew): drop the biggest games until it does
const big = ordered().sort((a, b) => flash(a) - flash(b));
@@ -491,7 +513,11 @@
}
const fetchObj = (rel) => fetchBytes(KIT + rel + '.gz');
// a game's object in the app's language, or English when that language's kit hasn't got it
- const objPath = (id) => (st.lang !== 'en' && kits[st.lang] && kits[st.lang].byId[id] ? st.lang + '/' : '') + 'games/' + id + '.o';
+ // (a big game's is the English one: kit.json "en")
+ const objPath = (id) => {
+ const g = st.lang !== 'en' && kits[st.lang] && kits[st.lang].byId[id];
+ return (g && !g.en ? st.lang + '/' : '') + 'games/' + id + '.o';
+ };
async function loadKit(lang) {
if (lang === 'en' || kits[lang]) return;
const k = await fetch(KIT + lang + '/kit.json').then((r) => { if (!r.ok) throw new Error(r.status); return r.json(); });
@@ -657,7 +683,7 @@
async function build() {
const one = solo();
- if (one) return { bytes: await fetchBytes(KIT + 'apps/' + one + '.nwa.gz'), file: byId[one].alone.file };
+ if (one) return { bytes: await fetchBytes(KIT + 'apps/' + one + '.nwa.gz'), file: game(one).alone.file };
await loadKit(st.lang);
const k = langKit();
const sel = ordered();
@@ -677,8 +703,11 @@
// the launcher shows the games in the order of their entries: yours, not the kit's
const entries = sel.map((id) => 'KEEP(*(.rodata.np_games.' + String((k.byId[id] || byId[id]).index).padStart(2, '0') + '))').join('\n ');
const head = k.script.head.replace('KEEP(*(SORT_BY_NAME(.rodata.np_games.*)))', entries);
+ // ...and the games' blocks in the kit's order: NumPlay's own games first, in the app area, then the big ones,
+ // which find the calculator's files past it too (Enlarged Extra Apps)
const block = (id) => k.script.blocks[id] || kit.script.blocks[id];
- files['numplay.ld'] = head + sel.map(block).join('') + k.script.tail;
+ const index = (id) => (k.byId[id] || byId[id]).index;
+ files['numplay.ld'] = head + sel.slice().sort((a, b) => index(a) - index(b)).map(block).join('') + k.script.tail;
const l = await run(t.ld, args.concat(['-o', 'out.nwa']), files);
if (l.code) throw new Error(l.log || 'ld ' + l.code);
const s = await run(t.oc, ['--strip-unneeded', 'in.nwa', 'out.nwa'], { 'in.nwa': l.m.FS.readFile('out.nwa') });
@@ -698,17 +727,18 @@
async function go(btn, sheet) {
if (btn.classList.contains('busy')) return;
btn.classList.add('busy');
- btn.parentNode.classList.add('down'); // (its key stays in while NumPlay is made)
+ const key = btn.closest('.key3d, .fkey');
+ if (key) key.classList.add('down'); // (its key stays in while NumPlay is made)
try {
const out = await build();
download(out.bytes, out.file);
if (sheet) openSheet(out.file);
} catch (e) {
console.error(e);
- toast(/more than/.test(e.message) ? e.message : solo() ? "Couldn't get " + byId[solo()].alone.file + ', try again' : "Couldn't make NumPlay.nwa, try again");
+ toast(/more than/.test(e.message) ? e.message : solo() ? "Couldn't get " + game(solo()).alone.file + ', try again' : "Couldn't make NumPlay.nwa, try again");
} finally {
btn.classList.remove('busy');
- btn.parentNode.classList.remove('down');
+ if (key) key.classList.remove('down');
}
}
function prefetch() {
@@ -723,13 +753,18 @@
}
// ------------------------------------------------------------------ the app's own settings
- let popOpen = null;
+ let popOpen = null, popAt = null;
function openPop(pop, chip, side) {
if (popOpen === pop) return closePops();
closePops();
pop.hidden = false;
popOpen = pop;
+ popAt = [chip, side];
chip.setAttribute('aria-expanded', 'true');
+ placePop();
+ }
+ function placePop() {
+ const pop = popOpen, [chip, side] = popAt;
const r = chip.getBoundingClientRect(), w = pop.offsetWidth, h = pop.offsetHeight;
if (side && r.right + 16 + w < innerWidth - 12) { // (beside it, over the calculator, not over the games)
pop.style.left = (r.right + 16) + 'px';
@@ -741,7 +776,7 @@
}
function closePops() {
for (const p of document.querySelectorAll('.pop')) p.hidden = true;
- for (const c of document.querySelectorAll('.chip, .cap button')) c.setAttribute('aria-expanded', 'false');
+ for (const c of document.querySelectorAll('.chip, .space-chip')) c.setAttribute('aria-expanded', 'false');
popOpen = null;
}
function renderApp() {
@@ -779,33 +814,52 @@
const b = el('button', '', { type: 'button', role: 'radio', 'aria-checked': st.lang === l });
b.textContent = LANGS[l][1];
b.addEventListener('click', async () => {
- if (l !== 'en' && ordered().some((id) => byId[id].xl && !alone(id))) { toast('The big games are in English: take them out first'); return; }
try { await loadKit(l); } catch (e) { toast("That language didn't load, try again"); return; }
+ const was = st.lang;
st.lang = l;
+ const over = usedBytes() - capacity(); // (NumPlay in another language is a little bigger or smaller)
+ if (over > 0) { st.lang = was; toast('In ' + LANGS[l][1] + ' that\'s ' + size(over) + ' too much: take a game out first'); return; }
closePops(); renderApp(); render();
});
langs.appendChild(b);
}
}
- // the 6 MB of Enlarged Extra Apps: what it is and how, before switching to it
- function askXL(btn) {
- let pop = $('#xl-pop');
- if (!pop) {
- pop = el('div', 'pop', { id: 'xl-pop', role: 'dialog', 'aria-label': 'Enlarged Extra Apps' });
- pop.innerHTML = '<b class="xl-title">6 MB with Enlarged Extra Apps</b>' +
- '<p class="xl-text">The calculator\'s installer gives apps 1.94 MB. nwagyu\'s <b>Nwagra</b> bookmark makes it use the rest of the flash, 6 MB in all, so several big games fit in one NumPlay.</p>' +
- '<ol class="xl-steps"><li>Add the Nwagra bookmark from nwagyu\'s guide</li><li>Update your calculator twice on my.numworks.com</li><li>On the installer page, click the bookmark, then drop NumPlay.nwa</li></ol>' +
- '<p class="xl-warn">It only works on older calculator software. On the newest, the calculator shows exam mode.</p>' +
- '<div class="xl-buttons"><a class="xl-guide" href="' + NWAGRA + '" target="_blank" rel="noopener">nwagyu\'s guide</a><button type="button" class="install xl-ok">Use 6 MB</button></div>';
- document.body.appendChild(pop);
- pop.querySelector('.xl-ok').addEventListener('click', () => {
- st.cap = 'xl';
- if (before) { st.picked = new Set([...before, ...st.picked]); before = null; } // (6 MB has room for it all)
- store('numplay-xl-seen', '1'); closePops(); render();
+ // ------------------------------------------------------------------ the calculator's space for apps
+ // Pick yours: its name and size, the installer's figure on each; with Nwagra, how to get it
+ function renderSpaces() {
+ const box = $('#spaces');
+ box.textContent = '';
+ for (const sp of spaces()) {
+ const b = el('button', '', { type: 'button', role: 'radio', 'aria-checked': st.cap === sp.id,
+ 'data-tip': Math.round(sp.size / 1024) + ' KB in NumWorks\' installer' });
+ b.appendChild(el('span')).textContent = SPACES[sp.id] || sp.id;
+ b.appendChild(el('b')).textContent = mb(sp.size);
+ b.addEventListener('click', () => {
+ if (!setSpace(sp.id)) return;
+ if (nwagra()) { renderSpaces(); placePop(); } else closePops();
});
+ box.appendChild(b);
}
- openPop(pop, btn, true);
+ $('#nwagra').hidden = !nwagra();
+ }
+ function setSpace(id) {
+ if (id === st.cap) return true;
+ const was = st.cap, picked = new Set(st.picked), had = before;
+ st.cap = id;
+ const one = ordered().find(alone);
+ if (one && ordered().length > 1) { // (it goes on its own here: the rest come back when it's out)
+ before = ordered().filter((x) => x !== one);
+ st.picked = new Set([one]);
+ toast(byId[one].title + ' goes on its own in ' + mb(capacity()) + '. Pick it again to get your other games back');
+ } else if (before && !solo()) { // (room beside it here: your other games come back, as many as fit)
+ for (const x of before) if (total(ordered().concat([x])) <= capacity()) st.picked.add(x);
+ before = null;
+ }
+ const over = usedBytes() - capacity();
+ if (over > 0) { st.cap = was; st.picked = picked; before = had; toast('Take ' + size(over) + ' of games out first'); return false; }
+ render();
+ return true;
}
// ------------------------------------------------------------------ the calculator in 3D, and its sticker
@@ -949,6 +1003,7 @@
for (const [k, v] of [[gl.TEXTURE_MIN_FILTER, gl.LINEAR], [gl.TEXTURE_MAG_FILTER, gl.LINEAR], [gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE], [gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE]])
gl.texParameteri(gl.TEXTURE_2D, k, v);
const upload = (data) => gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, ART, ART, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
+ sticker.lose = () => { const e = gl.getExtension('WEBGL_lose_context'); if (e) e.loseContext(); };
upload(stickerMap());
sticker.remap = () => upload(stickerMap());
const u = (n) => gl.getUniformLocation(prog, n);
@@ -1183,13 +1238,15 @@
// the foil comes from where the pointer is, and under the pointer the part of the sticker round the edge
// peels up off the side.
function depth() {
- if (matchMedia('(prefers-reduced-motion: reduce)').matches) return;
+ if (matchMedia('(prefers-reduced-motion: reduce)').matches || light.on) return;
const calc = $('#calc'), star = $('#star'), dev = document.querySelector('.device');
let mx = innerWidth * 0.6, my = innerHeight * 0.2, tx = 0, ty = 0, x = 0, y = 0;
let over = false, lift = 0, raf = 0;
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
- const draw = () => {
+ const draw = (now) => {
raf = 0;
+ if (light.on) return;
+ frameTime(now);
x += (tx - x) * 0.07; y += (ty - y) * 0.07;
calc.style.setProperty('--ry', (x * 18).toFixed(2) + 'deg');
calc.style.setProperty('--rx', (-y * 10).toFixed(2) + 'deg');
@@ -1204,7 +1261,7 @@
shadeStar(lift);
if (Math.abs(tx - x) + Math.abs(ty - y) > 0.0005 || Math.abs(want - lift) > 0.002) raf = requestAnimationFrame(draw);
};
- const kick = () => { if (!raf) raf = requestAnimationFrame(draw); };
+ const kick = () => { if (!raf && !light.on) raf = requestAnimationFrame(draw); };
addEventListener('pointermove', (e) => {
if (e.pointerType === 'touch') return;
mx = e.clientX; my = e.clientY;
@@ -1219,6 +1276,130 @@
kick();
}
+ // ------------------------------------------------------------------ the light calculator
+ // The 3D calculator is heavy for slow computers and phones. The light one is the same photo, flat: OK and Back
+ // go in when pressed, and the sticker is drawn once, as the 3D one looks from the front. It's the light one from
+ // the start on small or touch screens, with reduced motion, or with ?flat in the address (?3d: never); otherwise
+ // the page times its frames while things move, in its first seconds and as the calculator turns, and goes light
+ // for the rest of the visit when they're slow.
+ const light = { on: false, later: false, list: [], last: 0 };
+ const flag = (f) => new RegExp('[?&]' + f + '(=|&|$)').test(location.search);
+ function lightFromStart() {
+ if (flag('3d')) return false;
+ if (flag('flat')) return true;
+ try { if (sessionStorage.getItem('numplay-flat')) return true; } catch (e) { /* (no storage) */ }
+ return innerWidth < 900 || matchMedia('(pointer: coarse)').matches || matchMedia('(prefers-reduced-motion: reduce)').matches;
+ }
+ // each frame drawn while something moves: when half of 30 in a row take over 30 ms (fewer than 33 a second), slow
+ function frameTime(now) {
+ if (light.on || flag('3d') || now - light.last < 1) return;
+ if (document.hidden) { light.last = 0; return; }
+ if (light.last && now - light.last < 500) light.list.push(now - light.last);
+ light.last = now;
+ if (light.list.length < 30) return;
+ const median = light.list.sort((a, b) => a - b)[15];
+ light.list = [];
+ if (median > 30) goLight();
+ }
+ function watchFrames() { // (the first seconds: the page coming up, and the intro the first time)
+ const t0 = performance.now();
+ const tick = (now) => {
+ if (light.on || now - t0 > 6000) { light.last = 0; return; }
+ if (now - t0 > 700) frameTime(now);
+ requestAnimationFrame(tick);
+ };
+ requestAnimationFrame(tick);
+ }
+ function goLight() {
+ if (light.on) return;
+ if (introRun) { light.later = true; return; } // (once the intro is over)
+ try { sessionStorage.setItem('numplay-flat', '1'); } catch (e) { /* (no storage: light until the page is left) */ }
+ // the 3D calculator goes: its sides, its keys (OK and Back keep their buttons), its sticker
+ const calc = $('#calc'), plate = calc.querySelector('.plate');
+ for (const b of [$('#install'), $('#download')]) { b.style.transform = ''; plate.appendChild(b); }
+ for (const e of calc.querySelectorAll('.key3d, .keybed')) e.remove();
+ document.querySelector('.body3d').textContent = '';
+ if (sticker.lose) sticker.lose();
+ Object.assign(sticker, { draw: null, remap: null, lose: null, leaves: [] });
+ const star = $('#star');
+ star.textContent = '';
+ star.removeAttribute('style');
+ for (const v of ['--plate-mask', '--rx', '--ry', '--lx']) calc.style.removeProperty(v);
+ buildFlat();
+ }
+ function buildFlat() {
+ light.on = true;
+ document.documentElement.classList.add('flat');
+ const plate = $('#calc').querySelector('.plate'), r = 57.5, cy = 924;
+ for (const [key, b, cx] of [['ok', $('#install'), 718.5], ['back', $('#download'), 858]]) {
+ const k = part(plate, 'div', 'fkey', { left: U(cx - r), top: U(cy - r), width: U(2 * r), height: U(2 * r) });
+ k.dataset.key = key;
+ const img = el('img', '', { src: 'calculator.webp', alt: '', draggable: 'false' });
+ Object.assign(img.style, { left: U(r - cx), top: U(r - cy), width: U(1018), height: U(2000) });
+ part(k, 'i', 'ftop', {}).appendChild(img);
+ k.appendChild(b);
+ }
+ flatStar();
+ }
+ // The sticker, flat: its picture (the white vinyl, the gold foil and the line embossed in it, the ink), then seen
+ // from the front as it lies on the calculator: over the screen's bezel, a little darker down in it, and round the
+ // edge, squeezed and darker as the edge turns away; the part on the side is out of sight.
+ function stickerArt() {
+ const c = el('canvas');
+ c.width = c.height = ART;
+ const x = c.getContext('2d'), k = ART / 100;
+ x.lineJoin = 'round';
+ x.save();
+ x.shadowColor = 'rgba(0, 0, 0, 0.3)'; x.shadowBlur = 1.4 * k; x.shadowOffsetY = 0.5 * k;
+ starPath(x, k, 1); x.lineWidth = 14 * k; x.fillStyle = x.strokeStyle = '#f7f6f2'; x.fill(); x.stroke();
+ x.restore();
+ const g = x.createLinearGradient(14 * k, 8 * k, 84 * k, 96 * k);
+ [[0, '#fff0b5'], [0.2, '#e8bd52'], [0.42, '#b47e14'], [0.6, '#f4d47c'], [0.78, '#c28b1c'], [1, '#f2d27a']]
+ .forEach(([o, col]) => g.addColorStop(o, col));
+ starPath(x, k, 1); x.lineWidth = 3 * k; x.fillStyle = x.strokeStyle = g; x.fill(); x.stroke();
+ for (const [d, col] of [[0.3, 'rgba(120, 76, 0, 0.55)'], [-0.3, 'rgba(255, 249, 222, 0.75)']]) {
+ x.save(); x.translate(d * k, d * k); starPath(x, k, 0.8); x.lineWidth = 0.7 * k; x.strokeStyle = col; x.stroke(); x.restore();
+ }
+ const [big, small] = sticker.text;
+ x.save();
+ x.translate(50 * k, 53 * k);
+ x.rotate(deg(-12));
+ x.textAlign = 'center';
+ x.fillStyle = 'rgba(52, 31, 4, 0.92)';
+ const font = (w, px) => w + ' ' + px + 'px -apple-system, BlinkMacSystemFont, "Helvetica Neue", Arial, sans-serif';
+ x.font = font(800, (big.length > 3 ? 11.5 : 14.5) * k);
+ x.fillText(big, 0, 2.5 * k);
+ x.font = font(750, 3.6 * k);
+ if ('letterSpacing' in x) x.letterSpacing = (0.5 * k) + 'px';
+ x.fillText(small, 0, 8.6 * k);
+ x.restore();
+ return c;
+ }
+ function flatStar() {
+ // (the step down into the bezel, which the front doesn't see, shifts it as much: its tip at the screen's edge)
+ const S = STAR, star = $('#star'), K = ART / S.size, x0 = S.from + S.step, x1 = 1018;
+ const art = stickerArt(), c = el('canvas'), w = Math.ceil((x1 - x0) * K);
+ c.width = w; c.height = ART;
+ const x = c.getContext('2d');
+ for (let i = 0; i < w; i++) {
+ const px = x0 + (i + 0.5) / K; // (in the photo's pixels)
+ let u = px - S.step, du = 1, l = 1;
+ if (px < S.lip) l = px > S.lip - 1.6 ? 0.84 : 0.96; // (down in the bezel, and its edge)
+ else if (px > S.edge) { // (round the edge)
+ const a = Math.asin(Math.min(1, (px - S.edge) / EDGE_R));
+ u = S.edge - S.step + EDGE_R * a; du = 1 / Math.max(0.2, Math.cos(a)); l = lit([Math.sin(a), 0, Math.cos(a)]);
+ }
+ x.drawImage(art, (u - S.from) * K - du / 2, 0, du, ART, i, 0, 1, ART);
+ if (l < 1) {
+ x.save(); x.globalCompositeOperation = 'source-atop'; x.fillStyle = 'rgba(20, 14, 0, ' + (1 - l).toFixed(3) + ')';
+ x.fillRect(i, 0, 1, ART); x.restore();
+ }
+ }
+ star.textContent = '';
+ Object.assign(star.style, { left: (100 * x0 / 1018) + '%', top: (100 * S.top / 2000) + '%', width: U(x1 - x0), height: U(S.size) });
+ star.appendChild(c);
+ }
+
// ------------------------------------------------------------------ GitHub's star count, for the sticker
async function stars() {
try {
@@ -1232,14 +1413,27 @@
const v = +n, t = v >= 1000 ? (v / 1000).toFixed(v >= 10000 ? 0 : 1) + 'k' : String(v);
sticker.text = [t, v === 1 ? 'STAR' : 'STARS'];
if (sticker.remap) { sticker.remap(); paintSticker(); }
+ if (light.on) flatStar();
} catch (e) { /* (offline, or GitHub said no: the button still works) */ }
}
+ // ------------------------------------------------------------------ on a phone: install from under your thumb
+ // Once the calculator's keys are scrolled away, a bar at the bottom has them, with the space used.
+ function dock() {
+ const d = $('#dock'), keys = $('.legend.ok');
+ if (!window.IntersectionObserver) return;
+ new IntersectionObserver(([e]) => {
+ const below = !e.isIntersecting && e.boundingClientRect.top < 0;
+ d.classList.toggle('show', below);
+ document.body.classList.toggle('docked', below);
+ }).observe(keys);
+ }
+
// ------------------------------------------------------------------ the sheet, tips and toasts
function openSheet(file) {
const s = $('#sheet');
for (const f of s.querySelectorAll('.sheet-file')) f.textContent = file;
- for (const li of s.querySelectorAll('.xl-only')) li.hidden = st.cap !== 'xl';
+ for (const li of s.querySelectorAll('.xl-only')) li.hidden = !nwagra();
s.hidden = false;
s.querySelector('.sheet-card a.install').focus();
}
@@ -1383,6 +1577,7 @@
introRun = null;
hidePreview();
render();
+ if (light.later) goLight();
}
addEventListener('pointerdown', finish, true);
addEventListener('keydown', finish, true);
@@ -1476,28 +1671,16 @@
$('#app-chip').addEventListener('click', (e) => { renderApp(); openPop($('#app-pop'), e.currentTarget); });
$('#lang-chip').addEventListener('click', (e) => { renderApp(); openPop($('#lang-pop'), e.currentTarget); });
document.addEventListener('pointerdown', (e) => {
- if (popOpen && !e.target.closest('.pop, .chip, .cap button')) closePops();
+ if (popOpen && !e.target.closest('.pop, .chip, .space-chip')) closePops();
});
- for (const b of document.querySelectorAll('.cap button'))
- b.addEventListener('click', () => {
- if (b.dataset.cap === 'std' && st.cap === 'xl') {
- st.cap = 'std';
- const one = solo();
- if (one && ordered().length > 1) { // (it goes on its own in 1.94 MB: the rest come back when it's out)
- before = ordered().filter((id) => !alone(id));
- st.picked = new Set([one]);
- toast(byId[one].title + ' goes on its own in 1.94 MB. Pick it again to get your other games back');
- }
- const over = usedBytes() - kit.appSpace;
- if (over > 0) { st.cap = 'xl'; toast('Take ' + size(over) + ' of games out first'); return; }
- closePops(); render(); return;
- }
- if (b.dataset.cap === 'xl' && st.cap !== 'xl') askXL(b);
- });
+ $('#space-chip').addEventListener('click', (e) => { renderSpaces(); openPop($('#space-pop'), e.currentTarget, true); });
$('#install').addEventListener('click', (e) => go(e.currentTarget, true));
$('#download').addEventListener('click', (e) => go(e.currentTarget, false));
- for (const b of [$('#install'), $('#download'), $('#app-chip'), $('#lang-chip')]) {
+ $('#dock-install').addEventListener('click', (e) => go(e.currentTarget, true));
+ $('#dock-download').addEventListener('click', (e) => go(e.currentTarget, false));
+ dock();
+ for (const b of [$('#install'), $('#download'), $('#dock-install'), $('#dock-download'), $('#app-chip'), $('#lang-chip')]) {
b.addEventListener('pointerenter', prefetch, { once: true });
b.addEventListener('focus', prefetch, { once: true });
}
@@ -1526,8 +1709,9 @@
});
}
tips();
- build3d();
- depth();
+ if (lightFromStart()) buildFlat();
+ else { build3d(); depth(); watchFrames(); }
+ addEventListener('resize', () => { if (innerWidth < 900) goLight(); });
restore();
if (st.lang !== 'en') loadKit(st.lang).then(render).catch(() => { st.lang = 'en'; render(); });
render();
diff --git a/customize/index.html b/customize/index.html
index 1a94e3f1..6c296180 100644
--- a/customize/index.html
+++ b/customize/index.html
@@ -72,10 +72,10 @@
<aside class="side" aria-label="Big games, and your own Game Boy, NES and Sega games">
<div class="row-head">
<h2>Big games</h2>
- <div class="cap" role="radiogroup" aria-label="Space for apps">
- <button type="button" role="radio" data-cap="std" aria-checked="true" data-tip="Every NumWorks">1.94 MB</button>
- <button type="button" role="radio" data-cap="xl" aria-checked="false" data-tip="With Enlarged Extra Apps">6 MB</button>
- </div>
+ <button id="space-chip" type="button" class="space-chip" aria-haspopup="dialog" aria-expanded="false" aria-label="Your calculator's space for apps">
+ <span id="space-chip-label">1.94 MB</span>
+ <svg class="caret" viewBox="0 0 12 12" width="10" height="10" aria-hidden="true"><path d="M3 4.5l3 3 3-3" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>
+ </button>
</div>
<section id="big" class="grid big" aria-label="Big games, best first"></section>
<section id="retro" class="retro" aria-label="Your own Game Boy, NES and Sega games" hidden>
@@ -152,6 +152,18 @@
<div id="lang-pop" class="pop narrow" role="dialog" aria-label="Language" hidden>
<div id="langs" class="segctl col" role="radiogroup" aria-label="Language"></div>
</div>
+<div id="space-pop" class="pop space-pop" role="dialog" aria-labelledby="space-title" hidden>
+ <b id="space-title" class="pop-title">Your calculator's space for apps</b>
+ <div id="spaces" class="segctl col spaces" role="radiogroup" aria-labelledby="space-title"></div>
+ <div id="nwagra" class="nwagra" hidden>
+ <ol class="xl-steps">
+ <li>Add the Nwagra bookmark from <a href="https://nwagyu.org/guide/help/enlarge-your-memory.html" target="_blank" rel="noopener">nwagyu's guide</a></li>
+ <li>Update your calculator twice on my.numworks.com</li>
+ <li>On the installer page, click the bookmark, then drop NumPlay.nwa</li>
+ </ol>
+ <p class="xl-warn">If your calculator then says exam mode is on, Nwagra doesn't work with its version.</p>
+ </div>
+</div>
<input id="icon-file" type="file" accept="image/*" hidden>
<div id="sheet" class="sheet" hidden>
@@ -181,6 +193,14 @@
<noscript><p class="noscript">NumPlay Studio needs JavaScript to build your NumPlay. You can also <a href="https://github.com/Mason363/NumPlay/releases/latest/download/NumPlay.nwa">download NumPlay.nwa</a> with all of its games.</p></noscript>
+<div id="dock" class="dock" aria-label="Your NumPlay">
+ <span id="dock-used" class="dock-used"></span>
+ <button id="dock-download" type="button" class="dock-dl" aria-label="Download NumPlay.nwa">
+ <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 4v11"/><path d="M7 10l5 5 5-5"/><path d="M5 20h14"/></svg>
+ </button>
+ <button id="dock-install" type="button" class="install dock-install">Install</button>
+</div>
+
<div id="tip" class="tip" role="tooltip"></div>
<div id="toast" class="toast" role="status" aria-live="polite"></div>
<script src="app.js"></script>
diff --git a/games/donkeykong/Makefile b/games/donkeykong/Makefile
index 983541af..0de85faa 100644
--- a/games/donkeykong/Makefile
+++ b/games/donkeykong/Makefile
@@ -15,7 +15,7 @@ L = ../../launcher/src
SRC = src/main.c src/sim.c src/draw.c src/save.c src/plat_eadk.c
HEADERS = $(wildcard src/*.h) ../common/epsilon_app.h ../common/epsilon_files.h $(L)/gfx.h $(L)/np.h $(L)/font.h
-CFLAGS = -std=gnu11 $(shell $(NWLINK) eadk-cflags-device) -DPLATFORM_DEVICE=1
+CFLAGS = -std=gnu11 $(shell $(NWLINK) eadk-cflags-device) -DPLATFORM_DEVICE=1 -DEPSILON_XL=1
CFLAGS += -Os -Wall -Wextra -Wno-unused-parameter -fno-math-errno
CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal
CFLAGS += -ffunction-sections -fdata-sections
diff --git a/games/dune/Makefile b/games/dune/Makefile
index 197eecf0..dc14fe75 100644
--- a/games/dune/Makefile
+++ b/games/dune/Makefile
@@ -15,7 +15,7 @@ BUILD_DIR = output
SRC = src/main.c src/game.c src/draw.c src/save.c src/art.c src/plat_eadk.c
HEADERS = $(wildcard src/*.h) ../common/epsilon_app.h ../common/epsilon_files.h
-CFLAGS = -std=gnu11 $(shell $(NWLINK) eadk-cflags-device) -DPLATFORM_DEVICE=1
+CFLAGS = -std=gnu11 $(shell $(NWLINK) eadk-cflags-device) -DPLATFORM_DEVICE=1 -DEPSILON_XL=1
CFLAGS += -Os -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant
CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal
CFLAGS += -ffunction-sections -fdata-sections
diff --git a/games/jetpackjoyride/Makefile b/games/jetpackjoyride/Makefile
index 87149096..781e106e 100644
--- a/games/jetpackjoyride/Makefile
+++ b/games/jetpackjoyride/Makefile
@@ -15,7 +15,7 @@ L = ../../launcher/src
SRC = src/main.c src/sim.c src/draw.c src/save.c src/plat_eadk.c
HEADERS = $(wildcard src/*.h) ../common/epsilon_app.h ../common/epsilon_files.h ../common/np_text.h $(L)/gfx.h $(L)/np.h $(L)/font.h
-CFLAGS = -std=gnu11 $(shell $(NWLINK) eadk-cflags-device) -DPLATFORM_DEVICE=1
+CFLAGS = -std=gnu11 $(shell $(NWLINK) eadk-cflags-device) -DPLATFORM_DEVICE=1 -DEPSILON_XL=1
CFLAGS += -Os -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant
CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal
CFLAGS += -ffunction-sections -fdata-sections
diff --git a/games/stickmanhook/Makefile b/games/stickmanhook/Makefile
index cbada932..a94c7243 100644
--- a/games/stickmanhook/Makefile
+++ b/games/stickmanhook/Makefile
@@ -15,7 +15,7 @@ BUILD_DIR = output
SRC = src/main.c src/game.c src/draw.c src/save.c src/levels.c src/art.c src/plat_eadk.c
HEADERS = $(wildcard src/*.h) ../common/epsilon_app.h ../common/epsilon_files.h
-CFLAGS = -std=gnu11 $(shell $(NWLINK) eadk-cflags-device) -DPLATFORM_DEVICE=1
+CFLAGS = -std=gnu11 $(shell $(NWLINK) eadk-cflags-device) -DPLATFORM_DEVICE=1 -DEPSILON_XL=1
CFLAGS += -Os -Wall -Wextra -Wno-unused-parameter -fno-math-errno -fsingle-precision-constant
CFLAGS += -fno-tree-loop-distribute-patterns -flto -fno-fat-lto-objects -fwhole-program -fvisibility=internal
CFLAGS += -ffunction-sections -fdata-sections
diff --git a/tests/test_kit.py b/tests/test_kit.py
index 019ade8a..5c0bfd67 100644
--- a/tests/test_kit.py
+++ b/tests/test_kit.py
@@ -11,15 +11,20 @@ in the ARM emulator, with tests/test_games.py's sessions:
- ram: each big game's RAM inside NumPlay, against custom builds of 25.2 (133652 bytes), 23.2 (148928)
and Upsilon (107674). The games play with the least the calculators give where they fit, and where
one doesn't, OK on its card doesn't start it (the card says how much it lacks);
-- probe: each big game alone with --ram bytes of RAM, whatever it needs (to find the least it plays in).
+- probe: each big game alone with --ram bytes of RAM, whatever it needs (to find the least it plays in);
+- spaces: for each space for apps the website offers (kit.json "spaces": the app area from 0x90200000, or from
+ 0x90180000 as on Epsilon 26.4, each also on to 0x90800000 with Nwagra), the fullest NumPlay it lets you make
+ there, NumPlay's games and the big games in their order while they fit, installed at that space's start, with
+ the userland header's app area starting there: the last of NumPlay's games (without Nwagra) and the first and
+ last big games played where they are, in the app area, past it, and into the second slot.
In each session the game starts and plays, saves, and finds its saves again from its own copy as after
installing NumPlay again; Home and On/Off take you back out of NumPlay, which clears the RAM, with no
access outside the app's RAM, no write to flash or to the firmware's RAM. nwlink nwa-bin links each
NumPlay at the app area's start with its whole space (6 MB for the sets).
-Usage: test_kit.py [--kit build/site-kit] [--only alone,sets,ram,probe] [--game ID] [--set N] [--ram N]
- [--out DIR]
+Usage: test_kit.py [--kit build/data/site-kit] [--only alone,sets,ram,spaces,probe] [--game ID] [--set N]
+ [--space ID] [--ram N] [--out DIR]
"""
import argparse
import gzip
@@ -41,12 +46,14 @@ CUSTOM_RAM, RAM_LIMIT, UPSILON_RAM = 133652, 148928, 107674
MANIFEST = json.load(open(os.path.join(ROOT, "games", "games.json")))
XL = [g["id"] for g in MANIFEST if g.get("xl")] # the big games
SMALL = [g["id"] for g in MANIFEST if g.get("default", True)] # NumPlay's own
-# NumPlays for Enlarged Extra Apps: the three biggest; five more; four more; three with all of NumPlay's games
+# NumPlays for Enlarged Extra Apps: the three biggest; five more; four more; three with all of NumPlay's games; the
+# four newest past the app area, into the second slot, after the biggest that fits there
SETS = [
["celeste", "hollowknight", "championisland"],
["undertale", "doom", "pvz", "numpowder", "leveldevil"],
["cookieclicker", "subway", "fnaf", "isaac"],
SMALL + ["sonic", "hillclimb", "finalearth2"],
+ ["cookieclicker", "jetpackjoyride", "stickmanhook", "donkeykong", "dune"],
]
@@ -80,10 +87,10 @@ class Kit:
return self.k["launcherRam"] + self.games[i]["ram"]
-def installed(nwa, space, ram=RAM_LIMIT):
+def installed(nwa, space, ram=RAM_LIMIT, start=0x90200000):
"""the bytes nwlink installs, linked at the app area's start with this much space"""
b = nwa[:-4] + ".bin"
- r = subprocess.run(["nwlink", "nwa-bin", "--flash-start", hex(emu.EXT_FLASH_START), "--flash-length", str(space),
+ r = subprocess.run(["nwlink", "nwa-bin", "--flash-start", hex(start), "--flash-length", str(space),
"--ram-length", str(ram), nwa, b], capture_output=True, text=True)
return os.path.getsize(b) if r.returncode == 0 else None, (r.stdout + r.stderr).strip()
@@ -154,12 +161,13 @@ def report(tag, problems, extra=""):
def main():
ap = argparse.ArgumentParser()
- ap.add_argument("--kit", default=os.path.join(ROOT, "build", "site-kit"))
- ap.add_argument("--only", default="alone,sets,ram")
+ ap.add_argument("--kit", default=os.path.join(ROOT, "build", "data", "site-kit"))
+ ap.add_argument("--only", default="alone,sets,ram,spaces")
ap.add_argument("--game", help="only this big game (alone, ram)")
ap.add_argument("--set", type=int, help="only this set (0, 1...)")
+ ap.add_argument("--space", help="only this space (kit.json spaces: std, e26, xl, xl26)")
ap.add_argument("--ram", type=int, help="the RAM apps get (alone, sets; default: the least they fit in)")
- ap.add_argument("--out", default=os.path.join(ROOT, "build", "test_kit"))
+ ap.add_argument("--out", default=os.path.join(ROOT, "build", "data", "test_kit"))
a = ap.parse_args()
os.makedirs(a.out, exist_ok=True)
only = a.only.split(",")
@@ -178,27 +186,27 @@ def main():
size, msg = installed(nwa, k["appSpace"])
g = kit.games[i]
if size is None or size > k["appSpace"]:
- # too big for the app space next to the launcher: in NumPlay only with Enlarged Extra Apps, and the
- # website hands out its own app instead (kit.json "alone": build/apps' file, as it is)
+ # too big for the app space next to the launcher: in NumPlay only with more space (Epsilon 26's, or
+ # Enlarged Extra Apps), and the website hands out its own app instead (kit.json "alone", as it is)
big, msg2 = installed(nwa, k["xlAppSpace"])
problems = [] if big and big > k["appSpace"] else [f"nwa-bin: {msg or msg2}"]
own = g.get("alone") or {}
gz = os.path.join(a.kit, "apps", i + ".nwa.gz")
- app = os.path.join(ROOT, "build", "apps", own.get("file", "?"))
+ app = os.path.join(ROOT, "build", "data", "apps", own.get("file", "?"))
if not own or not os.path.exists(gz):
problems.append("the kit hasn't got it on its own (kit.json alone, apps/)")
else:
with gzip.open(gz) as f:
data = f.read()
if not os.path.exists(app) or open(app, "rb").read() != data:
- problems.append(f"apps/{i}.nwa.gz isn't build/apps/{own['file']}")
+ problems.append(f"apps/{i}.nwa.gz isn't build/data/apps/{own['file']}")
mine = os.path.join(tmp, f"own-{i}.nwa")
open(mine, "wb").write(data)
n, msg3 = installed(mine, k["appSpace"])
if n is None or n > k["appSpace"] or n != own["size"]:
problems.append(f"on its own: {n} bytes, kit.json says {own['size']} ({msg3})")
failed |= report(f"alone {i}", problems, f"{big} bytes, {big - k['appSpace']} over the app space: "
- f"only with Enlarged Extra Apps, else {own.get('file')} on its own" if big else "")
+ f"in NumPlay with more space (Epsilon 26, Nwagra), else {own.get('file')} on its own" if big else "")
continue
emu.configure("n0120", "epsilon", a.ram or (CUSTOM_RAM if kit.ram(i) <= CUSTOM_RAM else RAM_LIMIT))
problems, stack, heap = session(nwa, ids, i, a.out, f"alone_{i}")
@@ -230,6 +238,41 @@ def main():
problems, stack, heap = session(nwa, ids, i, a.out, f"set{n}_{i}")
failed |= report(f" set {n}: {i}", problems, f"stack {stack}, malloc {heap}")
+ if "spaces" in only:
+ for sp in k.get("spaces", []):
+ if a.space and a.space != sp["id"]:
+ continue
+ size, start = sp["size"], sp["start"]
+ ids = [g["id"] for g in sorted(k["games"], key=lambda g: g["index"]) if g["default"]]
+ used = k["base"] + sum(kit.games[i]["flash"] for i in ids)
+ for g in sorted(k["games"], key=lambda g: g["index"]):
+ if g["xl"] and used + g["flash"] <= size:
+ ids.append(g["id"])
+ used += g["flash"]
+ nwa = os.path.join(tmp, f"space-{sp['id']}.nwa")
+ ids = kit.link(ids, nwa)
+ n, msg = installed(nwa, size, start=start)
+ if n is None or n > size or n > used:
+ failed |= report(f"space {sp['id']}", [f"{n} bytes in {size} at {start:#x}, {used} by the kit: {msg}"])
+ continue
+ print(f"space {sp['id']}: {size} bytes from {start:#x}, {len(ids)} games installed as {n} bytes, "
+ f"up to {start + n:#x}", flush=True)
+ xl = sp["end"] > emu.EXT_FLASH_END
+ ram = a.ram or (CUSTOM_RAM if max(kit.ram(i) for i in ids) <= CUSTOM_RAM else RAM_LIMIT)
+ emu.configure("n0120", "epsilon", ram, xl=xl, apps_start=start)
+ # (where each game's block is, from the symbols of the NumPlay the emulator runs)
+ c = _Calculator(nwa)
+ at = {i: c.symbols.get(f"np_{i}_begin", 0) for i in ids}
+ # the last of NumPlay's games in the app area, and the first and last big games: in it or just past it,
+ # and the furthest out (the others are where the sets have them)
+ big = [x for x in ids if x in XL]
+ for i in ([] if xl else [x for x in ids if x in SMALL][-1:]) + big[:1] + big[1:][-1:]:
+ where = ("past the app area, in the second slot" if at[i] >= 0x90400000 else
+ "past the app area" if at[i] >= emu.EXT_FLASH_END else "in the app area")
+ problems, stack, heap = session(nwa, ids, i, a.out, f"space_{sp['id']}_{i}")
+ failed |= report(f" space {sp['id']}: {i}", problems, f"at {at[i]:#x}, {where}, stack {stack}")
+ emu.configure("n0120", "epsilon")
+
if "ram" in only:
print(f"{'RAM in NumPlay':18s} {'needs':>7s} {'133652':>8s} {'148928':>8s} {'107674':>8s}")
for i in xl:
diff --git a/tools/emu.py b/tools/emu.py
index e798db03..f3b463e4 100644
--- a/tools/emu.py
+++ b/tools/emu.py
@@ -48,6 +48,8 @@ EXT_RAM_END = 0x24037000
EXT_RAM_LEN = 153676
EXT_RAM_START = EXT_RAM_END - EXT_RAM_LEN
STACK_TOP = 0x2403F000
+# the software's app area: from where it ends (64 KiB aligned: 0x90200000, or 0x90180000 for Epsilon 26.4 on an
+# N0120, configure's apps_start) to 64 KiB before the end of its slot
EXT_FLASH_START = 0x90200000
EXT_FLASH_END = 0x903F0000
# where installed apps may reach: the app area's end, or with Enlarged Extra Apps (nwagyu's Nwagra, which
@@ -58,16 +60,18 @@ CPU_HZ = 216_000_000
MODEL, SYSTEM = "n0120", "epsilon"
-def configure(model="n0120", system="epsilon", ram_length=None, xl=False):
+def configure(model="n0120", system="epsilon", ram_length=None, xl=False, apps_start=None):
"""The calculator to emulate: the N0120 (RAM at 0x24000000, the userland after an extra data
sector) or the N0110/N0115 (RAM at 0x20000000); Epsilon or Upsilon (its userland header has no
device name, apps get 107674 bytes of RAM, its file system is Epsilon 15's and it has none of
the system calls for Home, checksums or flash). ram_length: the RAM apps get, when another
build of the software gives them another amount. xl: Enlarged Extra Apps, an app up to the
- external flash's end (its userland header still says the app area ends at 0x903F0000)."""
+ external flash's end (its userland header still says the app area ends at 0x903F0000). apps_start: where
+ the app area starts, where the software ends (0x90200000, or 0x90180000 for Epsilon 26.4 on an N0120)."""
global MODEL, SYSTEM, SRAM, USERLAND_HEADER, STORAGE, STORAGE_SIZE, EXT_RAM_END, EXT_RAM_LEN, EXT_RAM_START, \
- STACK_TOP, APPS_END
+ STACK_TOP, APPS_END, EXT_FLASH_START
MODEL, SYSTEM = model, system
+ EXT_FLASH_START = apps_start or 0x90200000
APPS_END = XL_APPS_END if xl else EXT_FLASH_END
SRAM = 0x20000000 if model == "n0110" else 0x24000000
USERLAND_HEADER = 0x90010000 if model == "n0110" else 0x90020000
@@ -173,8 +177,12 @@ class Font:
class Calculator:
- def __init__(self, nwa, flash_start=EXT_FLASH_START, storage_file=None, nwlink="nwlink", external_data=None):
+ def __init__(self, nwa, flash_start=None, storage_file=None, nwlink="nwlink", external_data=None):
+ """The app installed at flash_start (by default, where the app area starts); an app below EXT_FLASH_START
+ moves the app area's start there, as a smaller software leaves it."""
+ flash_start = EXT_FLASH_START if flash_start is None else flash_start
self.flash_start = flash_start
+ self.apps_start = min(EXT_FLASH_START, flash_start & ~0xFFFF)
self.storage_file = storage_file
with tempfile.TemporaryDirectory() as d:
elf = os.path.join(d, "app.elf")
@@ -210,11 +218,11 @@ class Calculator:
# userland header (Ion::Device::UserlandHeader) and slot info, as apps find them
if SYSTEM == "upsilon": # no device name; then Omega's and Upsilon's blocks
hdr = struct.pack("<I8sIIIIIIII4sI8s16sII16sII", 0xDEC0EDFE, b"15.5.0\0\0", STORAGE, STORAGE_SIZE,
- EXT_FLASH_START, 0x907FFFFF, EXT_RAM_START, EXT_RAM_END, 0xDEC0EDFE, 0xEFBEADDE,
+ self.apps_start, 0x907FFFFF, EXT_RAM_START, EXT_RAM_END, 0xDEC0EDFE, 0xEFBEADDE,
b"1.0\0", DRAW_STRING_HOOK | 1, bytes(8), bytes(16), 0xEFBEADDE, 0x55707369,
b"1.1.2", 0x79827178, 0x55707369)
else:
- hdr = struct.pack("<I8sIIIIIIIII", 0xDEC0EDFE, b"25.2.2\0\0", STORAGE, STORAGE_SIZE, EXT_FLASH_START,
+ hdr = struct.pack("<I8sIIIIIIIII", 0xDEC0EDFE, b"25.2.2\0\0", STORAGE, STORAGE_SIZE, self.apps_start,
EXT_FLASH_END, EXT_RAM_START, EXT_RAM_END, 0x903F0000, 0x903F0400, 0xDEC0EDFE)
uc.mem_write(USERLAND_HEADER, hdr)
uc.mem_write(SRAM, struct.pack("<IIII", 0xEFEEDBBA, 0x90000000, USERLAND_HEADER, 0xEFEEDBBA))
@@ -487,7 +495,7 @@ class Calculator:
ret = 0
elif n == 30: # erase sector
base, size = sector_range(r0)
- ok = EXT_FLASH_START <= base and base + size <= EXT_FLASH_END
+ ok = self.apps_start <= base and base + size <= EXT_FLASH_END
self.flash_log.append(("erase", r0, base, size, ok))
if ok:
uc.mem_write(base, b"\xff" * size)
@@ -495,7 +503,7 @@ class Calculator:
ret = 1 if ok else 0
elif n == 32: # write memory
dst, src, length = r0, r1, r2
- ok = EXT_FLASH_START <= dst and dst + length <= EXT_FLASH_END
+ ok = self.apps_start <= dst and dst + length <= EXT_FLASH_END
self.flash_log.append(("write", dst, length, ok))
if ok:
old = bytes(uc.mem_read(dst, length))
@@ -566,7 +574,9 @@ def main():
ap.add_argument("--fps", type=int, default=25)
ap.add_argument("--out", default=".")
ap.add_argument("--storage", help="file keeping the calculator's storage between runs")
- ap.add_argument("--flash-start", type=lambda s: int(s, 0), default=EXT_FLASH_START)
+ ap.add_argument("--flash-start", type=lambda s: int(s, 0), help="where the app is installed (default: the app area's "
+ "start; one below 0x90200000 starts the app area there, as on Epsilon 26.4: 0x90180000)")
+ ap.add_argument("--apps-start", type=lambda s: int(s, 0), help="where the app area starts (default 0x90200000)")
ap.add_argument("--nwlink", default="nwlink")
ap.add_argument("--model", choices=["n0120", "n0110"], default="n0120")
ap.add_argument("--system", choices=["epsilon", "upsilon"], default="epsilon")
@@ -577,7 +587,7 @@ def main():
ap.add_argument("--profile", type=int, default=0,
help="print the N functions the CPU was found in most (build the .nwa without stripping it)")
a = ap.parse_args()
- configure(a.model, a.system, a.ram_length, a.xl)
+ configure(a.model, a.system, a.ram_length, a.xl, a.apps_start)
os.makedirs(a.out, exist_ok=True)
c = Calculator(a.nwa, a.flash_start, a.storage, a.nwlink)
c.keys = parse_keys(a.keys)
diff --git a/tools/kit.py b/tools/kit.py
index 9eefabac..aea8f845 100644
--- a/tools/kit.py
+++ b/tools/kit.py
@@ -14,13 +14,20 @@ app area, where Enlarged Extra Apps put them, only they look for the calculator'
app area ("alone") comes as its own app too (apps/<id>.nwa.gz, --alone): the website hands it out
as it is, for calculators without Enlarged Extra Apps.
+The calculator's space for apps starts where its software ends, so it depends on the software (--spaces, kit.json
+"spaces": 0x90200000 or 0x90180000 to 0x903F0000, or on to 0x90800000 with Enlarged Extra Apps). For each, this
+links the fullest NumPlay the website lets you make, NumPlay's games and the big games in their order while they
+fit, at that space's start with its length, as the calculator's installer does; and checks each big game goes
+beside the launcher there, or has its own app that fits.
+
A game's "ram" in kit.json is what it takes in the arena (its .data, its .bss and the least heap
it needs): it fits a calculator when ram + launcherRam (NumPlay's own RAM, before the arena) is
-at most what the calculator's software gives apps ("ram", "ramLimit", "upsilonRam").
+at most what the calculator's software gives apps ("ram", "ramLimit", "upsilonRam"). Every game must fit
+"ram" (custom builds of 25.2, the least of the calculators NumPlay runs on but Upsilon).
Usage: kit.py games.json BUILD OUT --version V --variants "..." --default "ids" --upsilon "ids"
- --app-space N --xl-app-space N --ram N --ram-limit N --upsilon-ram N --nwlink NWLINK
- --alone "id=game.nwa:Name.nwa ..."
+ --app-space N --xl-app-space N --spaces "id:start:end ..." --ram N --ram-limit N
+ --upsilon-ram N --nwlink NWLINK --alone "id=game.nwa:Name.nwa ..."
"""
import argparse
import gzip
@@ -112,12 +119,14 @@ def main():
ap.add_argument("--upsilon", default="")
ap.add_argument("--app-space", type=int, required=True)
ap.add_argument("--xl-app-space", type=int, required=True)
+ ap.add_argument("--spaces", default="", help="the calculators' spaces for apps, id:start:end ...")
ap.add_argument("--ram", type=int, required=True)
ap.add_argument("--ram-limit", type=int, default=148928)
ap.add_argument("--upsilon-ram", type=int, required=True)
ap.add_argument("--nwlink", default="nwlink")
ap.add_argument("--langs", default="", help="the languages make kit-langs adds (site-kit/<code>)")
ap.add_argument("--alone", default="", help="each big game's own app, id=game.nwa:Name.nwa")
+ ap.add_argument("--english", help="a language's kit: the English kit, where the website gets the big games' own apps")
a = ap.parse_args()
B, O = a.build, a.out
manifest = json.load(open(a.manifest))
@@ -146,7 +155,7 @@ def main():
rounded(os.path.join(ROOT, "launcher", "assets", png), os.path.join(O, "variants", v + ".png"))
variants.append(v)
- games = []
+ games, raw = [], {}
for g in manifest:
i = g["id"]
obj = os.path.join(B, "kit", "games", i + ".o")
@@ -154,11 +163,15 @@ def main():
continue
local[i] = put(obj, f"games/{i}.o")
n = index[i]
- flash = 0
+ # its block's bytes ("flash" adds the most padding it can need before it: blocks end on a word)
+ flash, align = 0, 4
for s in sections(obj):
if s[2] & SHF_ALLOC and s[1] != SHT_NOBITS:
flash = (flash + s[4] - 1) & ~(s[4] - 1)
flash += s[3]
+ align = max(align, s[4])
+ raw[i] = flash
+ flash += align - 4
mod = json.load(open(os.path.join(B, "modules", i + ".json")))
ram = ((((mod["data"] + 7) & ~7) + mod["bss"] + 7) & ~7) + g.get("heap", 0)
icon = icon_of(i)
@@ -179,7 +192,7 @@ def main():
"icon": bool(icon), "thumb": os.path.exists(thumb), "preview": preview})
# ---- check: the default games, linked from the kit, are NumPlay.nwa on the calculator
- def link(ids, nwa):
+ def link(ids, nwa): # (the blocks in the order of ids)
ld_script = nwa[:-4] + ".ld"
open(ld_script, "w").write(script["head"] + "".join(script["blocks"][i] for i in ids) + script["tail"])
subprocess.run(["arm-none-eabi-ld"] + LINK + ["-T", ld_script, local["base.o"], local["arena.o"],
@@ -213,11 +226,20 @@ def main():
runtime = len(bins[0]) - installed_size(nwa)
if not 0 <= runtime < 4096:
sys.exit(f"kit: installed_size says {installed_size(nwa)}, nwlink {len(bins[0])}")
- base = len(bins[0]) - sum(g["flash"] for g in games if g["default"])
+ # NumPlay's own bytes, with the library functions its games call (a big game brings its own): with each
+ # game's "flash", what a NumPlay with any of them takes at most ("base")
+ base = len(bins[0]) - sum(raw[g["id"]] for g in games if g["default"])
+ if base + sum(g["flash"] for g in games if g["default"]) > a.app_space:
+ sys.exit(f"kit: NumPlay's games' sizes add up to more than the app space")
+ # ...and with big games only, the launcher alone, as each big game linked with it shows (and the most padding
+ # its code can need after their blocks)
+ tail = max([4] + [s[4] for s in sections(local["base.o"]) if s[2] & SHF_ALLOC and s[1] != SHT_NOBITS])
+ base_alone = max(installed_size(os.path.join(tmp, f"xl-{g['id']}.nwa")) + runtime - g["flash"]
+ for g in games if g["xl"]) + tail - 4
# a big game that only fits the app area without the launcher goes on its own, as its own app
apps = dict(x.split("=", 1) for x in a.alone.split())
for g in games:
- if not g["xl"] or installed_size(os.path.join(tmp, f"xl-{g['id']}.nwa")) + runtime <= a.app_space:
+ if not g["xl"] or base_alone + g["flash"] <= a.app_space:
continue
if g["id"] not in apps:
sys.exit(f"kit: {g['id']} doesn't fit beside the launcher, and --alone hasn't got its own app")
@@ -228,21 +250,68 @@ def main():
sys.exit(f"kit: {name} doesn't fit the app area even on its own")
gz(src, os.path.join(O, "apps", g["id"] + ".nwa.gz"))
g["alone"] = {"file": name, "size": os.path.getsize(b)}
+ # (a language's kit: the website hands out the same app from the English kit, make kit-langs puts it there)
+ theirs = os.path.join(a.english or O, "apps", g["id"] + ".nwa.gz")
+ if os.path.exists(theirs) and gzip.open(theirs).read() != open(src, "rb").read():
+ sys.exit(f"kit: {g['id']} goes on its own here, but {theirs} isn't its app")
# NumPlay's own RAM before the arena (the installer's few bytes too), as the calculator lays it out
elf = os.path.join(tmp, "custom.elf")
subprocess.run([a.nwlink, "nwa-elf", nwa, elf, "--ram-start", "0x20000000", "--ram-length", str(ram)],
check=True, stdout=subprocess.DEVNULL)
nm = subprocess.run(["arm-none-eabi-nm", elf], capture_output=True, text=True, check=True).stdout
launcher_ram = next(int(l.split()[0], 16) for l in nm.splitlines() if l.split()[-1] == "np_arena") - 0x20000000
+ hungry = max(games, key=lambda g: g["ram"])
+ over = [f"{g['id']} ({launcher_ram + g['ram']})" for g in games if launcher_ram + g["ram"] > a.ram]
+ if over:
+ sys.exit(f"kit: more RAM than custom builds of 25.2 give apps ({a.ram} bytes): {', '.join(over)}")
+
+ # ---- a NumPlay for each space, linked where the calculator's installer puts it
+ spaces = []
+ for x in a.spaces.split():
+ sid, start, end = x.split(":")
+ sp = {"id": sid, "start": int(start, 0), "end": int(end, 0)}
+ sp["size"] = sp["end"] - sp["start"]
+ size, ids, used = sp["size"], list(default), base + sum(g["flash"] for g in games if g["default"])
+ for g in sorted(games, key=lambda g: g["index"]):
+ if g["xl"] and used + g["flash"] <= size:
+ ids.append(g["id"])
+ used += g["flash"]
+ f = os.path.join(tmp, f"space-{sid}.nwa")
+ link(ids, f)
+ b = f + ".bin"
+ r = subprocess.run([a.nwlink, "nwa-bin", "--flash-start", hex(sp["start"]), "--flash-length", str(size),
+ "--ram-length", str(ram), f, b], capture_output=True, text=True)
+ if r.returncode or os.path.getsize(b) > size:
+ sys.exit(f"kit: a NumPlay of {used} bytes doesn't install in {sid} ({size} bytes at {sp['start']:#x}): "
+ f"{(r.stdout + r.stderr).strip()}")
+ n = os.path.getsize(b)
+ if n > used:
+ sys.exit(f"kit: in {sid}, NumPlay installs as {n} bytes, but its games' sizes add up to {used}")
+ # a big game that doesn't go beside the launcher there must have its own app that fits
+ for g in games:
+ if g["xl"] and base_alone + g["flash"] > size and (not g.get("alone") or g["alone"]["size"] > size):
+ sys.exit(f"kit: {g['id']} fits neither beside the launcher nor on its own in {sid}")
+ big = [i for i in ids if i not in default]
+ print(f"kit: {sid}, {size} bytes from {sp['start']:#x}: NumPlay with {len(ids)} games ({', '.join(big) or 'no big ones'}) "
+ f"installs as {n} bytes, up to {sp['start'] + n:#x}")
+ spaces.append(sp)
+ # a language's kit: a game whose object is the English kit's (the big games, in English) comes from there
+ if a.english:
+ for g in games:
+ mine, theirs = (os.path.join(d, "games", g["id"] + ".o.gz") for d in (O, a.english))
+ if os.path.exists(theirs) and gzip.open(mine).read() == gzip.open(theirs).read():
+ os.remove(mine)
+ g["en"] = True
kit = {"version": a.version, "appSpace": a.app_space, "xlAppSpace": a.xl_app_space, "ram": a.ram,
"ramLimit": a.ram_limit, "upsilonRam": a.upsilon_ram, "launcherRam": launcher_ram,
"arena": int(re.search(r"\.space (\d+)", open(os.path.join(B, "gen", "arena.s")).read()).group(1)),
- "base": base, "runtime": runtime, "numplay": len(bins[0]), "link": LINK, "variants": variants,
+ "spaces": spaces, "base": base, "baseAlone": base_alone, "runtime": runtime, "numplay": len(bins[0]), "link": LINK, "variants": variants,
"langs": ["en"] + a.langs.split(), "script": script, "games": games}
json.dump(kit, open(os.path.join(O, "kit.json"), "w"), indent=1)
shutil.rmtree(tmp)
- print(f"kit: {len(games)} games, NumPlay.nwa's {len(bins[0])} bytes linked again from {O}")
+ print(f"kit: {len(games)} games, NumPlay.nwa's {len(bins[0])} bytes linked again from {O}; RAM: NumPlay's own "
+ f"{launcher_ram} bytes, {hungry['id']}'s {hungry['ram']}: {launcher_ram + hungry['ram']} of {a.ram}")
if __name__ == "__main__":