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 own .nwa apps, each a game of your NumPlay

Mason363a80b54f21f21
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 6f236cda..ba1a6785 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -59,6 +59,7 @@ jobs:
python3 tests/test_numblocks_progress.py build/compiled/games/NumBlocks.nwa
python3 tests/test_upsilon.py build/compiled/NumPlay-Upsilon.nwa
python3 tests/test_small_ram.py build/compiled/NumPlay.nwa
+ python3 tests/test_apps.py build/data
make -C games/numblocks host test
make -C games/numdrive host test
make -C games/championisland host test
diff --git a/README.md b/README.md
index d18d9568..70f9f44b 100644
--- a/README.md
+++ b/README.md
@@ -159,6 +159,8 @@ These are too big to fit next to NumPlay, so each one is its own app. Install it
Retro-Go plays the Game Boy, Game Boy Color, NES, Master System and Game Gear games you choose: games you own, or free ones like homebrew games. It isn't in NumPlay.nwa. Drop your games on [NumPlay Studio](https://mason363.github.io/NumPlay/customize/) and you get a NumPlay with Retro-Go and your games inside. Big games, like the 2 MB Game Boy Color ones, need the extra space of Epsilon 26 or Nwagra: pick it in NumPlay Studio.
+Other apps for your calculator go in too: drop their .nwa files on [NumPlay Studio](https://mason363.github.io/NumPlay/customize/) and each one gets its own card in your NumPlay.
+
## How to install
You need your calculator, its USB cable, and a computer with **Google Chrome** or **Microsoft Edge**. It takes about 2 minutes.
@@ -393,7 +395,7 @@ NumPlay is a fan project, made out of love for these games and for the NumWorks
- **[Gabriel](https://github.com/tomcalif9-stack)**, who made the home screen's moving backgrounds, translated NumPlay into French first, and tests it on Upsilon and an N0115.
- **[LanoCodes17](https://github.com/LanoCodes17)**, whose idea the Konami code is: one of the secret ways into NumPlay from Matrices.
- **[Retro-Go](https://github.com/ducalex/retro-go)** by ducalex inspired NumPlay's Retro-Go, whose launcher, menus and frame skipping are written again for NumPlay with no code copied from it. Its emulators are **[gnuboy](https://github.com/rofl0r/gnuboy)** by Laguna and Gilgamesh (GNU GPL v2 or later) for the Game Boy and **nofrendo** by Matthew Conte (GNU LGPL v2, used under the GPL) for the NES; the Master System and Game Gear are NumPlay's own, around **[superzazu's z80](https://github.com/superzazu/z80)** by Nicolas Allemand (MIT License). Its tests use Blargg's test ROMs, Matt Currie's dmg-acid2 and cgb-acid2, kevtris's nestest and Frank Cringle's zexdoc and zexall. Not affiliated with them.
-- **NumPlay Studio** builds your NumPlay right in the browser with **GNU ld and objcopy** from [binutils](https://www.gnu.org/software/binutils/) (GNU GPL v3), compiled to WebAssembly with [emscripten](https://emscripten.org).
+- **NumPlay Studio** builds your NumPlay right in the browser with **GNU ld and objcopy** from [binutils](https://www.gnu.org/software/binutils/) (GNU GPL v3), compiled to WebAssembly with [emscripten](https://emscripten.org). Your own .nwa apps in it come from **[Banane-3000](https://github.com/Banane-3000)**'s idea and fork.
- Everyone who reported a bug: **NEE** ([reversallava63](https://github.com/reversallava63)), **Gabriel**, **[briac134](https://github.com/briac134)**, **[Raphanobie](https://github.com/Raphanobie)**, **[zbigzo](https://github.com/zbigzo)**, **Yacine**, **PelicanMan75**, **[Spykube](https://github.com/Spykube)** and **[axio-m](https://github.com/axio-m)**. Thank you!
## License
diff --git a/customize/app.css b/customize/app.css
index b374ee4b..06c8374c 100644
--- a/customize/app.css
+++ b/customize/app.css
@@ -299,6 +299,15 @@ body.dragging .drop-hint { display: flex; }
.drop:hover .c1, body.dragging .c1 { transform: rotate(-20deg) translate(-3px, -4px); }
.drop:hover .c2, body.dragging .c2 { transform: translateY(-9px); }
.drop:hover .c3, body.dragging .c3 { transform: rotate(20deg) translate(3px, -4px); }
+/* ...and for your own apps, three of the calculator's app icons, fanned the same way */
+.drop-art.apps i { width: 40px; height: 40px; border-radius: 10px; background: linear-gradient(#f2f2f5, #d6d6dc); }
+.drop-art.apps i::before { display: none; }
+.drop-art.apps i::after { left: 7px; right: 7px; top: 7px; bottom: 7px; border-radius: 6px; }
+.drop-art.apps .c1::after { background: linear-gradient(#ffcc4d, #f0a020); }
+.drop-art.apps .c2 { left: 26px; background: linear-gradient(#5a5a60, #3f3f45); }
+.drop-art.apps .c2::after { background: linear-gradient(#3fc76b, #23a04c); }
+.drop-art.apps .c3 { background: linear-gradient(#2c2c30, #18181b); }
+.drop-art.apps .c3::after { background: linear-gradient(#b06ae0, #8040c0); }
.drop-text { font-size: 15px; font-weight: 700; }
.drop-sub { font-size: 12px; color: var(--mute); font-weight: 600; letter-spacing: 0.02em; }
.carts { display: flex; flex-wrap: wrap; gap: 10px; }
@@ -319,6 +328,8 @@ body.dragging .drop-hint { display: flex; }
.cart:hover { transform: translateY(-3px) rotate(-2deg); }
.cart:active { transform: scale(0.92); transition-duration: 90ms; }
.cart.enter { animation: slot 420ms var(--spring); }
+/* an app of your own: its icon, as on the calculator's home screen */
+.cart.app { width: 48px; height: 48px; border-radius: 12px; background: center / cover no-repeat; image-rendering: pixelated; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.16); }
@keyframes slot { 0% { transform: translateY(-22px) scale(0.8); opacity: 0; } 100% { transform: none; opacity: 1; } }
/* ---- tooltip, toast and the install sheet */
diff --git a/customize/app.js b/customize/app.js
index f8e83b95..01909dcf 100644
--- a/customize/app.js
+++ b/customize/app.js
@@ -47,11 +47,11 @@
const kits = {}; // the kit of each language, loaded when picked
const byId = {};
const st = {
- picked: new Set(), order: [], roms: [], cap: 'std', lang: 'en',
+ picked: new Set(), order: [], roms: [], apps: [], cap: 'std', lang: 'en',
app: { icon: 'NumPlay', name: 'NumPlay', open: 'numplay', secret: 0, hint: true },
};
let custom = null; // an icon of your own: { url, obj }
- let romKey = 0;
+ let romKey = 0, appKey = 0;
// ------------------------------------------------------------------ sizes
const spaces = () => kit.spaces && kit.spaces.length ? kit.spaces :
@@ -72,12 +72,12 @@
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) {
+ // what a NumPlay of these games (and Game Boy, NES and Sega games, and your own apps) takes
+ function total(ids, roms = st.roms, apps = st.apps) {
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;
+ return n + apps.reduce((a, x) => a + x.flash, 0);
}
// 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
@@ -100,6 +100,7 @@
for (const r of st.roms)
out.push({ key: 'rom' + r.key, rom: r, name: r.name, bytes: romBytes(r), color: SYS[r.sys].color, tag: SYS[r.sys].tag });
}
+ for (const a of st.apps) out.push({ key: 'app' + a.key, app: a, name: a.title, bytes: a.flash, color: hex(a.accent.toString(16)), icon: a.url });
return out;
}
const usedBytes = () => items().reduce((s, it) => s + it.bytes, 0);
@@ -160,14 +161,14 @@
if (t.tag) e.appendChild(el('b')).textContent = t.tag;
map.appendChild(e);
tiles.set(t.key, e);
- if (t.id || t.rom) e.addEventListener('click', () => (t.rom ? removeRom(t.rom) : toggle(t.id)));
+ if (t.id || t.rom || t.app) e.addEventListener('click', () => (t.rom ? removeRom(t.rom) : t.app ? removeApp(t.app) : toggle(t.id)));
}
e.classList.toggle('free', !!t.free);
e.style.left = (100 * t.x / W) + '%';
e.style.top = (100 * t.y / H) + '%';
e.style.width = (100 * t.w / W) + '%';
e.style.height = (100 * t.h / H) + '%';
- e.style.cursor = t.id || t.rom ? 'pointer' : '';
+ e.style.cursor = t.id || t.rom || t.app ? 'pointer' : '';
if (!t.free)
e.style.background = 'radial-gradient(130% 130% at 30% 25%, ' + mix(t.color, 0.45) + ' 0%, ' + t.color + ' 45%, ' + mix(t.color, -0.55) + ' 100%)';
const s = Math.min(t.w, t.h);
@@ -271,6 +272,20 @@
box.appendChild(c);
}
for (const c of box.querySelectorAll('.cart[data-k]')) if (!have.has(c.dataset.k)) c.remove();
+ const apps = $('#app-carts'), mine = new Set();
+ for (const a of st.apps) {
+ mine.add('a' + a.key);
+ if (apps.querySelector('[data-k="a' + a.key + '"]')) continue;
+ const c = el('button', 'cart app enter', { type: 'button', 'data-k': 'a' + a.key, 'aria-label': 'Remove ' + a.title });
+ c.addEventListener('animationend', () => c.classList.remove('enter'), { once: true });
+ c.style.backgroundImage = 'url(' + a.url + ')';
+ c.dataset.tip = a.title + '|' + a.file + ', ' + size(a.flash);
+ c.appendChild(el('span', 'x')).innerHTML =
+ '<svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="currentColor" stroke-width="3.4" stroke-linecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>';
+ c.addEventListener('click', () => removeApp(a));
+ apps.appendChild(c);
+ }
+ for (const c of apps.querySelectorAll('.cart[data-k]')) if (!mine.has(c.dataset.k)) c.remove();
}
// ------------------------------------------------------------------ the game on the screen
@@ -379,6 +394,63 @@
render();
}
+ // ------------------------------------------------------------------ your own apps
+ // An app's .nwa becomes a game of NumPlay the way a big game's does (apps.js). It may only leave undefined what
+ // the calculator's installer gives an app (tools/kit.py's check) and what the launcher gives a big game (KIT_API)
+ const LOOSE = /^(eadk_|_heap_end$|_data_section_|_bss_section_|np_keyboard_scan$|np_event_get$|np_display_draw_string$|np_sbrk$|numplay_launcher$|__sf$|_printf_float$)/;
+ const MAX_GAMES = 64; // (launcher/src/np.h's NP_MAX_GAMES: games, Retro-Go and apps)
+ const entries = () => ordered().length + (rg && st.roms.length ? 1 : 0) + st.apps.length;
+ const ascii = (t) => (t || '').replace(/[^\x20-\x7e]/g, '').trim().slice(0, 24);
+ const allocBytes = (obj) => npApps.readElf(obj).secs.reduce((n, x) => n + (x.flags & 2 && x.type !== 8 ? align4(x.size) : 0), 0);
+ function iconUrlOf(icon) {
+ const c = document.createElement('canvas');
+ c.width = npApps.ICON_W; c.height = npApps.ICON_H;
+ const g = c.getContext('2d'), img = g.createImageData(c.width, c.height);
+ icon.forEach((v, p) => img.data.set([(v >> 11) * 255 / 31, (v >> 5 & 63) * 255 / 63, (v & 31) * 255 / 31, 255], 4 * p));
+ g.putImageData(img, 0, 0);
+ return c.toDataURL('image/png');
+ }
+ async function appFrom(f, key) {
+ const A = npApps, bytes = new Uint8Array(await f.arrayBuffer());
+ const id = 'app' + key, index = 200 + key, info = A.appInfo(bytes);
+ if (!kit.script.module) throw new Error("can't come in until NumPlay Studio's next update");
+ const t = await loadTools();
+ const l = await run(t.ld, ['-r', '-d', '-z', 'noexecstack', '--force-group-allocation', '-T', 'module.ld', 'app.nwa', '-o', '1.o'],
+ { 'module.ld': kit.script.module, 'app.nwa': bytes });
+ if (l.code) throw new Error("isn't an app NumPlay can take");
+ const o = await run(t.oc, ['--keep-global-symbol=main', '--redefine-sym', 'eadk_keyboard_scan=np_keyboard_scan',
+ '--redefine-sym', 'eadk_event_get=np_event_get', '--redefine-sym', 'eadk_display_draw_string=np_display_draw_string',
+ '--redefine-sym', '_heap_start=np_' + id + '_heap', '--redefine-sym', '_sbrk=np_sbrk', '1.o', '2.o'], { '1.o': l.m.FS.readFile('1.o') });
+ if (o.code) throw new Error("isn't an app NumPlay can take");
+ const m = A.npmodule(o.m.FS.readFile('2.o'), id, index);
+ const loose = m.undefined.filter((u) => u !== 'np_' + id + '_heap' && !LOOSE.test(u));
+ if (loose.length) throw new Error("needs " + loose[0] + ", which NumPlay doesn't have");
+ if (((m.data + 7) & ~7) + m.bss + kit.launcherRam > kit.ramLimit) throw new Error('needs more RAM than NumPlay can give it');
+ const c = A.colors(info.icon), cd = A.card(info.icon, c.bottom);
+ const z = new Uint8Array(await new Response(new Blob([cd.indices]).stream().pipeThrough(new CompressionStream('deflate-raw'))).arrayBuffer());
+ const file = ascii(f.name) || 'app.nwa', title = ascii(info.name) || ascii(f.name.replace(/\.nwa$/i, '')) || 'App';
+ const entry = A.entryObject({ id, index, title, tagline: file, ...c, data: m.data, bss: m.bss, palette: cd.palette, z });
+ return { key, id, index, title, file, obj: m.obj, entry, data: m.data, bss: m.bss, accent: c.accent,
+ flash: allocBytes(m.obj) + allocBytes(entry) + 8, url: info.icon ? iconUrlOf(info.icon) : KIT + 'variants/NumPlay.png' };
+ }
+ async function addApps(files) {
+ const drop = $('#app-drop');
+ if (solo()) { bump(drop, 'shake'); toast(byId[solo()].title + " takes the whole calculator, so there's no room for apps"); return; }
+ for (const f of files) {
+ if (entries() >= MAX_GAMES) { bump(drop, 'shake'); toast('NumPlay holds ' + MAX_GAMES + ' games and apps at most'); break; }
+ let a;
+ try { a = await appFrom(f, ++appKey); } catch (e) { console.error(e); bump(drop, 'shake'); toast(f.name + ' ' + e.message); continue; }
+ const over = total(ordered(), st.roms, st.apps.concat([a])) - capacity();
+ if (over > 0) { bump(drop, 'shake'); overflow(over); continue; }
+ st.apps.push(a);
+ }
+ render();
+ }
+ function removeApp(a) {
+ st.apps = st.apps.filter((x) => x !== a);
+ render();
+ }
+
// ------------------------------------------------------------------ moving games around
// Drag an icon to change where its game sits in the launcher; a click still picks it. On a
// phone, hold an icon, then tap where it goes.
@@ -708,18 +780,36 @@
const files = { 'base.o': base, 'arena.o': arena, 'app.o': appObject(), 'icon.o': icon };
sel.forEach((id, i) => { files[id + '.o'] = objs[i]; });
const args = k.link.concat(['-T', 'numplay.ld', 'base.o', 'arena.o', 'app.o', 'icon.o'], sel.map((id) => id + '.o'));
+ if (entries() > MAX_GAMES) throw new Error("That's more than the " + MAX_GAMES + ' games and apps NumPlay holds');
+ for (const a of st.apps) {
+ files[a.id + '.o'] = a.obj;
+ files[a.id + '-entry.o'] = a.entry;
+ args.push(a.id + '.o', a.id + '-entry.o');
+ }
if (roms) {
files['roms.o'] = romObject(romTable(st.roms));
args.push('roms.o');
}
// 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);
+ const keep = sel.map((id) => 'KEEP(*(.rodata.np_games.' + String((k.byId[id] || byId[id]).index).padStart(2, '0') + '))')
+ .concat(st.apps.map((a) => 'KEEP(*(.rodata.np_games.' + a.id + '))')).join('\n ');
+ const head = k.script.head.replace('KEEP(*(SORT_BY_NAME(.rodata.np_games.*)))', keep);
// ...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];
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;
+ // (your apps go before the big games, in the app area: they look for the calculator's files there; each one's RAM
+ // is at the start of the arena, as a game's is, tools/gen_games.py's arena.s)
+ const ids = sel.slice().sort((a, b) => index(a) - index(b)), firstXl = ids.findIndex((id) => byId[id].xl);
+ const parts = ids.map(block);
+ parts.splice(firstXl < 0 ? parts.length : firstXl, 0, ...st.apps.map((a) => kit.script.app.replace(/@ID@/g, a.id).replace(/@N@/g, a.index)));
+ const ram = st.apps.map((a) => {
+ const bss = (a.data + 7) & ~7, heap = (bss + a.bss + 7) & ~7;
+ return ' np_' + a.id + '_data = np_arena;\n np_' + a.id + '_bss = np_arena + ' + bss + ';\n np_' + a.id + '_heap = np_arena + ' + heap + ';\n';
+ }).join('');
+ const tail = k.script.tail.replace('*(.np_arena) }', '*(.np_arena)\n' + ram + ' }');
+ if (ram && tail === k.script.tail) throw new Error('no arena in the script');
+ files['numplay.ld'] = head + parts.join('') + 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') });
@@ -1707,19 +1797,23 @@
$('#rom-file').accept = exts.map((x) => '.' + x).join(',');
$('#drop-sub').textContent = exts.map((x) => '.' + x).join(' ');
$('#rom-file').addEventListener('change', (e) => { addRoms([...e.target.files]); e.target.value = ''; });
- let depth = 0;
- const files = (e) => e.dataTransfer && [...e.dataTransfer.types].includes('Files');
- addEventListener('dragenter', (e) => { if (files(e)) { depth++; document.body.classList.add('dragging'); e.preventDefault(); } });
- addEventListener('dragover', (e) => { if (files(e)) e.preventDefault(); });
- addEventListener('dragleave', () => { if (--depth <= 0) { depth = 0; document.body.classList.remove('dragging'); } });
- addEventListener('drop', (e) => {
- if (!files(e)) return;
- e.preventDefault();
- depth = 0;
- document.body.classList.remove('dragging');
- addRoms([...e.dataTransfer.files]);
- });
}
+ $('#app-file').addEventListener('change', (e) => { addApps([...e.target.files]); e.target.value = ''; });
+ // files dropped anywhere: apps (.nwa) to your apps, the rest to Retro-Go
+ let depth = 0;
+ const files = (e) => e.dataTransfer && [...e.dataTransfer.types].includes('Files');
+ addEventListener('dragenter', (e) => { if (files(e)) { depth++; document.body.classList.add('dragging'); e.preventDefault(); } });
+ addEventListener('dragover', (e) => { if (files(e)) e.preventDefault(); });
+ addEventListener('dragleave', () => { if (--depth <= 0) { depth = 0; document.body.classList.remove('dragging'); } });
+ addEventListener('drop', async (e) => {
+ if (!files(e)) return;
+ e.preventDefault();
+ depth = 0;
+ document.body.classList.remove('dragging');
+ const all = [...e.dataTransfer.files], nwa = all.filter((f) => /\.nwa$/i.test(f.name)), rest = all.filter((f) => !nwa.includes(f));
+ if (nwa.length) await addApps(nwa);
+ if (rest.length && rg) addRoms(rest);
+ });
tips();
if (lightFromStart()) buildFlat();
else { build3d(); depth(); watchFrames(); }
diff --git a/customize/apps.js b/customize/apps.js
new file mode 100644
index 00000000..9472870b
--- /dev/null
+++ b/customize/apps.js
@@ -0,0 +1,351 @@
+/* NumPlay Studio: your own .nwa apps as games of NumPlay. An app's .nwa goes the way a big game's does in the
+ * Makefile: `ld -r -T tools/module.ld` and objcopy's renames (app.js runs them), then tools/npmodule.py, which
+ * npmodule() is (the same bytes: tests/test_apps.py). Then it gets what tools/gen_games.py gives a game: its entry in
+ * the launcher's table and its marks (entryObject), its block and its place in the arena in the link script
+ * (app.js), and a card for the home screen, its icon on its own colours (card).
+ * Plain functions of bytes, for app.js in the browser and the test in Node. */
+'use strict';
+(function (root) {
+ const SHT_PROGBITS = 1, SHT_SYMTAB = 2, SHT_STRTAB = 3, SHT_RELA = 4, SHT_NOBITS = 8, SHT_REL = 9;
+ const SHT_ARM_ATTRIBUTES = 0x70000003;
+ const SHF_ALLOC = 2, SHF_EXECINSTR = 4, SHF_INFO_LINK = 0x40;
+ const STB_LOCAL = 0, STB_GLOBAL = 1;
+ const STT_NOTYPE = 0, STT_OBJECT = 1, STT_SECTION = 3, STT_FILE = 4;
+ const SHN_UNDEF = 0, SHN_ABS = 0xFFF1;
+ const R_ARM_ABS32 = 2;
+ const HEAD = 0x3147504E, TAIL = 0x444E4550; // (the marks around a game's block, as gen_games.py's)
+ const SHOT_W = 192, SHOT_H = 144; // (launcher/src/ui.h)
+ const ICON_W = 55, ICON_H = 56;
+
+ const cstr = (b, o) => { let e = o; while (b[e]) e++; return new TextDecoder().decode(b.subarray(o, e)); };
+ const pad = (n, a) => (n + a - 1) & ~(a - 1);
+
+ // ------------------------------------------------------------------ reading an object (npmodule.py's Elf)
+ function readElf(b) {
+ if (b.length < 52 || b[0] !== 0x7f || b[1] !== 0x45 || b[2] !== 0x4c || b[3] !== 0x46 || b[4] !== 1 || b[5] !== 1)
+ throw new Error("isn't an app for the calculator");
+ const v = new DataView(b.buffer, b.byteOffset, b.byteLength);
+ if (v.getUint16(16, true) !== 1 || v.getUint16(18, true) !== 40) throw new Error("isn't an app for the calculator");
+ const e = { flags: v.getUint32(0x24, true), secs: [], syms: [] };
+ const shoff = v.getUint32(0x20, true), shentsize = v.getUint16(0x2e, true);
+ const shnum = v.getUint16(0x30, true), shstrndx = v.getUint16(0x32, true);
+ for (let i = 0; i < shnum; i++) {
+ const f = [];
+ for (let k = 0; k < 10; k++) f.push(v.getUint32(shoff + i * shentsize + 4 * k, true));
+ const [name, type, flags, , off, size, link, info, align, entsize] = f;
+ e.secs.push({ name, type, flags, off, size, link, info, align, entsize,
+ data: type === SHT_NOBITS ? new Uint8Array(0) : b.subarray(off, off + size) });
+ }
+ const shstr = e.secs[shstrndx].data;
+ for (const s of e.secs) s.sname = cstr(shstr, s.name);
+ const tabs = e.secs.map((s, i) => i).filter((i) => e.secs[i].type === SHT_SYMTAB);
+ if (tabs.length !== 1) throw new Error('has no symbol table');
+ const st = e.secs[tabs[0]], strtab = e.secs[st.link].data;
+ const sv = new DataView(st.data.buffer, st.data.byteOffset, st.data.byteLength);
+ for (let k = 0; k < st.size / 16; k++) {
+ const info = sv.getUint8(16 * k + 12);
+ e.syms.push({ name: cstr(strtab, sv.getUint32(16 * k, true)), value: sv.getUint32(16 * k + 4, true),
+ size: sv.getUint32(16 * k + 8, true), bind: info >> 4, type: info & 15,
+ other: sv.getUint8(16 * k + 13), shndx: sv.getUint16(16 * k + 14, true) });
+ }
+ return e;
+ }
+ function relsFor(e, target) {
+ const out = [];
+ for (const s of e.secs) {
+ if (s.type === SHT_REL && s.info === target) {
+ const v = new DataView(s.data.buffer, s.data.byteOffset, s.data.byteLength);
+ for (let k = 0; k < s.size / 8; k++) {
+ const info = v.getUint32(8 * k + 4, true);
+ out.push([v.getUint32(8 * k, true), info & 255, info >>> 8]);
+ }
+ } else if (s.type === SHT_RELA && s.info === target) throw new Error('has relocations NumPlay can\'t place');
+ }
+ return out;
+ }
+
+ // ------------------------------------------------------------------ writing one (npmodule.py's layout)
+ // syms: [{ name, value, size, bind, type, other, shndx }], the null one first
+ function symbols(syms) {
+ const enc = new TextEncoder(), str = [0], at = new Map();
+ const add = (s) => {
+ if (!s) return 0;
+ if (!at.has(s)) { at.set(s, str.length); str.push(...enc.encode(s), 0); }
+ return at.get(s);
+ };
+ const tab = new Uint8Array(16 * syms.length), v = new DataView(tab.buffer);
+ syms.forEach((s, i) => {
+ v.setUint32(16 * i, add(s.name), true);
+ v.setUint32(16 * i + 4, s.value >>> 0, true);
+ v.setUint32(16 * i + 8, s.size >>> 0, true);
+ tab[16 * i + 12] = (s.bind << 4) | s.type;
+ tab[16 * i + 13] = s.other;
+ v.setUint16(16 * i + 14, s.shndx, true);
+ });
+ return { symtab: tab, strtab: Uint8Array.from(str) };
+ }
+ const relBytes = (rels) => {
+ const d = new Uint8Array(8 * rels.length), v = new DataView(d.buffer);
+ rels.forEach(([off, typ, si], k) => { v.setUint32(8 * k, off, true); v.setUint32(8 * k + 4, ((si << 8) | typ) >>> 0, true); });
+ return d;
+ };
+ // bodies: the sections after the null one ({ name, type, flags, data, link, info, align, entsize }); the one
+ // named .shstrtab gets the names
+ function writeElf(flags, bodies) {
+ const enc = new TextEncoder(), shstr = [0], nameOff = [0];
+ for (const b of bodies) { nameOff.push(shstr.length); shstr.push(...enc.encode(b.name), 0); }
+ const shstrndx = 1 + bodies.findIndex((b) => b.name === '.shstrtab');
+ bodies[shstrndx - 1].data = Uint8Array.from(shstr);
+ let at = 52;
+ const offs = bodies.map((b) => { at = pad(at, Math.max(b.align, 4)); const o = at; at += b.data.length; return o; });
+ const shoff = pad(at, 4), n = bodies.length + 1;
+ const out = new Uint8Array(shoff + 40 * n), v = new DataView(out.buffer);
+ out.set([0x7f, 0x45, 0x4c, 0x46, 1, 1, 1], 0);
+ v.setUint16(16, 1, true); v.setUint16(18, 40, true); v.setUint32(20, 1, true); v.setUint32(32, shoff, true);
+ v.setUint32(36, flags >>> 0, true); v.setUint16(40, 52, true); v.setUint16(46, 40, true);
+ v.setUint16(48, n, true); v.setUint16(50, shstrndx, true);
+ bodies.forEach((b, i) => {
+ out.set(b.data, offs[i]);
+ const o = shoff + 40 * (i + 1);
+ [nameOff[i + 1], b.type, b.flags, 0, offs[i], b.data.length, b.link, b.info, b.align, b.entsize]
+ .forEach((x, k) => v.setUint32(o + 4 * k, x >>> 0, true));
+ });
+ return out;
+ }
+
+ // ------------------------------------------------------------------ tools/npmodule.py
+ // An app linked with tools/module.ld (one .text, one .data, one .bss), every definition but main made local:
+ // its code in a section of its own, its .data a copy the launcher puts in RAM, its RAM at np_<g>_data and
+ // np_<g>_bss, main np_<g>_main.
+ function npmodule(b, g, index, entry = 'main') {
+ const e = readElf(b);
+ const byName = {};
+ e.secs.forEach((s, i) => {
+ if (s.flags & SHF_ALLOC) {
+ if (!['.text', '.data', '.bss'].includes(s.sname)) throw new Error('has a section NumPlay can\'t place (' + s.sname + ')');
+ byName[s.sname] = i;
+ }
+ });
+ if (!('.text' in byName)) throw new Error('has no code');
+ const textI = byName['.text'], dataI = byName['.data'], bssI = byName['.bss'];
+ const text = e.secs[textI], data = dataI === undefined ? null : e.secs[dataI], bss = bssI === undefined ? null : e.secs[bssI];
+ const dataSize = data ? data.size : 0, bssSize = bss ? bss.size : 0;
+ const ramAlign = Math.max(8, ...[data, bss].filter(Boolean).map((s) => s.align));
+
+ // the symbols: null, the code's and the init's sections, the locals, then the globals
+ const CODE = 1, INIT = 3;
+ const out = [{ name: '', value: 0, size: 0, bind: 0, type: 0, other: 0, shndx: 0 },
+ { name: '', value: 0, size: 0, bind: STB_LOCAL, type: STT_SECTION, other: 0, shndx: CODE },
+ { name: '', value: 0, size: 0, bind: STB_LOCAL, type: STT_SECTION, other: 0, shndx: INIT }];
+ const remap = new Map(), ram = new Map(), globalsOut = [], undef = new Map();
+ let found = false;
+ e.syms.forEach((s, k) => {
+ if (!k) return;
+ const sh = s.shndx;
+ if (s.type === STT_SECTION) {
+ if (sh === textI) remap.set(k, 1);
+ else if (sh === dataI) ram.set(k, ['data', 0]);
+ else if (sh === bssI) ram.set(k, ['bss', 0]);
+ return;
+ }
+ if (s.type === STT_FILE) return;
+ if (dataI !== undefined && sh === dataI) { ram.set(k, ['data', s.value]); return; }
+ if (bssI !== undefined && sh === bssI) { ram.set(k, ['bss', s.value]); return; }
+ if (sh === SHN_UNDEF) {
+ if (s.bind === STB_LOCAL) return;
+ if (!undef.has(s.name)) undef.set(s.name, { name: s.name, value: 0, size: 0, bind: s.bind, type: STT_NOTYPE, other: 0, shndx: SHN_UNDEF });
+ return;
+ }
+ if (sh === textI) {
+ const n = { ...s, shndx: CODE, other: 0 };
+ if (s.name === entry && s.bind !== STB_LOCAL) {
+ n.name = 'np_' + g + '_main';
+ n.bind = STB_GLOBAL;
+ found = true;
+ globalsOut.push([k, n]);
+ } else { // (every other definition stays private to the module)
+ n.bind = STB_LOCAL;
+ remap.set(k, out.length);
+ out.push(n);
+ }
+ return;
+ }
+ if (sh === SHN_ABS) { remap.set(k, out.length); out.push({ ...s, bind: STB_LOCAL }); return; }
+ throw new Error('has a symbol in a section NumPlay can\'t place (' + s.name + ')');
+ });
+ if (!found) throw new Error('has no main');
+ const firstGlobal = out.length;
+ for (const [k, n] of globalsOut) { remap.set(k, out.length); out.push(n); }
+ out.push({ name: 'np_' + g + '_init', value: 0, size: dataSize, bind: STB_GLOBAL, type: STT_OBJECT, other: 0, shndx: INIT });
+ const ramIndex = {};
+ for (const r of ['data', 'bss']) {
+ ramIndex[r] = out.length;
+ out.push({ name: 'np_' + g + '_' + r, value: 0, size: 0, bind: STB_GLOBAL, type: STT_NOTYPE, other: 0, shndx: SHN_UNDEF });
+ }
+ const undIndex = new Map();
+ for (const [name, n] of undef) { undIndex.set(name, out.length); out.push(n); }
+ e.syms.forEach((s, k) => {
+ if (k && s.shndx === SHN_UNDEF && s.bind !== STB_LOCAL && s.type !== STT_SECTION) remap.set(k, undIndex.get(s.name));
+ });
+
+ // the relocations: into the app's RAM, against np_<g>_data or np_<g>_bss (the offset goes in the addend)
+ const convert = (ti, blob) => {
+ blob = blob.slice();
+ const v = new DataView(blob.buffer), rels = [];
+ for (const [off, typ, si] of relsFor(e, ti)) {
+ if (ram.has(si)) {
+ const [region, value] = ram.get(si);
+ if (typ !== R_ARM_ABS32) throw new Error('reaches its RAM in a way NumPlay can\'t move');
+ if (value) v.setUint32(off, (v.getUint32(off, true) + value) >>> 0, true);
+ rels.push([off, typ, ramIndex[region]]);
+ } else if (remap.has(si)) rels.push([off, typ, remap.get(si)]);
+ else throw new Error('has a relocation NumPlay can\'t place');
+ }
+ return [blob, rels];
+ };
+ const [code, codeRels] = convert(textI, text.data);
+ const [init, initRels] = data ? convert(dataI, data.data) : [new Uint8Array(0), []];
+ for (const s of e.secs)
+ if (s.type === SHT_REL && s.info !== textI && s.info !== dataI && e.secs[s.info].flags & SHF_ALLOC)
+ throw new Error('has relocations NumPlay can\'t place');
+
+ const base = '.rodata.np.' + index + '.' + g;
+ const { symtab, strtab } = symbols(out);
+ const bodies = [
+ { name: base, type: SHT_PROGBITS, flags: SHF_ALLOC | SHF_EXECINSTR, data: code, link: 0, info: 0, align: Math.max(4, text.align), entsize: 0 },
+ { name: '.rel' + base, type: SHT_REL, flags: SHF_INFO_LINK, data: relBytes(codeRels), link: 5, info: 1, align: 4, entsize: 8 },
+ { name: base + '.init', type: SHT_PROGBITS, flags: SHF_ALLOC, data: init, link: 0, info: 0, align: data ? Math.max(4, data.align) : 4, entsize: 0 },
+ { name: '.rel' + base + '.init', type: SHT_REL, flags: SHF_INFO_LINK, data: relBytes(initRels), link: 5, info: 3, align: 4, entsize: 8 },
+ { name: '.symtab', type: SHT_SYMTAB, flags: 0, data: symtab, link: 6, info: firstGlobal, align: 4, entsize: 16 },
+ { name: '.strtab', type: SHT_STRTAB, flags: 0, data: strtab, link: 0, info: 0, align: 1, entsize: 0 },
+ { name: '.shstrtab', type: SHT_STRTAB, flags: 0, data: null, link: 0, info: 0, align: 1, entsize: 0 },
+ ];
+ const attrs = e.secs.find((s) => s.type === SHT_ARM_ATTRIBUTES);
+ if (attrs) bodies.push({ name: '.ARM.attributes', type: SHT_ARM_ATTRIBUTES, flags: 0, data: attrs.data, link: 0, info: 0, align: 1, entsize: 0 });
+ return { obj: writeElf(e.flags, bodies), code: code.length, data: dataSize, bss: bssSize, ramAlign,
+ undefined: [...undef.keys()].sort() };
+ }
+
+ // ------------------------------------------------------------------ the app's name and icon
+ function lz4(src, n) { // (an LZ4 block of n bytes)
+ const out = new Uint8Array(n);
+ let i = 0, o = 0;
+ const len = (l) => { if (l === 15) { let b; do { b = src[i++]; l += b; } while (b === 255 && i < src.length); } return l; };
+ while (i < src.length && o < n) {
+ const t = src[i++];
+ const lit = len(t >> 4);
+ out.set(src.subarray(i, i + lit).subarray(0, n - o), o);
+ i += lit; o += lit;
+ if (i >= src.length || o >= n) break;
+ const back = src[i] | src[i + 1] << 8;
+ i += 2;
+ if (!back || back > o) throw new Error('has a broken icon');
+ for (let m = len(t & 15) + 4; m > 0 && o < n; m--, o++) out[o] = out[o - back];
+ }
+ return out;
+ }
+ // { name, icon }: its name as the calculator shows it (or null), its icon's 55 x 56 RGB565 pixels (or null)
+ function appInfo(b) {
+ const e = readElf(b), sec = (n) => e.secs.find((s) => s.sname === n);
+ const nm = sec('.rodata.eadk_app_name'), ic = sec('.rodata.eadk_app_icon');
+ let name = nm ? cstr(nm.data, 0) : null, icon = null;
+ if (ic) {
+ try {
+ const raw = lz4(ic.data, ICON_W * ICON_H * 2);
+ icon = new Uint16Array(ICON_W * ICON_H);
+ for (let p = 0; p < icon.length; p++) icon[p] = raw[2 * p] | raw[2 * p + 1] << 8;
+ } catch (x) { icon = null; }
+ }
+ return { name, icon };
+ }
+
+ // ------------------------------------------------------------------ its card on the home screen
+ const rgb = (c) => [(c >> 11) * 255 / 31, (c >> 5 & 63) * 255 / 63, (c & 31) * 255 / 31];
+ const r565 = (r, g, b) => (Math.round(r * 31 / 255) << 11) | (Math.round(g * 63 / 255) << 5) | Math.round(b * 31 / 255);
+ const hex = (r, g, b) => (Math.round(r) << 16) | (Math.round(g) << 8) | Math.round(b);
+ // its colours (0xRRGGBB, as games.json's): what its icon looks like, light at the top, dark at the bottom
+ function colors(icon) {
+ let n = 0, s = [0, 0, 0];
+ if (icon) for (const c of icon) {
+ const p = rgb(c);
+ if (p[0] + p[1] + p[2] > 690) continue; // (white: the icon's ground)
+ s = s.map((x, k) => x + p[k]); n++;
+ }
+ const a = n ? s.map((x) => x / n) : [90, 90, 100];
+ const mix = (t, w) => a.map((x) => x + (t - x) * w);
+ return { top: hex(...mix(255, 0.25)), bottom: hex(...mix(0, 0.55)), accent: hex(...a) };
+ }
+ // its icon, twice its size, with the calculator's round corners, on its bottom colour: palette indices and the
+ // palette (RGB565), at most 255 colours
+ function card(icon, bottom) {
+ const bg = r565(bottom >> 16, bottom >> 8 & 255, bottom & 255);
+ const px = new Uint16Array(SHOT_W * SHOT_H).fill(bg);
+ if (icon) {
+ const s = 2, w = ICON_W * s, h = ICON_H * s, x0 = (SHOT_W - w) >> 1, y0 = (SHOT_H - h) >> 1, r = 16;
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
+ const cx = x < r ? r - x - 0.5 : x >= w - r ? x - (w - r) + 0.5 : 0;
+ const cy = y < r ? r - y - 0.5 : y >= h - r ? y - (h - r) + 0.5 : 0;
+ if (cx * cx + cy * cy > r * r) continue;
+ px[(y0 + y) * SHOT_W + x0 + x] = icon[(y / s | 0) * ICON_W + (x / s | 0)];
+ }
+ }
+ // (fewer bits of each colour until they're 255 at most)
+ for (const mask of [0xFFFF, 0xF7DE, 0xE79C, 0xC718, 0x8610]) {
+ const pal = [...new Set(px.map((c) => c & mask))];
+ if (pal.length > 255) continue;
+ const at = new Map(pal.map((c, i) => [c, i]));
+ return { palette: Uint16Array.from(pal), indices: Uint8Array.from(px, (c) => at.get(c & mask)) };
+ }
+ throw new Error('unreachable');
+ }
+
+ // ------------------------------------------------------------------ its entry and marks (gen_games.py's)
+ // a: { id, index, title, tagline, top, bottom, accent, data, bss, palette, z (the indices, raw DEFLATE) }
+ function entryObject(a) {
+ const enc = new TextEncoder(), p = '.rodata.np.' + a.index + '.' + a.id;
+ // the card's section: the np_shot_t, its palette, its pixels, the names, an empty list (no save files)
+ const parts = [], put = (bytes, align) => { const at = pad(parts.length, align); while (parts.length < at) parts.push(0); parts.push(...bytes); return at; };
+ put(new Uint8Array(20), 4);
+ const palAt = put(new Uint8Array(a.palette.buffer, a.palette.byteOffset, a.palette.byteLength), 2);
+ const zAt = put(a.z, 1);
+ const str = (s) => put([...enc.encode(s), 0], 1);
+ const idAt = str(a.id), titleAt = str(a.title), tagAt = str(a.tagline);
+ const noneAt = put(new Uint8Array(4), 4);
+ const shots = Uint8Array.from(parts), sv = new DataView(shots.buffer);
+ sv.setUint16(0, SHOT_W, true); sv.setUint16(2, SHOT_H, true); sv.setUint16(4, a.palette.length, true);
+ sv.setUint32(8, a.z.length, true); sv.setUint32(12, palAt, true); sv.setUint32(16, zAt, true);
+ // the np_game_t (launcher/src/np.h): 80 bytes
+ const ent = new Uint8Array(80), v = new DataView(ent.buffer);
+ const ENT = 1, SHOTS = 2, G = 3; // (symbols: the two sections', then np_<id>_begin, end, main, data, init, bss)
+ const names = ['begin', 'end', 'main', 'data', 'init', 'bss'];
+ const sym = (n) => G + names.indexOf(n);
+ const rels = [];
+ const at = (off, s, add) => { v.setUint32(off, add || 0, true); rels.push([off, R_ARM_ABS32, s]); };
+ at(0, SHOTS, idAt); at(4, SHOTS, titleAt); at(8, SHOTS, tagAt);
+ v.setUint32(16, a.top, true); v.setUint32(20, a.bottom, true); v.setUint32(24, a.accent, true);
+ at(28, sym('begin')); at(32, sym('end')); at(36, sym('main'));
+ at(40, sym('data')); at(44, sym('init')); v.setUint32(48, a.data, true); at(52, sym('bss')); v.setUint32(56, a.bss, true);
+ at(60, SHOTS, 0); ent[64] = 1; at(68, SHOTS, noneAt); at(72, SHOTS, noneAt);
+ const shotRels = [[12, R_ARM_ABS32, SHOTS], [16, R_ARM_ABS32, SHOTS]];
+ const word = (w) => { const d = new Uint8Array(4); new DataView(d.buffer).setUint32(0, w, true); return d; };
+ const syms = [{ name: '', value: 0, size: 0, bind: 0, type: 0, other: 0, shndx: 0 },
+ { name: '', value: 0, size: 0, bind: STB_LOCAL, type: STT_SECTION, other: 0, shndx: 1 },
+ { name: '', value: 0, size: 0, bind: STB_LOCAL, type: STT_SECTION, other: 0, shndx: 3 }]
+ .concat(names.map((n) => ({ name: 'np_' + a.id + '_' + n, value: 0, size: 0, bind: STB_GLOBAL, type: STT_NOTYPE, other: 0, shndx: SHN_UNDEF })));
+ const { symtab, strtab } = symbols(syms);
+ const sec = (name, data, align) => ({ name, type: SHT_PROGBITS, flags: SHF_ALLOC, data, link: 0, info: 0, align, entsize: 0 });
+ const rel = (name, rs, info) => ({ name: '.rel' + name, type: SHT_REL, flags: SHF_INFO_LINK, data: relBytes(rs), link: 7, info, align: 4, entsize: 8 });
+ return writeElf(0, [
+ sec('.rodata.np_games.' + a.id, ent, 4), rel('.rodata.np_games.' + a.id, rels, 1),
+ sec(p + '.shots', shots, 4), rel(p + '.shots', shotRels, 3),
+ sec(p + '.0head', word(HEAD), 4), sec(p + '.zztail', word(TAIL), 4),
+ { name: '.symtab', type: SHT_SYMTAB, flags: 0, data: symtab, link: 8, info: 3, align: 4, entsize: 16 },
+ { name: '.strtab', type: SHT_STRTAB, flags: 0, data: strtab, link: 0, info: 0, align: 1, entsize: 0 },
+ { name: '.shstrtab', type: SHT_STRTAB, flags: 0, data: null, link: 0, info: 0, align: 1, entsize: 0 },
+ ]);
+ }
+
+ const api = { readElf, npmodule, appInfo, colors, card, entryObject, SHOT_W, SHOT_H, ICON_W, ICON_H };
+ if (typeof module === 'object' && module.exports) module.exports = api; // (Node, for the test)
+ else root.npApps = api;
+})(this);
diff --git a/customize/index.html b/customize/index.html
index 6c296180..62477c8e 100644
--- a/customize/index.html
+++ b/customize/index.html
@@ -69,7 +69,7 @@
<section id="small" class="grid small" aria-label="Games in NumPlay, best first"></section>
</div>
- <aside class="side" aria-label="Big games, and your own Game Boy, NES and Sega games">
+ <aside class="side" aria-label="Big games, your own Game Boy, NES and Sega games, and your own apps">
<div class="row-head">
<h2>Big games</h2>
<button id="space-chip" type="button" class="space-chip" aria-haspopup="dialog" aria-expanded="false" aria-label="Your calculator's space for apps">
@@ -88,6 +88,16 @@
<input id="rom-file" type="file" multiple accept=".gb,.gbc,.nes,.sms,.gg">
<div id="carts" class="carts" aria-label="Your games"></div>
</section>
+ <section id="own" class="retro" aria-label="Your own apps">
+ <div class="row-head"><h2>Your own apps</h2></div>
+ <label id="app-drop" class="drop" for="app-file">
+ <span class="drop-art apps" aria-hidden="true"><i class="c1"></i><i class="c2"></i><i class="c3"></i></span>
+ <span class="drop-text">Add apps</span>
+ <span class="drop-sub">.nwa</span>
+ </label>
+ <input id="app-file" type="file" multiple accept=".nwa">
+ <div id="app-carts" class="carts" aria-label="Your apps"></div>
+ </section>
<footer class="foot">
<a href="https://github.com/Mason363/NumPlay">Made by Mason Chen as part of NumPlay</a>
<span aria-hidden="true">·</span>
@@ -203,6 +213,7 @@
<div id="tip" class="tip" role="tooltip"></div>
<div id="toast" class="toast" role="status" aria-live="polite"></div>
+<script src="apps.js"></script>
<script src="app.js"></script>
</body>
</html>
diff --git a/tests/test_apps.py b/tests/test_apps.py
new file mode 100644
index 00000000..82303a9b
--- /dev/null
+++ b/tests/test_apps.py
@@ -0,0 +1,48 @@
+#!/usr/bin/env python3
+"""NumPlay Studio's own .nwa apps (customize/apps.js): its npmodule() makes every game's module of a build to the
+byte as tools/npmodule.py did (from BUILD/modules/<game>.2.o to <game>.o), and an app's entry links into a NumPlay.
+
+Usage: test_apps.py BUILD (a build with its modules: build/data after tools/build.py)"""
+import json
+import os
+import subprocess
+import sys
+
+ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
+JS = os.path.join(ROOT, "customize", "apps.js")
+RUN = r"""
+const fs = require('fs'), a = require(process.argv[1]);
+for (const [inp, out, game, index, entry] of JSON.parse(process.argv[2])) {
+ try { fs.writeFileSync(out, a.npmodule(new Uint8Array(fs.readFileSync(inp)), game, index, entry).obj); }
+ catch (e) { console.error(game + ': ' + e.message); process.exitCode = 1; }
+}
+"""
+
+
+def main():
+ build = sys.argv[1] if len(sys.argv) > 1 else os.path.join(ROOT, "build", "data")
+ mods = os.path.join(build, "modules")
+ jobs, tmp = [], os.path.join(build, "test-apps")
+ os.makedirs(tmp, exist_ok=True)
+ for f in sorted(os.listdir(mods)):
+ if not f.endswith(".json"):
+ continue
+ g = f[:-5]
+ info = json.load(open(os.path.join(mods, f)))
+ src = os.path.join(mods, g + ".2.o")
+ if os.path.exists(src):
+ # (the Makefile's ENTRY_<game>: Tetris, made in Rust, starts at np_tetris_main)
+ entry = "np_tetris_main" if g == "tetris" else "main"
+ jobs.append((src, os.path.join(tmp, g + ".o"), g, info["index"], entry))
+ if not jobs:
+ sys.exit(f"test_apps: no modules in {mods}")
+ if subprocess.run(["node", "-e", RUN, JS, json.dumps(jobs)]).returncode:
+ sys.exit("test_apps: npmodule() failed")
+ bad = [g for _, out, g, _, _ in jobs if open(out, "rb").read() != open(os.path.join(mods, g + ".o"), "rb").read()]
+ if bad:
+ sys.exit(f"test_apps: npmodule() differs from tools/npmodule.py for {', '.join(bad)}")
+ print(f"test_apps: npmodule() makes {len(jobs)} modules as tools/npmodule.py does")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/gen_games.py b/tools/gen_games.py
index 3d3541ba..6cc252fa 100644
--- a/tools/gen_games.py
+++ b/tools/gen_games.py
@@ -180,20 +180,19 @@ def main():
" KEEP(*(SORT_BY_NAME(.rodata.np_games.*)))",
" np_games_end = .;",
" }"]
- blocks = {}
- for g in manifest:
- i, n = g["id"], index[g["id"]]
+ def block(i, n, roms=False):
p = f".rodata.np.{n}.{i}"
- blocks[i] = [f" {p} : {{",
- f" np_{i}_begin = .;",
- f" KEEP(*({p}.0head))",
- f" *({p})",
- f" *({p}.init)"] + (
- [" *(.rodata.np_roms)"] if g.get("roms") else []) + [
- f" KEEP(*({p}.shots))",
- f" KEEP(*({p}.zztail))",
- f" np_{i}_end = .;",
- " }"]
+ return [f" {p} : {{",
+ f" np_{i}_begin = .;",
+ f" KEEP(*({p}.0head))",
+ f" *({p})",
+ f" *({p}.init)"] + (
+ [" *(.rodata.np_roms)"] if roms else []) + [
+ f" KEEP(*({p}.shots))",
+ f" KEEP(*({p}.zztail))",
+ f" np_{i}_end = .;",
+ " }"]
+ blocks = {g["id"]: block(g["id"], index[g["id"]], g.get("roms")) for g in manifest}
tail = [" .text : { *(.text .text.*) }",
" .rodata : { *(.rodata .rodata.*) }",
" .data : { *(.data .data.*) }",
@@ -202,8 +201,12 @@ def main():
"}"]
D = head + [x for g in games for x in blocks[g["id"]]] + tail
open(os.path.join(a.out, "numplay.ld"), "w").write("\n".join(D) + "\n")
+ # (for the website's own .nwa apps: an app's block, its id @ID@ and index @N@, and the script that makes a big
+ # game's .nwa a module's first step, tools/module.ld)
+ module_ld = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "module.ld")).read()
json.dump({"head": "\n".join(head) + "\n", "tail": "\n".join(tail) + "\n",
- "blocks": {i: "\n".join(b) + "\n" for i, b in blocks.items()}},
+ "blocks": {i: "\n".join(b) + "\n" for i, b in blocks.items()},
+ "app": "\n".join(block("@ID@", "@N@")) + "\n", "module": module_ld},
open(os.path.join(a.out, "script.json"), "w"), indent=1)
print(f"games: {len(games)}, arena {arena} bytes, the hungriest game {need}")