-
Notifications
You must be signed in to change notification settings - Fork 8
/
parse_pwe_templates.py
1819 lines (1472 loc) · 68.3 KB
/
parse_pwe_templates.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import collections
import dataclasses
import keyword
import logging
import re
import struct
import typing
from pathlib import Path
from xml.etree import ElementTree
from xml.etree.ElementTree import Element
import inflection
# ruff: noqa: E501
# ruff: noqa: C901
# ruff: noqa: PLR0912 lots of branches
# ruff: noqa: PLR0915 lots of statements
# ruff: noqa: PLW0603 we use globals here
rds_root = Path(__file__).parent.joinpath("src", "retro_data_structures")
FAST_DECODE_ASSERT = True # fast import will assert the ids are in the correct order instead of failing if not
_game_id_to_file = {
"Prime": "prime",
"Echoes": "echoes",
"Corruption": "corruption",
"DKCReturns": "dkc_returns",
"PrimeRemastered": "prime_remastered",
}
_game_id_to_enum = {
"Prime": "PRIME",
"Echoes": "ECHOES",
"Corruption": "CORRUPTION",
"DKCReturns": "DKC_RETURNS",
"PrimeRemastered": "PRIME_REMASTER",
}
_CODE_PARSE_UINT16 = {
">": 'struct.unpack(">H", data.read(2))[0]',
"<": 'struct.unpack("<H", data.read(2))[0]',
}
_CODE_PARSE_UINT32 = {
">": 'struct.unpack(">L", data.read(4))[0]',
"<": 'struct.unpack("<L", data.read(4))[0]',
}
def get_endianness(game_id):
return ">" if game_id != "PrimeRemastered" else "<"
@dataclasses.dataclass(frozen=True)
class EnumDefinition:
name: str
values: dict[str, typing.Any]
enum_base: str = "Enum"
_enums_by_game: dict[str, list[EnumDefinition]] = {}
def _scrub_enum(string: str):
s = re.sub(r"\W", "", string) # remove non-word characters
s = re.sub(r"^(?=\d)", "_", s) # add leading underscore to strings starting with a number
s = re.sub(r"^None$", "_None", s) # add leading underscore to None
s = s or "_EMPTY" # add name for empty string keys
return s
def create_enums_file(game_id: str, enums: list[EnumDefinition]):
code = '"""\nGenerated file.\n"""\nimport enum\nimport typing\nimport struct\nimport typing_extensions\n'
code += "\nfrom retro_data_structures import json_util\n"
endianness = get_endianness(game_id)
for e in enums:
code += f"\n\nclass {_scrub_enum(e.name)}(enum.{e.enum_base}):\n"
for name, value in e.values.items():
code += f" {_scrub_enum(name)} = {value}\n"
code += "\n @classmethod\n"
code += " def from_stream(cls, data: typing.BinaryIO, size: int | None = None) -> typing_extensions.Self:\n"
code += f" return cls({_CODE_PARSE_UINT32[endianness]})\n"
code += "\n def to_stream(self, data: typing.BinaryIO) -> None:\n"
code += ' data.write(struct.pack("' + endianness + 'L", self.value))\n'
code += "\n @classmethod\n"
code += " def from_json(cls, data: json_util.JsonValue) -> typing_extensions.Self:\n"
code += " assert isinstance(data, int)\n"
code += " return cls(data)\n"
code += "\n def to_json(self) -> int:\n"
code += " return self.value\n"
return code
def _prop_default_value(element: Element, game_id: str, path: Path) -> dict:
default_value_types = {
"Int": lambda el: struct.unpack("l", struct.pack("L", (int(el.text, 10) & 0xFFFFFFFF)))[0],
"Float": lambda el: float(el.text),
"Bool": lambda el: el.text == "true",
"Short": lambda el: int(el.text, 10) & 0xFFFF,
"Color": lambda el: {e.tag: float(e.text) for e in el},
"Vector": lambda el: {e.tag: float(e.text) for e in el},
"Flags": lambda el: int(el.text, 10) & 0xFFFFFFFF,
"Choice": lambda el: int(el.text, 10) & 0xFFFFFFFF,
"Enum": lambda el: int(el.text, 16) & 0xFFFFFFFF,
"Sound": lambda el: int(el.text, 10) & 0xFFFFFFFF,
}
default_value = None
has_default = False
if (default_value_element := element.find("DefaultValue")) is not None:
default_value = default_value_types.get(element.attrib["Type"], lambda el: el.text)(default_value_element)
has_default = True
return {"has_default": has_default, "default_value": default_value}
def _prop_struct(element: Element, game_id: str, path: Path) -> dict:
return {
"archetype": element.attrib.get("Archetype"),
"properties": _parse_properties(element, game_id, path)["properties"],
}
def _prop_asset(element: Element, game_id: str, path: Path) -> dict:
type_filter = []
if element.find("TypeFilter"):
type_filter = [t.text for t in element.find("TypeFilter")]
return {"type_filter": type_filter}
def _prop_array(element: Element, game_id: str, path: Path) -> dict:
# print(ElementTree.tostring(element, encoding='utf8', method='xml'))
item_archetype = None
if (item_archetype_element := element.find("ItemArchetype")) is not None:
item_archetype = _parse_single_property(item_archetype_element, game_id, path, include_id=False)
# print(item_archetype)
return {"item_archetype": item_archetype}
def _prop_choice(element: Element, game_id: str, path: Path) -> dict:
_parse_choice(element, game_id, path)
extras = {"archetype": element.attrib.get("Archetype")}
extras.update(_prop_default_value(element, game_id, path))
return extras
def _prop_flags(element: Element, game_id: str, path: Path) -> dict:
extras = _prop_default_value(element, game_id, path)
if (flags_element := element.find("Flags")) is not None:
extras["flags"] = {
element.attrib["Name"]: int(element.attrib["Mask"], 16) for element in flags_element.findall("Element")
}
name = None
if element.find("Name") is not None:
name = element.find("Name").text
elif element.attrib.get("ID"):
name = property_names.get(int(element.attrib.get("ID"), 16))
if name == "Unknown" and element.attrib.get("ID"):
name += f'_{element.attrib.get("ID")}'
_enums_by_game[game_id].append(EnumDefinition(name, extras["flags"], enum_base="IntFlag"))
extras["flagset_name"] = name
return extras
def _parse_single_property(element: Element, game_id: str, path: Path, include_id: bool = True) -> dict:
parsed = {}
if include_id:
parsed.update({"id": int(element.attrib["ID"], 16)})
if (name := element.attrib.get("Name", "")) == "":
name_element = element.find("Name")
name = name_element.text if name_element is not None and name_element.text is not None else ""
cook = element.find("CookPreference")
parsed.update(
{
"type": element.attrib["Type"],
"name": name,
"cook_preference": cook.text if cook is not None and cook.text is not None else "Always",
}
)
ignore_dependencies_mlvl = element.attrib.get("IgnoreDependenciesMlvl", "False")
ignore_dependencies_mlvl = ignore_dependencies_mlvl.lower() != "false"
if ignore_dependencies_mlvl:
parsed["ignore_dependencies_mlvl"] = True
property_type_extras = {
"Struct": _prop_struct,
"Asset": _prop_asset,
"Array": _prop_array,
"Enum": _prop_choice,
"Choice": _prop_choice,
"Flags": _prop_flags,
}
parsed.update(property_type_extras.get(element.attrib["Type"], _prop_default_value)(element, game_id, path))
return parsed
def _parse_properties(properties: Element, game_id: str, path: Path) -> dict:
elements = []
if (sub_properties := properties.find("SubProperties")) is not None:
for element in sub_properties:
element = typing.cast(Element, element)
elements.append(_parse_single_property(element, game_id, path))
return {
"type": "Struct",
"name": properties.find("Name").text if properties.find("Name") is not None else "",
"atomic": properties.find("Atomic") is not None,
"incomplete": properties.attrib.get("Incomplete") == "true",
"properties": elements,
}
def _parse_choice(properties: Element, game_id: str, path: Path) -> dict:
_type = properties.attrib.get("Type", "Choice")
choices = {}
if (values := properties.find("Values")) is not None:
for element in values:
element = typing.cast(Element, element)
choices[element.attrib["Name"]] = int(element.attrib["ID"], 16)
name = ""
if properties.find("Name") is not None:
name = properties.find("Name").text
elif properties.attrib.get("ID"):
name = property_names.get(int(properties.attrib.get("ID"), 16), path.stem + properties.attrib.get("ID"))
else:
return {
"type": _type,
"choices": choices,
}
_enums_by_game[game_id].append(EnumDefinition(name, choices, enum_base="IntEnum"))
return {
"type": _type,
}
_parse_choice.unknowns = {}
def parse_script_object_file(path: Path, game_id: str) -> dict:
t = ElementTree.parse(path)
root = t.getroot()
result = _parse_properties(root.find("Properties"), game_id, path)
if modules := root.find("Modules"):
result["modules"] = [item.text for item in modules.findall("Element")]
return result
def parse_property_archetypes(path: Path, game_id: str) -> dict:
t = ElementTree.parse(path)
root = t.getroot()
archetype = root.find("PropertyArchetype")
_type = archetype.attrib["Type"]
if _type == "Struct":
return _parse_properties(archetype, game_id, path)
elif _type in {"Choice", "Enum"}:
return _parse_choice(archetype, game_id, path)
else:
raise ValueError(f"Unknown Archetype format: {_type}")
property_names: dict[int, str] = {}
def read_property_names(map_path: Path):
global property_names
t = ElementTree.parse(map_path)
root = t.getroot()
m = root.find("PropertyMap")
property_names = {
int(item.find("Key").attrib["ID"], 16): item.find("Value").attrib["Name"]
for item in typing.cast(typing.Iterable[Element], m)
}
return property_names
def get_paths(elements: typing.Iterable[Element]) -> dict[str, str]:
return {item.find("Key").text: item.find("Value").attrib["Path"] for item in elements}
def get_key_map(elements: typing.Iterable[Element]) -> dict[str, str]:
return {item.find("Key").text: item.find("Value").text for item in elements}
_to_snake_case_re = re.compile(r"(?<!^)(?=[A-Z])")
_invalid_chars_table = str.maketrans("", "", "()?'")
_to_underscore_table = str.maketrans("/ ", "__")
def _filter_property_name(n: str) -> str:
result = (
inflection.underscore(n.translate(_to_underscore_table).replace("#", "Number"))
.translate(_invalid_chars_table)
.lower()
)
if keyword.iskeyword(result):
result += "_"
return result
def _ensure_is_generated_dir(path: Path):
path.mkdir(parents=True, exist_ok=True)
path.joinpath(".gitignore").write_text("*")
init = path.joinpath("__init__.py")
if not init.is_file():
init.write_text("")
def _fix_module_name(output_path: Path, class_path: str):
# We created a nested module, but there was already a class with that name.
rename_root = output_path
for part in class_path.split("/")[:-1]:
nested_dir = rename_root.joinpath(part)
maybe_file = rename_root.joinpath(part + ".py")
_ensure_is_generated_dir(nested_dir)
if maybe_file.is_file():
maybe_file.replace(rename_root.joinpath(part, "__init__.py"))
rename_root = nested_dir
@dataclasses.dataclass
class PropDetails:
raw: dict
prop_type: str
json_type: str
need_enums: bool
comment: str | None
parse_code: str
build_code: list[str]
from_json_code: str
to_json_code: str
custom_cook_pref: bool
known_size: int | None
dataclass_field_params: dict
dataclass_metadata: dict
needed_imports: dict[str, str | bool]
format_specifier: str | None
dependency_code: str | None
@property
def id(self):
return self.raw["id"]
def get_from_json(self, prop_name: str) -> str:
if self.from_json_code == "{obj}":
return "json_util.identity"
elif self.from_json_code == f"{self.prop_type}.from_json({{obj}})":
return f"{self.prop_type}.from_json"
return f"_from_json_{prop_name}"
def get_to_json(self, prop_name: str) -> str:
if self.to_json_code == "{obj}":
return "json_util.identity"
elif self.to_json_code == "{obj}.to_json()":
return f"{self.prop_type}.to_json"
return f"_to_json_{prop_name}"
def _get_default(field_params: dict) -> str:
if "default" in field_params:
default_value = field_params["default"]
else:
default_value: str = field_params["default_factory"]
if default_value.startswith("lambda: "):
default_value = default_value[len("lambda: ") :]
else:
default_value += "()"
return default_value
@dataclasses.dataclass
class ClassDefinition:
game_id: str
raw_name: str
raw_def: dict
class_name: str
class_path: str
is_struct: bool
is_incomplete: bool
class_code: str = ""
type_checking_code: list[str] = dataclasses.field(default_factory=list)
before_class_code: str = ""
after_class_code: str = ""
properties_builder: str = ""
property_count: int = 0
modules: list[str] = dataclasses.field(default_factory=list)
all_props: dict[str, PropDetails] = dataclasses.field(default_factory=dict)
needed_imports: dict[str, str | bool] = dataclasses.field(default_factory=dict)
typing_imports: dict[str, str | bool] = dataclasses.field(default_factory=dict)
need_enums: bool = False
has_custom_cook_pref: bool = False
@property
def atomic(self) -> bool:
return self.raw_def["atomic"]
def add_prop(self, prop: PropDetails, prop_name: str, raw_name: str):
self.all_props[prop_name] = prop
self.need_enums = self.need_enums or prop.need_enums
self.has_custom_cook_pref = self.has_custom_cook_pref or prop.custom_cook_pref
endianness = get_endianness(self.game_id)
self.needed_imports.update(prop.needed_imports)
if prop.prop_type is None:
raise ValueError(f"Unable to parse property {prop_name} of {self.raw_name}")
self.class_code += f" {prop_name}: {prop.prop_type}"
self.class_code += " = dataclasses.field({}, metadata={{\n".format(
", ".join(f"{key}={value}" for key, value in prop.dataclass_field_params.items())
)
self.class_code += " "
dataclass_metadata = [f"'{key}': {value}" for key, value in prop.dataclass_metadata.items()]
dataclass_metadata.append(f"'reflection': FieldReflection[{prop.prop_type}](")
self.class_code += ", ".join(dataclass_metadata)
# from retro_data_structures.json_util import JsonValue
reflection_fields = [
prop.prop_type,
f"id=0x{prop.id:08x}",
f"original_name={repr(raw_name)}",
]
if (from_json := prop.get_from_json(prop_name)) != "json_util.identity":
reflection_fields.append(f"from_json={from_json}")
if (to_json := prop.get_to_json(prop_name)) != "json_util.identity":
reflection_fields.append(f"to_json={to_json}")
self.class_code += "\n " + ", ".join(reflection_fields) + "\n ),\n })"
if prop.comment is not None:
self.class_code += f" # {prop.comment}"
self.class_code += "\n"
if self.atomic or self.game_id == "Prime":
pass
# self.properties_builder is handled in write_to_stream
else:
# build
prop_id_bytes = struct.pack(endianness + "L", prop.id)
self.properties_builder += "\n"
build_prop = [f"data.write({repr(prop_id_bytes)}) # {hex(prop.id)}"]
if prop.known_size is not None:
placeholder = repr(struct.pack(endianness + "H", prop.known_size))
build_prop.append(f"data.write({placeholder}) # size")
else:
placeholder = repr(b"\x00\x00")
build_prop.append("before = data.tell()")
build_prop.append(f"data.write({placeholder}) # size placeholder")
for build in prop.build_code:
build_prop.append(build.replace("{obj}", f"self.{prop_name}"))
if prop.known_size is None:
build_prop.append("after = data.tell()")
build_prop.append("data.seek(before)")
build_prop.append(f'data.write(struct.pack("{endianness}H", after - before - 2))')
build_prop.append("data.seek(after)")
if not prop.custom_cook_pref:
build_prop = [f" {text}" for text in build_prop]
self.property_count += 1
elif prop.raw["cook_preference"] == "Never":
build_prop = []
else:
default_value = _get_default(prop.dataclass_field_params)
if prop.raw["cook_preference"] == "Default":
self.properties_builder += f" self.{prop_name} = default_override.get({repr(prop_name)}, {default_value}) # Cooks with Default\n"
build_prop = [f" {text}" for text in build_prop]
self.property_count += 1
elif prop.raw["cook_preference"] == "OnlyIfModified":
self.properties_builder += (
f" if self.{prop_name} != default_override.get({repr(prop_name)}, {default_value}):\n"
)
self.properties_builder += " num_properties_written += 1\n"
build_prop = [f" {text}" for text in build_prop]
else:
raise ValueError(f"Unknown cook preference: {prop.raw['cook_preference']}")
self.properties_builder += "\n".join(build_prop)
self.properties_builder += "\n"
def finalize_props(self):
if self.keep_unknown_properties():
self.class_code += " unknown_properties: dict[int, bytes] = dataclasses.field(default_factory=dict)\n"
def keep_unknown_properties(self):
return self.is_incomplete
def _can_fast_decode(self) -> bool:
return all(prop.format_specifier is not None for prop in self.all_props.values()) and self.all_props
def _create_fast_decode_body(self):
num_props = len(self.all_props)
ids = [hex(prop.id) for prop in self.all_props.values()]
big_format = get_endianness(self.game_id) + "".join(
f"LH{prop.format_specifier}" for prop in self.all_props.values()
)
self.before_class_code += "_FAST_FORMAT = None\n"
self.before_class_code += f"_FAST_IDS = ({', '.join(ids)})\n"
yield f" if property_count != {num_props}:"
yield " return None"
yield ""
yield " global _FAST_FORMAT"
yield " if _FAST_FORMAT is None:"
yield f" _FAST_FORMAT = struct.Struct({repr(big_format)})"
yield ""
if not FAST_DECODE_ASSERT:
yield " before = data.tell()"
yield f" dec = _FAST_FORMAT.unpack(data.read({struct.calcsize(big_format)}))"
fast_check = []
ret_state = [" return cls("]
offset = 0
for prop in self.all_props.values():
fast_check.append(f"dec[{offset}]")
offset += 2 # prop id + size
if len(prop.format_specifier) == 1:
value = f"dec[{offset}]"
if prop.prop_type.startswith("enums."):
st = f" {prop.prop_type}({value}),"
else:
st = f" {value},"
else:
st = f" {prop.prop_type}(*dec[{offset}:{offset + len(prop.format_specifier)}]),"
ret_state.append(st)
offset += len(prop.format_specifier)
if FAST_DECODE_ASSERT:
yield f" assert ({', '.join(fast_check)}) == _FAST_IDS"
else:
yield f" if ({', '.join(fast_check)}) != _FAST_IDS:"
yield " data.seek(before)"
yield " return None"
yield ""
yield from ret_state
yield " )"
def _create_simple_decode_body(self):
num_props = len(self.all_props)
endianness = get_endianness(self.game_id)
[hex(prop.id) for prop in self.all_props.values()]
yield f" if property_count != {num_props}:"
yield " return None"
yield ""
variables = []
for prop_name, prop in self.all_props.items():
variable_name = prop_name
if variable_name in ("data", "property_count", "property_id", "property_size", "cls"):
variable_name += "_"
# yield " data.read(6)" # TODO: assert correct
yield f' property_id, property_size = struct.unpack("{endianness}LH", data.read(6))'
yield f" assert property_id == 0x{prop.id:08x}"
yield f" {variable_name} = {prop.parse_code}"
yield ""
variables.append(variable_name)
all_fields = ", ".join(variables)
yield f" return cls({all_fields})"
def write_from_stream(self):
game_id = self.game_id
endianness = get_endianness(game_id)
self.class_code += """
@classmethod
def from_stream(cls, data: typing.BinaryIO, size: int | None = None, default_override: dict | None = None) -> typing_extensions.Self:
"""
if self.atomic or game_id == "Prime":
self.class_code += " property_size = None # Atomic\n"
if game_id == "Prime" and self.is_struct:
self.class_code += f" property_count = {_CODE_PARSE_UINT32[endianness]}\n"
for prop_name, prop in self.all_props.items():
self.class_code += f" {prop_name} = {prop.parse_code}\n"
self.class_code += f" return cls({', '.join(prop_name for prop_name in self.all_props)})\n"
return
if self.is_struct:
self.class_code += (
' struct_id, size, property_count = struct.unpack("' + endianness + 'LHH", data.read(8))\n'
)
self.class_code += " assert struct_id == 0xFFFFFFFF\n"
self.class_code += " root_size_start = data.tell() - 2\n\n"
else:
self.class_code += f" property_count = {_CODE_PARSE_UINT16[endianness]}\n"
self.class_code += " if (result := cls._fast_decode(data, property_count)) is not None:\n"
self.class_code += " return result\n\n"
if self.keep_unknown_properties():
read_unknown = 'present_fields["unknown_properties"][property_id] = data.read(property_size)'
unknown_fields_declare = '\n present_fields["unknown_properties"] = {}\n'
else:
read_unknown = 'raise RuntimeError(f"Unknown property: 0x{property_id:08x}")'
unknown_fields_declare = ""
self.class_code += f""" present_fields = default_override or {{}}{unknown_fields_declare}
for _ in range(property_count):
property_id, property_size = struct.unpack("{endianness}LH", data.read(6))
start = data.tell()
try:
property_name, decoder = _property_decoder[property_id]
present_fields[property_name] = decoder(data, property_size)
except KeyError:
{read_unknown}
assert data.tell() - start == property_size\n
"""
if self.is_struct:
self.class_code += " assert data.tell() - root_size_start == size\n"
self.class_code += " return cls(**present_fields)\n"
self.class_code += "\n @classmethod\n"
self.class_code += (
" def _fast_decode(cls, data: typing.BinaryIO, property_count: int"
") -> typing_extensions.Self | None:\n"
)
if self._can_fast_decode():
for fast_decode in self._create_fast_decode_body():
self.class_code += f" {fast_decode}\n"
else:
for fast_decode in self._create_simple_decode_body():
self.class_code += f" {fast_decode}\n"
# Defining the _decode_X methods and _property_decoder
signature = "data: typing.BinaryIO, property_size: int"
decode_names = {}
for prop_name, prop in self.all_props.items():
if prop.parse_code.endswith(".from_stream(data, property_size)"):
suffix_size = len("(data, property_size)")
decode_names[prop_name] = prop.parse_code[:-suffix_size]
else:
decode_names[prop_name] = f"_decode_{prop_name}"
self.after_class_code += f"def _decode_{prop_name}({signature}):\n"
self.after_class_code += f" return {prop.parse_code}\n\n\n"
decoder_type = "typing.Callable[[typing.BinaryIO, int], typing.Any]"
self.after_class_code += f"_property_decoder: typing.Dict[int, typing.Tuple[str, {decoder_type}]] = {{\n"
for prop_name, prop in self.all_props.items():
self.after_class_code += f" {hex(prop.id)}: ({repr(prop_name)}, {decode_names[prop_name]}),\n"
self.after_class_code += "}\n"
def write_to_stream(self):
self.class_code += """
def to_stream(self, data: typing.BinaryIO, default_override: dict | None = None) -> None:
default_override = default_override or {}
"""
endianness = get_endianness(self.game_id)
if self.has_custom_cook_pref:
assert self.game_id != "Prime"
if self.atomic or self.game_id == "Prime":
assert not self.has_custom_cook_pref
if self.game_id == "Prime" and self.is_struct:
num_props = len(self.all_props)
prop_count_repr = repr(struct.pack(endianness + "L", num_props))
self.class_code += f" data.write({prop_count_repr}) # {num_props} properties\n"
for prop_name, prop in self.all_props.items():
for build in prop.build_code:
self.class_code += f" {build.format(obj=f'self.{prop_name}')}\n"
return
# After here we don't need to worry about Prime (or atomic)
has_root_size_offset = False
if self.is_struct:
null_bytes = repr(b"\xff\xff\xff\xff")
self.class_code += f" data.write({null_bytes}) # struct object id\n"
placeholder = repr(b"\x00\x00")
self.class_code += " root_size_offset = data.tell()\n"
self.class_code += f" data.write({placeholder}) # placeholder for root struct size\n"
has_root_size_offset = True
elif self.has_custom_cook_pref:
self.class_code += " num_properties_offset = data.tell()\n"
if self.keep_unknown_properties():
self.class_code += f' data.write(struct.pack("{endianness}H", {self.property_count} + len(self.unknown_properties)))\n'
else:
prop_count_repr = repr(struct.pack(endianness + "H", self.property_count))
self.class_code += f" data.write({prop_count_repr}) # {self.property_count} properties\n"
if self.has_custom_cook_pref:
self.class_code += f" num_properties_written = {self.property_count}\n"
self.class_code += self.properties_builder
if self.keep_unknown_properties():
self.class_code += "\n for property_id, property_data in self.unknown_properties.items():\n"
self.class_code += (
f' data.write(struct.pack("{endianness}LH", property_id, len(property_data)))\n'
)
self.class_code += " data.write(property_data)\n"
num_props_variable = "num_properties_written + len(self.unknown_properties)"
else:
num_props_variable = "num_properties_written"
if has_root_size_offset:
self.class_code += "\n struct_end_offset = data.tell()\n"
self.class_code += " data.seek(root_size_offset)\n"
self.class_code += (
' data.write(struct.pack("' + endianness + 'H", struct_end_offset - root_size_offset - 2))\n'
)
if self.has_custom_cook_pref:
self.class_code += f' data.write(struct.pack("{endianness}H", {num_props_variable}))\n'
self.class_code += " data.seek(struct_end_offset)\n"
elif self.has_custom_cook_pref:
self.class_code += "\n"
self.class_code += f" if num_properties_written != {self.property_count}:\n"
self.class_code += " struct_end_offset = data.tell()\n"
self.class_code += " data.seek(num_properties_offset)\n"
self.class_code += f' data.write(struct.pack("{endianness}H", {num_props_variable}))\n'
self.class_code += " data.seek(struct_end_offset)\n"
def write_from_json(self):
self.class_code += """
@classmethod
def from_json(cls, data: json_util.JsonValue) -> typing_extensions.Self:
"""
data_var = "data"
if self.all_props:
data_var = "json_data"
self.class_code += f' json_data = typing.cast("{self.class_name}Json", data)\n'
self.type_checking_code.append(f"class {self.class_name}Json(typing_extensions.TypedDict):")
self.class_code += " return cls(\n"
space = " "
for prop_name, prop in self.all_props.items():
self.type_checking_code.append(f" {prop_name}: {prop.json_type}")
if prop.get_from_json(prop_name) == f"_from_json_{prop_name}":
self.before_class_code += (
f"def _from_json_{prop_name}(data: json_util.JsonValue) -> {prop.prop_type}:\n"
f" json_data = typing.cast({prop.json_type}, data)\n"
)
self.before_class_code += f" return {prop.from_json_code.format(obj=data_var)}\n\n"
self.class_code += (
f"{space}{prop_name}={prop.from_json_code.format(obj=f'{data_var}[{repr(prop_name)}]')},\n"
)
if self.all_props:
self.type_checking_code.append("")
if self.keep_unknown_properties():
self.needed_imports["base64"] = True
self.class_code += f"""{space}unknown_properties={{
int(property_id, 16): base64.b64decode(property_data)
for property_id, property_data in data["unknown_properties"].items()
}},
"""
self.class_code += " )\n"
def write_to_json(self):
self.class_code += """
def to_json(self) -> json_util.JsonObject:
return {
"""
space = " "
for prop_name, prop in self.all_props.items():
if prop.get_to_json(prop_name) == f"_to_json_{prop_name}":
self.before_class_code += f"\ndef _to_json_{prop_name}(obj: {prop.prop_type}) -> json_util.JsonValue:\n"
self.before_class_code += f" return {prop.to_json_code.format(obj='obj')}\n"
self.class_code += f"{space}{repr(prop_name)}: {prop.to_json_code.format(obj=f'self.{prop_name}')},\n"
if self.keep_unknown_properties():
self.needed_imports["base64"] = True
self.class_code += """
'unknown_properties': {
hex(property_id): base64.b64encode(property_data)
for property_id, property_data in self.unknown_properties.items()
}
"""
self.class_code += " }\n"
def write_dependencies(self):
if self.keep_unknown_properties() or self.game_id not in {"Prime", "Echoes"}:
return
has_dep = False
method_name = {}
for prop_name, prop in self.all_props.items():
if prop.dependency_code is None:
continue
has_dep = True
prop_code = prop.dependency_code.format(obj=f"self.{prop_name}")
if prop.dependency_code == "{obj}.dependencies_for(asset_manager)":
method_name[prop_name] = f"self.{prop_name}.dependencies_for"
else:
if prop.raw.get("ignore_dependencies_mlvl"):
self.needed_imports["retro_data_structures.base_resource"] = "Dependency"
prop_code = f"for it in {prop_code}:\n yield Dependency(it.type, it.id, True)"
else:
prop_code = f"yield from {prop_code}"
method_name[prop_name] = f"self._dependencies_for_{prop_name}"
self.class_code += f"""
def _dependencies_for_{prop_name}(self, asset_manager: AssetManager) -> typing.Iterator[Dependency]:
{prop_code}
"""
if has_dep:
method_list = "\n".join(
f' ({method_name[prop_name]}, "{prop_name}", "{prop.prop_type}"),'
for prop_name, prop in self.all_props.items()
if prop.dependency_code is not None
)
self.typing_imports["retro_data_structures.asset_manager"] = "AssetManager"
self.typing_imports["retro_data_structures.base_resource"] = "Dependency"
self.class_code += f"""
def dependencies_for(self, asset_manager: AssetManager) -> typing.Iterator[Dependency]:
for method, field_name, field_type in [
{method_list}
]:
try:
yield from method(asset_manager)
except Exception as e:
raise Exception(
f"Error finding dependencies for {self.class_name}.{{field_name}} ({{field_type}}): {{e}}"
)
"""
else:
self.class_code += """
def dependencies_for(self, asset_manager):
yield from []
"""
def _add_default_types(core_path: Path, game_id: str):
game_code = f"""
@classmethod
def game(cls) -> Game:
return Game.{_game_id_to_enum[game_id]}
"""
endianness = get_endianness(game_id)
core_path.joinpath("Color.py").write_text(
f"""# Generated file
import struct
import typing
import typing_extensions
from retro_data_structures.game_check import Game
from retro_data_structures.properties.base_color import BaseColor
class Color(BaseColor):
@classmethod
def from_stream(cls, data: typing.BinaryIO, size: int | None = None) -> typing_extensions.Self:
return cls(*struct.unpack('{endianness}ffff', data.read(16)))
def to_stream(self, data: typing.BinaryIO) -> None:
data.write(struct.pack('{endianness}ffff', self.r, self.g, self.b, self.a))
"""
+ game_code
)
core_path.joinpath("Vector.py").write_text(
f"""# Generated file
import struct
import typing
import typing_extensions
from retro_data_structures.game_check import Game
from retro_data_structures.properties.base_vector import BaseVector
class Vector(BaseVector):
@classmethod
def from_stream(cls, data: typing.BinaryIO, size: int | None = None) -> typing_extensions.Self:
return cls(*struct.unpack('{endianness}fff', data.read(12)))
def to_stream(self, data: typing.BinaryIO) -> None:
data.write(struct.pack('{endianness}fff', self.x, self.y, self.z))
"""
+ game_code
)
if game_id == "PrimeRemastered":
asset_code = "import uuid\n\nAssetId = uuid.UUID\ndefault_asset_id = uuid.UUID(int=0)\n"
else:
if game_id in ["Prime", "Echoes"]:
invalid_id = "0xFFFFFFFF"
else:
invalid_id = "0xFFFFFFFFFFFFFFFF"
asset_code = f"AssetId = int\ndefault_asset_id = {invalid_id}\n"
core_path.joinpath("AssetId.py").write_text(asset_code)
if game_id == "PrimeRemastered":
core_path.joinpath("PooledString.py").write_text(
f"""# Generated file
import dataclasses
import struct
import typing
import typing_extensions
from retro_data_structures import json_util
from retro_data_structures.game_check import Game
from retro_data_structures.properties.base_property import BaseProperty
from .AssetId import AssetId, default_asset_id
@dataclasses.dataclass()
class PooledString(BaseProperty):
index: int = -1
size_or_str: typing.Union[int, bytes] = b""
@classmethod
def from_stream(cls, data: typing.BinaryIO, size: int | None = None) -> typing_extensions.Self:
a, b = struct.unpack('{endianness}lL', data.read(8))
if a == -1:
b = data.read(b)
return cls(a, b)
def to_stream(self, data: typing.BinaryIO) -> None:
a, b = self.index, self.size_or_str
if a == -1:
b = len(b)
data.write(struct.pack('{endianness}lL', a, b))
if a == -1:
data.write(self.size_or_str)
@classmethod
def from_json(cls, data: json_util.JsonValue) -> typing_extensions.Self:
return cls(data["index"], data["size_or_str"])
def to_json(self) -> json_util.JsonObject:
return {{
"index": self.index,
"size_or_str": self.size_or_str,
}}
"""
+ game_code
)
return
if game_id in ["Prime", "Echoes"]:
format_specifier = "L"
known_size = 12
else:
format_specifier = "Q"