vector/ldtk: LDtk projects read + write as a TileMap (levels as groups, worlds, IntGrid / auto / tile / entity layers, fields, external levels through resolve)

This commit is contained in:
4DBug committed 2026-11-01 18:49:26 -06:00
1 parent 524179ec67
commit 1f74419ccf
11 files changed
+1557 -6

No files matched your search

+30
View File
@@ -0,0 +1,30 @@
-- tools/fixtures/_ldtk_encode: run by tools/fixtures/ldtk.py (luau CLI, repo root): decodes every LDtk case (external
-- levels through resolve) and writes it with our encoder, printing "<name>\t<hex>" lines for Python to summarise.
local Ldtk = require("@rosetta/vector/ldtk")
local Bytes = require("@rosetta/core/Bytes")
local Fx = require("@tests/gen/ldtk")
local HEX = {}
for i = 0, 255 do
HEX[i] = string.format("%02x", i)
end
local function hex(s: string): string
return (string.gsub(s, ".", function(c: string): string
return HEX[string.byte(c)]
end))
end
for _, c in Fx.cases do
local map = Ldtk.decode(Bytes.reader(buffer.fromstring(c.data)), {
resolve = function(p: string): buffer?
local f = c.files[p]
return if f then buffer.fromstring(f) else nil
end,
})
if map then
local out = Ldtk.encode(map)
if out then
print(c.name .. "\t" .. hex(buffer.tostring(out)))
end
end
end
+4 -3
View File
@@ -1,9 +1,9 @@
# Docs inputs for the engine / level-editor sections of the scene, tile map, archive and data pages (tools/fixtures.py,
# tools/docs_check.py): the hand-written ASE of tools/fixtures/ase.py.
# tools/docs_check.py): the hand-written ASE of tools/fixtures/ase.py, LDtk's AutoLayers_2_stamps sample (tools/fixtures/ldtk.py).
# tests/gen/docs_engines.luau { files = { [name] = bytes }, vars = { aseText = "hand.ase", ... } }
import importlib.util, os
INPUTS = ["tools/docs_check.py", "tools/fixtures/ase.py"]
INPUTS = ["tools/docs_check.py", "tools/fixtures/ase.py", "tools/fixtures/ldtk.py"]
def mod(ctx, name):
@@ -16,5 +16,6 @@ def mod(ctx, name):
def generate(ctx):
check = mod(ctx, "../docs_check")
files = {"hand.ase": mod(ctx, "ase").HAND.encode()}
vars = {"aseText": "hand.ase"}
files["stamps.ldtk"] = open(os.path.join(mod(ctx, "ldtk").samples_dir(ctx), "AutoLayers_2_stamps.ldtk"), "rb").read()
vars = {"aseText": "hand.ase", "ldtkText": "stamps.ldtk"}
check.emit_inputs(ctx, files, vars)
+111
View File
@@ -0,0 +1,111 @@
# 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)