Files
JIANT/tools/gen_drum_maps.py

174 lines
9.4 KiB
Python

#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-only
# Copyright (C) 2026 Juan Ignacio Antonucci (Juan Jiant)
"""(0.9.7, flash) GEN's drum maps packed: firmware/src/gen_tables.c keeps them as text (DRUM_MAP: a genre's eight lanes,
the throws' pools HAT_POOL OH_POOL RS_POOL CB_POOL TM_POOL: 16 characters a lane, '.' 0, '1'..'9', 'X'; "" no lane), read
here, not compiled. Out: each distinct lane once, 16 levels a nibble (GM_LANE[k]: step 2i in the high nibble of byte i,
'.' 0, '1'..'9' 1..9, 'X' 10; lane 0 the empty one), and the tables as lane numbers (DRUM_MAP_I[DM_..][8],
HAT_POOL_I ..). gen.c reads them through gm_level (the same levels as the text gave: glevel). Also DICE's bars
(firmware/src/song_dice.c DRUM_BAR, DRUM_BAR_KICK: '.' 'x' a hit, 'a' accented, 'g' a ghost): each distinct lane once at
2 bits a step (DB_LANE: step 4i in the top bits of byte i, '.' 0 'x' 1 'a' 2 'g' 3), the table as lane numbers
(DRUM_BAR_I; song_dice.c db_char), in their own header (song_dice.c comes before gen_tables.c). And GEN's bass archetypes (gen_tables.c BASS_ARCH: a
note and a flag a step as text, NOTES and FLAGS below): a byte a step, the note's code | the flag's << 4 (BA_STEP), each
archetype its first step and bars (gen.c ba_note, ba_flag).
gen_drum_maps.py GEN_TABLES.c SONG_DICE.c OUT.h DICE_OUT.h BASS_OUT.h"""
import re
import sys
from pathlib import Path
LEVEL = {".": 0, "X": 10, **{str(d): d for d in range(1, 10)}}
NOTES = ".=R23456789ALNSx" # (gen.c BA_NOTES: the same order)
FLAGS = ".asg"
def main(src, dice, out, dout, bout):
s = Path(src).read_text()
m = re.search(r"static const char \*const DRUM_MAP\[\]\[8\] = \{(.*?)\n\};", s, re.S)
rows = re.findall(r"\[(DM_\w+)\]\s*=\s*\{([^}]*)\}", m.group(1))
pools = re.findall(r"static const char \*const (\w+_POOL)\[(\d+)\] = \{(.*?)\};", s, re.S)
lanes, idx = [""], {"": 0}
def lane(x):
if x not in idx:
assert len(x) == 16 and set(x) <= set(LEVEL), f"gen_drum_maps: lane {x!r}"
assert set(x) != {"."}, "an all-rest lane would read as none"
idx[x] = len(lanes)
lanes.append(x)
return idx[x]
table = []
for name, body in rows:
ls = re.findall(r'"([^"]*)"', body)
assert len(ls) == 8, f"gen_drum_maps: {name} has {len(ls)} lanes"
table.append((name, [lane(x) for x in ls]))
ptab = []
for name, n, body in pools:
ls = re.findall(r'"([^"]*)"', body)
assert len(ls) == int(n), f"gen_drum_maps: {name}"
ptab.append((name, [lane(x) for x in ls]))
assert len(lanes) <= 256
L = ["/* generated by tools/gen_drum_maps.py from firmware/src/gen_tables.c (DRUM_MAP and the pools, as text there): */",
"/* each lane once, 16 levels a nibble ('.' 0, '1'..'9', 'X' 10; lane 0: none); the tables as lane numbers */",
"#pragma once", "#include <stdint.h>",
"#include \"gz.h\"", f"#define GM_LANE_N {len(lanes)}u",
"/* GM_LANE[GM_LANE_N][8] as one LZ4 block (tools/lz4blk.py compress_small; gz.h gz_get unpacks it): */"]
raw = bytearray()
for x in lanes:
v = [LEVEL[c] for c in x] if x else [0] * 16
raw += bytes(v[2 * i] << 4 | v[2 * i + 1] for i in range(8))
L += zblob("GM_LANE_Z", bytes(raw))
L += ["_Static_assert(GM_LANE_N * 8u <= GZ_MAX, \"gz.h: GM_LANE fits the buffer\");",
"#define GM_LANE ((const uint8_t (*)[8])gz_get(GM_LANE_Z, GM_LANE_N * 8u))"]
L.append("static const uint8_t DRUM_MAP_I[][8] = {")
for name, v in table:
L.append(f" [{name}] = {{{', '.join(map(str, v))}}},")
L.append("};")
for name, v in ptab:
L.append(f"static const uint8_t {name}_I[{len(v)}] = {{{', '.join(map(str, v))}}};")
size = 8 * len(lanes) + 8 * len(table) + sum(len(v) for _, v in ptab)
# DICE's bars (0.9.18: gone with song_dice.c's own generator; the header stays, empty, for an older source)
d = Path(dice).read_text()
m = re.search(r"static const char \*const DRUM_BAR\[\]\[8\] = \{(.*?)\n\};", d, re.S)
Path(out).write_text("\n".join(L) + "\n")
bl, btab = [""], []
if m:
brows = re.findall(r"\[(DS_\w+)\]\s*=\s*\{([^}]*)\}", m.group(1))
kick = re.findall(r'"([^"]*)"', re.search(r"static const char \*const DRUM_BAR_KICK\[1\] = \{(.*?)\};", d, re.S).group(1))
bi = {"": 0}
code = {".": 0, "x": 1, "a": 2, "g": 3}
def blane(x):
if x not in bi:
assert len(x) == 16 and set(x) <= set(code), f"gen_drum_maps: bar lane {x!r}"
assert set(x) != {"."}, "an all-rest lane would read as none"
bi[x] = len(bl)
bl.append(x)
return bi[x]
for name, body in brows:
ls = re.findall(r'"([^"]*)"', body)
assert len(ls) == 8, f"gen_drum_maps: {name} has {len(ls)} lanes"
btab.append((name, [blane(x) for x in ls]))
kk = [blane(x) for x in kick]
L = ["/* generated by tools/gen_drum_maps.py from firmware/src/song_dice.c (DRUM_BAR, DRUM_BAR_KICK, as text there): */",
"/* each lane once, 2 bits a step ('.' 0 'x' 1 'a' 2 'g' 3; lane 0: none); the table as lane numbers */",
"#pragma once", "#include <stdint.h>"]
if m:
L.append(f"static const uint8_t DB_LANE[{len(bl)}][4] = {{")
for x in bl:
v = [code[c] for c in x] if x else [0] * 16
L.append(" {" + ", ".join(f"0x{v[4 * i] << 6 | v[4 * i + 1] << 4 | v[4 * i + 2] << 2 | v[4 * i + 3]:02X}" for i in range(4))
+ "}," + (f" /* {x} */" if x else " /* (none) */"))
L.append("};")
L.append("static const uint8_t DRUM_BAR_I[][8] = {")
for name, v in btab:
L.append(f" [{name}] = {{{', '.join(map(str, v))}}},")
L.append("};")
L.append(f"#define DRUM_BAR_KICK_I {kk[0]}u")
Path(dout).write_text("\n".join(L) + "\n")
size2 = 4 * len(bl) + 8 * len(btab)
m = re.search(r"static const barch_t BASS_ARCH\[(\w+)\] = \{(.*?)\n\};", s, re.S) # (V10.6p: BA_NALL, the riffs too)
asz = m.group(1)
arch = re.findall(r"\[(BA_\w+)\]\s*=\s*\{(\"[^\"]*\"|0),\s*(\"[^\"]*\"|0),\s*(\d+)\}", m.group(2))
steps, rows3 = [], []
for name, n, f, bars in arch:
bars = int(bars)
if n == "0":
rows3.append((name, 0, bars))
continue
n, f = n.strip('"'), f.strip('"') if f != "0" else "." * (16 * bars)
assert len(n) == len(f) == 16 * bars and set(n) <= set(NOTES) and set(f) <= set(FLAGS), f"gen_drum_maps: {name}"
rows3.append((name, bytes(NOTES.index(a) | FLAGS.index(b) << 4 for a, b in zip(n, f)), bars))
# (V10.7.2) the archetypes overlapped where one's end is another's start (or one lies inside another): a greedy
# shortest common superstring, each archetype its first step in it (gen.c reads 16 x bars steps from there)
seqs = sorted({r[1] for r in rows3 if isinstance(r[1], bytes)}, key=lambda x: (-len(x), x))
seqs = [x for x in seqs if not any(x != y and x in y for y in seqs)]
while len(seqs) > 1:
best = (0, 0, 1)
for i, a in enumerate(seqs):
for j, b in enumerate(seqs):
if i != j:
k = next((k for k in range(min(len(a), len(b)) - 1, 0, -1) if a[-k:] == b[:k]), 0)
if k > best[0]:
best = (k, i, j)
k, i, j = best
if not k:
break
joined = seqs[i] + seqs[j][k:]
seqs = [x for t, x in enumerate(seqs) if t not in (i, j)] + [joined]
blob = b"".join(seqs)
rows3 = [(name, blob.find(at) if isinstance(at, bytes) else at, bars) for name, at, bars in rows3]
steps = list(blob)
assert len(steps) < 65536
L = ["/* generated by tools/gen_drum_maps.py from firmware/src/gen_tables.c (BASS_ARCH, as text there): a byte a step, */",
f"/* the note's code in \"{NOTES}\" | the flag's in \"{FLAGS}\" << 4; each archetype its first step, its bars */",
"#pragma once", "#include <stdint.h>", "#include \"gz.h\"", f"#define BA_STEP_N {len(steps)}u",
"/* BA_STEP[BA_STEP_N] as one LZ4 block (tools/lz4blk.py compress_small; gz.h gz_get unpacks it): */"]
L += zblob("BA_STEP_Z", bytes(steps))
L += ["_Static_assert(BA_STEP_N <= GZ_MAX, \"gz.h: BA_STEP fits the buffer\");",
"#define BA_STEP gz_get(BA_STEP_Z, BA_STEP_N)"]
L += ["_Static_assert(BA_STEP_N <= 8192u, \"gen_tables.c barch_t: at in 13 bits\");"]
L += [f"static const barch_t BASS_ARCH[{asz}] = {{"]
for name, at, bars in rows3:
assert at < 8192 and 0 < bars < 8, (name, at, bars) # (barch_t: at 13 bits, bars 3)
L.append(f" [{name}] = {{{at}, {bars}}},")
L.append("};")
Path(bout).write_text("\n".join(L) + "\n")
size3 = len(steps) + 2 * len(rows3)
print(f"drum maps: {len(table)} maps, {len(ptab)} pools, {len(lanes) - 1} distinct lanes, {size} B; DICE's bars: "
f"{len(btab)}, {len(bl) - 1} distinct lanes, {size2} B; bass archetypes {len(rows3)}, {size3} B -> {out}, {dout}, {bout}")
return 0
def zblob(name, raw):
"""a table as an LZ4 block (lz4blk.compress_small, checked by unpacking it): C lines"""
import lz4blk
z = lz4blk.compress_small(raw)
assert lz4blk.boot_unpack(z, 0, len(raw))[0] == raw
L = [f"static const uint8_t {name}[{len(z)}] = {{ /* {len(raw)} B */"]
for i in range(0, len(z), 24):
L.append(" " + ", ".join(f"0x{v:02X}" for v in z[i:i + 24]) + ",")
return L + ["};"]
if __name__ == "__main__":
sys.exit(main(*sys.argv[1:6]))