Files

112 lines
5.7 KiB
Python

# LDtk fixtures (tools/fixtures.py): the sample projects shipped with LDtk 1.5.3 (MIT; extraFiles/samples inside
# the nixpkgs ldtk AppImage, read there and never committed), including SeparateLevelFiles (.ldtkl external levels),
# plus a multi-world project made here from Typical_TopDown_example (its levels split over two worlds). Reference
# values are read from the LDtk JSON by Python (the editor's own export: __cWid / __identifier / tile and entity
# lists). Then our encoder's output (tools/fixtures/_ldtk_encode.luau) is summarised the same way.
# tests/gen/ldtk.luau { cases = { { name, data, files = { [relPath] = bytes }, stats } } }
# tests/gen/ldtk_ours.luau { { name, stats } }
# stats: { levels = { { identifier, worldX, worldY, pxWid, pxHei, world, fields, layers = { { identifier, type, cWid,
# cHei, grid, tiles, tileSum, flips, intCount, intSum, entities, entityNames, entityPx } } } }, tilesets = { names } }
import copy, importlib.util, json, os, subprocess, tempfile, zlib
INPUTS = ["src/Rosetta/vector/ldtk", "tools/fixtures/_ldtk_encode.luau", "tools/fixtures/_model_ref.py"]
SAMPLES = ["Test_file_for_API_showing_all_features.ldtk", "Typical_2D_platformer_example.ldtk", "Typical_TopDown_example.ldtk",
"Entities.ldtk", "AutoLayers_1_basic.ldtk", "AutoLayers_2_stamps.ldtk", "AutoLayers_4_Assistant.ldtk",
"AutoLayers_5_Advanced.ldtk", "SeparateLevelFiles.ldtk", "WorldMap_Free_layout.ldtk"]
def samples_dir(ctx):
store = subprocess.run(["nix", "build", "nixpkgs#ldtk", "--no-link", "--print-out-paths"], capture_output=True, check=True).stdout.decode().split()[-1]
image = os.path.join(store, "share", "ldtk.AppImage")
out = os.path.join(tempfile.gettempdir(), "rosetta-ldtk-" + os.path.basename(store))
target = os.path.join(out, "sq", "extraFiles", "samples")
if os.path.isdir(target):
return target
os.makedirs(out, exist_ok=True)
data = open(image, "rb").read()
at = 0
while True:
at = data.find(b"hsqs", at + 1)
if at < 0:
raise RuntimeError("no squashfs in the LDtk AppImage")
try:
ctx.nix("squashfsTools", ["unsquashfs", "-q", "-f", "-o", str(at), "-d", os.path.join(out, "sq"), image, "extraFiles/samples"])
if os.path.isdir(target):
return target
except subprocess.CalledProcessError:
pass
def stats(project, files):
def levels_of(p):
if p.get("worlds"):
for w in p["worlds"]:
for lv in w["levels"]:
yield w["identifier"], lv
else:
for lv in p["levels"]:
yield "", lv
out = []
for world, lv in levels_of(project):
if lv.get("layerInstances") is None and lv.get("externalRelPath"):
lv = json.loads(files[lv["externalRelPath"]])
layers = []
for li in reversed(lv["layerInstances"] or []):
tl = li["gridTiles"] if li["__type"] == "Tiles" else li["autoLayerTiles"]
ents = li["entityInstances"]
ints = li["intGridCsv"]
layers.append({
"identifier": li["__identifier"], "type": li["__type"], "cWid": li["__cWid"], "cHei": li["__cHei"],
"grid": li["__gridSize"], "tiles": len(tl), "tileSum": sum(t["t"] * (i % 7 + 1) for i, t in enumerate(tl)),
"flips": sum(1 for t in tl if t["f"]), "intCount": sum(1 for v in ints if v), "intSum": sum(ints),
"entities": len(ents), "entityNames": ",".join(e["__identifier"] for e in ents),
"entityPx": sum(e["px"][0] * 3 + e["px"][1] for e in ents),
})
out.append({"identifier": lv["identifier"], "worldX": lv["worldX"], "worldY": lv["worldY"], "pxWid": lv["pxWid"],
"pxHei": lv["pxHei"], "world": world, "fields": len(lv["fieldInstances"]), "layers": layers})
return {"levels": out, "tilesets": [t["identifier"] for t in project["defs"]["tilesets"]]}
def multiworld(project):
p = copy.deepcopy(project)
lv = p["levels"]
half = max(1, len(lv) // 2)
p["worlds"] = [
{"iid": "a0000000-0000-4000-8000-000000000001", "identifier": "Overworld", "worldGridWidth": 256, "worldGridHeight": 256,
"worldLayout": "Free", "levels": lv[:half]},
{"iid": "a0000000-0000-4000-8000-000000000002", "identifier": "Caves", "worldGridWidth": 256, "worldGridHeight": 256,
"worldLayout": "Free", "levels": lv[half:]},
]
p["levels"] = []
p["flags"] = sorted(set(p.get("flags", [])) | {"MultiWorlds"})
p["worldLayout"] = None
return p
def generate(ctx):
d = samples_dir(ctx)
cases = []
for name in SAMPLES:
raw = open(os.path.join(d, name), "rb").read()
project = json.loads(raw)
files = {}
for lv in project["levels"]:
rel = lv.get("externalRelPath")
if rel:
files[rel] = open(os.path.join(d, rel), "rb").read()
cases.append({"name": name, "data": raw, "files": files, "stats": stats(project, files)})
top = json.loads(open(os.path.join(d, "Typical_TopDown_example.ldtk"), "rb").read())
mw = multiworld(top)
cases.append({"name": "multiworld.ldtk", "data": json.dumps(mw, indent=1).encode(), "files": {}, "stats": stats(mw, {})})
ctx.emit("ldtk", {"cases": cases})
spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py"))
M = importlib.util.module_from_spec(spec)
spec.loader.exec_module(M)
ours = []
for name, data in sorted(M.luau_encode(ctx, "tools/fixtures/_ldtk_encode.luau").items()):
p = json.loads(data)
ours.append({"name": name, "stats": stats(p, {})})
ctx.emit("ldtk_ours", ours)