merge ws/engines
This commit is contained in:
commit
8bd15840d8
66 files changed
+31751
-1331
No files matched your search
@@ -2172,3 +2172,39 @@ do
|
||||
assert(BspFmt.decode(Bytes.reader(bsp)))
|
||||
end)
|
||||
end
|
||||
|
||||
-- ws-engines: text scene / level formats, MB/s of file text: Godot .tscn (Godot's own main.tscn with a 2210-vertex
|
||||
-- sphere and base64 surfaces; codecs/text/GodotVariant + ArrayMesh surfaces), an LDtk sample project, 3ds Max ASE
|
||||
-- (assimp's MotionCaptureROM.ase); fixtures tools/fixtures/godot.py, ldtk.py, ase.py
|
||||
do
|
||||
local Godot = require("@rosetta/model/godot")
|
||||
local Ldtk = require("@rosetta/vector/ldtk")
|
||||
local Ase = require("@rosetta/model/ase")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local GF = require("@tests/gen/godot")
|
||||
local LF = require("@tests/gen/ldtk")
|
||||
local AF = require("@tests/gen/ase_cases")
|
||||
local main = buffer.fromstring(GF.cases[2].data)
|
||||
local files = GF.cases[2].files
|
||||
bench("godot tscn decode", 5, buffer.len(main), function()
|
||||
assert(Godot.decode(Bytes.reader(main), { resolve = function(p: string): buffer?
|
||||
return if files[p] then buffer.fromstring(files[p]) else nil
|
||||
end }))
|
||||
end)
|
||||
local scene = assert(Godot.decode(Bytes.reader(main)))
|
||||
bench("godot tscn encode", 5, buffer.len(main), function()
|
||||
assert(Godot.encode(scene))
|
||||
end)
|
||||
local ld = buffer.fromstring(LF.cases[2].data)
|
||||
bench("ldtk decode (" .. LF.cases[2].name .. ")", 3, buffer.len(ld), function()
|
||||
assert(Ldtk.decode(Bytes.reader(ld)))
|
||||
end)
|
||||
for _, c in AF do
|
||||
if string.find(c.name, "MotionCaptureROM", 1, true) then
|
||||
local b = buffer.fromstring(c.data)
|
||||
bench("ase decode (MotionCaptureROM)", 3, buffer.len(b), function()
|
||||
assert(Ase.decode(Bytes.reader(b)))
|
||||
end)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,29 @@
|
||||
-- tools/fixtures/_ase_encode: run by tools/fixtures/ase.py (luau CLI, repo root): decodes every ASE case and writes it
|
||||
-- back with our ASE writer, printing "<file>\t<hex>" lines for assimp to read. Files: case_<i>.ase.
|
||||
local Ase = require("@rosetta/model/ase")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Cases = require("@tests/gen/ase_cases")
|
||||
|
||||
local HEX = {}
|
||||
for i = 0, 255 do
|
||||
HEX[i] = string.format("%02x", i)
|
||||
end
|
||||
local function hex(b: buffer): string
|
||||
local out = table.create(buffer.len(b))
|
||||
for i = 0, buffer.len(b) - 1 do
|
||||
out[i + 1] = HEX[buffer.readu8(b, i)]
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
for i, c in Cases do
|
||||
local scene = Ase.decode(Bytes.reader(buffer.fromstring(c.data)))
|
||||
if scene then
|
||||
local out, err = Ase.encode(scene)
|
||||
if out then
|
||||
print(string.format("case_%d.ase", i) .. "\t" .. hex(out))
|
||||
else
|
||||
print("encode failed " .. c.name .. ": " .. tostring(err))
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,80 @@
|
||||
# tools/fixtures/_godot_dump.gd: run by tools/fixtures/godot.py (godot --headless -s ... -- <scene.tscn>...): loads
|
||||
# each scene with Godot's own loader and prints one JSON line per scene: every node (path, class, global transform as
|
||||
# 12 numbers: basis rows then origin, visibility), every MeshInstance3D's surfaces (mesh.surface_get_arrays: vertex,
|
||||
# normal, tangent, uv, uv2, color, index; the active material's albedo / metallic / roughness / emission / texture
|
||||
# path / transparency / cull mode), cameras and lights.
|
||||
extends SceneTree
|
||||
|
||||
func xf(t):
|
||||
var b = t.basis
|
||||
return [b.x.x, b.y.x, b.z.x, b.x.y, b.y.y, b.z.y, b.x.z, b.y.z, b.z.z, t.origin.x, t.origin.y, t.origin.z]
|
||||
|
||||
func flat(a):
|
||||
var out = []
|
||||
if a == null:
|
||||
return out
|
||||
for v in a:
|
||||
if v is Vector3:
|
||||
out.append_array([v.x, v.y, v.z])
|
||||
elif v is Vector2:
|
||||
out.append_array([v.x, v.y])
|
||||
elif v is Color:
|
||||
out.append_array([v.r, v.g, v.b, v.a])
|
||||
else:
|
||||
out.append(v)
|
||||
return out
|
||||
|
||||
func mat(m):
|
||||
if m == null:
|
||||
return null
|
||||
var d = {"class": m.get_class(), "name": m.resource_name}
|
||||
if m is BaseMaterial3D:
|
||||
d["albedo"] = [m.albedo_color.r, m.albedo_color.g, m.albedo_color.b, m.albedo_color.a]
|
||||
d["metallic"] = m.metallic
|
||||
d["roughness"] = m.roughness
|
||||
d["emission"] = [m.emission.r, m.emission.g, m.emission.b] if m.emission_enabled else null
|
||||
d["emission_energy"] = m.emission_energy_multiplier
|
||||
d["texture"] = m.albedo_texture.resource_path if m.albedo_texture else null
|
||||
d["transparency"] = m.transparency
|
||||
d["cull"] = m.cull_mode
|
||||
return d
|
||||
|
||||
func walk(n, root, out):
|
||||
var e = {"path": str(root.get_path_to(n)), "class": n.get_class()}
|
||||
if n is Node3D:
|
||||
e["xf"] = xf(n.transform)
|
||||
e["visible"] = n.visible
|
||||
if n is MeshInstance3D and n.mesh:
|
||||
var surfs = []
|
||||
for s in n.mesh.get_surface_count():
|
||||
var a = n.mesh.surface_get_arrays(s)
|
||||
surfs.append({
|
||||
"vertex": flat(a[Mesh.ARRAY_VERTEX]), "normal": flat(a[Mesh.ARRAY_NORMAL]), "tangent": flat(a[Mesh.ARRAY_TANGENT]),
|
||||
"uv": flat(a[Mesh.ARRAY_TEX_UV]), "uv2": flat(a[Mesh.ARRAY_TEX_UV2]), "color": flat(a[Mesh.ARRAY_COLOR]),
|
||||
"index": flat(a[Mesh.ARRAY_INDEX]), "material": mat(n.get_active_material(s)),
|
||||
})
|
||||
e["surfaces"] = surfs
|
||||
e["mesh_class"] = n.mesh.get_class()
|
||||
if n is Camera3D:
|
||||
e["camera"] = {"fov": n.fov, "near": n.near, "far": n.far, "projection": n.projection, "size": n.size}
|
||||
if n is Light3D:
|
||||
var l = {"color": [n.light_color.r, n.light_color.g, n.light_color.b], "energy": n.light_energy}
|
||||
if n is OmniLight3D:
|
||||
l["range"] = n.omni_range
|
||||
if n is SpotLight3D:
|
||||
l["range"] = n.spot_range
|
||||
l["angle"] = n.spot_angle
|
||||
e["light"] = l
|
||||
out.append(e)
|
||||
for c in n.get_children():
|
||||
walk(c, root, out)
|
||||
|
||||
func _init():
|
||||
for path in OS.get_cmdline_user_args():
|
||||
var ps = load(path)
|
||||
var res = {"file": path, "ok": ps != null, "nodes": []}
|
||||
if ps:
|
||||
var root = ps.instantiate()
|
||||
walk(root, root, res["nodes"])
|
||||
print("JSON:" + JSON.stringify(res))
|
||||
quit()
|
||||
@@ -0,0 +1,45 @@
|
||||
-- tools/fixtures/_godot_encode: run by tools/fixtures/godot.py (luau CLI, repo root): decodes every Godot scene case
|
||||
-- (files through resolve) and writes it with our .tscn writer, printing "ours_<name>.tscn\t<hex>" lines for Godot to
|
||||
-- load, and every .tres case through data/tres ("ours_<name>.tres").
|
||||
local Godot = require("@rosetta/model/godot")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Fx = require("@tests/gen/godot")
|
||||
|
||||
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 scene, err = Godot.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 scene then
|
||||
local out = Godot.encode(scene)
|
||||
if out then
|
||||
local base = string.gsub(c.name, "%.%w+$", "")
|
||||
print("ours_" .. base .. ".tscn\t" .. hex(buffer.tostring(out)))
|
||||
end
|
||||
else
|
||||
print("decode failed " .. c.name .. ": " .. tostring(err))
|
||||
end
|
||||
end
|
||||
|
||||
local Tres = require("@rosetta/data/tres")
|
||||
for _, c in Fx.tres do
|
||||
local v = Tres.decode(Bytes.reader(buffer.fromstring(c.data)))
|
||||
if v then
|
||||
local out = Tres.encode(v)
|
||||
if out then
|
||||
print("ours_" .. c.name .. "\t" .. hex(buffer.tostring(out)))
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,120 @@
|
||||
# tools/fixtures/_godot_make.gd: run by tools/fixtures/godot.py (godot --headless -s): builds test scenes in Godot and
|
||||
# saves them as .tscn (Godot's own writer) into the project folder: meshes from SurfaceTool (normals, tangents, UVs,
|
||||
# UV2, colours, two surfaces, indexed and not), materials (sRGB albedo, metallic, roughness, emission, a texture,
|
||||
# transparency, culling), nested transforms, cameras, lights, primitive meshes, a Node2D subtree, a material override
|
||||
# and an instanced sub-scene.
|
||||
extends SceneTree
|
||||
|
||||
func tri_mesh(mat_a, mat_b):
|
||||
var st = SurfaceTool.new()
|
||||
st.begin(Mesh.PRIMITIVE_TRIANGLES)
|
||||
var pts = [Vector3(0, 0, 0), Vector3(1, 0, 0), Vector3(0, 1, 0), Vector3(1, 1, 0.5)]
|
||||
var uvs = [Vector2(0, 0), Vector2(1, 0), Vector2(0, 1), Vector2(1, 1)]
|
||||
for i in [0, 1, 2, 2, 1, 3]:
|
||||
st.set_normal(Vector3(0.1 * i, 0.2, 1).normalized())
|
||||
st.set_tangent(Plane(Vector3(1, 0, -0.1 * i).normalized(), -1.0 if i == 3 else 1.0))
|
||||
st.set_uv(uvs[i])
|
||||
st.set_uv2(uvs[i] * 0.5)
|
||||
st.set_color(Color(i / 3.0, 1.0 - i / 3.0, 0.25, 1.0))
|
||||
st.add_vertex(pts[i])
|
||||
st.index()
|
||||
st.set_material(mat_a)
|
||||
var mesh = st.commit()
|
||||
var st2 = SurfaceTool.new()
|
||||
st2.begin(Mesh.PRIMITIVE_TRIANGLES)
|
||||
for p in [Vector3(0, 0, 1), Vector3(0, 2, 1), Vector3(2, 0, 1)]:
|
||||
st2.set_normal(Vector3(0, 0, -1))
|
||||
st2.add_vertex(p)
|
||||
st2.set_material(mat_b)
|
||||
st2.commit(mesh)
|
||||
return mesh
|
||||
|
||||
func scene_main():
|
||||
var root = Node3D.new()
|
||||
root.name = "Root"
|
||||
var tex = load("res://checker.png")
|
||||
var a = StandardMaterial3D.new()
|
||||
a.resource_name = "Painted"
|
||||
a.albedo_color = Color(0.8, 0.4, 0.2, 1.0)
|
||||
a.metallic = 0.25
|
||||
a.roughness = 0.6
|
||||
a.albedo_texture = tex
|
||||
a.emission_enabled = true
|
||||
a.emission = Color(0.1, 0.2, 0.3)
|
||||
a.emission_energy_multiplier = 2.0
|
||||
var b = StandardMaterial3D.new()
|
||||
b.resource_name = "Glass"
|
||||
b.albedo_color = Color(0.2, 0.6, 1.0, 0.5)
|
||||
b.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA
|
||||
b.cull_mode = BaseMaterial3D.CULL_DISABLED
|
||||
var pivot = Node3D.new()
|
||||
pivot.name = "Pivot"
|
||||
pivot.transform = Transform3D(Basis.from_euler(Vector3(0.3, -0.7, 0.2)), Vector3(1, 2, 3))
|
||||
root.add_child(pivot); pivot.owner = root
|
||||
var mi = MeshInstance3D.new()
|
||||
mi.name = "Shape"
|
||||
mi.mesh = tri_mesh(a, b)
|
||||
mi.transform = Transform3D(Basis(Vector3(0, 0, 1), 0.4).scaled(Vector3(2, 1, 0.5)), Vector3(-1, 0.5, 4))
|
||||
pivot.add_child(mi); mi.owner = root
|
||||
var over = MeshInstance3D.new()
|
||||
over.name = "Override"
|
||||
over.mesh = mi.mesh
|
||||
var red = StandardMaterial3D.new()
|
||||
red.albedo_color = Color(1, 0, 0)
|
||||
over.set_surface_override_material(0, red)
|
||||
over.position = Vector3(5, 0, 0)
|
||||
root.add_child(over); over.owner = root
|
||||
var cam = Camera3D.new(); cam.name = "Cam"; cam.fov = 50; cam.near = 0.1; cam.far = 300
|
||||
cam.transform = Transform3D(Basis.looking_at(Vector3(0, -0.5, -1)), Vector3(0, 3, 8))
|
||||
root.add_child(cam); cam.owner = root
|
||||
var ortho = Camera3D.new(); ortho.name = "Ortho"; ortho.projection = Camera3D.PROJECTION_ORTHOGONAL; ortho.size = 6
|
||||
root.add_child(ortho); ortho.owner = root
|
||||
var omni = OmniLight3D.new(); omni.name = "Omni"; omni.light_color = Color(1, 0.5, 0.25); omni.light_energy = 2; omni.omni_range = 7
|
||||
omni.position = Vector3(0, 4, 0)
|
||||
root.add_child(omni); omni.owner = root
|
||||
var spot = SpotLight3D.new(); spot.name = "Spot"; spot.spot_angle = 30; spot.spot_range = 12; spot.light_energy = 3
|
||||
spot.rotation = Vector3(-1.2, 0.3, 0)
|
||||
root.add_child(spot); spot.owner = root
|
||||
var sun = DirectionalLight3D.new(); sun.name = "Sun"; sun.light_energy = 0.8
|
||||
sun.rotation_degrees = Vector3(-45, 30, 0)
|
||||
root.add_child(sun); sun.owner = root
|
||||
var prims = Node3D.new(); prims.name = "Prims"; prims.position = Vector3(0, -3, 0)
|
||||
root.add_child(prims); prims.owner = root
|
||||
var shapes = [BoxMesh.new(), PlaneMesh.new(), QuadMesh.new(), SphereMesh.new(), CylinderMesh.new()]
|
||||
shapes[0].size = Vector3(2, 1, 3)
|
||||
shapes[1].size = Vector2(4, 2)
|
||||
shapes[3].radius = 0.75; shapes[3].height = 1.5
|
||||
shapes[4].top_radius = 0.25; shapes[4].height = 3
|
||||
for i in shapes.size():
|
||||
var p = MeshInstance3D.new(); p.name = "Prim%d" % i; p.mesh = shapes[i]; p.position = Vector3(i * 3, 0, 0)
|
||||
prims.add_child(p); p.owner = root
|
||||
var ui = Node2D.new(); ui.name = "Hud"; ui.position = Vector2(10, 20); ui.rotation = 0.5
|
||||
root.add_child(ui); ui.owner = root
|
||||
var spr = Sprite2D.new(); spr.name = "Icon"; spr.texture = tex; spr.position = Vector2(3, 4)
|
||||
ui.add_child(spr); spr.owner = root
|
||||
var hidden = Node3D.new(); hidden.name = "Hidden"; hidden.visible = false; hidden.scale = Vector3(1, 2, 3)
|
||||
root.add_child(hidden); hidden.owner = root
|
||||
var sub = load("res://part.tscn").instantiate()
|
||||
sub.name = "PartInstance"
|
||||
sub.position = Vector3(0, 0, -6)
|
||||
root.add_child(sub); sub.owner = root
|
||||
return root
|
||||
|
||||
func scene_part():
|
||||
var root = Node3D.new(); root.name = "Part"
|
||||
var m = MeshInstance3D.new(); m.name = "Cube"; var box = BoxMesh.new(); box.size = Vector3(0.5, 0.5, 0.5); m.mesh = box
|
||||
m.position = Vector3(0, 1, 0)
|
||||
root.add_child(m); m.owner = root
|
||||
return root
|
||||
|
||||
func save(root, path):
|
||||
var ps = PackedScene.new()
|
||||
ps.pack(root)
|
||||
var err = ResourceSaver.save(ps, path)
|
||||
if err != OK:
|
||||
printerr("save failed ", path, " ", err)
|
||||
|
||||
func _init():
|
||||
save(scene_part(), "res://part.tscn")
|
||||
save(scene_main(), "res://main.tscn")
|
||||
quit()
|
||||
@@ -0,0 +1,15 @@
|
||||
# tools/fixtures/_godot_tres.gd: run by tools/fixtures/godot.py (godot --headless -s ... -- <file.tres>...): loads each
|
||||
# resource with Godot's loader and prints one JSON line: its class and every stored property as var_to_str text.
|
||||
extends SceneTree
|
||||
|
||||
func _init():
|
||||
for path in OS.get_cmdline_user_args():
|
||||
var r = load(path)
|
||||
var res = {"file": path, "ok": r != null, "props": {}}
|
||||
if r:
|
||||
res["class"] = r.get_class()
|
||||
for p in r.get_property_list():
|
||||
if p.usage & PROPERTY_USAGE_STORAGE and p.name != "script" and p.name != "resource_path":
|
||||
res["props"][p.name] = var_to_str(r.get(p.name))
|
||||
print("JSON:" + JSON.stringify(res))
|
||||
quit()
|
||||
@@ -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
|
||||
@@ -0,0 +1,28 @@
|
||||
-- tools/fixtures/_ogmo_encode: run by tools/fixtures/ogmo.py (luau CLI, repo root): decodes every Ogmo level with its
|
||||
-- project and writes the level and a project made from the map with our encoder, printing "<name>.json\t<hex>" and
|
||||
-- "<name>.ogmo\t<hex>" lines for Python to read.
|
||||
local Ogmo = require("@rosetta/vector/ogmo")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Fx = require("@tests/gen/ogmo")
|
||||
|
||||
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 = Ogmo.decode(Bytes.reader(buffer.fromstring(c.data)), { project = c.project })
|
||||
if map then
|
||||
local lv = Ogmo.encode(map)
|
||||
local pj = Ogmo.encode(map, { kind = "project" })
|
||||
if lv and pj then
|
||||
print(c.name .. ".json\t" .. hex(buffer.tostring(lv)))
|
||||
print(c.name .. ".ogmo\t" .. hex(buffer.tostring(pj)))
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,36 @@
|
||||
-- tools/fixtures/_unitypackage_encode: run by tools/fixtures/unitypackage.py (luau CLI, repo root): re-encodes every
|
||||
-- package case and a package built from scratch, printing "<file>\t<hex>" lines for Python's tarfile to read.
|
||||
local UnityPackage = require("@rosetta/archive/unitypackage")
|
||||
local Bytes = require("@rosetta/core/Bytes")
|
||||
local Fx = require("@tests/gen/unitypackage")
|
||||
|
||||
local HEX = {}
|
||||
for i = 0, 255 do
|
||||
HEX[i] = string.format("%02x", i)
|
||||
end
|
||||
local function hex(b: buffer): string
|
||||
local out = table.create(buffer.len(b))
|
||||
for i = 0, buffer.len(b) - 1 do
|
||||
out[i + 1] = HEX[buffer.readu8(b, i)]
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
for _, c in Fx.cases do
|
||||
local a = UnityPackage.decode(Bytes.reader(buffer.fromstring(c.data)))
|
||||
if a then
|
||||
local out = UnityPackage.encode(a)
|
||||
if out then
|
||||
print(c.name .. ".unitypackage\t" .. hex(out))
|
||||
end
|
||||
end
|
||||
end
|
||||
local a = UnityPackage.new()
|
||||
a:add("Assets/Models", "", { dir = true })
|
||||
a:add("Assets/Models/cube.obj", "v 0 0 0\n")
|
||||
a:add("Assets/readme.txt", "hello\n")
|
||||
a:add("Assets/readme.txt.meta", "fileFormatVersion: 2\nguid: 0123456789abcdef0123456789abcdef\n")
|
||||
local out = UnityPackage.encode(a)
|
||||
if out then
|
||||
print("scratch.unitypackage\t" .. hex(out))
|
||||
end
|
||||
@@ -0,0 +1,249 @@
|
||||
# ASE fixtures (tools/fixtures.py): assimp's ASE test models (test/models/ASE and test/models-nonbsd/ASE, read from the
|
||||
# nixpkgs assimp source, never committed) plus a hand-written file (Multi/Sub-Object material, a bitmap map with UVW
|
||||
# tiling, a second mapping channel, vertex colours, explicit normals, a helper parent, a camera, a light), with
|
||||
# reference values from assimp (`assimp info -r`: meshes, faces, vertices, cameras, lights; world bounds from its
|
||||
# PreTransformVertices export). Then our encoder's output (tools/fixtures/_ase_encode.luau) read back by assimp.
|
||||
# tests/gen/ase_cases.luau { name, data, assimp }
|
||||
# tests/gen/ase_xcheck.luau { name, case, assimp }
|
||||
import importlib.util, os
|
||||
|
||||
INPUTS = ["src/Rosetta/model/ase", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py", "tools/fixtures/_ase_encode.luau"]
|
||||
|
||||
HAND = """*3DSMAX_ASCIIEXPORT\t200
|
||||
*COMMENT "hand-written for rosetta"
|
||||
*SCENE {
|
||||
\t*SCENE_FILENAME "hand.max"
|
||||
\t*SCENE_FIRSTFRAME 0
|
||||
\t*SCENE_LASTFRAME 50
|
||||
\t*SCENE_FRAMESPEED 25
|
||||
\t*SCENE_TICKSPERFRAME 192
|
||||
\t*SCENE_BACKGROUND_STATIC 0.1000\t0.2000\t0.3000
|
||||
\t*SCENE_AMBIENT_STATIC 0.0000\t0.0000\t0.0000
|
||||
}
|
||||
*MATERIAL_LIST {
|
||||
\t*MATERIAL_COUNT 1
|
||||
\t*MATERIAL 0 {
|
||||
\t\t*MATERIAL_NAME "Multi"
|
||||
\t\t*MATERIAL_CLASS "Multi/Sub-Object"
|
||||
\t\t*NUMSUBMTLS 2
|
||||
\t\t*SUBMATERIAL 0 {
|
||||
\t\t\t*MATERIAL_NAME "Brick"
|
||||
\t\t\t*MATERIAL_CLASS "Standard"
|
||||
\t\t\t*MATERIAL_AMBIENT 0.1000\t0.1000\t0.1000
|
||||
\t\t\t*MATERIAL_DIFFUSE 0.8000\t0.4000\t0.2000
|
||||
\t\t\t*MATERIAL_SPECULAR 0.9000\t0.9000\t0.9000
|
||||
\t\t\t*MATERIAL_SHINE 0.2500
|
||||
\t\t\t*MATERIAL_SHINESTRENGTH 0.5000
|
||||
\t\t\t*MATERIAL_TRANSPARENCY 0.0000
|
||||
\t\t\t*MATERIAL_SELFILLUM 0.0000
|
||||
\t\t\t*MAP_DIFFUSE {
|
||||
\t\t\t\t*MAP_NAME "BrickMap"
|
||||
\t\t\t\t*MAP_CLASS "Bitmap"
|
||||
\t\t\t\t*MAP_SUBNO 1
|
||||
\t\t\t\t*MAP_AMOUNT 1.0000
|
||||
\t\t\t\t*BITMAP "textures\\brick.png"
|
||||
\t\t\t\t*MAP_TYPE Screen
|
||||
\t\t\t\t*UVW_U_OFFSET 0.0000
|
||||
\t\t\t\t*UVW_V_OFFSET 0.0000
|
||||
\t\t\t\t*UVW_U_TILING 2.0000
|
||||
\t\t\t\t*UVW_V_TILING 3.0000
|
||||
\t\t\t\t*UVW_ANGLE 0.0000
|
||||
\t\t\t}
|
||||
\t\t}
|
||||
\t\t*SUBMATERIAL 1 {
|
||||
\t\t\t*MATERIAL_NAME "Glass"
|
||||
\t\t\t*MATERIAL_CLASS "Standard"
|
||||
\t\t\t*MATERIAL_AMBIENT 0.0000\t0.0000\t0.0000
|
||||
\t\t\t*MATERIAL_DIFFUSE 0.2000\t0.6000\t0.9000
|
||||
\t\t\t*MATERIAL_SPECULAR 1.0000\t1.0000\t1.0000
|
||||
\t\t\t*MATERIAL_SHINE 0.9000
|
||||
\t\t\t*MATERIAL_TRANSPARENCY 0.5000
|
||||
\t\t\t*MATERIAL_TWOSIDED
|
||||
\t\t}
|
||||
\t}
|
||||
}
|
||||
*HELPEROBJECT {
|
||||
\t*NODE_NAME "Pivot"
|
||||
\t*HELPER_CLASS "Dummy"
|
||||
\t*NODE_TM {
|
||||
\t\t*NODE_NAME "Pivot"
|
||||
\t\t*TM_ROW0 1.0000\t0.0000\t0.0000
|
||||
\t\t*TM_ROW1 0.0000\t1.0000\t0.0000
|
||||
\t\t*TM_ROW2 0.0000\t0.0000\t1.0000
|
||||
\t\t*TM_ROW3 10.0000\t0.0000\t0.0000
|
||||
\t}
|
||||
}
|
||||
*GEOMOBJECT {
|
||||
\t*NODE_NAME "Quad"
|
||||
\t*NODE_PARENT "Pivot"
|
||||
\t*NODE_TM {
|
||||
\t\t*NODE_NAME "Quad"
|
||||
\t\t*TM_ROW0 0.0000\t1.0000\t0.0000
|
||||
\t\t*TM_ROW1 -1.0000\t0.0000\t0.0000
|
||||
\t\t*TM_ROW2 0.0000\t0.0000\t1.0000
|
||||
\t\t*TM_ROW3 10.0000\t5.0000\t0.0000
|
||||
\t}
|
||||
\t*MESH {
|
||||
\t\t*TIMEVALUE 0
|
||||
\t\t*MESH_NUMVERTEX 4
|
||||
\t\t*MESH_NUMFACES 2
|
||||
\t\t*MESH_VERTEX_LIST {
|
||||
\t\t\t*MESH_VERTEX 0\t10.0000\t5.0000\t0.0000
|
||||
\t\t\t*MESH_VERTEX 1\t10.0000\t7.0000\t0.0000
|
||||
\t\t\t*MESH_VERTEX 2\t8.0000\t7.0000\t0.0000
|
||||
\t\t\t*MESH_VERTEX 3\t8.0000\t5.0000\t0.0000
|
||||
\t\t}
|
||||
\t\t*MESH_FACE_LIST {
|
||||
\t\t\t*MESH_FACE 0: A: 0 B: 1 C: 2 AB: 1 BC: 1 CA: 0\t*MESH_SMOOTHING 1\t*MESH_MTLID 0
|
||||
\t\t\t*MESH_FACE 1: A: 0 B: 2 C: 3 AB: 1 BC: 1 CA: 0\t*MESH_SMOOTHING \t*MESH_MTLID 1
|
||||
\t\t}
|
||||
\t\t*MESH_NUMTVERTEX 4
|
||||
\t\t*MESH_TVERTLIST {
|
||||
\t\t\t*MESH_TVERT 0\t0.0000\t0.0000\t0.0000
|
||||
\t\t\t*MESH_TVERT 1\t1.0000\t0.0000\t0.0000
|
||||
\t\t\t*MESH_TVERT 2\t1.0000\t1.0000\t0.0000
|
||||
\t\t\t*MESH_TVERT 3\t0.0000\t1.0000\t0.0000
|
||||
\t\t}
|
||||
\t\t*MESH_NUMTVFACES 2
|
||||
\t\t*MESH_TFACELIST {
|
||||
\t\t\t*MESH_TFACE 0\t0\t1\t2
|
||||
\t\t\t*MESH_TFACE 1\t0\t2\t3
|
||||
\t\t}
|
||||
\t\t*MESH_MAPPINGCHANNEL 2 {
|
||||
\t\t\t*MESH_NUMTVERTEX 1
|
||||
\t\t\t*MESH_TVERTLIST {
|
||||
\t\t\t\t*MESH_TVERT 0\t0.2500\t0.7500\t0.0000
|
||||
\t\t\t}
|
||||
\t\t\t*MESH_NUMTVFACES 2
|
||||
\t\t\t*MESH_TFACELIST {
|
||||
\t\t\t\t*MESH_TFACE 0\t0\t0\t0
|
||||
\t\t\t\t*MESH_TFACE 1\t0\t0\t0
|
||||
\t\t\t}
|
||||
\t\t}
|
||||
\t\t*MESH_NUMCVERTEX 2
|
||||
\t\t*MESH_CVERTLIST {
|
||||
\t\t\t*MESH_VERTCOL 0\t1.0000\t0.0000\t0.0000
|
||||
\t\t\t*MESH_VERTCOL 1\t0.0000\t1.0000\t0.0000
|
||||
\t\t}
|
||||
\t\t*MESH_NUMCVFACES 2
|
||||
\t\t*MESH_CFACELIST {
|
||||
\t\t\t*MESH_CFACE 0\t0\t1\t0
|
||||
\t\t\t*MESH_CFACE 1\t1\t1\t1
|
||||
\t\t}
|
||||
\t\t*MESH_NORMALS {
|
||||
\t\t\t*MESH_FACENORMAL 0\t0.0000\t0.0000\t1.0000
|
||||
\t\t\t\t*MESH_VERTEXNORMAL 0\t0.0000\t0.0000\t1.0000
|
||||
\t\t\t\t*MESH_VERTEXNORMAL 1\t0.0000\t0.0000\t1.0000
|
||||
\t\t\t\t*MESH_VERTEXNORMAL 2\t0.0000\t0.6000\t0.8000
|
||||
\t\t\t*MESH_FACENORMAL 1\t0.0000\t0.0000\t1.0000
|
||||
\t\t\t\t*MESH_VERTEXNORMAL 0\t0.0000\t0.0000\t1.0000
|
||||
\t\t\t\t*MESH_VERTEXNORMAL 2\t0.0000\t0.6000\t0.8000
|
||||
\t\t\t\t*MESH_VERTEXNORMAL 3\t0.0000\t0.0000\t1.0000
|
||||
\t\t}
|
||||
\t}
|
||||
\t*PROP_MOTIONBLUR 0
|
||||
\t*PROP_CASTSHADOW 1
|
||||
\t*PROP_RECVSHADOW 1
|
||||
\t*MATERIAL_REF 0
|
||||
}
|
||||
*CAMERAOBJECT {
|
||||
\t*NODE_NAME "Cam"
|
||||
\t*CAMERA_TYPE Free
|
||||
\t*NODE_TM {
|
||||
\t\t*NODE_NAME "Cam"
|
||||
\t\t*TM_ROW0 1.0000\t0.0000\t0.0000
|
||||
\t\t*TM_ROW1 0.0000\t0.0000\t1.0000
|
||||
\t\t*TM_ROW2 0.0000\t-1.0000\t0.0000
|
||||
\t\t*TM_ROW3 0.0000\t-50.0000\t10.0000
|
||||
\t}
|
||||
\t*CAMERA_SETTINGS {
|
||||
\t\t*TIMEVALUE 0
|
||||
\t\t*CAMERA_NEAR 1.0000
|
||||
\t\t*CAMERA_FAR 500.0000
|
||||
\t\t*CAMERA_FOV 0.7854
|
||||
\t\t*CAMERA_TDIST 50.0000
|
||||
\t}
|
||||
}
|
||||
*LIGHTOBJECT {
|
||||
\t*NODE_NAME "Spot"
|
||||
\t*LIGHT_TYPE Target
|
||||
\t*NODE_TM {
|
||||
\t\t*NODE_NAME "Spot"
|
||||
\t\t*TM_ROW0 1.0000\t0.0000\t0.0000
|
||||
\t\t*TM_ROW1 0.0000\t1.0000\t0.0000
|
||||
\t\t*TM_ROW2 0.0000\t0.0000\t1.0000
|
||||
\t\t*TM_ROW3 0.0000\t0.0000\t100.0000
|
||||
\t}
|
||||
\t*NODE_TM {
|
||||
\t\t*NODE_NAME "Spot.Target"
|
||||
\t\t*TM_ROW0 1.0000\t0.0000\t0.0000
|
||||
\t\t*TM_ROW1 0.0000\t1.0000\t0.0000
|
||||
\t\t*TM_ROW2 0.0000\t0.0000\t1.0000
|
||||
\t\t*TM_ROW3 0.0000\t0.0000\t0.0000
|
||||
\t}
|
||||
\t*LIGHT_SHADOWS Off
|
||||
\t*LIGHT_SETTINGS {
|
||||
\t\t*TIMEVALUE 0
|
||||
\t\t*LIGHT_COLOR 1.0000\t0.9000\t0.8000
|
||||
\t\t*LIGHT_INTENS 2.0000
|
||||
\t\t*LIGHT_HOTSPOT 30.0000
|
||||
\t\t*LIGHT_FALLOFF 60.0000
|
||||
\t}
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def load(ctx, name):
|
||||
spec = importlib.util.spec_from_file_location("_" + name.replace(".", "_"), os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
def reference(ctx, M, X, paths, tmp):
|
||||
out = []
|
||||
for p, a in zip(paths, M.assimp_info(ctx, paths, raw=True)):
|
||||
a.update(X.assimp_extra(ctx, p))
|
||||
for k in ("min", "max", "perMesh"):
|
||||
a.pop(k, None)
|
||||
if not a.get("failed"):
|
||||
a.update(X.ptv_bounds(ctx, p, tmp))
|
||||
out.append(a)
|
||||
return out
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
M = load(ctx, "_model_ref")
|
||||
X = load(ctx, "fbx")
|
||||
tmp = M.tempdir()
|
||||
src = X.assimp_src(ctx)
|
||||
cases = []
|
||||
for sub in ("models", "models-nonbsd"):
|
||||
d = os.path.join(src, "test", sub, "ASE")
|
||||
for root, _, files in sorted(os.walk(d)):
|
||||
for f in sorted(files):
|
||||
if f.lower().endswith((".ase", ".ask")) or f == "TestFormatDetection":
|
||||
p = os.path.join(root, f)
|
||||
cases.append({"name": "assimp/%s/%s" % (sub, os.path.relpath(p, d)), "path": p})
|
||||
hand = os.path.join(tmp, "hand.ase")
|
||||
with open(hand, "w") as fh:
|
||||
fh.write(HAND)
|
||||
cases.append({"name": "hand.ase", "path": hand})
|
||||
for c, a in zip(cases, reference(ctx, M, X, [c["path"] for c in cases], tmp)):
|
||||
c["assimp"] = a
|
||||
c["data"] = open(c["path"], "rb").read()
|
||||
del c["path"]
|
||||
ctx.emit("ase_cases", cases)
|
||||
|
||||
ours = M.luau_encode(ctx, "tools/fixtures/_ase_encode.luau")
|
||||
names = sorted((n for n in ours if n.endswith(".ase")), key=lambda n: int(n[5:-4]))
|
||||
paths = []
|
||||
for n in names:
|
||||
p = os.path.join(tmp, n)
|
||||
with open(p, "wb") as f:
|
||||
f.write(ours[n])
|
||||
paths.append(p)
|
||||
xs = []
|
||||
for n, a in zip(names, reference(ctx, M, X, paths, tmp)):
|
||||
xs.append({"name": n, "case": int(n[5:-4]), "assimp": a})
|
||||
ctx.emit("ase_xcheck", xs)
|
||||
@@ -0,0 +1,62 @@
|
||||
# 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, LDtk's AutoLayers_2_stamps sample (tools/fixtures/ldtk.py),
|
||||
# HaxeFlixel's TurnBasedRPG Ogmo project and level (tests/fixtures/ogmo), a small Godot scene and resource, the
|
||||
# UE1 map of tools/fixtures/t3d.py.
|
||||
# tests/gen/docs_engines.luau { files = { [name] = bytes }, vars = { aseText = "hand.ase", ... } }
|
||||
import importlib.util, os
|
||||
|
||||
TSCN = """[gd_scene load_steps=3 format=3]
|
||||
|
||||
[sub_resource type="StandardMaterial3D" id="Mat_1"]
|
||||
albedo_color = Color(1, 0.5, 0, 1)
|
||||
metallic = 0.5
|
||||
|
||||
[sub_resource type="BoxMesh" id="Box_1"]
|
||||
material = SubResource("Mat_1")
|
||||
size = Vector3(1, 2, 1)
|
||||
|
||||
[node name="World" type="Node3D"]
|
||||
|
||||
[node name="Box" type="MeshInstance3D" parent="."]
|
||||
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0, 0)
|
||||
mesh = SubResource("Box_1")
|
||||
|
||||
[node name="Camera" type="Camera3D" parent="."]
|
||||
fov = 60.0
|
||||
|
||||
[node name="Hud" type="Node2D" parent="."]
|
||||
position = Vector2(10, 20)
|
||||
"""
|
||||
|
||||
TRES = """[gd_resource type="StandardMaterial3D" load_steps=2 format=3]
|
||||
|
||||
[ext_resource type="Texture2D" path="res://brick.png" id="1"]
|
||||
|
||||
[resource]
|
||||
albedo_color = Color(0.8, 0.4, 0.2, 1)
|
||||
albedo_texture = ExtResource("1")
|
||||
metallic = 0.25
|
||||
roughness = 1.0
|
||||
"""
|
||||
|
||||
INPUTS = ["tools/docs_check.py", "tools/fixtures/t3d.py", "tools/fixtures/ase.py", "tools/fixtures/ldtk.py", "tests/fixtures/ogmo"]
|
||||
|
||||
|
||||
def mod(ctx, name):
|
||||
spec = importlib.util.spec_from_file_location("fx_" + name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
check = mod(ctx, "../docs_check")
|
||||
files = {"hand.ase": mod(ctx, "ase").HAND.encode()}
|
||||
files["stamps.ldtk"] = open(os.path.join(mod(ctx, "ldtk").samples_dir(ctx), "AutoLayers_2_stamps.ldtk"), "rb").read()
|
||||
for f in ("turnBasedRPG.ogmo", "room-001.json"):
|
||||
files[f] = ctx.read("tests/fixtures/ogmo/" + f)
|
||||
files["world.tscn"] = TSCN.encode()
|
||||
files["level.t3d"] = mod(ctx, "t3d").ue1()[0].encode()
|
||||
files["brick.tres"] = TRES.encode()
|
||||
vars = {"t3dText": "level.t3d", "tscnText": "world.tscn", "tresText": "brick.tres", "aseText": "hand.ase", "ldtkText": "stamps.ldtk", "ogmoProjectText": "turnBasedRPG.ogmo", "ogmoLevelText": "room-001.json"}
|
||||
check.emit_inputs(ctx, files, vars)
|
||||
@@ -0,0 +1,224 @@
|
||||
# Godot fixtures (tools/fixtures.py), with Godot 4 itself (nixpkgs#godot_4, headless) as the reference:
|
||||
# tools/fixtures/_godot_make.gd builds scenes in Godot and saves them with Godot's .tscn writer;
|
||||
# tools/fixtures/_godot_dump.gd loads scenes with Godot's loader and prints every node, mesh surface (the arrays
|
||||
# Godot decoded), material, camera and light as JSON. A hand-written format-2 .escn (the Blender exporter's layout:
|
||||
# "arrays" surfaces, SpatialMaterial, Godot 3 node types) and .tres resources are added. Then our writer's .tscn output
|
||||
# (tools/fixtures/_godot_encode.luau) is loaded and dumped by Godot. Resources are loaded by Godot
|
||||
# (tools/fixtures/_godot_tres.gd: every stored property as var_to_str text), ours too.
|
||||
# tests/gen/godot.luau { cases = { { name, data, files = { [rel] = bytes }, dump? } }, tres = { { name, data, godot } } }
|
||||
# tests/gen/godot_ours.luau { { name, data, dump } }; ours_*.tres entries carry godot (the resource dump) instead
|
||||
import importlib.util, json, os, shutil, struct, subprocess, tempfile, zlib
|
||||
|
||||
INPUTS = ["src/Rosetta/model/godot", "src/Rosetta/data/tres", "src/Rosetta/codecs/text/GodotVariant.luau", "tools/fixtures/_godot_make.gd",
|
||||
"tools/fixtures/_godot_dump.gd", "tools/fixtures/_godot_tres.gd", "tools/fixtures/_godot_encode.luau", "tools/fixtures/_model_ref.py"]
|
||||
|
||||
ESCN = """[gd_scene load_steps=4 format=2]
|
||||
|
||||
[sub_resource id=1 type="SpatialMaterial"]
|
||||
|
||||
resource_name = "Material"
|
||||
albedo_color = Color(0.8, 0.2, 0.1, 1.0)
|
||||
metallic = 0.5
|
||||
roughness = 0.25
|
||||
flags_transparent = false
|
||||
params_cull_mode = 2
|
||||
|
||||
[sub_resource id=2 type="ArrayMesh"]
|
||||
|
||||
resource_name = "Cube"
|
||||
surfaces/0 = {
|
||||
\t"material":SubResource(1),
|
||||
\t"primitive":4,
|
||||
\t"arrays":[
|
||||
\t\tVector3Array(1.0, 1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0),
|
||||
\t\tVector3Array(0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0),
|
||||
\t\tFloatArray(1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0),
|
||||
\t\tnull, ; no Vertex Colors,
|
||||
\t\tVector2Array(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0),
|
||||
\t\tnull, ; No UV2,
|
||||
\t\tnull, ; No Bones,
|
||||
\t\tnull, ; No Weights,
|
||||
\t\tIntArray(0, 2, 1, 0, 3, 2)
|
||||
\t],
|
||||
\t"morph_arrays":[]
|
||||
}
|
||||
|
||||
[sub_resource id=3 type="ArrayMesh"]
|
||||
|
||||
surfaces/0 = {
|
||||
\t"primitive":5,
|
||||
\t"arrays":[
|
||||
\t\tVector3Array(0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0),
|
||||
\t\tnull, null, ColorArray(1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1), null, null, null, null, null
|
||||
\t],
|
||||
\t"morph_arrays":[]
|
||||
}
|
||||
|
||||
[node type="Spatial" name="Scene"]
|
||||
|
||||
[node name="Cube" type="MeshInstance" parent="."]
|
||||
|
||||
mesh = SubResource(2)
|
||||
visible = true
|
||||
transform = Transform(1.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 1.0, 0.0, 2.0, 3.0, 4.0)
|
||||
|
||||
[node name="Strip" type="MeshInstance" parent="Cube"]
|
||||
|
||||
mesh = SubResource(3)
|
||||
transform = Transform(2.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 1.0)
|
||||
|
||||
[node name="Camera" type="Camera" parent="."]
|
||||
|
||||
fov = 60.0
|
||||
far = 250.0
|
||||
|
||||
[node name="Lamp" type="OmniLight" parent="."]
|
||||
|
||||
light_color = Color(1, 1, 0.5, 1)
|
||||
light_energy = 3.0
|
||||
omni_range = 9.0
|
||||
transform = Transform(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 5, 0)
|
||||
"""
|
||||
|
||||
TRES = [
|
||||
("material.tres", """[gd_resource type="StandardMaterial3D" load_steps=2 format=3 uid="uid://b1x2y3z4"]
|
||||
|
||||
[ext_resource type="Texture2D" path="res://checker.png" id="1_ab"]
|
||||
|
||||
[resource]
|
||||
resource_name = "Brick"
|
||||
albedo_color = Color(0.8, 0.4, 0.2, 1)
|
||||
albedo_texture = ExtResource("1_ab")
|
||||
metallic = 0.25
|
||||
uv1_scale = Vector3(2, 2, 1)
|
||||
"""),
|
||||
("data.tres", """[gd_resource type="Resource" script_class="Stats" load_steps=3 format=3]
|
||||
|
||||
[ext_resource type="Script" path="res://stats.gd" id="1"]
|
||||
|
||||
[sub_resource type="Curve" id="Curve_1"]
|
||||
_data = [Vector2(0, 0), 0.0, 1.0, 0, 0, Vector2(1, 1), 1.0, 0.0, 0, 0]
|
||||
point_count = 2
|
||||
|
||||
[resource]
|
||||
script = ExtResource("1")
|
||||
name = "Goblin \\"Grr\\"\\nline two"
|
||||
hp = 12
|
||||
speed = 3.5
|
||||
tags = PackedStringArray("green", "small")
|
||||
weights = PackedFloat32Array(0.5, 0.25, -1e-05, inf)
|
||||
spawn = Vector3i(1, -2, 3)
|
||||
rect = Rect2(0, 0, 32, 16)
|
||||
curve = SubResource("Curve_1")
|
||||
drops = {
|
||||
"gold": 5,
|
||||
"items": [&"sword", NodePath("../Path"), null, true],
|
||||
3: Color(1, 0, 0, 1)
|
||||
}
|
||||
typed = Array[int]([1, 2, 3])
|
||||
basis = Basis(1, 0, 0, 0, 1, 0, 0, 0, 1)
|
||||
quat = Quaternion(0, 0, 0, 1)
|
||||
obj = Object(Resource,"resource_local_to_scene":false,"resource_name":"x")
|
||||
"""),
|
||||
]
|
||||
|
||||
|
||||
def png(w, h):
|
||||
def chunk(t, d):
|
||||
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xffffffff)
|
||||
raw = b"".join(b"\0" + bytes(((x + y) % 2) * 255 for x in range(w) for _ in range(3)) for y in range(h))
|
||||
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def godot(ctx, project, args):
|
||||
cmd = ["nix", "shell", "nixpkgs#godot_4", "-c", "godot", "--headless", "--path", project] + args
|
||||
return subprocess.run(cmd, capture_output=True, timeout=600).stdout.decode("utf-8", "replace")
|
||||
|
||||
|
||||
def dump(ctx, project, files):
|
||||
out = godot(ctx, project, ["-s", os.path.join(ctx.root, "tools", "fixtures", "_godot_dump.gd"), "--"] + ["res://" + f for f in files])
|
||||
res = {}
|
||||
for line in out.split("\n"):
|
||||
if line.startswith("JSON:"):
|
||||
d = json.loads(line[5:])
|
||||
res[d["file"][6:]] = d
|
||||
return res
|
||||
|
||||
|
||||
STATS_GD = """class_name Stats
|
||||
extends Resource
|
||||
@export var name: String
|
||||
@export var hp: int
|
||||
@export var speed: float
|
||||
@export var tags: PackedStringArray
|
||||
@export var weights: PackedFloat32Array
|
||||
@export var spawn: Vector3i
|
||||
@export var rect: Rect2
|
||||
@export var curve: Curve
|
||||
@export var drops: Dictionary
|
||||
@export var typed: Array[int]
|
||||
@export var basis: Basis
|
||||
@export var quat: Quaternion
|
||||
@export var obj: Resource
|
||||
"""
|
||||
|
||||
|
||||
def tres_dump(ctx, project, files):
|
||||
out = godot(ctx, project, ["-s", os.path.join(ctx.root, "tools", "fixtures", "_godot_tres.gd"), "--"] + ["res://" + f for f in files])
|
||||
res = {}
|
||||
for line in out.split("\n"):
|
||||
if line.startswith("JSON:"):
|
||||
d = json.loads(line[5:])
|
||||
res[d["file"][6:]] = d
|
||||
return res
|
||||
|
||||
|
||||
def clean(v):
|
||||
# None cannot sit in a Luau table: drop null fields
|
||||
if isinstance(v, dict):
|
||||
return {k: clean(x) for k, x in v.items() if x is not None}
|
||||
if isinstance(v, list):
|
||||
return [clean(x) for x in v if x is not None]
|
||||
return v
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp(prefix="rosetta-godot-")
|
||||
try:
|
||||
with open(os.path.join(tmp, "project.godot"), "w") as f:
|
||||
f.write('config_version=5\n[application]\nconfig/name="rosetta"\n')
|
||||
checker = png(4, 4)
|
||||
with open(os.path.join(tmp, "checker.png"), "wb") as f:
|
||||
f.write(checker)
|
||||
godot(ctx, tmp, ["--import"])
|
||||
godot(ctx, tmp, ["-s", os.path.join(ctx.root, "tools", "fixtures", "_godot_make.gd")])
|
||||
made = ["part.tscn", "main.tscn"]
|
||||
dumps = dump(ctx, tmp, made)
|
||||
read = lambda f: open(os.path.join(tmp, f), "rb").read()
|
||||
cases = []
|
||||
for f in made:
|
||||
cases.append({"name": f, "data": read(f), "files": {"part.tscn": read("part.tscn"), "checker.png": checker}, "dump": clean(dumps.get(f, {}))})
|
||||
cases.append({"name": "hand.escn", "data": ESCN.encode(), "files": {}})
|
||||
with open(os.path.join(tmp, "stats.gd"), "w") as f:
|
||||
f.write(STATS_GD)
|
||||
for n, t in TRES:
|
||||
with open(os.path.join(tmp, n), "w") as f:
|
||||
f.write(t)
|
||||
td = tres_dump(ctx, tmp, [n for n, _ in TRES])
|
||||
tres = [{"name": n, "data": t.encode(), "godot": td.get(n, {"ok": False})} for n, t in TRES]
|
||||
ctx.emit("godot", {"cases": cases, "tres": tres})
|
||||
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 = M.luau_encode(ctx, "tools/fixtures/_godot_encode.luau")
|
||||
names = sorted(ours)
|
||||
for n in names:
|
||||
with open(os.path.join(tmp, n), "wb") as f:
|
||||
f.write(ours[n])
|
||||
scenes = [n for n in names if n.endswith(".tscn")]
|
||||
od = dump(ctx, tmp, scenes)
|
||||
rd = tres_dump(ctx, tmp, [n for n in names if n.endswith(".tres")])
|
||||
ctx.emit("godot_ours", [{"name": n, "data": ours[n], "dump": clean(od.get(n, {"ok": False}))} for n in scenes] +
|
||||
[{"name": n, "data": ours[n], "godot": rd.get(n, {"ok": False})} for n in names if n.endswith(".tres")])
|
||||
finally:
|
||||
shutil.rmtree(tmp)
|
||||
@@ -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)
|
||||
@@ -0,0 +1,165 @@
|
||||
# Ogmo Editor 3 fixtures (tools/fixtures.py): the HaxeFlixel TurnBasedRPG project + level (tests/fixtures/ogmo, MIT,
|
||||
# saved by Ogmo 3.3), and a project + levels written here in the shapes OgmoEditor3-CE 3.4 saves (src/modules/*/
|
||||
# *Layer.hx save(): tile layers as ids / coords in 1D / 2D arrays with tileFlags, grid layers 1D / 2D, entities with
|
||||
# origin, rotation (radians), flips, nodes and values, decals). Reference values come from a Python reading of the
|
||||
# same layouts (what the editor's load() does). Then our encoder's output (tools/fixtures/_ogmo_encode.luau) is read
|
||||
# by the same Python reader.
|
||||
# tests/gen/ogmo.luau { cases = { { name, data, project, stats } }, projects = { { name, data } } }
|
||||
# tests/gen/ogmo_ours.luau { { name, stats } }
|
||||
import base64, importlib.util, json, math, os, struct, zlib
|
||||
|
||||
INPUTS = ["tests/fixtures/ogmo", "src/Rosetta/vector/ogmo", "tools/fixtures/_ogmo_encode.luau", "tools/fixtures/_model_ref.py"]
|
||||
|
||||
|
||||
def png(w, h):
|
||||
def chunk(t, d):
|
||||
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xffffffff)
|
||||
raw = b"".join(b"\0" + bytes((x * 7 + y * 3) & 255 for x in range(w * 3)) for y in range(h))
|
||||
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def project():
|
||||
uri = "data:image/png;base64," + base64.b64encode(png(64, 32)).decode()
|
||||
uri2 = "data:image/png;base64," + base64.b64encode(png(36, 20)).decode()
|
||||
return {
|
||||
"name": "Rosetta test", "ogmoVersion": "3.4.0", "levelPaths": ["."], "backgroundColor": "#282c34ff",
|
||||
"gridColor": "#3c4049cc", "anglesRadians": True, "directoryDepth": 5, "layerGridDefaultSize": {"x": 8, "y": 8},
|
||||
"levelDefaultSize": {"x": 64, "y": 48}, "levelMinSize": {"x": 8, "y": 8}, "levelMaxSize": {"x": 4096, "y": 4096},
|
||||
"levelValues": [{"name": "music", "definition": "String", "display": 0, "defaults": ""},
|
||||
{"name": "gravity", "definition": "Float", "display": 0, "defaults": 1, "bounded": False, "min": 0, "max": 100}],
|
||||
"defaultExportMode": ".json", "compactExport": False, "externalScript": "", "playCommand": "", "entityTags": [],
|
||||
"layers": [
|
||||
{"definition": "entity", "name": "things", "gridSize": {"x": 8, "y": 8}, "exportID": "11", "requiredTags": [], "excludedTags": []},
|
||||
{"definition": "decal", "name": "decor", "gridSize": {"x": 8, "y": 8}, "exportID": "12", "folder": "decals", "includeImageSequence": True, "scaleable": True, "rotatable": True, "values": []},
|
||||
{"definition": "tile", "name": "front", "gridSize": {"x": 8, "y": 8}, "exportID": "13", "exportMode": 1, "arrayMode": 1, "defaultTileset": "small"},
|
||||
{"definition": "grid", "name": "solid", "gridSize": {"x": 16, "y": 16}, "exportID": "14", "arrayMode": 1, "legend": {"0": "#00000000", "1": "#ffffffff", "w": "#0000ffff"}},
|
||||
{"definition": "grid", "name": "zones", "gridSize": {"x": 8, "y": 8}, "exportID": "15", "arrayMode": 0, "legend": {"0": "#00000000", "1": "#ff0000ff"}},
|
||||
{"definition": "tile", "name": "back", "gridSize": {"x": 8, "y": 8}, "exportID": "16", "exportMode": 0, "arrayMode": 0, "defaultTileset": "main"},
|
||||
],
|
||||
"entities": [
|
||||
{"exportID": "21", "name": "player", "limit": 1, "size": {"x": 8, "y": 16}, "origin": {"x": 4, "y": 16}, "originAnchored": True,
|
||||
"shape": {"label": "Rectangle", "points": []}, "color": "#ff0000ff", "tileX": False, "tileY": False, "tileSize": {"x": 8, "y": 8},
|
||||
"resizeableX": False, "resizeableY": False, "rotatable": True, "rotationDegrees": 360, "canFlipX": True, "canFlipY": False,
|
||||
"canSetColor": False, "hasNodes": True, "nodeLimit": 0, "nodeDisplay": 0, "nodeGhost": True, "tags": [],
|
||||
"values": [{"name": "hp", "definition": "Integer", "display": 0, "defaults": 3, "bounded": False, "min": 0, "max": 100},
|
||||
{"name": "boss", "definition": "Boolean", "display": 0, "defaults": False}]},
|
||||
{"exportID": "22", "name": "door", "limit": -1, "size": {"x": 8, "y": 8}, "origin": {"x": 0, "y": 0}, "originAnchored": True,
|
||||
"shape": {"label": "Rectangle", "points": []}, "color": "#00ff00ff", "tileX": False, "tileY": False, "tileSize": {"x": 8, "y": 8},
|
||||
"resizeableX": True, "resizeableY": True, "rotatable": False, "rotationDegrees": 360, "canFlipX": False, "canFlipY": False,
|
||||
"canSetColor": False, "hasNodes": False, "nodeLimit": 0, "nodeDisplay": 0, "nodeGhost": True, "tags": [], "values": []},
|
||||
],
|
||||
"tilesets": [
|
||||
{"label": "main", "path": "tiles/main.png", "image": uri, "tileWidth": 8, "tileHeight": 8, "tileSeparationX": 0, "tileSeparationY": 0, "tileMarginX": 0, "tileMarginY": 0},
|
||||
{"label": "small", "path": "tiles/small.png", "image": uri2, "tileWidth": 8, "tileHeight": 8, "tileSeparationX": 1, "tileSeparationY": 1, "tileMarginX": 1, "tileMarginY": 1},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def level(rng, w, h):
|
||||
cx, cy = w // 8, h // 8
|
||||
ids = [(-1 if rng.random() < 0.3 else rng.randrange(32)) for _ in range(cx * cy)]
|
||||
flags = [(rng.choice([0, 0, 0, 4, 2, 1, 6]) if t >= 0 else 0) for t in ids]
|
||||
# "small": (36 - 2 + 1) // 9 = 3 columns, 2 rows
|
||||
coords = [[-1] if rng.random() < 0.5 else [rng.randrange(3), rng.randrange(2)] for _ in range(cx * cy)]
|
||||
rows = lambda flat, n: [flat[i * n:(i + 1) * n] for i in range(len(flat) // n)]
|
||||
gx, gy = w // 16, h // 16
|
||||
solid = [rng.choice("001w") for _ in range(gx * gy)]
|
||||
zones = [rng.choice("0001") for _ in range(cx * cy)]
|
||||
base = {"offsetX": 0, "offsetY": 0}
|
||||
return {
|
||||
"ogmoVersion": "3.4.0", "width": w, "height": h, "offsetX": 0, "offsetY": 0,
|
||||
"values": {"music": "cave.ogg", "gravity": 9.5},
|
||||
"layers": [
|
||||
dict(name="things", _eid="11", gridCellWidth=8, gridCellHeight=8, gridCellsX=cx, gridCellsY=cy, **base, entities=[
|
||||
{"name": "player", "id": 0, "_eid": "21", "x": 20, "y": 32, "originX": 4, "originY": 16, "rotation": math.pi / 2,
|
||||
"flippedX": True, "nodes": [{"x": 40, "y": 32}, {"x": 48, "y": 8}], "values": {"hp": 5, "boss": False}},
|
||||
{"name": "door", "id": 1, "_eid": "22", "x": 8, "y": 0, "width": 16, "height": 24, "originX": 0, "originY": 0},
|
||||
]),
|
||||
dict(name="decor", _eid="12", gridCellWidth=8, gridCellHeight=8, gridCellsX=cx, gridCellsY=cy, **base, decals=[
|
||||
{"x": 12, "y": 14, "scaleX": 2, "scaleY": 1, "rotation": math.pi, "texture": "tree.png", "originX": 0.5, "originY": 1},
|
||||
], folder="decals"),
|
||||
dict(name="front", _eid="13", gridCellWidth=8, gridCellHeight=8, gridCellsX=cx, gridCellsY=cy, **base, tileset="small",
|
||||
dataCoords2D=rows(coords, cx), exportMode=1, arrayMode=1),
|
||||
dict(name="solid", _eid="14", gridCellWidth=16, gridCellHeight=16, gridCellsX=gx, gridCellsY=gy, **base, grid2D=rows(solid, gx), arrayMode=1),
|
||||
dict(name="zones", _eid="15", gridCellWidth=8, gridCellHeight=8, gridCellsX=cx, gridCellsY=cy, **base, grid=zones, arrayMode=0),
|
||||
dict(name="back", _eid="16", gridCellWidth=8, gridCellHeight=8, gridCellsX=cx, gridCellsY=cy, **base, tileset="main", data=ids,
|
||||
tileFlags=flags, exportMode=0, arrayMode=0),
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def flat(v2):
|
||||
return [c for row in v2 for c in row]
|
||||
|
||||
|
||||
def stats(lv, proj):
|
||||
"""what Ogmo's load() reads, summarised; layers bottom first"""
|
||||
radians = proj.get("anglesRadians", True) if proj else True
|
||||
tsets = {t["label"]: t for t in (proj or {}).get("tilesets", [])}
|
||||
defs = {e["name"]: e for e in (proj or {}).get("entities", [])}
|
||||
out = []
|
||||
for li in reversed(lv["layers"]):
|
||||
d = {"name": li["name"], "w": li["gridCellsX"], "h": li["gridCellsY"]}
|
||||
if "entities" in li:
|
||||
ents = []
|
||||
for e in li["entities"]:
|
||||
t = defs.get(e["name"], {})
|
||||
rot = e.get("rotation", 0)
|
||||
ents.append("%s@%g,%g %gx%g r%d n%d %s" % (e["name"], e["x"] - e.get("originX", 0), e["y"] - e.get("originY", 0),
|
||||
e.get("width", t.get("size", {}).get("x", 16)), e.get("height", t.get("size", {}).get("y", 16)),
|
||||
round(math.degrees(rot) if radians else rot), len(e.get("nodes", [])),
|
||||
",".join("%s=%s" % (k, json.dumps(v)) for k, v in sorted(e.get("values", {}).items()))))
|
||||
d["kind"], d["items"] = "entity", ents
|
||||
elif "decals" in li:
|
||||
d["kind"] = "decal"
|
||||
d["items"] = ["%s@%g,%g s%g,%g r%d" % (x["texture"], x["x"], x["y"], x.get("scaleX", 1), x.get("scaleY", 1),
|
||||
round(math.degrees(x.get("rotation", 0)) if radians else x.get("rotation", 0))) for x in li["decals"]]
|
||||
elif "grid" in li or "grid2D" in li:
|
||||
d["kind"] = "grid"
|
||||
d["cells"] = "".join(str(c) for c in (li["grid"] if "grid" in li else flat(li["grid2D"])))
|
||||
else:
|
||||
d["kind"] = "tile"
|
||||
ts = tsets.get(li.get("tileset"))
|
||||
cols = 1
|
||||
if ts:
|
||||
img = base64.b64decode(ts["image"].split(",", 1)[1])
|
||||
iw = struct.unpack(">I", img[16:20])[0]
|
||||
sx, mx = ts.get("tileSeparationX", 0), ts.get("tileMarginX", 0)
|
||||
cols = max(1, (iw - 2 * mx + sx) // (ts["tileWidth"] + sx))
|
||||
if li.get("exportMode", 0) == 1:
|
||||
cells = li["dataCoords"] if li.get("arrayMode", 0) == 0 else flat(li["dataCoords2D"])
|
||||
ids = [-1 if c[0] == -1 else c[1] * cols + c[0] for c in cells]
|
||||
else:
|
||||
ids = li["data"] if li.get("arrayMode", 0) == 0 else flat(li["data2D"])
|
||||
fl = li.get("tileFlags") or (flat(li["tileFlags2D"]) if "tileFlags2D" in li else [0] * len(ids))
|
||||
d["tileset"] = li.get("tileset", "")
|
||||
d["nonEmpty"] = sum(1 for i in ids if i >= 0)
|
||||
d["idSum"] = sum((i + 1) * (k % 7 + 1) for k, i in enumerate(ids))
|
||||
d["flagSum"] = sum(f * (k % 5 + 1) for k, f in enumerate(fl))
|
||||
out.append(d)
|
||||
return {"width": lv["width"], "height": lv["height"], "values": ",".join("%s=%s" % (k, json.dumps(v)) for k, v in sorted(lv.get("values", {}).items())), "layers": out}
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(11)
|
||||
src = os.path.join(ctx.root, "tests", "fixtures", "ogmo")
|
||||
rpg_proj = open(os.path.join(src, "turnBasedRPG.ogmo"), "rb").read()
|
||||
rpg_lvl = open(os.path.join(src, "room-001.json"), "rb").read()
|
||||
proj = project()
|
||||
proj_bytes = json.dumps(proj, indent=2).encode()
|
||||
cases = [{"name": "turnBasedRPG/room-001", "data": rpg_lvl, "project": rpg_proj, "stats": stats(json.loads(rpg_lvl), json.loads(rpg_proj))}]
|
||||
for i, (w, h) in enumerate([(64, 48), (128, 32)]):
|
||||
lv = level(rng, w, h)
|
||||
cases.append({"name": "made/level%d" % i, "data": json.dumps(lv).encode(), "project": proj_bytes, "stats": stats(lv, proj)})
|
||||
projects = [{"name": "turnBasedRPG.ogmo", "data": rpg_proj}, {"name": "made.ogmo", "data": proj_bytes}]
|
||||
ctx.emit("ogmo", {"cases": cases, "projects": projects})
|
||||
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 = []
|
||||
out = M.luau_encode(ctx, "tools/fixtures/_ogmo_encode.luau")
|
||||
for c in cases:
|
||||
lv, pj = out.get(c["name"] + ".json"), out.get(c["name"] + ".ogmo")
|
||||
if lv and pj:
|
||||
ours.append({"name": c["name"], "stats": stats(json.loads(lv), json.loads(pj))})
|
||||
ctx.emit("ogmo_ours", ours)
|
||||
@@ -0,0 +1,204 @@
|
||||
# Unreal T3D fixtures (tools/fixtures.py): maps written here in UnrealEd's export layout (UE1-3: Begin Map / Actor /
|
||||
# Brush / PolyList / Polygon with Origin / Normal / TextureU / TextureV / Pan / Vertex records, Location / Rotation in
|
||||
# 65536ths of a turn, PrePivot / MainScale / PostScale; UE4: Begin Level, components with Relative* in degrees), with
|
||||
# reference values computed here independently: each brush's world vertices (ABrush coords: v - PrePivot, MainScale,
|
||||
# FRotationMatrix, PostScale, + Location), polygon areas per texture, bounds, and the texel coordinates of probe
|
||||
# vertices; actors, lights and static mesh references.
|
||||
# tests/gen/t3d.luau { cases = { { name, data, sizes = { [texture] = { w, h } }, actors = { { name, class, mesh?,
|
||||
# area = { [texture] = a }, triangles, min, max, probe = { x, y, z, u, v }, origin } } } } }
|
||||
import math
|
||||
|
||||
INPUTS = ["src/Rosetta/model/t3d"]
|
||||
|
||||
|
||||
def box(sx, sy, sz, tex):
|
||||
"""an axis box centred on 0: six quads as UnrealEd's cube builder lists them (CCW about the outward normal)"""
|
||||
hx, hy, hz = sx / 2, sy / 2, sz / 2
|
||||
faces = []
|
||||
for axis in range(3):
|
||||
for sign in (-1, 1):
|
||||
n = [0, 0, 0]
|
||||
n[axis] = sign
|
||||
a, b = [(1, 2), (2, 0), (0, 1)][axis]
|
||||
h = [hx, hy, hz]
|
||||
pts = []
|
||||
for ca, cb in ((-1, -1), (-1, 1), (1, 1), (1, -1)) if sign < 0 else ((-1, -1), (1, -1), (1, 1), (-1, 1)):
|
||||
p = [0, 0, 0]
|
||||
p[axis] = sign * h[axis]
|
||||
p[a] = ca * h[a]
|
||||
p[b] = cb * h[b]
|
||||
pts.append(p)
|
||||
# make it CCW about n (right-handed cross)
|
||||
e1 = [pts[1][i] - pts[0][i] for i in range(3)]
|
||||
e2 = [pts[2][i] - pts[0][i] for i in range(3)]
|
||||
c = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]]
|
||||
if sum(c[i] * n[i] for i in range(3)) < 0:
|
||||
pts.reverse()
|
||||
u = [0, 0, 0]
|
||||
v = [0, 0, 0]
|
||||
u[a] = 1
|
||||
v[b] = -1
|
||||
faces.append({"tex": tex(axis, sign), "normal": n, "origin": pts[0], "u": u, "v": v, "pan": (axis * 8, sign * 4), "verts": pts, "flags": 0})
|
||||
return faces
|
||||
|
||||
|
||||
def fmt(v):
|
||||
return ",".join("%+013.6f" % x for x in v)
|
||||
|
||||
|
||||
def polylist(faces, ind=" "):
|
||||
out = [ind + "Begin PolyList"]
|
||||
for f in faces:
|
||||
out.append(ind + " Begin Polygon Texture=%s Flags=%d Link=0" % (f["tex"], f["flags"]))
|
||||
out.append(ind + " Origin " + fmt(f["origin"]))
|
||||
out.append(ind + " Normal " + fmt(f["normal"]))
|
||||
out.append(ind + " TextureU " + fmt(f["u"]))
|
||||
out.append(ind + " TextureV " + fmt(f["v"]))
|
||||
out.append(ind + " Pan U=%d V=%d" % f["pan"])
|
||||
for p in f["verts"]:
|
||||
out.append(ind + " Vertex " + fmt(p))
|
||||
out.append(ind + " End Polygon")
|
||||
out.append(ind + "End PolyList")
|
||||
return out
|
||||
|
||||
|
||||
def rotmat(pitch, yaw, roll, k):
|
||||
p, y, r = pitch * k, yaw * k, roll * k
|
||||
SP, CP, SY, CY, SR, CR = math.sin(p), math.cos(p), math.sin(y), math.cos(y), math.sin(r), math.cos(r)
|
||||
# FRotationMatrix rows = axes
|
||||
return [[CP * CY, CP * SY, SP], [SR * SP * CY - CR * SY, SR * SP * SY + CR * CY, -SR * CP], [-(CR * SP * CY + SR * SY), CY * SR - CR * SP * SY, CR * CP]]
|
||||
|
||||
|
||||
def world(v, a):
|
||||
x = [v[i] - a["prepivot"][i] for i in range(3)]
|
||||
x = [x[i] * a["main"][i] for i in range(3)]
|
||||
R = a["rot"]
|
||||
x = [x[0] * R[0][i] + x[1] * R[1][i] + x[2] * R[2][i] for i in range(3)]
|
||||
x = [x[i] * a["post"][i] for i in range(3)]
|
||||
return [x[i] + a["loc"][i] for i in range(3)]
|
||||
|
||||
|
||||
def area(pts):
|
||||
ax = ay = az = 0
|
||||
for k in range(1, len(pts) - 1):
|
||||
u = [pts[k][i] - pts[0][i] for i in range(3)]
|
||||
v = [pts[k + 1][i] - pts[0][i] for i in range(3)]
|
||||
ax += u[1] * v[2] - u[2] * v[1]
|
||||
ay += u[2] * v[0] - u[0] * v[2]
|
||||
az += u[0] * v[1] - u[1] * v[0]
|
||||
return math.sqrt(ax * ax + ay * ay + az * az) / 2
|
||||
|
||||
|
||||
def reference(a, faces, sizes, builder=False):
|
||||
ref = {"name": a["name"], "class": a["class"]}
|
||||
if builder:
|
||||
return ref
|
||||
ar, tris = {}, 0
|
||||
lo, hi = [1e30] * 3, [-1e30] * 3
|
||||
for f in faces:
|
||||
w = [world(p, a) for p in f["verts"]]
|
||||
ar[f["tex"]] = ar.get(f["tex"], 0) + area(w)
|
||||
tris += len(w) - 2
|
||||
for p in w:
|
||||
lo = [min(lo[i], p[i]) for i in range(3)]
|
||||
hi = [max(hi[i], p[i]) for i in range(3)]
|
||||
f = faces[0]
|
||||
p = f["verts"][2]
|
||||
W, H = sizes.get(f["tex"], (256, 256))
|
||||
du = sum((p[i] - f["origin"][i]) * f["u"][i] for i in range(3)) + f["pan"][0]
|
||||
dv = sum((p[i] - f["origin"][i]) * f["v"][i] for i in range(3)) + f["pan"][1]
|
||||
ref.update({"mesh": True, "area": ar, "triangles": tris, "min": lo, "max": hi, "probe": list(p) + [du / W, dv / H]})
|
||||
return ref
|
||||
|
||||
|
||||
K = math.pi * 2 / 65536
|
||||
|
||||
|
||||
def ue1():
|
||||
sizes = {"Bricks": (128, 64), "Floor": (256, 256), "Glass": (64, 64)}
|
||||
lines = ["Begin Map", "Begin Actor Class=LevelInfo Name=LevelInfo0", " Title=\"Test Level\"", " Author=\"rosetta\"", "End Actor"]
|
||||
actors = []
|
||||
# the builder brush (skipped)
|
||||
builder = {"name": "Brush", "class": "Brush", "loc": [0, 0, 0], "rot": rotmat(0, 0, 0, K), "prepivot": [0, 0, 0], "main": [1, 1, 1], "post": [1, 1, 1]}
|
||||
fb = box(256, 256, 256, lambda a, s: "Bricks")
|
||||
lines += ["Begin Actor Class=Brush Name=Brush", " MainScale=(SheerAxis=SHEER_ZX)", " PostScale=(SheerAxis=SHEER_ZX)", " Begin Brush Name=Brush"] + polylist(fb) + [" End Brush", " Brush=Model'MyLevel.Brush'", "End Actor"]
|
||||
actors.append(reference(builder, fb, sizes, True))
|
||||
# a subtracted room: yawed a quarter turn, pre-pivot, main scale
|
||||
room = {"name": "Brush0", "class": "Brush", "loc": [64, -32, 16], "rot": rotmat(0, 16384, 0, K), "prepivot": [16, 0, 8], "main": [2, 1, 0.5], "post": [1, 1, 1]}
|
||||
fr = box(512, 384, 256, lambda a, s: "Floor" if a == 2 else "Bricks")
|
||||
lines += ["Begin Actor Class=Brush Name=Brush0", " CsgOper=CSG_Subtract", " MainScale=(Scale=(X=2.000000,Z=0.500000),SheerAxis=SHEER_ZX)",
|
||||
" PostScale=(SheerAxis=SHEER_ZX)", " Location=(X=64.000000,Y=-32.000000,Z=16.000000)", " Rotation=(Yaw=16384)",
|
||||
" PrePivot=(X=16.000000,Z=8.000000)", " Begin Brush Name=Model1"] + polylist(fr) + [" End Brush", " Brush=Model'MyLevel.Model1'", "End Actor"]
|
||||
actors.append(reference(room, fr, sizes))
|
||||
# an added pillar: pitch + roll, post scale
|
||||
pil = {"name": "Brush1", "class": "Brush", "loc": [-100, 50, 0], "rot": rotmat(8192, 0, 4096, K), "prepivot": [0, 0, 0], "main": [1, 1, 1], "post": [1, 1.5, 2]}
|
||||
fp = box(32, 32, 200, lambda a, s: "Glass")
|
||||
for f in fp[:2]:
|
||||
f["flags"] = 2
|
||||
lines += ["Begin Actor Class=Brush Name=Brush1", " CsgOper=CSG_Add", " PostScale=(Scale=(Y=1.500000,Z=2.000000),SheerAxis=SHEER_ZX)",
|
||||
" Location=(X=-100.000000,Y=50.000000)", " Rotation=(Pitch=8192,Roll=4096)", " Begin Brush Name=Model2"] + polylist(fp) + [" End Brush", " Brush=Model'MyLevel.Model2'", "End Actor"]
|
||||
actors.append(reference(pil, fp, sizes))
|
||||
lines += ["Begin Actor Class=Light Name=Light0", " LightBrightness=128", " LightHue=40", " LightSaturation=64", " LightRadius=32",
|
||||
" Location=(X=0.000000,Y=0.000000,Z=96.000000)", "End Actor"]
|
||||
actors.append({"name": "Light0", "class": "Light", "origin": [0, 0, 96]})
|
||||
lines += ["Begin Actor Class=PlayerStart Name=PlayerStart0", " Location=(X=10.000000,Y=20.000000,Z=30.000000)", " Rotation=(Yaw=-16384)", " DrawScale=2.000000", "End Actor"]
|
||||
actors.append({"name": "PlayerStart0", "class": "PlayerStart", "origin": [10, 20, 30]})
|
||||
lines += ["End Map", ""]
|
||||
return "\r\n".join(lines), sizes, actors
|
||||
|
||||
|
||||
def ue4():
|
||||
sizes = {}
|
||||
lines = ["Begin Map", " Begin Level"]
|
||||
actors = []
|
||||
a = {"name": "Brush_1", "class": "/Script/Engine.Brush", "loc": [100, 200, 300], "rot": rotmat(0, 45, 0, math.pi / 180), "prepivot": [0, 0, 0], "main": [1, 1, 1], "post": [1, 1, 1]}
|
||||
fb = box(200, 200, 100, lambda ax, s: "/Game/Materials/M_Wall.M_Wall")
|
||||
lines += [" Begin Actor Class=/Script/Engine.Brush Name=Brush_1 Archetype=/Script/Engine.Brush'/Script/Engine.Default__Brush'",
|
||||
" Begin Object Class=/Script/Engine.BrushComponent Name=\"BrushComponent0\" Archetype=BrushComponent'/Script/Engine.Default__Brush:BrushComponent0'",
|
||||
" End Object",
|
||||
" Begin Object Name=\"BrushComponent0\"",
|
||||
" Brush=Model'\"Model_1\"'",
|
||||
" RelativeLocation=(X=100.000000,Y=200.000000,Z=300.000000)",
|
||||
" RelativeRotation=(Pitch=0.000000,Yaw=45.000000,Roll=0.000000)",
|
||||
" End Object",
|
||||
" BrushType=Brush_Add",
|
||||
" Begin Brush Name=Model_1"] + polylist(fb, " ") + [" End Brush",
|
||||
" Brush=Model'\"Model_1\"'", " BrushComponent=BrushComponent'\"BrushComponent0\"'", " RootComponent=BrushComponent'\"BrushComponent0\"'",
|
||||
" ActorLabel=\"Box Brush\"", " End Actor"]
|
||||
actors.append(reference(a, fb, sizes))
|
||||
lines += [" Begin Actor Class=/Script/Engine.StaticMeshActor Name=StaticMeshActor_3",
|
||||
" Begin Object Class=/Script/Engine.StaticMeshComponent Name=\"StaticMeshComponent0\"",
|
||||
" End Object",
|
||||
" Begin Object Name=\"StaticMeshComponent0\"",
|
||||
" StaticMesh=StaticMesh'\"/Game/Meshes/SM_Chair.SM_Chair\"'",
|
||||
" RelativeLocation=(X=-50.000000,Y=0.000000,Z=10.000000)",
|
||||
" RelativeScale3D=(X=2.000000,Y=2.000000,Z=2.000000)",
|
||||
" End Object",
|
||||
" StaticMeshComponent=StaticMeshComponent0",
|
||||
" RootComponent=StaticMeshComponent0",
|
||||
" End Actor"]
|
||||
actors.append({"name": "StaticMeshActor_3", "class": "/Script/Engine.StaticMeshActor", "origin": [-50, 0, 10], "staticMesh": "/Game/Meshes/SM_Chair.SM_Chair"})
|
||||
lines += [" Begin Actor Class=/Script/Engine.PointLight Name=PointLight_0",
|
||||
" Begin Object Class=/Script/Engine.PointLightComponent Name=\"LightComponent0\"",
|
||||
" End Object",
|
||||
" Begin Object Name=\"LightComponent0\"",
|
||||
" AttenuationRadius=500.000000",
|
||||
" Intensity=3000.000000",
|
||||
" LightColor=(B=64,G=128,R=255,A=255)",
|
||||
" RelativeLocation=(X=0.000000,Y=0.000000,Z=250.000000)",
|
||||
" End Object",
|
||||
" PointLightComponent=LightComponent0",
|
||||
" LightComponent=LightComponent0",
|
||||
" RootComponent=LightComponent0",
|
||||
" End Actor"]
|
||||
actors.append({"name": "PointLight_0", "class": "/Script/Engine.PointLight", "origin": [0, 0, 250]})
|
||||
lines += [" End Level", "Begin Surface", "End Surface", "End Map", ""]
|
||||
return "\n".join(lines), sizes, actors
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
cases = []
|
||||
for name, f in (("ue1.t3d", ue1), ("ue4.t3d", ue4)):
|
||||
text, sizes, actors = f()
|
||||
cases.append({"name": name, "data": text.encode(), "sizes": {k: list(v) for k, v in sizes.items()}, "actors": actors})
|
||||
ctx.emit("t3d", {"cases": cases})
|
||||
@@ -0,0 +1,95 @@
|
||||
# .unitypackage fixtures (tools/fixtures.py): packages built here with Python's tarfile + gzip to the layout Unity
|
||||
# writes (<guid>/asset, <guid>/asset.meta, <guid>/pathname, optional preview.png; folders carry only a meta), with
|
||||
# the expected asset table; then our encoder's output (tools/fixtures/_unitypackage_encode.luau) read back by
|
||||
# Python's tarfile.
|
||||
# tests/gen/unitypackage.luau { cases = { { name, data, assets = { { path, guid, md5?, metaMd5, dir } } } },
|
||||
# ours = { { name, ok, assets = { { path, guid, md5?, metaMd5, dir } }, error? } } }
|
||||
import gzip, hashlib, importlib.util, io, os, tarfile, uuid
|
||||
|
||||
INPUTS = ["src/Rosetta/archive/unitypackage", "tools/fixtures/_unitypackage_encode.luau", "tools/fixtures/_model_ref.py"]
|
||||
|
||||
|
||||
def meta(guid, folder=False):
|
||||
s = "fileFormatVersion: 2\nguid: %s\n" % guid
|
||||
if folder:
|
||||
s += "folderAsset: yes\n"
|
||||
return (s + "DefaultImporter:\n externalObjects: {}\n userData: \n").encode()
|
||||
|
||||
|
||||
def build(items, dot=False, extra_line=False, mtime=1600000000):
|
||||
"""items: [(path, data or None for a folder, preview bytes or None)]"""
|
||||
raw = io.BytesIO()
|
||||
assets = []
|
||||
with tarfile.open(fileobj=raw, mode="w", format=tarfile.GNU_FORMAT) as tf:
|
||||
def add(name, data):
|
||||
ti = tarfile.TarInfo(("./" if dot else "") + name)
|
||||
ti.size = len(data)
|
||||
ti.mtime = mtime
|
||||
tf.addfile(ti, io.BytesIO(data))
|
||||
for path, data, preview in items:
|
||||
guid = uuid.uuid5(uuid.NAMESPACE_URL, path).hex
|
||||
d = tarfile.TarInfo(("./" if dot else "") + guid)
|
||||
d.type = tarfile.DIRTYPE
|
||||
d.mtime = mtime
|
||||
tf.addfile(d)
|
||||
m = meta(guid, data is None)
|
||||
if data is not None:
|
||||
add(guid + "/asset", data)
|
||||
add(guid + "/asset.meta", m)
|
||||
add(guid + "/pathname", (path + ("\n00" if extra_line else "")).encode())
|
||||
if preview:
|
||||
add(guid + "/preview.png", preview)
|
||||
a = {"path": path, "guid": guid, "metaMd5": hashlib.md5(m).hexdigest(), "dir": data is None}
|
||||
if data is not None:
|
||||
a["md5"] = hashlib.md5(data).hexdigest()
|
||||
assets.append(a)
|
||||
return gzip.compress(raw.getvalue(), mtime=0), assets
|
||||
|
||||
|
||||
def read_package(data):
|
||||
out = []
|
||||
with tarfile.open(fileobj=io.BytesIO(gzip.decompress(data))) as tf:
|
||||
files = {}
|
||||
for m in tf.getmembers():
|
||||
if m.isfile():
|
||||
files[m.name] = tf.extractfile(m).read()
|
||||
guids = sorted({n.split("/")[0] for n in files})
|
||||
for g in guids:
|
||||
path = files[g + "/pathname"].decode().split("\n")[0]
|
||||
m = files[g + "/asset.meta"]
|
||||
if ("guid: " + g).encode() not in m:
|
||||
raise ValueError("meta guid mismatch for " + path)
|
||||
a = {"path": path, "guid": g, "metaMd5": hashlib.md5(m).hexdigest(), "dir": (g + "/asset") not in files}
|
||||
if not a["dir"]:
|
||||
a["md5"] = hashlib.md5(files[g + "/asset"]).hexdigest()
|
||||
out.append(a)
|
||||
return out
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(7)
|
||||
png = b"\x89PNG\r\n\x1a\n" + rng.randbytes(200)
|
||||
items = [
|
||||
("Assets", None, None),
|
||||
("Assets/Textures", None, None),
|
||||
("Assets/Textures/brick.png", png, b"\x89PNG\r\n\x1a\npreview"),
|
||||
("Assets/Scripts/Player.cs", b"using UnityEngine;\npublic class Player : MonoBehaviour { }\n", None),
|
||||
("Assets/Scenes/Main Scene.unity", b"%YAML 1.1\n%TAG !u! tag:unity3d.com,2011:\n--- !u!1 &1\n", None),
|
||||
("Assets/Audio/empty.wav", b"", None),
|
||||
("Assets/Big/blob.bin", rng.randbytes(70000), None),
|
||||
]
|
||||
cases = []
|
||||
for name, kw in (("plain", {}), ("dot", {"dot": True}), ("extra-line", {"extra_line": True})):
|
||||
data, assets = build(items, **kw)
|
||||
cases.append({"name": name, "data": data, "assets": assets})
|
||||
ctx.emit("unitypackage", {"cases": cases, "ours": []})
|
||||
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/_unitypackage_encode.luau").items()):
|
||||
try:
|
||||
ours.append({"name": name, "ok": True, "assets": read_package(data)})
|
||||
except Exception as e:
|
||||
ours.append({"name": name, "ok": False, "assets": [], "error": str(e)})
|
||||
ctx.emit("unitypackage", {"cases": cases, "ours": ours})
|
||||
Reference in new issue
Block a user