Merge pull request #438 from s4Ys369/revert-434-patch-1
[sm64pc.git] / tools / demo_data_converter.py
blobab656bd73d31d1c3752b71132518cde9ee6ee7dc
1 #!/usr/bin/env python3
2 import sys
3 import re
4 import json
6 def main():
7 need_help = False
8 defines = []
9 skip_next = 0
10 prog_args = []
11 for i, a in enumerate(sys.argv[1:], 1):
12 if skip_next > 0:
13 skip_next -= 1
14 continue
15 if a == "--help" or a == "-h":
16 need_help = True
17 if a == "-D":
18 defines.append(sys.argv[i + 1])
19 skip_next = 1
20 elif a.startswith("-D"):
21 defines.append(a[2:])
22 else:
23 prog_args.append(a)
25 defines = [d.split("=")[0] for d in defines]
27 if len(prog_args) < 1 or need_help:
28 print("Usage: {} <demo_data.json> [-D <symbol>] > <demo_data.c>".format(sys.argv[0]))
29 sys.exit(0 if need_help else 1)
31 with open(prog_args[0], "r") as file:
32 descr = json.loads(re.sub(r"/\*[\w\W]*?\*/", "", file.read()))
34 table = []
35 for item in descr["table"]:
36 if not "ifdef" in item or any(d in defines for d in item["ifdef"]):
37 table.append(item)
39 demofiles = []
40 for item in descr["demofiles"]:
41 if not "ifdef" in item or any(d in defines for d in item["ifdef"]):
42 demofiles.append(item)
44 structdef = ["u32 numEntries;",
45 "const void *addrPlaceholder;",
46 "struct OffsetSizePair entries[" + str(len(table)) + "];"]
47 structobj = [str(len(table)) + ",",
48 "NULL,"]
50 structobj.append("{")
51 for item in table:
52 offset_to_data = "offsetof(struct DemoInputsObj, " + item["demofile"] + ")"
53 size = "sizeof(gDemoInputs." + item["demofile"] + ")"
54 if "extraSize" in item:
55 size += " + " + str(item["extraSize"])
56 structobj.append("{" + offset_to_data + ", " + size + "},")
57 structobj.append("},")
59 for item in demofiles:
60 with open("assets/demos/" + item["name"] + ".bin", "rb") as file:
61 demobytes = file.read()
62 structdef.append("u8 " + item["name"] + "[" + str(len(demobytes)) + "];")
63 structobj.append("{" + ",".join(hex(x) for x in demobytes) + "},")
65 print("#include \"types.h\"")
66 print("#include <stddef.h>")
67 print("")
69 print("struct DemoInputsObj {")
70 for s in structdef:
71 print(s)
72 print("} gDemoInputs = {")
73 for s in structobj:
74 print(s)
75 print("};")
77 if __name__ == "__main__":
78 main()