280 lines
11 KiB
Python
280 lines
11 KiB
Python
# Tiled fixtures (tools/fixtures.py), with Tiled itself (nixpkgs#tiled, run headless) as the reference:
|
|
# tests/gen/tiled.luau { cases = { { name, tmx (hand-written), tmj (Tiled's export), tiled_tmx (Tiled's re-save) } },
|
|
# tsx, tsj (an external tileset and Tiled's JSON export of it) }
|
|
# tests/gen/tiled_ours.luau { checks = { { label, ok } } }: a map built and written by our encoder (TMX with
|
|
# base64 + zlib data, and TMJ; tools/fixtures/_ours.luau) re-exported by Tiled as JSON and
|
|
# compared with our own TMJ
|
|
import base64, gzip, json, os, shutil, struct, subprocess, tempfile, zlib
|
|
|
|
INPUTS = ["src/Rosetta/vector/tiled", "tools/fixtures/_ours.luau"]
|
|
|
|
TSX = """<?xml version="1.0" encoding="UTF-8"?>
|
|
<tileset version="1.10" tiledversion="1.10.2" name="ext" tilewidth="16" tileheight="16" spacing="0" margin="0" tilecount="8" columns="4">
|
|
<tileoffset x="2" y="-3"/>
|
|
<properties>
|
|
<property name="kind" value="terrain"/>
|
|
</properties>
|
|
<image source="tiles.png" width="64" height="32"/>
|
|
<tile id="1" type="Water" probability="0.5">
|
|
<properties>
|
|
<property name="speed" type="float" value="0.25"/>
|
|
</properties>
|
|
<animation>
|
|
<frame tileid="1" duration="100"/>
|
|
<frame tileid="2" duration="150"/>
|
|
</animation>
|
|
</tile>
|
|
<tile id="5">
|
|
<objectgroup draworder="index" id="2">
|
|
<object id="1" x="1" y="2" width="10" height="12"/>
|
|
<object id="2" x="3" y="3">
|
|
<ellipse/>
|
|
</object>
|
|
</objectgroup>
|
|
</tile>
|
|
</tileset>
|
|
"""
|
|
|
|
|
|
def layer_bytes(gids):
|
|
return b"".join(struct.pack("<I", g) for g in gids)
|
|
|
|
|
|
def ortho():
|
|
W, H = 6, 4
|
|
g1 = [(x + y * W) % 9 for y in range(H) for x in range(W)]
|
|
g1[3] |= 0x80000000
|
|
g1[7] |= 0x40000000
|
|
g1[11] |= 0x20000000
|
|
g2 = [(x * y) % 5 for y in range(H) for x in range(W)]
|
|
g3 = [9 + (x + y) % 8 if (x + y) % 3 else 0 for y in range(H) for x in range(W)]
|
|
g4 = [1 + (x % 2) for y in range(H) for x in range(W)]
|
|
csv = ",\n".join(",".join(str(g) for g in g1[y * W:(y + 1) * W]) for y in range(H))
|
|
z = base64.b64encode(zlib.compress(layer_bytes(g2))).decode()
|
|
gz = base64.b64encode(gzip.compress(layer_bytes(g3), mtime=0)).decode()
|
|
raw = base64.b64encode(layer_bytes(g4)).decode()
|
|
return f"""<?xml version="1.0" encoding="UTF-8"?>
|
|
<map version="1.10" tiledversion="1.10.2" class="Level" orientation="orthogonal" renderorder="left-up" width="{W}" height="{H}" tilewidth="16" tileheight="16" backgroundcolor="#ff102030" infinite="0" nextlayerid="9" nextobjectid="10">
|
|
<properties>
|
|
<property name="title" value="Ünïcode & more"/>
|
|
<property name="count" type="int" value="42"/>
|
|
<property name="ratio" type="float" value="1.5"/>
|
|
<property name="on" type="bool" value="true"/>
|
|
<property name="tint" type="color" value="#80ff0000"/>
|
|
<property name="file" type="file" value="other.tmx"/>
|
|
<property name="target" type="object" value="3"/>
|
|
<property name="notes">line one
|
|
line two</property>
|
|
</properties>
|
|
<tileset firstgid="1" name="inner" tilewidth="16" tileheight="16" spacing="0" margin="0" tilecount="8" columns="4">
|
|
<image source="tiles.png" width="64" height="32"/>
|
|
<tile id="0">
|
|
<properties>
|
|
<property name="solid" type="bool" value="true"/>
|
|
</properties>
|
|
</tile>
|
|
<tile id="3" type="Door"/>
|
|
</tileset>
|
|
<tileset firstgid="9" source="ext.tsx"/>
|
|
<layer id="1" name="csv" width="{W}" height="{H}" opacity="0.75" offsetx="3" offsety="-2" tintcolor="#ff00ff">
|
|
<properties>
|
|
<property name="layerprop" value="x"/>
|
|
</properties>
|
|
<data encoding="csv">
|
|
{csv}
|
|
</data>
|
|
</layer>
|
|
<layer id="2" name="zlib" width="{W}" height="{H}" visible="0" parallaxx="0.5">
|
|
<data encoding="base64" compression="zlib">
|
|
{z}
|
|
</data>
|
|
</layer>
|
|
<layer id="3" name="gzip" width="{W}" height="{H}" locked="1">
|
|
<data encoding="base64" compression="gzip">
|
|
{gz}
|
|
</data>
|
|
</layer>
|
|
<layer id="4" name="raw" class="Deco" width="{W}" height="{H}">
|
|
<data encoding="base64">
|
|
{raw}
|
|
</data>
|
|
</layer>
|
|
<group id="5" name="group" opacity="0.5" offsetx="1">
|
|
<imagelayer id="6" name="sky" repeatx="1">
|
|
<image source="sky.png" width="40" height="20"/>
|
|
</imagelayer>
|
|
<objectgroup id="7" name="things" color="#a0a0a4" draworder="index">
|
|
<object id="1" name="box" type="Crate" x="10" y="12.5" width="16" height="8" rotation="45">
|
|
<properties>
|
|
<property name="weight" type="float" value="2.25"/>
|
|
</properties>
|
|
</object>
|
|
<object id="2" name="ring" x="40" y="5" width="10" height="10">
|
|
<ellipse/>
|
|
</object>
|
|
<object id="3" name="spot" x="7" y="9">
|
|
<point/>
|
|
</object>
|
|
<object id="4" name="poly" x="20" y="20">
|
|
<polygon points="0,0 16,0 8,-12.5"/>
|
|
</object>
|
|
<object id="5" name="line" x="30" y="30" visible="0">
|
|
<polyline points="0,0 5,5 10,0 15,5"/>
|
|
</object>
|
|
<object id="6" name="label" x="2" y="40" width="80" height="20">
|
|
<text fontfamily="Serif" pixelsize="12" wrap="1" color="#ff0000" bold="1" halign="center" valign="bottom">Hello <Tiled></text>
|
|
</object>
|
|
<object id="7" name="tile" gid="2147483651" x="50" y="50" width="16" height="16"/>
|
|
</objectgroup>
|
|
</group>
|
|
</map>
|
|
"""
|
|
|
|
|
|
def iso():
|
|
W, H = 3, 3
|
|
tiles = "\n".join(' <tile gid="%d"/>' % ((x + y) % 4) for y in range(H) for x in range(W))
|
|
return f"""<?xml version="1.0" encoding="UTF-8"?>
|
|
<map version="1.10" tiledversion="1.10.2" orientation="hexagonal" renderorder="right-down" width="{W}" height="{H}" tilewidth="32" tileheight="28" infinite="0" hexsidelength="14" staggeraxis="x" staggerindex="even" nextlayerid="2" nextobjectid="1">
|
|
<tileset firstgid="1" name="inner" tilewidth="16" tileheight="16" tilecount="8" columns="4">
|
|
<image source="tiles.png" width="64" height="32"/>
|
|
</tileset>
|
|
<layer id="1" name="xmltiles" width="{W}" height="{H}">
|
|
<data>
|
|
{tiles}
|
|
</data>
|
|
</layer>
|
|
</map>
|
|
"""
|
|
|
|
|
|
def infinite():
|
|
def chunk(cx, cy):
|
|
g = [(cx // 16 + cy // 16 + x + y) % 5 for y in range(16) for x in range(16)]
|
|
rows = ",\n".join(",".join(str(v) for v in g[y * 16:(y + 1) * 16]) for y in range(16))
|
|
return f' <chunk x="{cx}" y="{cy}" width="16" height="16">\n{rows}\n</chunk>'
|
|
# Tiled's canonical layout: chunks by row, the layer's size = the chunks' bounds
|
|
chunks = "\n".join(chunk(cx, cy) for cx, cy in ((16, -16), (-16, 0), (0, 0)))
|
|
return f"""<?xml version="1.0" encoding="UTF-8"?>
|
|
<map version="1.10" tiledversion="1.10.2" orientation="orthogonal" renderorder="right-down" width="30" height="20" tilewidth="16" tileheight="16" infinite="1" nextlayerid="2" nextobjectid="1">
|
|
<tileset firstgid="1" name="inner" tilewidth="16" tileheight="16" tilecount="8" columns="4">
|
|
<image source="tiles.png" width="64" height="32"/>
|
|
</tileset>
|
|
<layer id="1" name="chunks" width="48" height="32">
|
|
<data encoding="csv">
|
|
{chunks}
|
|
</data>
|
|
</layer>
|
|
</map>
|
|
"""
|
|
|
|
|
|
def tiled(ctx, argv, cwd):
|
|
env = dict(os.environ, QT_QPA_PLATFORM="offscreen")
|
|
if shutil.which("tiled"):
|
|
subprocess.run(["tiled"] + argv, check=True, capture_output=True, cwd=cwd, env=env)
|
|
else:
|
|
subprocess.run(["nix", "shell", "nixpkgs#tiled", "-c", "tiled"] + argv, check=True, capture_output=True, cwd=cwd, env=env)
|
|
|
|
|
|
def magick(ctx, argv):
|
|
try:
|
|
subprocess.run(argv, check=True, capture_output=True)
|
|
except (OSError, subprocess.CalledProcessError):
|
|
ctx.nix("imagemagick", argv)
|
|
|
|
|
|
def workdir(ctx, d):
|
|
magick(ctx, ["magick", "-size", "64x32", "gradient:red-blue", os.path.join(d, "tiles.png")])
|
|
magick(ctx, ["magick", "-size", "40x20", "xc:skyblue", os.path.join(d, "sky.png")])
|
|
open(os.path.join(d, "ext.tsx"), "w").write(TSX)
|
|
|
|
|
|
def run_ours(ctx, fmt):
|
|
script = os.path.join(ctx.root, "tools", "fixtures", "_ours.luau")
|
|
luau = shutil.which("luau")
|
|
argv = [luau, script, "-a", fmt] if luau else ["nix", "shell", "nixpkgs#luau", "-c", "luau", script, "-a", fmt]
|
|
return json.loads(subprocess.run(argv, check=True, capture_output=True, cwd=ctx.root).stdout)
|
|
|
|
|
|
def gids(layer):
|
|
"""a JSON tile layer's gids (arrays, or base64 with compression) -> list"""
|
|
d = layer.get("data")
|
|
if isinstance(d, str):
|
|
raw = base64.b64decode(d)
|
|
c = layer.get("compression", "")
|
|
raw = zlib.decompress(raw) if c == "zlib" else gzip.decompress(raw) if c == "gzip" else raw
|
|
return list(struct.unpack("<%dI" % (len(raw) // 4), raw))
|
|
return d
|
|
|
|
|
|
IGNORE = {"version", "tiledversion", "compressionlevel", "encoding", "compression", "opacity_obj"}
|
|
|
|
|
|
DEFAULTS = {"offsetx": 0, "offsety": 0, "parallaxx": 1, "parallaxy": 1, "locked": False}
|
|
|
|
|
|
def norm(v, obj=False):
|
|
"""a JSON map without the fields that only say which Tiled wrote it, or that hold defaults"""
|
|
if isinstance(v, dict):
|
|
out = {}
|
|
if v.get("type") == "tilelayer" and "data" in v:
|
|
v = dict(v, data=gids(v))
|
|
for k, x in v.items():
|
|
if k in IGNORE or (k in DEFAULTS and x == DEFAULTS[k]) or (obj and k == "opacity"):
|
|
continue
|
|
out[k] = [norm(o, True) for o in x] if k == "objects" else norm(x)
|
|
return out
|
|
if isinstance(v, list):
|
|
return [norm(x) for x in v]
|
|
if isinstance(v, float) and v.is_integer():
|
|
return int(v)
|
|
return v
|
|
|
|
|
|
def diff(a, b, path="", out=None):
|
|
out = [] if out is None else out
|
|
if isinstance(a, dict) and isinstance(b, dict):
|
|
for k in sorted(set(a) | set(b)):
|
|
if k not in a or k not in b:
|
|
out.append("%s.%s: %s vs %s" % (path, k, a.get(k, "<missing>"), b.get(k, "<missing>")))
|
|
else:
|
|
diff(a[k], b[k], path + "." + k, out)
|
|
elif isinstance(a, list) and isinstance(b, list):
|
|
if len(a) != len(b):
|
|
out.append("%s: length %d vs %d" % (path, len(a), len(b)))
|
|
for i, (x, y) in enumerate(zip(a, b)):
|
|
diff(x, y, "%s[%d]" % (path, i), out)
|
|
elif a != b:
|
|
out.append("%s: %r vs %r" % (path, a, b))
|
|
return out
|
|
|
|
|
|
def generate(ctx):
|
|
cases = []
|
|
with tempfile.TemporaryDirectory() as d:
|
|
workdir(ctx, d)
|
|
for name, text in (("ortho", ortho()), ("hex", iso()), ("infinite", infinite())):
|
|
open(os.path.join(d, name + ".tmx"), "w").write(text)
|
|
tiled(ctx, ["--export-map", name + ".tmx", name + "-out.tmj"], d)
|
|
tiled(ctx, ["--export-map", name + ".tmx", name + "-out.tmx"], d)
|
|
cases.append({"name": name, "tmx": text, "tmj": open(os.path.join(d, name + "-out.tmj"), "rb").read(),
|
|
"tiled_tmx": open(os.path.join(d, name + "-out.tmx"), "rb").read()})
|
|
tiled(ctx, ["--export-tileset", "ext.tsx", "ext.tsj"], d)
|
|
tsj = open(os.path.join(d, "ext.tsj"), "rb").read()
|
|
ctx.emit("tiled", {"cases": cases, "tsx": TSX, "tsj": tsj})
|
|
|
|
# our encoder's files, read by Tiled
|
|
o = run_ours(ctx, "tiled")
|
|
open(os.path.join(d, "ours.tmx"), "wb").write(bytes.fromhex(o["tmx"]))
|
|
open(os.path.join(d, "ours.tmj"), "wb").write(bytes.fromhex(o["tmj"]))
|
|
tiled(ctx, ["--export-map", "ours.tmx", "ours-from-tmx.tmj"], d)
|
|
tiled(ctx, ["--export-map", "ours.tmj", "ours-from-tmj.tmj"], d)
|
|
mine = norm(json.loads(bytes.fromhex(o["tmj"])))
|
|
checks = []
|
|
for label, f in (("Tiled on our TMX", "ours-from-tmx.tmj"), ("Tiled on our TMJ", "ours-from-tmj.tmj")):
|
|
theirs = norm(json.load(open(os.path.join(d, f))))
|
|
dd = diff(mine, theirs)
|
|
checks.append({"label": label + (": " + "; ".join(dd[:5]) if dd else ""), "ok": not dd})
|
|
ctx.emit("tiled_ours", {"checks": checks})
|