aboutsummaryrefslogtreecommitdiff
path: root/tools/map.py
blob: d4a23a011f8d56431071a18840fcfb382a2e9a3f (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
#!/usr/bin/env python3

from argparse import ArgumentParser
import subprocess
import os
import json

__version__ = "1.0"

ld = os.environ.get("LD", "i586-pc-msdosdjgpp-ld")
strip = os.environ.get("STRIP", "i586-pc-msdosdjgpp-strip")


def get_layer(data, name):
    for layer in data["layers"]:
        if layer["name"] == name:
            return layer
    raise ValueError("Layer %s not found" % name)


def main():
    parser = ArgumentParser(
        description="Tiled JSON Map to .o",
        epilog="Copyright (C) 2023 Juan J Martinez <jjm@usebox.net>",
    )

    parser.add_argument(
        "--version", action="version", version="%(prog)s " + __version__
    )
    parser.add_argument("file_json", help="JSON map to convert")
    parser.add_argument("output", help="object name for the map data")

    args = parser.parse_args()

    with open(args.file_json, "rt") as fd:
        data = json.load(fd)

    if len(data["tilesets"]) != 1:
        parser.error("Unsupported number of tilesets %d" % len(data["tilesets"]))

    tileset = data["tilesets"][0]

    map_layer = get_layer(data, "Map")

    out = list(map(lambda x: (x - tileset["firstgid"]) & 0xFF, map_layer["data"]))

    gold_layer = get_layer(data, "Gold")
    out.extend(map(lambda x: (x - tileset["firstgid"]) & 0xFF, gold_layer["data"]))

    # TODO: process map entities

    tmp = args.output.rstrip(".o")
    with open(tmp, "wb") as fd:
        fd.write(bytearray(out))
        fd.flush()

        # create an object file from the binary
        rc = subprocess.call(
            [
                ld,
                "-r",
                "-b",
                "binary",
                "-o",
                args.output,
                tmp,
            ]
        )
        os.unlink(tmp)
        if rc != 0:
            parser.error("Failed to run %s" % ld)

        # strip unwanted symbols
        rc = subprocess.call([strip, "-w", "-K", "*_%s_*" % tmp, args.output])
        if rc != 0:
            parser.error("Failed to run %s" % ld)


if __name__ == "__main__":
    main()