summaryrefslogtreecommitdiff
path: root/tools/assets/descriptor/base.py
blob: 320d9101d87967e8f8af87162efef766700ddc0f (plain)
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
# SPDX-FileCopyrightText: © 2025 ZeldaRET
# SPDX-License-Identifier: CC0-1.0

import abc
import dataclasses
from functools import cache
from pathlib import Path
import re
from typing import Callable, Optional
from xml.etree import ElementTree

from tools import version_config


class BackingMemory(abc.ABC):
    pass


@dataclasses.dataclass
class BaseromFileBackingMemory(BackingMemory):
    name: str
    range: Optional[tuple[int, int]]
    """If set, consider file_data[range[0]:range[1]] instead of the full file"""


@dataclasses.dataclass
class NoBackingMemory(BackingMemory):
    pass


class ResourceHasNoSizeError(Exception):
    pass


# eq=False so this uses id-based equality and hashing
# Subclasses must also be made to use id-based equality and hashing
@dataclasses.dataclass(eq=False)
class ResourceDesc(abc.ABC):
    """A resource is a data unit.
    For example, a symbol's data such as a DList or a texture."""

    symbol_name: str
    offset: int
    """How many bytes into the backing memory the resource is located at"""
    collection: "ResourcesDescCollection" = dataclasses.field(repr=False)
    origin: object
    """opaque object with data about where this resource comes from (for debugging)"""

    hack_modes: set[str] = dataclasses.field(init=False, default_factory=set)

    def get_size(self) -> int:
        raise ResourceHasNoSizeError()


class StartAddress(abc.ABC):
    pass


@dataclasses.dataclass
class VRAMStartAddress(StartAddress):
    vram: int


@dataclasses.dataclass
class SegmentStartAddress(StartAddress):
    segment: int


@dataclasses.dataclass(eq=False)
class ResourcesDescCollection:
    """A collection is a list of resources backed by the same memory."""

    out_path: Path
    backing_memory: BackingMemory
    start_address: Optional[StartAddress]
    resources: list[ResourceDesc]
    last_modified_time: float
    depends: list["ResourcesDescCollection"]


@dataclasses.dataclass(eq=False)
class ResourcesDescCollectionsPool:
    """A pool contains a minimal set of interconnected collections.
    For example, gkeep and all files using gkeep,
    or more simply a single collection with no connection."""

    collections: list[ResourcesDescCollection]


ResourceHandlerPass2Callback = Callable[[ResourcesDescCollectionsPool], None]


@dataclasses.dataclass
class ResourceHandlerNeedsPass2Exception(Exception):
    resource: ResourceDesc
    pass2_callback: ResourceHandlerPass2Callback


# eq=False so this uses id-based equality and hashing
@dataclasses.dataclass(eq=False)
class AssetConfigPiece:
    ac: version_config.AssetConfig
    last_modified_time: float = None
    etree: ElementTree.ElementTree = None
    depends: list["AssetConfigPiece"] = dataclasses.field(default_factory=list)
    """The AssetConfigPiece s this instance depends on"""
    collections: list[ResourcesDescCollection] = dataclasses.field(default_factory=list)


def get_resources_desc(vc: version_config.VersionConfig):
    # Wrap AssetConfig objects in AssetConfigPiece for hashability and to collect data
    acps = [AssetConfigPiece(ac) for ac in vc.assets]

    # Parse xmls
    for acp in acps:
        acp.last_modified_time = acp.ac.xml_path.stat().st_mtime
        try:
            with acp.ac.xml_path.open(encoding="UTF-8") as f:
                etree = ElementTree.parse(f)
            acp.etree = etree
        except Exception as e:
            raise Exception(f"Error when parsing XML for {acp}") from e

    # Resolve pools
    acp_by_name = {acp.ac.name: acp for acp in acps}
    pools = {acp: {acp} for acp in acps}
    for acp in acps:
        try:
            rootelem = acp.etree.getroot()
            assert rootelem.tag == "Root", rootelem.tag
            for fileelem in rootelem:
                assert fileelem.tag in {"ExternalFile", "File"}, fileelem.tag
                if fileelem.tag == "ExternalFile":
                    externalfile_name = str(
                        Path(fileelem.attrib["OutPath"]).relative_to("assets")
                    )
                    assert externalfile_name in acp_by_name, externalfile_name
                    externalfile_acp = acp_by_name[externalfile_name]
                    acp.depends.append(externalfile_acp)
                    acp_pool = pools[acp]
                    externalfile_acp_pool = pools[externalfile_acp]
                    merged_pool = acp_pool | externalfile_acp_pool
                    for merged_pool_acp in merged_pool:
                        pools[merged_pool_acp] = merged_pool
        except Exception as e:
            raise Exception(f"Error while resolving pools with {acp}") from e

    # List unique pools
    pools_unique: list[set[AssetConfigPiece]] = []
    while pools:
        pool = next(iter(pools.values()))
        pools_unique.append(pool)
        for acp in pool:
            del pools[acp]

    # Build resources for all pools
    pools: list[ResourcesDescCollectionsPool] = []
    for pool in pools_unique:
        try:
            all_needs_pass2_exceptions: list[ResourceHandlerNeedsPass2Exception] = []
            rescolls: list[ResourcesDescCollection] = []

            # Pass 1: create Resource objects
            for acp in pool:
                try:
                    rootelem = acp.etree.getroot()
                    for fileelem in rootelem:
                        if fileelem.tag == "File":
                            rc, needs_pass2_exceptions = (
                                _get_resources_fileelem_to_resourcescollection_pass1(
                                    vc, pool, acp, fileelem
                                )
                            )
                            acp.collections.append(rc)
                            rescolls.append(rc)
                            all_needs_pass2_exceptions.extend(needs_pass2_exceptions)
                except Exception as e:
                    raise Exception(f"Error with {acp}") from e

            rcpool = ResourcesDescCollectionsPool(rescolls)

            #
            for acp in pool:
                for acp_coll in acp.collections:
                    acp_coll.depends.extend(
                        (_coll for _coll in acp.collections if _coll != acp_coll)
                    )
                    for acp_dep in acp.depends:
                        acp_coll.depends.extend(acp_dep.collections)

            # Pass 2: execute callbacks
            for needs_pass2_exc in all_needs_pass2_exceptions:
                try:
                    needs_pass2_exc.pass2_callback(rcpool)
                except Exception as e:
                    raise Exception(
                        f"Error with pass 2 callback for {needs_pass2_exc.resource}"
                    ) from e

            pools.append(rcpool)

        except Exception as e:
            raise Exception(f"Error with pool {pool}") from e

    return pools


def _get_version_resources(fileelem: ElementTree.Element, version: str):
    for reselem in fileelem:
        if reselem.tag == "Version":
            if re.fullmatch(reselem.attrib["Pattern"], version):
                yield from reselem
        else:
            yield reselem


def _get_resources_fileelem_to_resourcescollection_pass1(
    vc: version_config.VersionConfig,
    pool: list[AssetConfigPiece],
    acp: AssetConfigPiece,
    fileelem: ElementTree.Element,
):
    # Determine backing_memory
    if acp.ac.start_offset is None:
        assert acp.ac.end_offset is None
        baserom_file_range = None
    else:
        assert acp.ac.end_offset is not None
        baserom_file_range = (acp.ac.start_offset, acp.ac.end_offset)
    backing_memory = BaseromFileBackingMemory(
        name=fileelem.attrib["Name"],
        range=baserom_file_range,
    )

    # Determine start_address
    if any(
        acp.ac.name.startswith(_prefix) for _prefix in ("code/", "n64dd/", "overlays/")
    ):
        # File start address is vram
        assert "Segment" not in fileelem.attrib
        assert acp.ac.start_offset is not None and acp.ac.end_offset is not None, (
            "Unsupported combination: "
            f"start/end offset not in config for vram asset {acp.ac.name}"
        )
        if acp.ac.name.startswith("overlays/"):
            overlay_name = acp.ac.name.split("/")[1]
            start_address = VRAMStartAddress(
                vc.dmadata_segments[overlay_name].vram + acp.ac.start_offset
            )
        else:
            file_name = acp.ac.name.split("/")[0]  # "code" or "n64dd"
            start_address = VRAMStartAddress(
                vc.dmadata_segments[file_name].vram + acp.ac.start_offset
            )
    elif "Segment" in fileelem.attrib:
        # File start address is a segmented address
        assert acp.ac.start_offset is None and acp.ac.end_offset is None, (
            "Unsupported combination: "
            "start/end offset in config and file starts at a segmented address"
        )
        start_address = SegmentStartAddress(int(fileelem.attrib["Segment"]))
    else:
        # File does not have a start address
        start_address = None

    # resources
    resources: list[ResourceDesc] = []
    collection = ResourcesDescCollection(
        Path(acp.ac.name),
        backing_memory,
        start_address,
        resources,
        acp.last_modified_time,
        [],
    )
    needs_pass2_exceptions: list[ResourceHandlerNeedsPass2Exception] = []

    prev_resource_end_offset = 0

    for reselem in _get_version_resources(fileelem, vc.version):
        try:
            symbol_name = reselem.attrib["Name"]
            if "Offset" in reselem.attrib:
                offset_str = reselem.attrib["Offset"]
                if offset_str.startswith(".+"):
                    if prev_resource_end_offset is None:
                        raise Exception(
                            f"Resource {symbol_name} has a relative Offset"
                            " and previous resource has no known end offset"
                        )
                    rel_offset = int(offset_str.removeprefix(".+"), 16)
                    offset = prev_resource_end_offset + rel_offset
                else:
                    offset = int(offset_str, 16)
            else:
                if prev_resource_end_offset is None:
                    raise Exception(
                        f"Resource {symbol_name} has no Offset"
                        " and previous resource has no known end offset"
                    )
                offset = prev_resource_end_offset
            res_handler = _get_resource_handler(reselem.tag)
            try:
                res = res_handler(symbol_name, offset, collection, reselem)
            except ResourceHandlerNeedsPass2Exception as needs_pass2_exc:
                res = needs_pass2_exc.resource
                needs_pass2_exceptions.append(needs_pass2_exc)
            assert isinstance(res, ResourceDesc)
            resources.append(res)
            try:
                prev_resource_end_offset = res.offset + res.get_size()
            except ResourceHasNoSizeError:
                prev_resource_end_offset = None
        except Exception as e:
            raise Exception(
                "Error with resource element:\n"
                + ElementTree.tostring(reselem, encoding="unicode")
            ) from e

    return collection, needs_pass2_exceptions


ResourceHandler = Callable[
    [str, int, ResourcesDescCollection, ElementTree.Element],
    ResourceDesc,
]


@cache
def _get_resource_handler(tag: str) -> ResourceHandler:
    from . import n64resources
    from . import z64resources

    resource_handlers = {
        "DList": n64resources.handler_DList,
        "Blob": n64resources.handler_Blob,
        "Mtx": n64resources.handler_Mtx,
        "Array": n64resources.handler_Array,
        "Texture": n64resources.handler_Texture,
        "Collision": z64resources.handler_Collision,
        "Animation": z64resources.handler_Animation,
        "PlayerAnimation": z64resources.handler_PlayerAnimation,
        "LegacyAnimation": z64resources.handler_LegacyAnimation,
        "Cutscene": z64resources.handler_Cutscene,
        "Scene": z64resources.handler_Scene,
        "Room": z64resources.handler_Room,
        "PlayerAnimationData": z64resources.handler_PlayerAnimationData,
        "Path": z64resources.handler_PathList,
        "Skeleton": z64resources.handler_Skeleton,
        "Limb": z64resources.handler_Limb,
        "CurveAnimation": z64resources.handler_CurveAnimation,
        "LimbTable": z64resources.handler_LimbTable,
    }

    rh = resource_handlers.get(tag)

    if rh is None:
        raise Exception(f"Unknown resource tag {tag}")
    else:
        return rh