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.
C calculatorcalculator-gamescasiochesscrossy-roaddrive-madfx-cg50gamesgeometry-dashgraphing-calculatorndlessnumworksnumworks-appsnumworks-calculatornumworks-gamenumworks-gamestetristi-84-plus-ceti-nspire
Add self-contained Donkey Kong packaging tools
Bobydeluxead8675ab48d7
diff --git a/games/donkeykong/tools/assets.py b/games/donkeykong/tools/assets.pynew file mode 100644index 00000000..b386a830--- /dev/null+++ b/games/donkeykong/tools/assets.py@@ -0,0 +1,98 @@+#!/usr/bin/env python3+"""Hand-drawn pixel art. Pack two palette indices per byte; no runtime decoding buffer.+Also makes the launcher icon with only the Python standard library.+These are original drawings, not extracted Nintendo sprites.+"""+from pathlib import Path+import struct+import zlib++ROOT = Path(__file__).resolve().parents[1]+COLORS = [0x070B16, 0xFF5545, 0xFFD6A0, 0x407EDB, 0xFFE16B, 0x663520,+ 0xAD6134, 0xF5AE66, 0xFFF0CD, 0xF566AF, 0x77DAEA, 0xAE7DFF,+ 0xE77F37, 0x2A344A, 0xB9C5D9, 0xFFFFFF]+ART = {+"mario": [+"....11111....", "...11111111..", "...555225....", "..525522252..",+"..5255222252.", "..552222555..", "....222222...", "...11311.....",+"..111311311..", ".11113333111.", ".22134343122.", ".22233333222.",+"...3333333...", "...333.333...", "..555...555..", ".5555...5555."],+"kong": [+".........5555555555.........", ".......5566666666555.......",+"......566666666666665......", ".....56667777777766665.....",+"....5666777777777766665....", "...566677555775557766665...",+"...566677588775887766665...", "..56666775577775577666665..",+"..56666677777777776666665..", ".5666666777555577766666665.",+".5666666777888877766666665.", "56666666677777776666666665",+"56666666667777766666666665", "56666566777777776656666665",+"56665567777777777655666665", "56665567777777777655666665",+"56665567777777777655666665", "57775567777777777655777765",+"57775567777777777655777765", "57775566777777776655777765",+".555556667777776665555555.", ".....566666666666665......",+".....566666..6666665......", "....5777775..57777775.....",+"...57777775..577777775...."],+"pauline": [+"...4444...", "..455555..", "..522525..", "..522225..", "..552255..",+"...9229...", "..299992..", ".22999922.", ".2.9999.2.", "...9999...",+"..999999..", "..999999..", ".99999999.", ".99999999.", "....22....",+"...22.2...", "...99.99..", "..999.999."],+"barrel": [+"..CCCCCC..", ".C477774C.", "C74777474C", "C77474774C", "C77747774C",+"C77474774C", "C74777474C", ".C477774C.", "..CCCCCC.."],+"fire": [+"....1.....", "...11..1..", "...C1.C1..", ".1.CCCC1..", ".1CCCCC1..",+".CCCCCCC1.", "CCCCCCCCC1", "CCC4CC4CC1", "CCC8CC8CC1", ".CC444CC1.",+"..CC4CC1..", "..C...C..."],+"tub": [".EEEEEEEE.", "EDDDDDDDDE", "ECCCCCCCCE", ".ECCCCCCE.", ".ECCCCCCE.", "..EEEEEE..", "..D....D.."],+"hammer": [".EEEEEEE.", "EEEEEEEE.", "EEEEEEEE.", ".EEEEEEE.", "....77...", "....77...", "....77...", "....77...", "....77..."],+"bag": ["...444...", "..4...4..", ".9999999.", "999999999", "999494999", "999494999", "999999999", ".9999999."],+"hat": ["..99999..", "..99999..", ".9999999.", "444444444", "999999999"],+"parasol": ["....B....", "..BBBBB..", ".BB9B9BB.", "BB9BB9BBB", "....4....", "....4....", "....4....", "..4.4....", "...4....."],+}++def rows(name):+ art = ART[name]+ width = max(map(len, art))+ return [row.ljust(width, '.') for row in art]++def main():+ result = ['/* SPDX-License-Identifier: GPL-3.0-only; generated by tools/assets.py */',+ 'typedef struct {uint8_t w,h;const uint8_t *p;} dk_sprite;']+ result.append('static const uint16_t palette[]={' + ','.join(+ str(((c >> 8) & 0xF800) | ((c >> 5) & 0x7E0) | ((c >> 3) & 31)) for c in COLORS) + '};')+ for name in ART:+ art = rows(name)+ values = [0 if ch == '.' else int(ch, 16) for row in art for ch in row]+ if len(values) % 2:+ values.append(0)+ data = [values[i] << 4 | values[i+1] for i in range(0, len(values), 2)]+ result.append('static const uint8_t pixels_' + name + '[]={' + ','.join(map(str, data)) + '};')+ result.append(f'static const dk_sprite spr_{name}={{{len(art[0])},{len(art)},pixels_{name}}};')+ (ROOT/'src/assets.h').write_text('\n'.join(result)+'\n')+ # A tiny arcade cabinet icon: ape, red girders and blue ladders.+ pixels = [[COLORS[0]]*55 for _ in range(56)]+ for y in (6, 38, 50):+ for x in range(3, 52):+ pixels[y][x] = COLORS[1]+ pixels[y+3][x] = COLORS[9]+ if x%6 < 2:+ pixels[y+1][x] = pixels[y+2][x] = COLORS[9]+ for y in range(41, 50):+ for x in (9, 15, 39, 45):+ pixels[y][x] = COLORS[10]+ if y%3 == 0:+ for x in list(range(9, 16))+list(range(39, 46)):+ pixels[y][x] = COLORS[10]+ for y, row in enumerate(rows('kong')):+ for x, ch in enumerate(row):+ if ch != '.':+ pixels[y+11][x+14] = COLORS[int(ch,16)]+ raw = b''.join(b'\0'+b''.join(bytes((c >> 16, c >> 8 & 255, c & 255)) for c in row) for row in pixels)+ def chunk(kind, data):+ return struct.pack('>I',len(data))+kind+data+struct.pack('>I',zlib.crc32(kind+data))+ png = b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',55,56,8,2,0,0,0))+ png += chunk(b'IDAT',zlib.compress(raw,9))+chunk(b'IEND',b'')+ (ROOT/'src/icon.png').write_bytes(png)++if __name__ == '__main__':+ main()diff --git a/games/donkeykong/tools/compact_nwa.py b/games/donkeykong/tools/compact_nwa.pynew file mode 100644index 00000000..f320bb54--- /dev/null+++ b/games/donkeykong/tools/compact_nwa.py@@ -0,0 +1,228 @@+#!/usr/bin/env python3+"""Lossless standalone NWA packing. Python standard library + ARM binutils.++Keep the standard ELF/NWI formats: no runtime decoder, extra RAM, or archive.+"""+import argparse+from bisect import bisect_left, insort+import json+from pathlib import Path+import subprocess+import tempfile++ICON_BYTES = 55 * 56 * 2+++def decode_lz4(data, expected_size):+ """Decode a raw LZ4 block, with an exact output bound for launcher icons."""+ out = bytearray()+ pos = 0++ def length(value):+ nonlocal pos+ if value == 15:+ while True:+ if pos >= len(data):+ raise ValueError('Truncated LZ4 length')+ extra = data[pos]+ pos += 1+ value += extra+ if extra != 255:+ break+ return value++ while pos < len(data):+ token = data[pos]+ pos += 1+ size = length(token >> 4)+ if pos + size > len(data) or len(out) + size > expected_size:+ raise ValueError('Invalid LZ4 literal run')+ out += data[pos:pos + size]+ pos += size+ if pos == len(data):+ break+ if pos + 2 > len(data):+ raise ValueError('Truncated LZ4 offset')+ distance = data[pos] | data[pos + 1] << 8+ pos += 2+ size = length(token & 15) + 4+ if not distance or distance > len(out) or len(out) + size > expected_size:+ raise ValueError('Invalid LZ4 match')+ for _ in range(size):+ out.append(out[-distance])+ if len(out) != expected_size:+ raise ValueError('Unexpected decoded icon size')+ return bytes(out)+++def _extension_cost(value, threshold):+ return 0 if value < threshold else 1 + (value - threshold) // 255+++def compress_lz4(data):+ """Find a minimum-size raw LZ4 parse for a small (<= 65535 byte) image.++ A suffix array finds the longest legal previous match. Dynamic programming+ chooses literal/match lengths, including extension-byte costs. The final+ five bytes are literals; the last match starts at least twelve bytes from+ the end, as required by standard LZ4 block decoders.+ """+ n = len(data)+ if n > 65535:+ raise ValueError('Only small build-time assets are supported')+ if not n:+ return b'\0'+ suffixes = sorted(range(n), key=lambda i: data[i:])+ rank = [0] * n+ for r, pos in enumerate(suffixes):+ rank[pos] = r+ seen = []+ matches = [(0, 0)] * n+ for i in range(n - 11):+ r = rank[i]+ at = bisect_left(seen, r)+ best, distance = 0, 0+ # Among earlier suffixes, a lexicographic neighbour has the longest+ # common prefix. Overlapping matches are legal in LZ4.+ for q in seen[max(0, at - 1):at + 1]:+ j = suffixes[q]+ lo, hi = 0, n - i - 5+ while lo < hi:+ mid = (lo + hi + 1) // 2+ if data[i:i + mid] == data[j:j + mid]:+ lo = mid+ else:+ hi = mid - 1+ if lo > best:+ best, distance = lo, i - j+ matches[i] = best, distance+ insort(seen, r)++ dp = [0] * (n + 1)+ plan = [None] * n+ match_cost = [0] * n+ match_length = [0] * n+ starts = []+ for i in range(n - 1, -1, -1):+ best = n - i + 1 + _extension_cost(n - i, 15)+ longest, _ = matches[i]+ if longest >= 4:+ cost, size = min((2 + _extension_cost(size, 19) + dp[i + size], size)+ for size in range(4, longest + 1))+ match_cost[i], match_length[i] = cost, size+ starts.append(i)+ for j in reversed(starts):+ literal = j - i+ if literal + 3 >= best:+ break+ cost = 1 + literal + _extension_cost(literal, 15) + match_cost[j]+ if cost < best:+ best = cost+ plan[i] = j, match_length[j], matches[j][1]+ dp[i] = best++ out = bytearray()++ def emit_length(value):+ while value >= 255:+ out.append(255)+ value -= 255+ out.append(value)++ anchor = 0+ while anchor < n:+ entry = plan[anchor]+ if entry is None:+ literal = n - anchor+ out.append(min(literal, 15) << 4)+ if literal >= 15:+ emit_length(literal - 15)+ out += data[anchor:]+ break+ j, size, distance = entry+ literal = j - anchor+ out.append(min(literal, 15) << 4 | min(size - 4, 15))+ if literal >= 15:+ emit_length(literal - 15)+ out += data[anchor:j]+ out += bytes((distance & 255, distance >> 8))+ if size >= 19:+ emit_length(size - 19)+ anchor = j + size+ if len(out) != dp[0] or decode_lz4(out, n) != data:+ raise ValueError('Lossless compression verification failed')+ return bytes(out)+++def compact_icon(source, output, objcopy):+ output.parent.mkdir(parents=True, exist_ok=True)+ with tempfile.TemporaryDirectory(dir=output.parent) as folder:+ folder = Path(folder)+ original, packed, obj = folder/'original.nwi', folder/'packed.nwi', folder/'icon.o'+ section = '.rodata.eadk_app_icon'+ subprocess.run([objcopy, '--dump-section=' + section + '=' + str(original),+ str(source), str(obj)], check=True)+ before = original.read_bytes()+ pixels = decode_lz4(before, ICON_BYTES)+ after = compress_lz4(pixels)+ if len(after) > len(before):+ after = before+ packed.write_bytes(after)+ subprocess.run([objcopy, '--update-section=' + section + '=' + str(packed),+ str(obj), str(output)], check=True)+ # Verify the bytes actually stored in the resulting ELF, too.+ subprocess.run([objcopy, '--dump-section=' + section + '=' + str(packed),+ str(output), str(folder/'verify.o')], check=True)+ if decode_lz4(packed.read_bytes(), ICON_BYTES) != pixels:+ raise ValueError('Packed icon pixels changed')+ return dict(source_icon_bytes=len(before), icon_bytes=len(after), decoded_icon_bytes=ICON_BYTES)+++def compact_app(source, output, linker):+ output.parent.mkdir(parents=True, exist_ok=True)+ script = Path(__file__).with_name('standalone.ld')+ with tempfile.TemporaryDirectory(dir=output.parent) as folder:+ packed = Path(folder)/'packed.nwa'+ subprocess.run([linker, '--relocatable', '--script', str(script), str(source),+ '-o', str(packed)], check=True)+ output.write_bytes(packed.read_bytes())+++def compact_release(source, output, objcopy):+ """Remove unused ARM mapping symbols from the transport ELF only.++ GNU objcopy preserves $t/$d symbols specially even when unused. Rename+ them in a temporary release copy, then let objcopy decide which symbols+ relocations still need. Keep the debug ELF intact for ARM disassembly.+ Python builders compare release/debug bytes on all supported profiles;+ Make's check target compares them on the smallest RAM profile.+ """+ output.parent.mkdir(parents=True, exist_ok=True)+ with tempfile.TemporaryDirectory(dir=output.parent) as folder:+ folder = Path(folder)+ stripped, renamed = folder/'stripped.nwa', folder/'renamed.nwa'+ subprocess.run([objcopy, '--strip-unneeded', str(source), str(stripped)], check=True)+ subprocess.run([objcopy, '--redefine-sym=$t=unused_thumb_marker',+ '--redefine-sym=$d=unused_data_marker', str(stripped),+ str(renamed)], check=True)+ subprocess.run([objcopy, '--strip-unneeded', str(renamed), str(output)], check=True)+++def main():+ ap = argparse.ArgumentParser(description=__doc__)+ ap.add_argument('kind', choices=('icon', 'app', 'release'))+ ap.add_argument('source', type=Path)+ ap.add_argument('output', type=Path)+ ap.add_argument('--objcopy', default='arm-none-eabi-objcopy')+ ap.add_argument('--ld', default='arm-none-eabi-ld')+ args = ap.parse_args()+ if args.kind == 'icon':+ print(json.dumps(compact_icon(args.source, args.output, args.objcopy)))+ elif args.kind == 'release':+ compact_release(args.source, args.output, args.objcopy)+ else:+ compact_app(args.source, args.output, args.ld)+++if __name__ == '__main__':+ main()diff --git a/games/donkeykong/tools/standalone.ld b/games/donkeykong/tools/standalone.ldnew file mode 100644index 00000000..28679582--- /dev/null+++ b/games/donkeykong/tools/standalone.ld@@ -0,0 +1,15 @@+/* Compact a standalone NWA after the first link has removed unused code.+ * Keep EADK metadata separate, and preserve mergeable strings for nwlink.+ * NumPlay modules retain their original sections for launcher garbage collection.+ */+SECTIONS {+ .rodata.eadk_app_name : { *(.rodata.eadk_app_name) }+ .rodata.eadk_app_icon : { *(.rodata.eadk_app_icon) }+ .rodata.eadk_api_level : { *(.rodata.eadk_api_level) }+ .text : { *(.text.startup.main) *(.text .text.*) }+ .rodata.str1.1 : { *(.rodata*.str1.1) }+ .rodata : { *(.rodata .rodata.*) }+ .data : { *(.data .data.*) }+ .bss : { *(.bss .bss.*) *(COMMON) }+ /DISCARD/ : { *(.comment) *(.note.GNU-stack) }+}