merge ws/3d2
This commit is contained in:
commit
17c00a15df
45 files changed
+16368
-2
No files matched your search
@@ -774,3 +774,127 @@ do
|
||||
realtime("tracker 32 ch (mod)", song("mod", false), 32)
|
||||
realtime("tracker 32 ch + NNA, filters", song("it", true), 64)
|
||||
end
|
||||
do
|
||||
-- 3D (ws-3d): a 400 x 400 grid mesh (160k vertices, 318k triangles) through our own writers, then the readers; a
|
||||
-- 128^3 noise voxel grid through VOX and greedy meshing
|
||||
local Types = require("@formats/Types")
|
||||
local MeshOps = require("@formats/ops/MeshOps")
|
||||
local Gltf = require("@formats/model/gltf")
|
||||
local Obj = require("@formats/model/obj")
|
||||
local Stl = require("@formats/model/stl")
|
||||
local Ply = require("@formats/model/ply")
|
||||
local Vox = require("@formats/model/vox")
|
||||
local N = 400
|
||||
local pos = Types.Scene.accessor(nil, "f32", 3, N * N)
|
||||
local uv = Types.Scene.accessor(nil, "f32", 2, N * N)
|
||||
for y = 0, N - 1 do
|
||||
for x = 0, N - 1 do
|
||||
local i = y * N + x
|
||||
buffer.writef32(pos.data, i * 12, x / N)
|
||||
buffer.writef32(pos.data, i * 12 + 4, math.sin(x * 0.1) * math.cos(y * 0.1) * 0.05)
|
||||
buffer.writef32(pos.data, i * 12 + 8, y / N)
|
||||
buffer.writef32(uv.data, i * 8, x / N)
|
||||
buffer.writef32(uv.data, i * 8 + 4, y / N)
|
||||
end
|
||||
end
|
||||
local ind = Types.Scene.accessor(nil, "u32", 1, (N - 1) * (N - 1) * 6)
|
||||
local k = 0
|
||||
for y = 0, N - 2 do
|
||||
for x = 0, N - 2 do
|
||||
local a = y * N + x
|
||||
for _, v in { a, a + N, a + 1, a + 1, a + N, a + N + 1 } do
|
||||
buffer.writeu32(ind.data, k * 4, v)
|
||||
k += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
local prim = { attributes = { POSITION = pos, TEXCOORD_0 = uv }, indices = ind, mode = "triangles" } :: any
|
||||
MeshOps.computeNormals(prim)
|
||||
local scene = Types.Scene.fromPrimitive(prim, "grid")
|
||||
bench("meshops computeNormals 318k tris", 3, buffer.len(pos.data), function()
|
||||
MeshOps.computeNormals(prim)
|
||||
end)
|
||||
local glb = assert(Gltf.encode(scene, { binary = true }))
|
||||
bench("gltf glb decode (" .. buffer.len(glb) // 1000 .. " KB)", 5, buffer.len(glb), function()
|
||||
Gltf.decode(Bytes.reader(glb))
|
||||
end)
|
||||
bench("gltf glb encode", 3, buffer.len(glb), function()
|
||||
Gltf.encode(scene, { binary = true })
|
||||
end)
|
||||
local obj = assert(Obj.encode(scene))
|
||||
bench("obj decode (" .. buffer.len(obj) // 1000 .. " KB)", 2, buffer.len(obj), function()
|
||||
Obj.decode(Bytes.reader(obj))
|
||||
end)
|
||||
bench("obj encode", 2, buffer.len(obj), function()
|
||||
Obj.encode(scene)
|
||||
end)
|
||||
local stl = assert(Stl.encode(scene))
|
||||
bench("stl binary decode (" .. buffer.len(stl) // 1000 .. " KB)", 5, buffer.len(stl), function()
|
||||
Stl.decode(Bytes.reader(stl))
|
||||
end)
|
||||
local ply = assert(Ply.encode(scene))
|
||||
bench("ply binary decode (" .. buffer.len(ply) // 1000 .. " KB)", 5, buffer.len(ply), function()
|
||||
Ply.decode(Bytes.reader(ply))
|
||||
end)
|
||||
local Fbx = require("@formats/model/fbx")
|
||||
local fbx = assert(Fbx.encode(scene))
|
||||
bench("fbx binary decode (" .. buffer.len(fbx) // 1000 .. " KB)", 3, buffer.len(fbx), function()
|
||||
Fbx.decode(Bytes.reader(fbx))
|
||||
end)
|
||||
bench("fbx binary encode (zlib arrays)", 2, buffer.len(fbx), function()
|
||||
Fbx.encode(scene)
|
||||
end)
|
||||
bench("fbx binary encode (raw arrays)", 3, buffer.len(fbx), function()
|
||||
Fbx.encode(scene, { compress = false })
|
||||
end)
|
||||
local fbxa = assert(Fbx.encode(scene, { ascii = true }))
|
||||
bench("fbx ascii decode (" .. buffer.len(fbxa) // 1000 .. " KB)", 2, buffer.len(fbxa), function()
|
||||
Fbx.decode(Bytes.reader(fbxa))
|
||||
end)
|
||||
local ThreeMf = require("@formats/model/3mf")
|
||||
local tmf = assert(ThreeMf.encode(scene))
|
||||
bench("3mf decode (" .. buffer.len(tmf) // 1000 .. " KB zipped)", 2, buffer.len(tmf), function()
|
||||
ThreeMf.decode(Bytes.reader(tmf))
|
||||
end)
|
||||
bench("3mf encode", 2, buffer.len(tmf), function()
|
||||
ThreeMf.encode(scene)
|
||||
end)
|
||||
local V = 128
|
||||
local grid = Types.Voxels.new(V, V, V)
|
||||
for z = 0, V - 1 do
|
||||
for y = 0, V - 1 do
|
||||
for x = 0, V - 1 do
|
||||
local h = (math.sin(x * 0.11) + math.cos(y * 0.07) + 2) * V / 8 + z * 0
|
||||
if z < h then
|
||||
Types.Voxels.set(grid, x, y, z, 1 + (x // 8 + y // 8) % 6)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local vox = assert(Vox.encode(grid))
|
||||
bench("vox decode (" .. buffer.len(vox) // 1000 .. " KB)", 5, buffer.len(vox), function()
|
||||
Vox.decode(Bytes.reader(vox))
|
||||
end)
|
||||
bench("greedy mesh 128^3 (MB of cells)", 3, V * V * V, function()
|
||||
MeshOps.voxelsToPrimitive(grid)
|
||||
end)
|
||||
end
|
||||
do
|
||||
-- STEP (tools/fixtures/step.py): the largest case, parse and write
|
||||
local Step = require("@formats/cad/step")
|
||||
local SC = require("@tests/gen/step_cases")
|
||||
local big = SC[1]
|
||||
for _, c in SC do
|
||||
if #c.data > #big.data then
|
||||
big = c
|
||||
end
|
||||
end
|
||||
local data = buffer.fromstring(big.data)
|
||||
local cad = assert(Step.decode(Bytes.reader(data)))
|
||||
bench(string.format("step parse (%.1f MB)", #big.data / 1e6), 3, #big.data, function()
|
||||
Step.decode(Bytes.reader(data))
|
||||
end)
|
||||
bench("step write", 3, #big.data, function()
|
||||
Step.encode(cad)
|
||||
end)
|
||||
end
|
||||
@@ -0,0 +1,111 @@
|
||||
# 3MF fixtures (tools/fixtures.py): the lib3mf test suite and SDK example files (nixpkgs#lib3mf.src, read only, never
|
||||
# committed: core, materials (base / colour / texture / composite / multiproperties), production parts, metadata,
|
||||
# units, thumbnails, files lib3mf rejects), assimp's box.3mf (nixpkgs#assimp.src), and files written by assimp's and
|
||||
# trimesh's 3MF exporters, with reference values from lib3mf 2.5 (tools/fixtures/_3mf_reference.py: world-space
|
||||
# triangles / area / bounds through build items and components, mesh object sizes, material group counts, unit),
|
||||
# assimp (`assimp info -r`) and trimesh (area, faces).
|
||||
# tests/gen/3mf_cases.luau { name, data, lib3mf = {...} | { failed }, assimp, trimesh }
|
||||
# tests/gen/3mf_xcheck.luau our encoder's output for every case (tools/fixtures/_3mf_encode.luau) read back by
|
||||
# lib3mf / assimp / trimesh: { name, case, lib3mf, assimp, trimesh }
|
||||
import importlib.util, json, os, subprocess, sys
|
||||
|
||||
INPUTS = ["src/Formats/model/3mf", "src/Formats/codecs/Xml", "src/Formats/containers/Zip",
|
||||
"tools/fixtures/_3mf_reference.py", "tools/fixtures/_3mf_encode.luau", "tools/fixtures/_model_ref.py"]
|
||||
MAX_SIZE = 500_000
|
||||
|
||||
|
||||
def ref_module(ctx):
|
||||
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)
|
||||
return m
|
||||
|
||||
|
||||
def store(attr):
|
||||
out = subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#" + attr], check=True, capture_output=True)
|
||||
return out.stdout.decode().strip().split("\n")[-1]
|
||||
|
||||
|
||||
def lib3mf(ctx, paths):
|
||||
src, lib = store("lib3mf.src"), store("lib3mf")
|
||||
res = subprocess.run([sys.executable, "-I", os.path.join(ctx.root, "tools", "fixtures", "_3mf_reference.py"),
|
||||
os.path.join(src, "Autogenerated", "Bindings", "Python"), os.path.join(lib, "lib", "lib3mf")],
|
||||
input=json.dumps(paths).encode(), capture_output=True, check=True)
|
||||
return json.loads(res.stdout)
|
||||
|
||||
|
||||
TRIMESH_EXPORT = r"""
|
||||
import sys, trimesh
|
||||
m = trimesh.creation.icosphere(subdivisions=2, radius=10.0)
|
||||
b = trimesh.creation.box(extents=(4, 6, 8))
|
||||
b.apply_translation((20, 0, 0))
|
||||
s = trimesh.Scene([m, b])
|
||||
open(sys.argv[1] if len(sys.argv) > 1 else "/dev/stdout", "wb").write(s.export(file_type="3mf"))
|
||||
"""
|
||||
|
||||
|
||||
def ply_torus(R=20.0, r=5.0, a=24, b=12):
|
||||
import math
|
||||
vs, fs = [], []
|
||||
for i in range(a):
|
||||
for j in range(b):
|
||||
u, v = 2 * math.pi * i / a, 2 * math.pi * j / b
|
||||
vs.append(((R + r * math.cos(v)) * math.cos(u), (R + r * math.cos(v)) * math.sin(u), r * math.sin(v)))
|
||||
for i in range(a):
|
||||
for j in range(b):
|
||||
p, q = i * b + j, ((i + 1) % a) * b + j
|
||||
p2, q2 = i * b + (j + 1) % b, ((i + 1) % a) * b + (j + 1) % b
|
||||
fs.append((p, q2, p2))
|
||||
fs.append((p, q, q2))
|
||||
head = "ply\nformat ascii 1.0\nelement vertex %d\nproperty float x\nproperty float y\nproperty float z\nelement face %d\nproperty list uchar int vertex_indices\nend_header\n" % (len(vs), len(fs))
|
||||
return (head + "".join("%r %r %r\n" % v for v in vs) + "".join("3 %d %d %d\n" % f for f in fs)).encode()
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
M = ref_module(ctx)
|
||||
src = store("lib3mf.src")
|
||||
files = []
|
||||
for base in ("Tests/TestFiles", "SDK/Examples/Files"):
|
||||
for d, _, fs in sorted(os.walk(os.path.join(src, base))):
|
||||
for f in sorted(fs):
|
||||
p = os.path.join(d, f)
|
||||
if f.endswith(".3mf") and os.path.getsize(p) <= MAX_SIZE:
|
||||
files.append(("lib3mf/" + os.path.relpath(p, os.path.join(src, base)), p))
|
||||
files.append(("assimp/box.3mf", os.path.join(store("assimp.src"), "test", "models", "3MF", "box.3mf")))
|
||||
tmp = M.tempdir()
|
||||
ply = os.path.join(tmp, "torus.ply")
|
||||
with open(ply, "wb") as f:
|
||||
f.write(ply_torus())
|
||||
out = os.path.join(tmp, "torus_assimp.3mf")
|
||||
ctx.nix(["assimp"], ["assimp", "export", ply, out, "-f3mf"])
|
||||
files.append(("assimp/torus_export.3mf", out))
|
||||
tm = ctx.python(["trimesh", "numpy", "networkx", "lxml"], TRIMESH_EXPORT)
|
||||
out = os.path.join(tmp, "trimesh_export.3mf")
|
||||
with open(out, "wb") as f:
|
||||
f.write(tm)
|
||||
files.append(("trimesh/export.3mf", out))
|
||||
|
||||
paths = [p for _, p in files]
|
||||
refs = lib3mf(ctx, paths)
|
||||
infos = M.assimp_info(ctx, paths, raw=True)
|
||||
tms = M.trimesh_metrics(ctx, paths)
|
||||
cases = []
|
||||
for (name, p), r, a, t in zip(files, refs, infos, tms):
|
||||
cases.append({"name": name, "data": open(p, "rb").read(), "lib3mf": r, "assimp": a, "trimesh": t})
|
||||
ctx.emit("3mf_cases", cases)
|
||||
|
||||
# the reference tools read our output
|
||||
ours = M.luau_encode(ctx, "tools/fixtures/_3mf_encode.luau")
|
||||
xtmp = M.tempdir()
|
||||
names = sorted(ours, key=lambda n: int(n.split("_")[1].split(".")[0]))
|
||||
xp = []
|
||||
for n in names:
|
||||
p = os.path.join(xtmp, n)
|
||||
with open(p, "wb") as f:
|
||||
f.write(ours[n])
|
||||
xp.append(p)
|
||||
xr = lib3mf(ctx, xp)
|
||||
xi = M.assimp_info(ctx, xp, raw=True)
|
||||
xt = M.trimesh_metrics(ctx, xp)
|
||||
ctx.emit("3mf_xcheck", [{"name": n, "case": int(n.split("_")[1].split(".")[0]), "lib3mf": r, "assimp": a, "trimesh": t}
|
||||
for n, r, a, t in zip(names, xr, xi, xt)])
|
||||
@@ -0,0 +1,28 @@
|
||||
-- tools/fixtures/_3mf_encode: run by tools/fixtures/3mf.py (luau CLI, repo root): decodes every 3MF case that lib3mf
|
||||
-- reads with our reader and encodes it with our writer, printing "rt_<case>.3mf\t<hex>" lines for the reference tools
|
||||
-- (lib3mf, assimp, trimesh) to read back.
|
||||
local ThreeMf = require("@formats/model/3mf")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Cases = require("@tests/gen/3mf_cases")
|
||||
|
||||
local HEX = {}
|
||||
for i = 0, 255 do
|
||||
HEX[i] = string.format("%02x", i)
|
||||
end
|
||||
local function hex(s: string): string
|
||||
local out = table.create(#s)
|
||||
for i = 1, #s do
|
||||
out[i] = HEX[string.byte(s, i)]
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
for i, c in Cases do
|
||||
if not c.lib3mf.failed then
|
||||
local scene = ThreeMf.decode(Bytes.reader(buffer.fromstring(c.data)))
|
||||
if scene then
|
||||
local out = assert(ThreeMf.encode(scene))
|
||||
print(string.format("rt_%d.3mf\t%s", i, hex(buffer.tostring(out))))
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,115 @@
|
||||
# 3MF reference values through lib3mf's Python binding (ctypes over lib3mf.so; both from nixpkgs), run by 3mf.py as
|
||||
# `python3 -I _3mf_reference.py <bindings dir> <lib3mf.so without .so> < paths.json` -> JSON list, one entry per file:
|
||||
# { unit, items, meshObjects = [ [vertices, triangles] ... sorted ], triangles, area, min, max (world space, every
|
||||
# build item through its components), baseGroups, colorGroups, textures, texGroups } or { failed = message }
|
||||
import json, math, sys
|
||||
|
||||
sys.path.insert(0, sys.argv[1])
|
||||
import Lib3MF # noqa: E402
|
||||
|
||||
W = Lib3MF.Wrapper(sys.argv[2])
|
||||
UNITS = {0: "micron", 1: "millimeter", 2: "centimeter", 3: "inch", 4: "foot", 5: "meter"}
|
||||
|
||||
|
||||
def mat(t):
|
||||
f = t.Fields
|
||||
return [[f[r][c] for c in range(3)] for r in range(4)]
|
||||
|
||||
|
||||
def mul(a, b): # row-vector 4x3 affine: p * a * b
|
||||
out = []
|
||||
for r in range(4):
|
||||
row = []
|
||||
for c in range(3):
|
||||
s = sum(a[r][k] * b[k][c] for k in range(3))
|
||||
if r == 3:
|
||||
s += b[3][c]
|
||||
row.append(s)
|
||||
out.append(row)
|
||||
return out
|
||||
|
||||
|
||||
IDENT = [[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 0]]
|
||||
|
||||
|
||||
def count(it):
|
||||
n = 0
|
||||
while it.MoveNext():
|
||||
n += 1
|
||||
return n
|
||||
|
||||
|
||||
def info(path):
|
||||
model = W.CreateModel()
|
||||
reader = model.QueryReader("3mf")
|
||||
reader.SetStrictModeActive(False)
|
||||
reader.ReadFromFile(path)
|
||||
res = {"unit": UNITS.get(model.GetUnit().value if hasattr(model.GetUnit(), "value") else model.GetUnit(), "?")}
|
||||
meshes = []
|
||||
it = model.GetMeshObjects()
|
||||
while it.MoveNext():
|
||||
m = it.GetCurrentMeshObject()
|
||||
meshes.append([m.GetVertexCount(), m.GetTriangleCount()])
|
||||
res["meshObjects"] = sorted(meshes)
|
||||
tot = {"tri": 0, "area": 0.0, "min": [math.inf] * 3, "max": [-math.inf] * 3}
|
||||
|
||||
def place(rid, M, depth):
|
||||
if depth > 32:
|
||||
return
|
||||
try:
|
||||
mo = model.GetMeshObjectByID(rid)
|
||||
except Exception:
|
||||
mo = None
|
||||
if mo is not None:
|
||||
verts = mo.GetVertices()
|
||||
tris = mo.GetTriangleIndices()
|
||||
P = []
|
||||
for v in verts:
|
||||
x, y, z = v.Coordinates[0], v.Coordinates[1], v.Coordinates[2]
|
||||
P.append([x * M[0][c] + y * M[1][c] + z * M[2][c] + M[3][c] for c in range(3)])
|
||||
for p in P:
|
||||
for c in range(3):
|
||||
tot["min"][c] = min(tot["min"][c], p[c])
|
||||
tot["max"][c] = max(tot["max"][c], p[c])
|
||||
for t in tris:
|
||||
a, b, c = (P[i] for i in t.Indices)
|
||||
e1 = [b[k] - a[k] for k in range(3)]
|
||||
e2 = [c[k] - a[k] for k in range(3)]
|
||||
cx = e1[1] * e2[2] - e1[2] * e2[1]
|
||||
cy = e1[2] * e2[0] - e1[0] * e2[2]
|
||||
cz = e1[0] * e2[1] - e1[1] * e2[0]
|
||||
tot["area"] += math.sqrt(cx * cx + cy * cy + cz * cz) / 2
|
||||
tot["tri"] += 1
|
||||
return
|
||||
co = model.GetComponentsObjectByID(rid)
|
||||
for i in range(co.GetComponentCount()):
|
||||
comp = co.GetComponent(i)
|
||||
T = mat(comp.GetTransform()) if comp.HasTransform() else IDENT
|
||||
place(comp.GetObjectResourceID(), mul(T, M), depth + 1)
|
||||
|
||||
items = model.GetBuildItems()
|
||||
n = 0
|
||||
while items.MoveNext():
|
||||
bi = items.GetCurrent()
|
||||
n += 1
|
||||
T = mat(bi.GetObjectTransform()) if bi.HasObjectTransform() else IDENT
|
||||
place(bi.GetObjectResourceID(), T, 0)
|
||||
res["items"] = n
|
||||
res["triangles"] = tot["tri"]
|
||||
res["area"] = tot["area"]
|
||||
if tot["tri"]:
|
||||
res["min"], res["max"] = tot["min"], tot["max"]
|
||||
res["baseGroups"] = count(model.GetBaseMaterialGroups())
|
||||
res["colorGroups"] = count(model.GetColorGroups())
|
||||
res["textures"] = count(model.GetTexture2Ds())
|
||||
res["texGroups"] = count(model.GetTexture2DGroups())
|
||||
return res
|
||||
|
||||
|
||||
out = []
|
||||
for p in json.loads(sys.stdin.read()):
|
||||
try:
|
||||
out.append(info(p))
|
||||
except Exception as e: # noqa: BLE001
|
||||
out.append({"failed": str(e)[:200]})
|
||||
print(json.dumps(out))
|
||||
@@ -0,0 +1,36 @@
|
||||
-- tools/fixtures/_dae_encode: run by tools/fixtures/dae.py (luau CLI, repo root): decodes every Collada case with our
|
||||
-- reader and encodes it with our writer (rt_<case>.dae + its image files, and rt_<case>.zae for the first cases),
|
||||
-- printing "<file>\t<hex>" lines for assimp to read back.
|
||||
local Dae = require("@formats/model/dae")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Cases = require("@tests/gen/dae_cases")
|
||||
|
||||
local HEX = {}
|
||||
for i = 0, 255 do
|
||||
HEX[i] = string.format("%02x", i)
|
||||
end
|
||||
local function hex(s: string): string
|
||||
local out = table.create(#s)
|
||||
for i = 1, #s do
|
||||
out[i] = HEX[string.byte(s, i)]
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
for i, c in Cases do
|
||||
local scene, err = Dae.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files })
|
||||
if scene then
|
||||
local files = {}
|
||||
local dae = assert(Dae.encode(scene, { files = files, name = "rt_" .. i .. ".dae" }))
|
||||
print(string.format("rt_%d.dae\t%s", i, hex(buffer.tostring(dae))))
|
||||
for name, data in files do
|
||||
print(name .. "\t" .. hex(if type(data) == "string" then data else buffer.tostring(data)))
|
||||
end
|
||||
if i <= 3 then
|
||||
local zae = assert(Dae.encode(scene, { format = "zae" }))
|
||||
print(string.format("rt_%d.zae\t%s", i, hex(buffer.tostring(zae))))
|
||||
end
|
||||
else
|
||||
print("skipped " .. c.name .. ": " .. tostring(err))
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,94 @@
|
||||
# tools/fixtures/_fbx_blender: run by tools/fixtures/fbx.py inside Blender (blender -b --python <this> -- <outdir>): builds
|
||||
# test scenes (textured cube with two materials, vertex colours and a child; a skinned, animated cylinder with a
|
||||
# shape key; a camera and three lights) and exports each to binary FBX 7.4.
|
||||
import bpy, sys, os, math
|
||||
out = sys.argv[sys.argv.index("--") + 1]
|
||||
def reset():
|
||||
bpy.ops.wm.read_factory_settings(use_empty=True)
|
||||
def export(name, **kw):
|
||||
bpy.ops.export_scene.fbx(filepath=os.path.join(out, name), **kw)
|
||||
|
||||
# 1. textured cube: material, uv, vertex colours, packed image
|
||||
reset()
|
||||
bpy.ops.mesh.primitive_cube_add(size=2, location=(1, 2, 3), rotation=(0.3, 0.2, 0.1))
|
||||
cube = bpy.context.object
|
||||
cube.name = "Cube"
|
||||
mesh = cube.data
|
||||
mesh.color_attributes.new("Col", "BYTE_COLOR", "CORNER")
|
||||
for i, d in enumerate(mesh.color_attributes["Col"].data):
|
||||
d.color = ((i % 3) / 2, (i % 5) / 4, (i % 7) / 6, 1)
|
||||
img = bpy.data.images.new("checker", 8, 8)
|
||||
img.pixels = [((x + y) % 2) * 1.0 if c < 3 else 1.0 for y in range(8) for x in range(8) for c in range(4)]
|
||||
img.filepath_raw = os.path.join(out, "checker.png")
|
||||
img.file_format = "PNG"
|
||||
img.save()
|
||||
img.pack()
|
||||
mat = bpy.data.materials.new("Red")
|
||||
mat.use_nodes = True
|
||||
bsdf = mat.node_tree.nodes["Principled BSDF"]
|
||||
bsdf.inputs["Base Color"].default_value = (0.8, 0.1, 0.1, 1)
|
||||
bsdf.inputs["Roughness"].default_value = 0.4
|
||||
tex = mat.node_tree.nodes.new("ShaderNodeTexImage")
|
||||
tex.image = img
|
||||
mat.node_tree.links.new(tex.outputs["Color"], bsdf.inputs["Base Color"])
|
||||
mesh.materials.append(mat)
|
||||
mat2 = bpy.data.materials.new("Blue")
|
||||
mat2.diffuse_color = (0.1, 0.1, 0.9, 1)
|
||||
mesh.materials.append(mat2)
|
||||
for i, p in enumerate(mesh.polygons):
|
||||
p.material_index = i % 2
|
||||
bpy.ops.mesh.primitive_uv_sphere_add(segments=12, ring_count=6, location=(-3, 0, 0))
|
||||
bpy.context.object.name = "Sphere"
|
||||
bpy.context.object.parent = cube
|
||||
export("blender_cube.fbx", path_mode="COPY", embed_textures=True)
|
||||
|
||||
# 2. skinned, animated mesh with shape keys
|
||||
reset()
|
||||
bpy.ops.object.armature_add(location=(0, 0, 0))
|
||||
arm = bpy.context.object
|
||||
arm.name = "Rig"
|
||||
bpy.ops.object.mode_set(mode="EDIT")
|
||||
b0 = arm.data.edit_bones[0]
|
||||
b0.name = "root"
|
||||
b0.head, b0.tail = (0, 0, 0), (0, 0, 1)
|
||||
b1 = arm.data.edit_bones.new("tip")
|
||||
b1.head, b1.tail, b1.parent = (0, 0, 1), (0, 0, 2), b0
|
||||
bpy.ops.object.mode_set(mode="OBJECT")
|
||||
bpy.ops.mesh.primitive_cylinder_add(vertices=8, depth=2, radius=0.3, location=(0, 0, 1))
|
||||
cyl = bpy.context.object
|
||||
cyl.name = "Body"
|
||||
bpy.ops.object.mode_set(mode="EDIT")
|
||||
bpy.ops.mesh.subdivide(number_cuts=3)
|
||||
bpy.ops.object.mode_set(mode="OBJECT")
|
||||
cyl.shape_key_add(name="Basis")
|
||||
sk = cyl.shape_key_add(name="Fat")
|
||||
for v in sk.data:
|
||||
v.co.x *= 1.5
|
||||
v.co.y *= 1.5
|
||||
sk.value = 0.25
|
||||
cyl.select_set(True)
|
||||
arm.select_set(True)
|
||||
bpy.context.view_layer.objects.active = arm
|
||||
bpy.ops.object.parent_set(type="ARMATURE_AUTO")
|
||||
bpy.context.scene.frame_start, bpy.context.scene.frame_end = 1, 20
|
||||
bpy.ops.object.mode_set(mode="POSE")
|
||||
pb = arm.pose.bones["tip"]
|
||||
pb.rotation_mode = "XYZ"
|
||||
for f, a in ((1, 0), (10, 0.8), (20, 0)):
|
||||
pb.rotation_euler = (a, 0, 0)
|
||||
pb.keyframe_insert("rotation_euler", frame=f)
|
||||
bpy.ops.object.mode_set(mode="OBJECT")
|
||||
for f, v in ((1, 0), (20, 1)):
|
||||
sk.value = v
|
||||
sk.keyframe_insert("value", frame=f)
|
||||
export("blender_skin.fbx", add_leaf_bones=False, bake_anim=True)
|
||||
|
||||
# 3. camera and lights
|
||||
reset()
|
||||
bpy.ops.object.camera_add(location=(0, -5, 1), rotation=(math.pi / 2, 0, 0))
|
||||
bpy.context.object.data.lens = 35
|
||||
for kind, loc in (("POINT", (1, 0, 3)), ("SUN", (0, 0, 5)), ("SPOT", (2, 2, 2))):
|
||||
bpy.ops.object.light_add(type=kind, location=loc)
|
||||
bpy.context.object.data.energy = 10
|
||||
bpy.ops.mesh.primitive_plane_add(size=4)
|
||||
export("blender_camlight.fbx")
|
||||
@@ -0,0 +1,31 @@
|
||||
# tools/fixtures/_fbx_blender_stats: run by tools/fixtures/fbx.py inside Blender (blender -b --python <this> -- <json
|
||||
# list of paths>): imports each FBX with Blender's importer and prints one JSON line "STATS <list>" with per file
|
||||
# counts: mesh objects, polygons, vertices, materials, bones, actions, shape keys, cameras, lights, images; or
|
||||
# {"failed": message}.
|
||||
import bpy, sys, json
|
||||
paths = json.loads(sys.argv[sys.argv.index("--") + 1])
|
||||
res = []
|
||||
for p in paths:
|
||||
bpy.ops.wm.read_factory_settings(use_empty=True)
|
||||
try:
|
||||
r = bpy.ops.import_scene.fbx(filepath=p)
|
||||
if "FINISHED" not in r:
|
||||
raise RuntimeError(str(r))
|
||||
except Exception as e:
|
||||
res.append({"failed": str(e)[:200]})
|
||||
continue
|
||||
obs = bpy.context.scene.objects
|
||||
meshes = [o for o in obs if o.type == "MESH"]
|
||||
res.append({
|
||||
"meshes": len(meshes),
|
||||
"polygons": sum(len(o.data.polygons) for o in meshes),
|
||||
"vertices": sum(len(o.data.vertices) for o in meshes),
|
||||
"materials": len([m for m in bpy.data.materials if m.users > 0]),
|
||||
"bones": sum(len(o.data.bones) for o in obs if o.type == "ARMATURE"),
|
||||
"actions": len(bpy.data.actions),
|
||||
"shapeKeys": sum(len(o.data.shape_keys.key_blocks) - 1 for o in meshes if o.data.shape_keys),
|
||||
"cameras": len([o for o in obs if o.type == "CAMERA"]),
|
||||
"lights": len([o for o in obs if o.type == "LIGHT"]),
|
||||
"images": len([i for i in bpy.data.images if i.users > 0]),
|
||||
})
|
||||
print("STATS " + json.dumps(res))
|
||||
@@ -0,0 +1,38 @@
|
||||
-- tools/fixtures/_fbx_encode: run by tools/fixtures/fbx.py (luau CLI, repo root): decodes every FBX case with our
|
||||
-- reader and writes it back with our writer (binary 7.4, and ASCII for every third case), printing "<file>\t<hex>"
|
||||
-- lines for assimp and Blender to read back. Files: rt_<case>.fbx (binary), rt_<case>.a.fbx (ASCII).
|
||||
local Fbx = require("@formats/model/fbx")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Cases = require("@tests/gen/fbx_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, err = Fbx.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files, triangulate = false })
|
||||
if scene then
|
||||
local bin, e2 = Fbx.encode(scene)
|
||||
if bin then
|
||||
print(string.format("rt_%d.fbx\t%s", i, hex(bin)))
|
||||
else
|
||||
print("encode failed " .. c.name .. ": " .. tostring(e2))
|
||||
end
|
||||
if i % 3 == 0 then
|
||||
local a = Fbx.encode(scene, { ascii = true })
|
||||
if a then
|
||||
print(string.format("rt_%d.a.fbx\t%s", i, hex(a)))
|
||||
end
|
||||
end
|
||||
else
|
||||
print("skipped " .. c.name .. ": " .. tostring(err))
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,27 @@
|
||||
-- tools/fixtures/_step_encode: run by tools/fixtures/step.py (luau CLI, repo root): decodes every STEP case with our
|
||||
-- reader and writes it back with our writer, printing "case_<i>.step\t<hex>" lines for OCCT (through gmsh) to read.
|
||||
local Step = require("@formats/cad/step")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Cases = require("@tests/gen/step_cases")
|
||||
|
||||
local HEX = {}
|
||||
for i = 0, 255 do
|
||||
HEX[i] = string.format("%02x", i)
|
||||
end
|
||||
local function hex(s: string): string
|
||||
local out = table.create(#s)
|
||||
for i = 1, #s do
|
||||
out[i] = HEX[string.byte(s, i)]
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
for i, c in Cases do
|
||||
local cad, err = Step.decode(Bytes.reader(buffer.fromstring(c.data)))
|
||||
if cad then
|
||||
local out = assert(Step.encode(cad))
|
||||
print(string.format("case_%d.step\t%s", i, hex(buffer.tostring(out))))
|
||||
else
|
||||
print("skipped " .. c.name .. ": " .. tostring(err))
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,34 @@
|
||||
-- tools/fixtures/_usda_encode: run by tools/fixtures/usda.py (luau CLI, repo root): decodes every USDA case with our
|
||||
-- reader and writes it back with our writer, printing "<file>\t<hex>" lines (case_<n>.usda + the texture files it
|
||||
-- references) for OpenUSD (pxr) to read back.
|
||||
local Usda = require("@formats/model/usda")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Cases = require("@tests/gen/usda_cases")
|
||||
|
||||
local HEX = {}
|
||||
for i = 0, 255 do
|
||||
HEX[i] = string.format("%02x", i)
|
||||
end
|
||||
local function hex(s: string): string
|
||||
local out = table.create(#s)
|
||||
for i = 1, #s do
|
||||
out[i] = HEX[string.byte(s, i)]
|
||||
end
|
||||
return table.concat(out)
|
||||
end
|
||||
|
||||
for i, c in Cases do
|
||||
if not c.expect then
|
||||
local scene = Usda.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files })
|
||||
if scene then
|
||||
local files = {}
|
||||
local out = assert(Usda.encode(scene, { files = files, name = "case_" .. i .. ".usda" }))
|
||||
print(string.format("case_%d.usda\t%s", i, hex(buffer.tostring(out))))
|
||||
for name, data in files do
|
||||
if not string.find(name, "%.%.") and string.sub(name, 1, 1) ~= "/" then
|
||||
print(name .. "\t" .. hex(if type(data) == "string" then data else buffer.tostring(data)))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,404 @@
|
||||
# OpenUSD (pxr) side of tools/fixtures/usda.py, run by ctx.python(["openusd"], <this file's text>) with a JSON
|
||||
# request on stdin:
|
||||
# {"mode": "author", "dir": d} -> writes the authored test stages into d (usda, plus a usdc and a usdz) and prints
|
||||
# the file names
|
||||
# {"mode": "metrics", "paths": [...]} -> prints [ metrics per file ] (see metrics() below)
|
||||
# {"mode": "convert", "src": a, "dst": b} -> usdc -> usda through Sdf (as usdcat does)
|
||||
# {"mode": "specs", "paths": [...]} -> the number of prim specs in each layer (parse-only checks)
|
||||
import json, math, os, struct, sys, zlib
|
||||
from pxr import Gf, Sdf, Usd, UsdGeom, UsdLux, UsdShade, UsdUtils, Vt
|
||||
|
||||
req = json.loads(sys.stdin.read())
|
||||
|
||||
|
||||
def png(w, h, rgba):
|
||||
raw = b"".join(b"\0" + bytes(rgba[(y * w) * 4:(y * w + w) * 4]) for y in range(h))
|
||||
def chunk(t, d):
|
||||
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xffffffff)
|
||||
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def cube(stage, path, size=1.0, quads=True):
|
||||
m = UsdGeom.Mesh.Define(stage, path)
|
||||
s = size / 2
|
||||
pts = [(-s, -s, -s), (s, -s, -s), (s, s, -s), (-s, s, -s), (-s, -s, s), (s, -s, s), (s, s, s), (-s, s, s)]
|
||||
faces = [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)]
|
||||
m.CreatePointsAttr([Gf.Vec3f(*p) for p in pts])
|
||||
if quads:
|
||||
m.CreateFaceVertexCountsAttr([4] * 6)
|
||||
m.CreateFaceVertexIndicesAttr([i for f in faces for i in f])
|
||||
else:
|
||||
m.CreateFaceVertexCountsAttr([3] * 12)
|
||||
m.CreateFaceVertexIndicesAttr([i for f in faces for i in (f[0], f[1], f[2], f[0], f[2], f[3])])
|
||||
m.CreateExtentAttr([Gf.Vec3f(-s, -s, -s), Gf.Vec3f(s, s, s)])
|
||||
return m
|
||||
|
||||
|
||||
def author(d):
|
||||
names = []
|
||||
# 1. transforms: every op kind and order
|
||||
st = Usd.Stage.CreateInMemory()
|
||||
UsdGeom.SetStageUpAxis(st, UsdGeom.Tokens.y)
|
||||
UsdGeom.SetStageMetersPerUnit(st, 1.0)
|
||||
root = UsdGeom.Xform.Define(st, "/World")
|
||||
st.SetDefaultPrim(root.GetPrim())
|
||||
x = UsdGeom.Xform.Define(st, "/World/TRS")
|
||||
x.AddTranslateOp().Set(Gf.Vec3d(1, 2, 3))
|
||||
x.AddRotateXYZOp().Set(Gf.Vec3f(30, 45, 60))
|
||||
x.AddScaleOp().Set(Gf.Vec3f(1, 2, 0.5))
|
||||
cube(st, "/World/TRS/Cube")
|
||||
for k, order in enumerate(["XZY", "YXZ", "YZX", "ZXY", "ZYX"]):
|
||||
x = UsdGeom.Xform.Define(st, "/World/R%s" % order)
|
||||
x.AddTranslateOp().Set(Gf.Vec3d(k * 3, 0, 0))
|
||||
op = x.AddXformOp(getattr(UsdGeom.XformOp, "TypeRotate" + order))
|
||||
op.Set(Gf.Vec3f(10 + k, 70, -25))
|
||||
cube(st, "/World/R%s/Cube" % order, 0.5)
|
||||
x = UsdGeom.Xform.Define(st, "/World/Single")
|
||||
x.AddRotateYOp().Set(33.0)
|
||||
x.AddRotateXOp().Set(-12.0)
|
||||
x.AddScaleOp().Set(Gf.Vec3f(2, 2, 2))
|
||||
cube(st, "/World/Single/Cube")
|
||||
x = UsdGeom.Xform.Define(st, "/World/Orient")
|
||||
x.AddOrientOp().Set(Gf.Quatf(0.9238795, 0, 0.3826834, 0))
|
||||
x.AddTranslateOp().Set(Gf.Vec3d(0, 1, 0))
|
||||
cube(st, "/World/Orient/Cube")
|
||||
x = UsdGeom.Xform.Define(st, "/World/Pivot")
|
||||
x.AddTranslateOp().Set(Gf.Vec3d(5, 0, 0))
|
||||
piv = x.AddTranslateOp(opSuffix="pivot")
|
||||
piv.Set(Gf.Vec3d(1, 1, 0))
|
||||
x.AddRotateZOp().Set(90.0)
|
||||
x.AddTranslateOp(opSuffix="pivot", isInverseOp=True)
|
||||
cube(st, "/World/Pivot/Cube")
|
||||
x = UsdGeom.Xform.Define(st, "/World/Matrix")
|
||||
x.AddTransformOp().Set(Gf.Matrix4d(Gf.Rotation(Gf.Vec3d(1, 1, 0), 40), Gf.Vec3d(-2, 0, 4)) * Gf.Matrix4d().SetScale(Gf.Vec3d(1.5, 1.5, 1.5)))
|
||||
cube(st, "/World/Matrix/Cube")
|
||||
r = UsdGeom.Xform.Define(st, "/World/Matrix/Reset")
|
||||
r.SetResetXformStack(True)
|
||||
r.AddTranslateOp().Set(Gf.Vec3d(0, -3, 0))
|
||||
cube(st, "/World/Matrix/Reset/Cube", 0.25)
|
||||
neg = UsdGeom.Xform.Define(st, "/World/Negative")
|
||||
neg.AddScaleOp().Set(Gf.Vec3f(-1, 1, 1))
|
||||
cube(st, "/World/Negative/Cube")
|
||||
names.append(("xforms.usda", st))
|
||||
|
||||
# 2. primvars, interpolations, holes, orientation, n-gons
|
||||
st = Usd.Stage.CreateInMemory()
|
||||
UsdGeom.SetStageUpAxis(st, UsdGeom.Tokens.z)
|
||||
UsdGeom.SetStageMetersPerUnit(st, 0.01)
|
||||
m = UsdGeom.Mesh.Define(st, "/Grid")
|
||||
st.SetDefaultPrim(m.GetPrim())
|
||||
n = 4
|
||||
pts = [Gf.Vec3f(i, j, 0.1 * i * j) for j in range(n + 1) for i in range(n + 1)]
|
||||
counts, idx = [], []
|
||||
for j in range(n):
|
||||
for i in range(n):
|
||||
a = j * (n + 1) + i
|
||||
counts.append(4)
|
||||
idx += [a, a + 1, a + n + 2, a + n + 1]
|
||||
# a pentagon and a triangle
|
||||
pts += [Gf.Vec3f(10, 0, 0), Gf.Vec3f(11, 0, 0), Gf.Vec3f(11.5, 1, 0), Gf.Vec3f(10.5, 2, 0), Gf.Vec3f(9.5, 1, 0)]
|
||||
b = (n + 1) * (n + 1)
|
||||
counts += [5, 3]
|
||||
idx += [b, b + 1, b + 2, b + 3, b + 4, b, b + 2, b + 3]
|
||||
m.CreatePointsAttr(pts)
|
||||
m.CreateFaceVertexCountsAttr(counts)
|
||||
m.CreateFaceVertexIndicesAttr(idx)
|
||||
m.CreateHoleIndicesAttr([5])
|
||||
pv = UsdGeom.PrimvarsAPI(m)
|
||||
stp = pv.CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying)
|
||||
stp.Set([Gf.Vec2f(0, 0), Gf.Vec2f(1, 0), Gf.Vec2f(1, 1), Gf.Vec2f(0, 1)])
|
||||
stp.SetIndices(Vt.IntArray([k % 4 for k in range(len(idx))]))
|
||||
col = pv.CreatePrimvar("displayColor", Sdf.ValueTypeNames.Color3fArray, UsdGeom.Tokens.uniform)
|
||||
col.Set([Gf.Vec3f((k % 3) / 2, (k % 5) / 4, 1 - (k % 2)) for k in range(len(counts))])
|
||||
op = pv.CreatePrimvar("displayOpacity", Sdf.ValueTypeNames.FloatArray, UsdGeom.Tokens.vertex)
|
||||
op.Set([0.5 + 0.5 * (k % 2) for k in range(len(pts))])
|
||||
uv2 = pv.CreatePrimvar("uv2", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex)
|
||||
uv2.Set([Gf.Vec2f(p[0] / 12, p[1] / 4) for p in pts])
|
||||
m.CreateNormalsAttr([Gf.Vec3f(0, 0, 1)] * len(pts))
|
||||
m.SetNormalsInterpolation(UsdGeom.Tokens.vertex)
|
||||
m2 = cube(st, "/Grid/Left")
|
||||
m2.CreateOrientationAttr(UsdGeom.Tokens.leftHanded)
|
||||
UsdGeom.Xformable(m2).AddTranslateOp().Set(Gf.Vec3d(0, 0, 5))
|
||||
m3 = cube(st, "/Grid/ConstColor", 2)
|
||||
UsdGeom.Xformable(m3).AddTranslateOp().Set(Gf.Vec3d(0, 6, 0))
|
||||
m3.CreateDisplayColorPrimvar(UsdGeom.Tokens.constant).Set([Gf.Vec3f(0.2, 0.4, 0.8)])
|
||||
names.append(("primvars.usda", st))
|
||||
|
||||
# 3. materials: textures, transforms, subsets, inherited bindings, interface inputs
|
||||
st = Usd.Stage.CreateInMemory()
|
||||
UsdGeom.SetStageUpAxis(st, UsdGeom.Tokens.y)
|
||||
root = UsdGeom.Xform.Define(st, "/Root")
|
||||
st.SetDefaultPrim(root.GetPrim())
|
||||
UsdGeom.Scope.Define(st, "/Root/Looks")
|
||||
|
||||
def surface(path, **inputs):
|
||||
mat = UsdShade.Material.Define(st, path)
|
||||
sh = UsdShade.Shader.Define(st, path + "/Surface")
|
||||
sh.CreateIdAttr("UsdPreviewSurface")
|
||||
for k, v in inputs.items():
|
||||
if isinstance(v, tuple):
|
||||
sh.CreateInput(k, Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f(*v))
|
||||
else:
|
||||
sh.CreateInput(k, Sdf.ValueTypeNames.Float).Set(v)
|
||||
mat.CreateSurfaceOutput().ConnectToSource(sh.ConnectableAPI(), "surface")
|
||||
return mat, sh
|
||||
|
||||
def texture(mat, sh, name, file, varname="st", wrap="repeat", transform=None, iface=False):
|
||||
path = mat.GetPath().pathString
|
||||
reader = UsdShade.Shader.Define(st, path + "/" + name + "_Reader")
|
||||
reader.CreateIdAttr("UsdPrimvarReader_float2")
|
||||
if iface:
|
||||
mi = mat.CreateInput("frame:stPrimvarName", Sdf.ValueTypeNames.Token)
|
||||
mi.Set(varname)
|
||||
reader.CreateInput("varname", Sdf.ValueTypeNames.Token).ConnectToSource(mi)
|
||||
else:
|
||||
reader.CreateInput("varname", Sdf.ValueTypeNames.Token).Set(varname)
|
||||
src = reader.ConnectableAPI()
|
||||
if transform:
|
||||
tr = UsdShade.Shader.Define(st, path + "/" + name + "_Transform")
|
||||
tr.CreateIdAttr("UsdTransform2d")
|
||||
tr.CreateInput("in", Sdf.ValueTypeNames.Float2).ConnectToSource(src, "result")
|
||||
tr.CreateInput("rotation", Sdf.ValueTypeNames.Float).Set(transform[0])
|
||||
tr.CreateInput("scale", Sdf.ValueTypeNames.Float2).Set(Gf.Vec2f(*transform[1]))
|
||||
tr.CreateInput("translation", Sdf.ValueTypeNames.Float2).Set(Gf.Vec2f(*transform[2]))
|
||||
src = tr.ConnectableAPI()
|
||||
t = UsdShade.Shader.Define(st, path + "/" + name)
|
||||
t.CreateIdAttr("UsdUVTexture")
|
||||
t.CreateInput("file", Sdf.ValueTypeNames.Asset).Set(file)
|
||||
t.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource(src, "result")
|
||||
t.CreateInput("wrapS", Sdf.ValueTypeNames.Token).Set(wrap)
|
||||
t.CreateInput("wrapT", Sdf.ValueTypeNames.Token).Set("clamp")
|
||||
return t.ConnectableAPI()
|
||||
|
||||
red, _ = surface("/Root/Looks/Red", diffuseColor=(0.8, 0.1, 0.1), metallic=0.25, roughness=0.75)
|
||||
glass, _ = surface("/Root/Looks/Glass", diffuseColor=(0.9, 0.9, 1.0), opacity=0.3, roughness=0.05, ior=1.33)
|
||||
glow, _ = surface("/Root/Looks/Glow", emissiveColor=(1.0, 0.5, 0.0), opacityThreshold=0.4, opacity=0.9)
|
||||
tex, tsh = surface("/Root/Looks/Textured", roughness=0.5)
|
||||
c = texture(tex, tsh, "Diffuse", "./textures/checker.png", iface=True)
|
||||
tsh.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).ConnectToSource(c, "rgb")
|
||||
mr = texture(tex, tsh, "MetalRough", "textures/mr.png", varname="uv2", wrap="mirror", transform=(30.0, (2, 2), (0.25, 0.5)))
|
||||
tsh.CreateInput("metallic", Sdf.ValueTypeNames.Float).ConnectToSource(mr, "b")
|
||||
tsh.CreateInput("roughness", Sdf.ValueTypeNames.Float).ConnectToSource(mr, "g")
|
||||
nrm = texture(tex, tsh, "Normal", "textures/normal.png")
|
||||
tsh.CreateInput("normal", Sdf.ValueTypeNames.Normal3f).ConnectToSource(nrm, "rgb")
|
||||
grp = UsdGeom.Xform.Define(st, "/Root/Group")
|
||||
UsdShade.MaterialBindingAPI.Apply(grp.GetPrim()).Bind(red)
|
||||
a = cube(st, "/Root/Group/Inherits")
|
||||
b = cube(st, "/Root/Group/Own")
|
||||
UsdGeom.Xformable(b).AddTranslateOp().Set(Gf.Vec3d(2, 0, 0))
|
||||
UsdShade.MaterialBindingAPI.Apply(b.GetPrim()).Bind(glass)
|
||||
s = cube(st, "/Root/Subsets", 1.0, quads=False)
|
||||
UsdGeom.Xformable(s).AddTranslateOp().Set(Gf.Vec3d(0, 3, 0))
|
||||
pv = UsdGeom.PrimvarsAPI(s)
|
||||
pv.CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex).Set([Gf.Vec2f((k % 2), (k // 2) % 2) for k in range(8)])
|
||||
pv.CreatePrimvar("uv2", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex).Set([Gf.Vec2f((k % 4) / 4, k / 8) for k in range(8)])
|
||||
mb = UsdShade.MaterialBindingAPI.Apply(s.GetPrim())
|
||||
mb.Bind(glow)
|
||||
s1 = mb.CreateMaterialBindSubset("top", Vt.IntArray([0, 1, 2, 3]))
|
||||
UsdShade.MaterialBindingAPI.Apply(s1.GetPrim()).Bind(tex)
|
||||
s2 = mb.CreateMaterialBindSubset("side", Vt.IntArray([4, 5, 6]))
|
||||
UsdShade.MaterialBindingAPI.Apply(s2.GetPrim()).Bind(red)
|
||||
names.append(("materials.usda", st))
|
||||
|
||||
# 4. cameras and lights
|
||||
st = Usd.Stage.CreateInMemory()
|
||||
UsdGeom.SetStageUpAxis(st, UsdGeom.Tokens.y)
|
||||
root = UsdGeom.Xform.Define(st, "/Scene")
|
||||
st.SetDefaultPrim(root.GetPrim())
|
||||
cam = UsdGeom.Camera.Define(st, "/Scene/Persp")
|
||||
cam.CreateFocalLengthAttr(35)
|
||||
cam.CreateHorizontalApertureAttr(36)
|
||||
cam.CreateVerticalApertureAttr(24)
|
||||
cam.CreateClippingRangeAttr(Gf.Vec2f(0.1, 500))
|
||||
UsdGeom.Xformable(cam).AddTranslateOp().Set(Gf.Vec3d(0, 1, 10))
|
||||
o = UsdGeom.Camera.Define(st, "/Scene/Ortho")
|
||||
o.CreateProjectionAttr(UsdGeom.Tokens.orthographic)
|
||||
o.CreateHorizontalApertureAttr(40)
|
||||
o.CreateVerticalApertureAttr(30)
|
||||
UsdLux.DistantLight.Define(st, "/Scene/Sun").CreateIntensityAttr(3)
|
||||
sp = UsdLux.SphereLight.Define(st, "/Scene/Bulb")
|
||||
sp.CreateIntensityAttr(50)
|
||||
sp.CreateColorAttr(Gf.Vec3f(1, 0.8, 0.6))
|
||||
sp.CreateExposureAttr(2)
|
||||
UsdGeom.Xformable(sp).AddTranslateOp().Set(Gf.Vec3d(0, 4, 0))
|
||||
spot = UsdLux.SphereLight.Define(st, "/Scene/Spot")
|
||||
sh = UsdLux.ShapingAPI.Apply(spot.GetPrim())
|
||||
sh.CreateShapingConeAngleAttr(30)
|
||||
sh.CreateShapingConeSoftnessAttr(0.5)
|
||||
UsdLux.RectLight.Define(st, "/Scene/Panel").CreateIntensityAttr(7)
|
||||
UsdLux.DiskLight.Define(st, "/Scene/Disk")
|
||||
cube(st, "/Scene/Floor", 10)
|
||||
names.append(("camlights.usda", st))
|
||||
|
||||
# 5. time samples
|
||||
st = Usd.Stage.CreateInMemory()
|
||||
st.SetTimeCodesPerSecond(30)
|
||||
st.SetStartTimeCode(0)
|
||||
st.SetEndTimeCode(60)
|
||||
root = UsdGeom.Xform.Define(st, "/Anim")
|
||||
st.SetDefaultPrim(root.GetPrim())
|
||||
x = UsdGeom.Xform.Define(st, "/Anim/Mover")
|
||||
t = x.AddTranslateOp()
|
||||
for k, v in ((0, (0, 0, 0)), (30, (4, 1, 0)), (60, (4, 1, -6))):
|
||||
t.Set(Gf.Vec3d(*v), k)
|
||||
r = x.AddRotateXYZOp()
|
||||
for k, v in ((0, (0, 0, 0)), (20, (0, 90, 0)), (45, (30, 180, 10))):
|
||||
r.Set(Gf.Vec3f(*v), k)
|
||||
s = x.AddScaleOp()
|
||||
s.Set(Gf.Vec3f(1, 1, 1))
|
||||
cube(st, "/Anim/Mover/Box")
|
||||
y = UsdGeom.Xform.Define(st, "/Anim/Mover/Child")
|
||||
q = y.AddOrientOp()
|
||||
q.Set(Gf.Quatf(1, 0, 0, 0), 0)
|
||||
q.Set(Gf.Quatf(0.7071068, 0.7071068, 0, 0), 60)
|
||||
y.AddTranslateOp().Set(Gf.Vec3d(0, 2, 0))
|
||||
cube(st, "/Anim/Mover/Child/Box", 0.5)
|
||||
names.append(("anim.usda", st))
|
||||
|
||||
out = []
|
||||
for name, st in names:
|
||||
st.GetRootLayer().Export(os.path.join(d, name))
|
||||
out.append(name)
|
||||
os.makedirs(os.path.join(d, "textures"), exist_ok=True)
|
||||
checker = []
|
||||
for yy in range(8):
|
||||
for xx in range(8):
|
||||
v = 255 if (xx + yy) % 2 else 40
|
||||
checker += [v, v, v, 255]
|
||||
for f, data in (("checker.png", png(8, 8, checker)), ("mr.png", png(2, 2, [0, 128, 255, 255] * 4)), ("normal.png", png(2, 2, [128, 128, 255, 255] * 4))):
|
||||
with open(os.path.join(d, "textures", f), "wb") as fh:
|
||||
fh.write(data)
|
||||
# a usdc (UNSUPPORTED) and a usdz package of the materials stage
|
||||
Sdf.Layer.FindOrOpen(os.path.join(d, "xforms.usda")).Export(os.path.join(d, "xforms.usdc"))
|
||||
out.append("xforms.usdc")
|
||||
cwd = os.getcwd()
|
||||
os.chdir(d)
|
||||
UsdUtils.CreateNewUsdzPackage(Sdf.AssetPath("materials.usda"), "materials.usdz")
|
||||
os.chdir(cwd)
|
||||
out.append("materials.usdz")
|
||||
return out
|
||||
|
||||
|
||||
def mat16(m):
|
||||
return [float(m[i][j]) for i in range(4) for j in range(4)]
|
||||
|
||||
|
||||
def metrics(path):
|
||||
stage = Usd.Stage.Open(path)
|
||||
if stage is None:
|
||||
return {"failed": True}
|
||||
res = {
|
||||
"upAxis": str(UsdGeom.GetStageUpAxis(stage)),
|
||||
"metersPerUnit": float(UsdGeom.GetStageMetersPerUnit(stage)) if UsdGeom.StageHasAuthoredMetersPerUnit(stage) else -1.0,
|
||||
"tcps": float(stage.GetTimeCodesPerSecond()),
|
||||
"meshes": [], "xforms": [], "materials": [], "cameras": [], "lights": [], "anim": [],
|
||||
}
|
||||
t0 = Usd.TimeCode.EarliestTime()
|
||||
cache = UsdGeom.XformCache(t0)
|
||||
for prim in stage.Traverse():
|
||||
if not prim.IsA(UsdGeom.Xformable):
|
||||
continue
|
||||
path_s = prim.GetPath().pathString
|
||||
world = cache.GetLocalToWorldTransform(prim)
|
||||
res["xforms"].append({"path": path_s, "type": str(prim.GetTypeName()), "world": mat16(world)})
|
||||
x = UsdGeom.Xformable(prim)
|
||||
times = x.GetTimeSamples()
|
||||
if len(times) > 1:
|
||||
samples = []
|
||||
for t in times:
|
||||
samples.append({"time": float(t), "world": mat16(x.ComputeLocalToWorldTransform(t))})
|
||||
res["anim"].append({"path": path_s, "samples": samples})
|
||||
if prim.IsA(UsdGeom.Mesh):
|
||||
m = UsdGeom.Mesh(prim)
|
||||
pts = m.GetPointsAttr().Get(t0) or []
|
||||
counts = m.GetFaceVertexCountsAttr().Get(t0) or []
|
||||
idx = m.GetFaceVertexIndicesAttr().Get(t0) or []
|
||||
holes = set(m.GetHoleIndicesAttr().Get(t0) or [])
|
||||
wp = [world.Transform(Gf.Vec3d(*p)) for p in pts]
|
||||
tris, area, at = 0, 0.0, 0
|
||||
lo, hi = [math.inf] * 3, [-math.inf] * 3
|
||||
for f, c in enumerate(counts):
|
||||
corners = list(idx[at:at + c])
|
||||
at += c
|
||||
if c < 3 or f in holes:
|
||||
continue
|
||||
for k in range(1, c - 1):
|
||||
a, b, cc = wp[corners[0]], wp[corners[k]], wp[corners[k + 1]]
|
||||
area += 0.5 * Gf.Cross(b - a, cc - a).GetLength()
|
||||
tris += 1
|
||||
for v in corners:
|
||||
for j in range(3):
|
||||
lo[j] = min(lo[j], wp[v][j])
|
||||
hi[j] = max(hi[j], wp[v][j])
|
||||
mat, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
|
||||
subsets = UsdShade.MaterialBindingAPI(prim).GetMaterialBindSubsets()
|
||||
res["meshes"].append({
|
||||
"path": path_s, "triangles": tris, "area": area, "min": lo if tris else [], "max": hi if tris else [],
|
||||
"material": mat.GetPath().pathString if mat else "", "subsets": len(subsets),
|
||||
"subsetMaterials": sorted(
|
||||
(UsdShade.MaterialBindingAPI(sub.GetPrim()).ComputeBoundMaterial()[0].GetPath().pathString if UsdShade.MaterialBindingAPI(sub.GetPrim()).ComputeBoundMaterial()[0] else "") for sub in subsets),
|
||||
})
|
||||
if prim.IsA(UsdGeom.Camera):
|
||||
c = UsdGeom.Camera(prim)
|
||||
cr = c.GetClippingRangeAttr().Get(t0)
|
||||
res["cameras"].append({
|
||||
"path": path_s, "projection": str(c.GetProjectionAttr().Get(t0)), "focal": float(c.GetFocalLengthAttr().Get(t0)),
|
||||
"hap": float(c.GetHorizontalApertureAttr().Get(t0)), "vap": float(c.GetVerticalApertureAttr().Get(t0)),
|
||||
"near": float(cr[0]), "far": float(cr[1]),
|
||||
})
|
||||
for lt in ("DistantLight", "SphereLight", "RectLight", "DiskLight"):
|
||||
cls = getattr(UsdLux, lt)
|
||||
if prim.IsA(cls):
|
||||
l = cls(prim)
|
||||
col = l.GetColorAttr().Get(t0)
|
||||
cone = prim.GetAttribute("inputs:shaping:cone:angle")
|
||||
res["lights"].append({
|
||||
"path": path_s, "type": lt, "intensity": float(l.GetIntensityAttr().Get(t0)) * 2 ** float(l.GetExposureAttr().Get(t0)),
|
||||
"color": [float(v) for v in col], "cone": float(cone.Get(t0)) if cone and cone.HasAuthoredValue() else -1.0,
|
||||
})
|
||||
for prim in stage.Traverse():
|
||||
if not prim.IsA(UsdShade.Material):
|
||||
continue
|
||||
mat = UsdShade.Material(prim)
|
||||
surf = mat.ComputeSurfaceSource()
|
||||
sh = surf[0] if surf else None
|
||||
if not sh or sh.GetIdAttr().Get() != "UsdPreviewSurface":
|
||||
continue
|
||||
d = {"path": prim.GetPath().pathString, "textures": {}}
|
||||
for name in ("diffuseColor", "emissiveColor", "metallic", "roughness", "opacity", "opacityThreshold", "ior", "normal", "occlusion"):
|
||||
inp = sh.GetInput(name)
|
||||
if not inp:
|
||||
continue
|
||||
srcs = inp.GetConnectedSources()[0] if inp.HasConnectedSource() else []
|
||||
if srcs:
|
||||
src = UsdShade.Shader(srcs[0].source.GetPrim())
|
||||
f = src.GetInput("file")
|
||||
if f:
|
||||
d["textures"][name] = {"file": f.Get().path, "output": str(srcs[0].sourceName)}
|
||||
else:
|
||||
v = inp.Get()
|
||||
if v is not None:
|
||||
d[name] = [float(x) for x in v] if hasattr(v, "__len__") else float(v)
|
||||
res["materials"].append(d)
|
||||
return res
|
||||
|
||||
|
||||
mode = req["mode"]
|
||||
if mode == "author":
|
||||
print(json.dumps(author(req["dir"])))
|
||||
elif mode == "metrics":
|
||||
print(json.dumps([metrics(p) for p in req["paths"]]))
|
||||
elif mode == "convert":
|
||||
Sdf.Layer.FindOrOpen(req["src"]).Export(req["dst"])
|
||||
print("[]")
|
||||
elif mode == "specs":
|
||||
out = []
|
||||
for p in req["paths"]:
|
||||
layer = Sdf.Layer.FindOrOpen(p)
|
||||
n = [0]
|
||||
def visit(path):
|
||||
if path.IsPrimPath():
|
||||
n[0] += 1
|
||||
layer.Traverse(Sdf.Path.absoluteRootPath, visit)
|
||||
out.append(n[0])
|
||||
print(json.dumps(out))
|
||||
@@ -0,0 +1,106 @@
|
||||
# Collada fixtures (tools/fixtures.py): assimp's Collada test models (read from the nixpkgs assimp source at fixture
|
||||
# time, never committed: test/models/Collada, licences in that folder's licence.md), glTF sample models converted to
|
||||
# .dae by assimp's Collada exporter (skins, animations, cameras, textures), with reference values from `assimp info -r`
|
||||
# (meshes, faces, vertices, bounds, materials, animations, cameras, lights, bones). Blender 5 has no Collada support.
|
||||
# tests/gen/dae_cases.luau { name, main, data, files = { name -> bytes }, assimp, gltf? + gltfFiles? (the original
|
||||
# of an assimp export: the test compares skins and animations with it) }
|
||||
# tests/gen/dae_xcheck.luau our encoder's .dae of every case (tools/fixtures/_dae_encode.luau) read back by assimp:
|
||||
# { name, case, assimp }
|
||||
import importlib.util, os, re, subprocess
|
||||
|
||||
INPUTS = ["src/Formats/model/dae", "src/Formats/codecs/Xml", "tools/fixtures/_model_ref.py", "tools/fixtures/_dae_encode.luau",
|
||||
"tests/fixtures/gltf"]
|
||||
|
||||
|
||||
def ref_module(ctx):
|
||||
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)
|
||||
return m
|
||||
|
||||
|
||||
def assimp_src():
|
||||
out = subprocess.run(["nix", "build", "nixpkgs#assimp.src", "--no-link", "--print-out-paths"], capture_output=True, check=True)
|
||||
return out.stdout.decode().strip().split("\n")[-1]
|
||||
|
||||
|
||||
def info(ctx, M, path):
|
||||
a = M.assimp_info(ctx, [path], raw=True)[0]
|
||||
try:
|
||||
txt = ctx.nix("assimp", ["assimp", "info", path, "-r"]).decode("utf-8", "replace")
|
||||
except subprocess.CalledProcessError:
|
||||
return {"failed": True}
|
||||
for label in ("Animations", "Cameras", "Lights", "Bones", "Materials"):
|
||||
m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M)
|
||||
if m:
|
||||
a[label.lower()] = int(m.group(1))
|
||||
# assimp's root node transform (its Collada importer bakes up axis / unit conversion into it): not reported by
|
||||
# `assimp info`; the test applies the conversion itself
|
||||
return a
|
||||
|
||||
|
||||
IMAGE_EXT = (".jpg", ".jpeg", ".png", ".tga", ".bmp")
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
M = ref_module(ctx)
|
||||
src = os.path.join(assimp_src(), "test", "models", "Collada")
|
||||
cases = []
|
||||
images = {f: os.path.join(src, f) for f in sorted(os.listdir(src)) if f.lower().endswith(IMAGE_EXT)}
|
||||
for f in sorted(os.listdir(src)):
|
||||
if not (f.lower().endswith(".dae") or f.lower().endswith(".zae")) or "_triangulate" in f:
|
||||
continue # the *_triangulate files are the same models again (fixture size)
|
||||
path = os.path.join(src, f)
|
||||
data = open(path, "rb").read()
|
||||
files = {}
|
||||
text = data.decode("latin-1")
|
||||
for im, ip in images.items():
|
||||
if im in text:
|
||||
files[im] = open(ip, "rb").read()
|
||||
cases.append({"name": "assimp/" + f, "main": f, "path": path, "files": files})
|
||||
# glTF samples -> assimp's Collada exporter
|
||||
tmp = M.tempdir()
|
||||
groot = os.path.join(ctx.root, "tests", "fixtures", "gltf")
|
||||
for model, variant, main in (("SimpleSkin", "glTF", "SimpleSkin.gltf"), ("RiggedSimple", "glTF-Binary", "RiggedSimple.glb"),
|
||||
("BoxTextured", "glTF", "BoxTextured.gltf"), ("AnimatedTriangle", "glTF", "AnimatedTriangle.gltf"),
|
||||
("Cameras", "glTF", "Cameras.gltf"), ("BoxVertexColors", "glTF-Binary", "BoxVertexColors.glb"),
|
||||
("SimpleMeshes", "glTF", "SimpleMeshes.gltf"), ("InterpolationTest", "glTF-Binary", "InterpolationTest.glb"),
|
||||
("MultiUVTest", "glTF-Binary", "MultiUVTest.glb")):
|
||||
d = os.path.join(groot, model, variant)
|
||||
if not os.path.exists(os.path.join(d, main)):
|
||||
continue
|
||||
out = os.path.join(tmp, model + ".dae")
|
||||
try:
|
||||
ctx.nix("assimp", ["assimp", "export", os.path.join(d, main), out, "-fcollada"])
|
||||
except subprocess.CalledProcessError:
|
||||
continue
|
||||
files = {}
|
||||
text = open(out, "rb").read().decode("latin-1")
|
||||
for f in os.listdir(tmp):
|
||||
if f.lower().endswith(IMAGE_EXT) and f in text:
|
||||
files[f] = open(os.path.join(tmp, f), "rb").read()
|
||||
for f in os.listdir(d):
|
||||
if f.lower().endswith(IMAGE_EXT) and f in text:
|
||||
files[f] = open(os.path.join(d, f), "rb").read()
|
||||
orig = {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != main}
|
||||
cases.append({"name": "assimp-export/" + model, "main": model + ".dae", "path": out, "files": files,
|
||||
"gltf": open(os.path.join(d, main), "rb").read(), "gltfFiles": orig})
|
||||
for c in cases:
|
||||
c["assimp"] = info(ctx, M, c["path"])
|
||||
c["data"] = open(c["path"], "rb").read()
|
||||
del c["path"]
|
||||
ctx.emit("dae_cases", cases)
|
||||
|
||||
# assimp reads our output
|
||||
ours = M.luau_encode(ctx, "tools/fixtures/_dae_encode.luau")
|
||||
xtmp = M.tempdir()
|
||||
names = []
|
||||
for name, data in sorted(ours.items()):
|
||||
with open(os.path.join(xtmp, name), "wb") as f:
|
||||
f.write(data)
|
||||
if name.endswith(".dae") or name.endswith(".zae"):
|
||||
names.append(name)
|
||||
out = []
|
||||
for n in names:
|
||||
out.append({"name": n, "case": int(n.split("_")[1].split(".")[0]), "assimp": info(ctx, M, os.path.join(xtmp, n))})
|
||||
ctx.emit("dae_xcheck", out)
|
||||
@@ -0,0 +1,179 @@
|
||||
# FBX fixtures (tools/fixtures.py): assimp's FBX test models (binary 7.4 / 7.5, ASCII 7.4 / 7.5 / 7.7, embedded
|
||||
# textures, skeletons, animation; read from the nixpkgs assimp source, never committed), scenes exported by Blender
|
||||
# (tools/fixtures/_fbx_blender.py: materials, textures, vertex colours, skin, shape keys, animation, camera, lights)
|
||||
# and by assimp's FBX exporters (binary and ASCII), with reference values from assimp (`assimp info -r`: meshes,
|
||||
# faces, vertices, bounds, materials, animations, cameras, lights, bones) and Blender's importer
|
||||
# (tools/fixtures/_fbx_blender_stats.py). Then our encoder's output (tools/fixtures/_fbx_encode.luau) read back by
|
||||
# assimp and Blender.
|
||||
# tests/gen/fbx_cases.luau { name, data, files = { name -> bytes }, assimp, blender? }
|
||||
# tests/gen/fbx_xcheck.luau { name, case, assimp, blender? }
|
||||
# tests/gen/fbx_gltf.luau glTF sample models (tests/fixtures/gltf) for the writer round trips: { name, data, files }
|
||||
import importlib.util, json, os, shutil, subprocess
|
||||
|
||||
INPUTS = ["src/Formats/model/fbx", "tests/fixtures/gltf", "src/Formats/codecs/Deflate", "tools/fixtures/_model_ref.py",
|
||||
"tools/fixtures/_fbx_blender.py", "tools/fixtures/_fbx_blender_stats.py", "tools/fixtures/_fbx_encode.luau"]
|
||||
|
||||
|
||||
def ref_module(ctx):
|
||||
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)
|
||||
return m
|
||||
|
||||
|
||||
def assimp_extra(ctx, path):
|
||||
import re
|
||||
try:
|
||||
txt = ctx.nix("assimp", ["assimp", "info", path, "-r"]).decode("utf-8", "replace")
|
||||
except subprocess.CalledProcessError:
|
||||
return {}
|
||||
out = {}
|
||||
for label in ("Animations", "Cameras", "Lights", "Bones", "Animation Channels"):
|
||||
m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M)
|
||||
if m:
|
||||
out[label.lower().replace(" ", "_")] = int(m.group(1))
|
||||
return out
|
||||
|
||||
|
||||
def ptv_bounds(ctx, path, tmp):
|
||||
# world-space bounds: assimp's PreTransformVertices output (`assimp info` multiplies node matrices in the wrong
|
||||
# order for nested nodes, so its own bounds are not used)
|
||||
out = os.path.join(tmp, "ptv.obj")
|
||||
try:
|
||||
ctx.nix("assimp", ["assimp", "export", path, out, "-ptv"])
|
||||
lo, hi = [1e30] * 3, [-1e30] * 3
|
||||
with open(out) as f:
|
||||
for line in f:
|
||||
if line.startswith("v "):
|
||||
v = [float(x) for x in line.split()[1:4]]
|
||||
lo = [min(a, b) for a, b in zip(lo, v)]
|
||||
hi = [max(a, b) for a, b in zip(hi, v)]
|
||||
os.remove(out)
|
||||
return {"min": lo, "max": hi} if lo[0] <= hi[0] else {}
|
||||
except (subprocess.CalledProcessError, OSError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
def blender():
|
||||
return shutil.which("blender")
|
||||
|
||||
|
||||
def blender_stats(ctx, paths):
|
||||
exe = blender()
|
||||
if not exe or not paths:
|
||||
return [None] * len(paths)
|
||||
script = os.path.join(ctx.root, "tools", "fixtures", "_fbx_blender_stats.py")
|
||||
try:
|
||||
res = subprocess.run([exe, "-b", "--factory-startup", "--python", script, "--", json.dumps(paths)],
|
||||
capture_output=True, timeout=900)
|
||||
except (subprocess.TimeoutExpired, OSError):
|
||||
return [None] * len(paths)
|
||||
for line in res.stdout.decode("utf-8", "replace").split("\n"):
|
||||
if line.startswith("STATS "):
|
||||
return json.loads(line[6:])
|
||||
return [None] * len(paths)
|
||||
|
||||
|
||||
def assimp_src(ctx):
|
||||
out = subprocess.run(["nix", "build", "nixpkgs#assimp.src", "--no-link", "--print-out-paths"], capture_output=True, check=True)
|
||||
return out.stdout.decode().strip().split("\n")[-1]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
M = ref_module(ctx)
|
||||
tmp = M.tempdir()
|
||||
cases = []
|
||||
# assimp's test models (read only)
|
||||
src = os.path.join(assimp_src(ctx), "test", "models", "FBX")
|
||||
for root, _, files in sorted(os.walk(src)):
|
||||
for f in sorted(files):
|
||||
if f.lower().endswith(".fbx"):
|
||||
p = os.path.join(root, f)
|
||||
cases.append({"name": "assimp/" + os.path.relpath(p, src), "path": p, "files": {}})
|
||||
# Blender's exporter
|
||||
exe = blender()
|
||||
if exe:
|
||||
bdir = os.path.join(tmp, "blender")
|
||||
os.makedirs(bdir)
|
||||
subprocess.run([exe, "-b", "--factory-startup", "--python", os.path.join(ctx.root, "tools", "fixtures", "_fbx_blender.py"), "--", bdir],
|
||||
capture_output=True, check=True, timeout=600)
|
||||
for f in sorted(os.listdir(bdir)):
|
||||
if f.endswith(".fbx"):
|
||||
cases.append({"name": "blender/" + f, "path": os.path.join(bdir, f), "files": {}})
|
||||
# assimp's exporters: binary and ASCII, from a few glTF sample models (skin, morph, textures) and a PLY torus
|
||||
gl = os.path.join(ctx.root, "tests", "fixtures", "gltf")
|
||||
for model, variant, main in (("SimpleSkin", "glTF", "SimpleSkin.gltf"), ("BoxTextured", "glTF", "BoxTextured.gltf"),
|
||||
("RiggedSimple", "glTF-Binary", "RiggedSimple.glb"), ("Cameras", "glTF", "Cameras.gltf"),
|
||||
("BoxVertexColors", "glTF-Binary", "BoxVertexColors.glb")):
|
||||
inp = os.path.join(gl, model, variant, main)
|
||||
if not os.path.exists(inp):
|
||||
continue
|
||||
for fmt in ("fbx", "fbxa"):
|
||||
out = os.path.join(tmp, "%s_%s.fbx" % (model, fmt))
|
||||
try:
|
||||
ctx.nix("assimp", ["assimp", "export", inp, out, "-f" + fmt])
|
||||
except subprocess.CalledProcessError:
|
||||
continue
|
||||
cases.append({"name": "assimp-export/%s.%s" % (model, fmt), "path": out, "files": {}})
|
||||
paths = [c["path"] for c in cases]
|
||||
infos = M.assimp_info(ctx, paths, raw=True)
|
||||
bl = blender_stats(ctx, paths)
|
||||
for c, a, b in zip(cases, infos, bl):
|
||||
a.update(assimp_extra(ctx, c["path"]))
|
||||
a.pop("min", None)
|
||||
a.pop("max", None)
|
||||
a.update(ptv_bounds(ctx, c["path"], tmp))
|
||||
c["assimp"] = a
|
||||
if b:
|
||||
c["blender"] = b
|
||||
c["data"] = open(c["path"], "rb").read()
|
||||
# sibling files a model refers to (textures next to it)
|
||||
d = os.path.dirname(c["path"])
|
||||
for f in sorted(os.listdir(d)):
|
||||
if f.lower().endswith((".png", ".jpg", ".jpeg", ".tga")) and os.path.getsize(os.path.join(d, f)) < 300000:
|
||||
c["files"][f] = open(os.path.join(d, f), "rb").read()
|
||||
del c["path"]
|
||||
ctx.emit("fbx_cases", cases)
|
||||
|
||||
# glTF sample models for the writer round trips (glTF -> FBX -> Scene, compared with the glTF scene)
|
||||
picks = []
|
||||
for model in ("Box", "BoxTextured", "BoxVertexColors", "SimpleSkin", "RiggedSimple", "SimpleMorph", "AnimatedMorphCube",
|
||||
"Cameras", "MultiUVTest", "InterpolationTest", "NegativeScaleTest", "PointLightIntensityTest",
|
||||
"AnimatedTriangle", "TextureCoordinateTest", "MeshPrimitiveModes", "SimpleMeshes"):
|
||||
d0 = os.path.join(gl, model)
|
||||
if not os.path.isdir(d0):
|
||||
continue
|
||||
for variant in sorted(os.listdir(d0)):
|
||||
d = os.path.join(d0, variant)
|
||||
if not os.path.isdir(d):
|
||||
continue
|
||||
mains = [f for f in sorted(os.listdir(d)) if f.endswith(".gltf") or f.endswith(".glb")]
|
||||
if mains:
|
||||
picks.append({"name": model + "/" + variant, "data": open(os.path.join(d, mains[0]), "rb").read(),
|
||||
"files": {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != mains[0]}})
|
||||
break
|
||||
ctx.emit("fbx_gltf", picks)
|
||||
|
||||
# the reference tools read our output
|
||||
ours = M.luau_encode(ctx, "tools/fixtures/_fbx_encode.luau")
|
||||
xtmp = M.tempdir()
|
||||
names = sorted(n for n in ours if n.endswith(".fbx"))
|
||||
for name, data in ours.items():
|
||||
with open(os.path.join(xtmp, name), "wb") as f:
|
||||
f.write(data)
|
||||
xpaths = [os.path.join(xtmp, n) for n in names]
|
||||
xi = M.assimp_info(ctx, xpaths, raw=True)
|
||||
bin_paths = [p for p in xpaths if not p.endswith(".a.fbx")] # Blender reads binary FBX only
|
||||
xb_bin = dict(zip(bin_paths, blender_stats(ctx, bin_paths)))
|
||||
xb = [xb_bin.get(p) for p in xpaths]
|
||||
out = []
|
||||
for n, p, a, b in zip(names, xpaths, xi, xb):
|
||||
a.update(assimp_extra(ctx, p))
|
||||
a.pop("min", None)
|
||||
a.pop("max", None)
|
||||
a.update(ptv_bounds(ctx, p, xtmp))
|
||||
e = {"name": n, "case": int(n.split("_")[1].split(".")[0]), "assimp": a}
|
||||
if b:
|
||||
e["blender"] = b
|
||||
out.append(e)
|
||||
ctx.emit("fbx_xcheck", out)
|
||||
@@ -0,0 +1,185 @@
|
||||
# STEP fixtures (tools/fixtures.py): solids modelled in gmsh's OpenCASCADE kernel and written as STEP by OCCT
|
||||
# (gmsh -0 x.geo -o x.step), plus public STEP files fetched at fixture time into a fresh temporary directory
|
||||
# (untrusted input, only read; skipped when offline). Reference values:
|
||||
# - a Part 21 instance census by an independent Python tokenizer (instance count, count per entity type),
|
||||
# - OCCT through gmsh's Python API: number of solids, total volume, number of faces, total area, bounding box.
|
||||
# Our writer's output (tools/fixtures/_step_encode.luau re-encodes every case) is read back by OCCT through gmsh too.
|
||||
# tests/gen/step_cases.luau { name, data, census = { count, types = { TYPE = n } }, occt = { solids, volume,
|
||||
# faces, area, bbox }, ours = occt values of our re-encoded file }
|
||||
# tests/gen/step_brep.luau brep-luau's modules ({ Step, StepBrep, StepWrite, Tess, Build, Boolean, M }) through the
|
||||
# tests/gen/.luaurc alias "brep" (only when ~/dev/luau/brep-luau, or $BREP_LUAU, exists; luau CLI only)
|
||||
import json, os, re, shutil, subprocess, tempfile, urllib.request
|
||||
|
||||
INPUTS = ["src/Formats/cad/step", "tools/fixtures/_step_encode.luau"]
|
||||
|
||||
GEO = {
|
||||
"plate": """Box(1) = {0,0,0, 40,30,5};
|
||||
Cylinder(2) = {20,15,-1, 0,0,7, 6};
|
||||
BooleanDifference{ Volume{1}; Delete; }{ Volume{2}; Delete; }""",
|
||||
"sphere": "Sphere(1) = {0,0,0, 10};",
|
||||
"torus": "Torus(1) = {0,0,0, 20, 5};",
|
||||
"cone": "Cone(1) = {0,0,0, 0,0,12, 6, 2};",
|
||||
"two_boxes": """Box(1) = {0,0,0, 10,10,10};
|
||||
Box(2) = {20,0,0, 5,5,30};""",
|
||||
"bracket": """Box(1) = {0,0,0, 60,40,8};
|
||||
Box(2) = {0,0,0, 8,40,50};
|
||||
BooleanUnion{ Volume{1}; Delete; }{ Volume{2}; Delete; }
|
||||
Cylinder(3) = {30,20,-1, 0,0,10, 7};
|
||||
Sphere(4) = {4,20,35, 9};
|
||||
BooleanDifference{ Volume{1}; Delete; }{ Volume{3,4}; Delete; }""",
|
||||
}
|
||||
|
||||
URLS = {
|
||||
# build123d documentation example (Apache-2.0)
|
||||
"nema17_bracket": "https://raw.githubusercontent.com/gumyr/build123d/dev/docs/topology_selection/examples/nema-17-bracket.step",
|
||||
# pythonocc-demos sample model (parse + OCCT reference only; not committed)
|
||||
"ventilator": "https://raw.githubusercontent.com/tpaviot/pythonocc-demos/master/assets/models/Ventilator.stp",
|
||||
}
|
||||
MAX_FETCH = 4 << 20
|
||||
|
||||
OCCT = r"""
|
||||
import json, sys, gmsh
|
||||
gmsh.initialize()
|
||||
gmsh.option.setNumber("General.Terminal", 0)
|
||||
res = []
|
||||
for p in json.loads(sys.stdin.read()):
|
||||
try:
|
||||
gmsh.clear()
|
||||
gmsh.model.occ.importShapes(p)
|
||||
gmsh.model.occ.synchronize()
|
||||
vols = gmsh.model.getEntities(3)
|
||||
faces = gmsh.model.getEntities(2)
|
||||
bb = gmsh.model.getBoundingBox(-1, -1)
|
||||
res.append({"solids": len(vols), "volume": sum(gmsh.model.occ.getMass(3, t) for _, t in vols),
|
||||
"faces": len(faces), "area": sum(gmsh.model.occ.getMass(2, t) for _, t in faces), "bbox": list(bb)})
|
||||
except Exception as e:
|
||||
res.append({"failed": True})
|
||||
print(json.dumps(res))
|
||||
"""
|
||||
|
||||
|
||||
def census(text):
|
||||
# an independent Part 21 tokenizer: comments and strings removed, statements split at ';'
|
||||
out = []
|
||||
i, n = 0, len(text)
|
||||
while i < n:
|
||||
c = text[i]
|
||||
if c == "'":
|
||||
j = i + 1
|
||||
while True:
|
||||
j = text.index("'", j)
|
||||
if j + 1 < n and text[j + 1] == "'":
|
||||
j += 2
|
||||
else:
|
||||
break
|
||||
out.append("''")
|
||||
i = j + 1
|
||||
elif c == "/" and text.startswith("/*", i):
|
||||
i = text.index("*/", i + 2) + 2
|
||||
else:
|
||||
out.append(c)
|
||||
i += 1
|
||||
clean = "".join(out)
|
||||
data = clean[clean.index("DATA"):]
|
||||
types = {}
|
||||
count = 0
|
||||
for st in data.split(";"):
|
||||
m = re.match(r"\s*#(\d+)\s*=\s*(\(|[A-Za-z_][A-Za-z0-9_]*)", st)
|
||||
if m:
|
||||
count += 1
|
||||
t = "COMPLEX" if m.group(2) == "(" else m.group(2).upper()
|
||||
types[t] = types.get(t, 0) + 1
|
||||
return {"count": count, "types": types}
|
||||
|
||||
|
||||
def occt(ctx, paths):
|
||||
expr = "with import <nixpkgs> {}; python3.withPackages (p: [p.gmsh])"
|
||||
cmd = ["nix", "shell", "--impure", "--expr", expr, "-c", "python3", "-I", "-c", OCCT]
|
||||
res = subprocess.run(cmd, input=json.dumps(paths).encode(), capture_output=True, check=True)
|
||||
return json.loads(res.stdout)
|
||||
|
||||
|
||||
def luau(ctx, script):
|
||||
exe = shutil.which("luau")
|
||||
cmd = [exe, script] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau", script]
|
||||
res = subprocess.run(cmd, cwd=ctx.root, capture_output=True, check=True)
|
||||
files = {}
|
||||
for line in res.stdout.decode().split("\n"):
|
||||
if "\t" in line:
|
||||
name, hexdata = line.split("\t", 1)
|
||||
files[name] = bytes.fromhex(hexdata.strip())
|
||||
return files
|
||||
|
||||
|
||||
def brep(ctx):
|
||||
root = os.environ.get("BREP_LUAU") or os.path.expanduser("~/dev/luau/brep-luau")
|
||||
rc = os.path.join(ctx.gen, ".luaurc")
|
||||
mod = os.path.join(ctx.gen, "step_brep.luau")
|
||||
if not os.path.exists(os.path.join(root, "src", "step", "StepBrep.luau")):
|
||||
for p in (rc, mod):
|
||||
if os.path.exists(p):
|
||||
os.remove(p)
|
||||
ctx.emit("step_brep", False)
|
||||
return
|
||||
with open(rc, "w") as f:
|
||||
json.dump({"aliases": {"brep": os.path.join(os.path.abspath(root), "src")}}, f)
|
||||
path = os.path.join(ctx.gen, "step_brep.luau")
|
||||
with open(path, "w") as f:
|
||||
f.write("-- generated by tools/fixtures.py (tools/fixtures/step.py) - do not edit\n"
|
||||
"-- brep-luau through the tests/gen/.luaurc alias \"brep\" (luau CLI only)\n"
|
||||
"return {\n"
|
||||
"\tStep = require(\"@brep/step/Step\"),\n"
|
||||
"\tStepBrep = require(\"@brep/step/StepBrep\"),\n"
|
||||
"\tStepWrite = require(\"@brep/kernel/StepWrite\"),\n"
|
||||
"\tTess = require(\"@brep/kernel/Tess\"),\n"
|
||||
"\tBuild = require(\"@brep/kernel/Build\"),\n"
|
||||
"\tBoolean = require(\"@brep/kernel/Boolean\"),\n"
|
||||
"\tM = require(\"@brep/kernel/Math\"),\n"
|
||||
"}\n")
|
||||
ctx.outputs.append(path)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp(prefix="formats-step-")
|
||||
cases = []
|
||||
for name, geo in GEO.items():
|
||||
g = os.path.join(tmp, name + ".geo")
|
||||
with open(g, "w") as f:
|
||||
f.write('SetFactory("OpenCASCADE");\n' + geo + "\n")
|
||||
out = os.path.join(tmp, name + ".step")
|
||||
ctx.nix("gmsh", ["gmsh", "-0", g, "-o", out])
|
||||
cases.append({"name": "gmsh/" + name, "path": out})
|
||||
fetched = tempfile.mkdtemp(prefix="formats-step-fetch-")
|
||||
for name, url in URLS.items():
|
||||
dst = os.path.join(fetched, name + ".step")
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=30) as r:
|
||||
data = r.read(MAX_FETCH + 1)
|
||||
if len(data) > MAX_FETCH:
|
||||
continue
|
||||
with open(dst, "wb") as f:
|
||||
f.write(data)
|
||||
cases.append({"name": "public/" + name, "path": dst, "public": True})
|
||||
except Exception:
|
||||
pass
|
||||
refs = occt(ctx, [c["path"] for c in cases])
|
||||
for c, r in zip(cases, refs):
|
||||
c["data"] = open(c["path"], "rb").read()
|
||||
c["census"] = census(c["data"].decode("latin-1"))
|
||||
c["occt"] = r
|
||||
# our writer's output of every case, read back by OCCT
|
||||
ctx.emit("step_cases", [{k: v for k, v in c.items() if k != "path"} for c in cases])
|
||||
ours = luau(ctx, "tools/fixtures/_step_encode.luau")
|
||||
xtmp = tempfile.mkdtemp(prefix="formats-step-ours-")
|
||||
paths = []
|
||||
for i in range(len(cases)):
|
||||
data = ours.get("case_%d.step" % (i + 1))
|
||||
p = os.path.join(xtmp, "case_%d.step" % (i + 1))
|
||||
with open(p, "wb") as f:
|
||||
f.write(data or b"")
|
||||
paths.append(p)
|
||||
back = occt(ctx, paths)
|
||||
for c, r in zip(cases, back):
|
||||
c["ours"] = r
|
||||
ctx.emit("step_cases", [{k: v for k, v in c.items() if k != "path"} for c in cases])
|
||||
brep(ctx)
|
||||
@@ -0,0 +1,264 @@
|
||||
# USDA fixtures (tools/fixtures.py): stages authored through OpenUSD's own API (pxr, nixpkgs python3Packages.openusd:
|
||||
# every xform op kind / order, pivots, !resetXformStack!, primvar interpolations + indices, holes, leftHanded, n-gons,
|
||||
# UsdPreviewSurface + UsdUVTexture / UsdTransform2d / interface inputs, GeomSubsets, inherited bindings, cameras,
|
||||
# UsdLux lights, time samples; plus a .usdc and a .usdz), assimp's USD test models (models-nonbsd/USD: the .usda files
|
||||
# and the .usdc ones converted to .usda by Sdf, read from the nixpkgs assimp source, not committed), Blender 5 USD
|
||||
# exports of glTF sample models (when blender is on PATH), a hand-written file exercising the text grammar, and the
|
||||
# OpenUSD schema layers (parse-only). Reference values come from pxr (Usd.Stage: world transforms, triangles / area /
|
||||
# bounds per mesh, bound materials, cameras, lights, xform time samples).
|
||||
# tests/gen/usda_cases.luau { name, data, files = { uri -> bytes }, ref = pxr metrics | nil, expect = "UNSUPPORTED"? }
|
||||
# tests/gen/usda_specs.luau { name, data, prims = number of prim specs (Sdf) }
|
||||
# tests/gen/usda_xcheck.luau our writer's .usda for every case (tools/fixtures/_usda_encode.luau) read back by pxr:
|
||||
# { name, case, ref }
|
||||
import json, os, shutil, subprocess, tempfile
|
||||
|
||||
INPUTS = ["src/Formats/model/usda", "tools/fixtures/_usda_reference.py", "tools/fixtures/_usda_encode.luau",
|
||||
"tools/fixtures/_model_ref.py", "tests/fixtures/gltf"]
|
||||
|
||||
# the text grammar: comments, metadata of every kind, list ops, variants, class / over, dictionaries, strings,
|
||||
# relative paths, typed values that the Scene ignores
|
||||
HANDWRITTEN = r'''#usda 1.0
|
||||
(
|
||||
"""A layer written by hand: every construct of the text format the reader has to get through."""
|
||||
customLayerData = {
|
||||
string creator = "formats-luau tests"
|
||||
dictionary nested = {
|
||||
int[] numbers = [1, 2, 3]
|
||||
double "quoted key" = 1.5
|
||||
}
|
||||
}
|
||||
defaultPrim = "Hand"
|
||||
metersPerUnit = 0.0254
|
||||
upAxis = "Z"
|
||||
timeCodesPerSecond = 24
|
||||
)
|
||||
|
||||
# a class (abstract: not a node) and an over of nothing
|
||||
class "_Template"
|
||||
{
|
||||
float3 xformOp:translate = (100, 100, 100)
|
||||
}
|
||||
|
||||
def Xform "Hand" (
|
||||
kind = "assembly"
|
||||
doc = 'single quoted doc'
|
||||
variants = {
|
||||
string look = "big"
|
||||
}
|
||||
prepend variantSets = "look"
|
||||
customData = { bool flag = true }
|
||||
)
|
||||
{
|
||||
custom string notes = """multi
|
||||
line""" // trailing comment
|
||||
custom asset path = @@@[email protected]@@@
|
||||
custom double[] empty = []
|
||||
custom float big = inf
|
||||
custom float small = -inf
|
||||
custom token[] tokens = ["a", "b"]
|
||||
custom rel others = [</Hand/Big>, <../Hand>]
|
||||
reorder nameChildren = ["Big", "Tri"]
|
||||
|
||||
def Mesh "Tri" ( active = true )
|
||||
{
|
||||
point3f[] points = [(0,0,0),(1,0,0),(0,1,0)] ; int[] faceVertexCounts = [3]
|
||||
int[] faceVertexIndices = [0, 1, 2]
|
||||
double3 xformOp:translate = (1, 0, 0)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate"]
|
||||
rel material:binding = <../Looks/Blue>
|
||||
}
|
||||
|
||||
variantSet "look" = {
|
||||
"big" (doc = "selected") {
|
||||
def Mesh "Big"
|
||||
{
|
||||
float3 xformOp:scale = (3, 3, 3)
|
||||
uniform token[] xformOpOrder = ["xformOp:scale"]
|
||||
point3f[] points = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)]
|
||||
int[] faceVertexCounts = [4]
|
||||
int[] faceVertexIndices = [0, 1, 2, 3]
|
||||
color3f[] primvars:displayColor = [(1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 1, 1)] (
|
||||
interpolation = "vertex"
|
||||
)
|
||||
}
|
||||
}
|
||||
"small" {
|
||||
def Mesh "Small"
|
||||
{
|
||||
point3f[] points = [(0, 0, 0), (1, 0, 0), (0, 1, 0)]
|
||||
int[] faceVertexCounts = [3]
|
||||
int[] faceVertexIndices = [0, 1, 2]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
def Scope "Looks"
|
||||
{
|
||||
def Material "Blue"
|
||||
{
|
||||
color3f inputs:tint = (0.1, 0.2, 0.9)
|
||||
token outputs:surface.connect = <Surface.outputs:surface>
|
||||
|
||||
def Shader "Surface"
|
||||
{
|
||||
uniform token info:id = "UsdPreviewSurface"
|
||||
color3f inputs:diffuseColor.connect = </Hand/Looks/Blue.inputs:tint>
|
||||
float inputs:roughness = 0.25
|
||||
token outputs:surface
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
def "Untyped"
|
||||
{
|
||||
def Xform "Inner" (
|
||||
prepend references = @missing.usda@</Thing>
|
||||
)
|
||||
{
|
||||
matrix4d xformOp:transform.timeSamples = {
|
||||
0: ( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1) ),
|
||||
10: ( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 5, 1) ),
|
||||
}
|
||||
uniform token[] xformOpOrder = ["xformOp:transform"]
|
||||
|
||||
def Mesh "Quad"
|
||||
{
|
||||
point3f[] points = [(0, 0, 0), (2, 0, 0), (2, 2, 0), (0, 2, 0)]
|
||||
int[] faceVertexCounts = [4]
|
||||
int[] faceVertexIndices = [0, 1, 2, 3]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
over "Elsewhere"
|
||||
{
|
||||
def Xform "Undefined"
|
||||
{
|
||||
double3 xformOp:translate = (0, 0, -1)
|
||||
uniform token[] xformOpOrder = ["xformOp:translate"]
|
||||
}
|
||||
}
|
||||
'''
|
||||
|
||||
GLTF_MODELS = [("Box", "glTF", "Box.gltf"), ("BoxTextured", "glTF", "BoxTextured.gltf"), ("AnimatedTriangle", "glTF", "AnimatedTriangle.gltf"),
|
||||
("Cameras", "glTF", "Cameras.gltf"), ("MultiUVTest", "glTF-Binary", None), ("BoxVertexColors", "glTF-Binary", None)]
|
||||
|
||||
BLENDER = r'''
|
||||
import bpy, sys
|
||||
args = sys.argv[sys.argv.index("--") + 1:]
|
||||
bpy.ops.wm.read_factory_settings(use_empty=True)
|
||||
bpy.ops.import_scene.gltf(filepath=args[0])
|
||||
bpy.ops.wm.usd_export(filepath=args[1], export_materials=True, export_animation=True, relative_paths=True)
|
||||
'''
|
||||
|
||||
|
||||
def pxr(ctx, req):
|
||||
code = ctx.read("tools/fixtures/_usda_reference.py").decode()
|
||||
try:
|
||||
return json.loads(ctx.python(["openusd"], code, input=json.dumps(req).encode()))
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise RuntimeError("pxr (%s) failed:\n%s" % (req["mode"], e.stderr.decode(errors="replace")[-3000:])) from None
|
||||
|
||||
|
||||
def files_under(d, skip):
|
||||
out = {}
|
||||
for root, _, fs in os.walk(d):
|
||||
for f in fs:
|
||||
p = os.path.join(root, f)
|
||||
rel = os.path.relpath(p, d).replace(os.sep, "/")
|
||||
if rel != skip and not rel.endswith((".usda", ".usdc", ".usdz", ".usd", ".py")):
|
||||
out[rel] = open(p, "rb").read()
|
||||
return out
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp(prefix="formats-usda-")
|
||||
cases = [] # name, path, files, expect?
|
||||
# 1. stages authored through pxr
|
||||
adir = os.path.join(tmp, "authored")
|
||||
os.makedirs(adir)
|
||||
for name in pxr(ctx, {"mode": "author", "dir": adir}):
|
||||
p = os.path.join(adir, name)
|
||||
c = {"name": "pxr/" + name, "path": p, "files": files_under(adir, name)}
|
||||
if name.endswith(".usdc"):
|
||||
c["expect"] = "UNSUPPORTED"
|
||||
if name.endswith(".usdz"):
|
||||
c["files"] = {}
|
||||
c["like"] = "pxr/materials.usda"
|
||||
cases.append(c)
|
||||
# 2. hand-written grammar test
|
||||
hand = os.path.join(tmp, "hand.usda")
|
||||
with open(hand, "w") as f:
|
||||
f.write(HANDWRITTEN)
|
||||
cases.append({"name": "hand.usda", "path": hand, "files": {}})
|
||||
# 3. assimp's USD test models (untrusted data: read only, from the nix store)
|
||||
src = subprocess.run(["nix", "build", "nixpkgs#assimp.src", "--no-link", "--print-out-paths"], capture_output=True, check=True).stdout.decode().strip()
|
||||
usd = os.path.join(src, "test", "models-nonbsd", "USD")
|
||||
conv = os.path.join(tmp, "assimp")
|
||||
os.makedirs(conv)
|
||||
for f in sorted(os.listdir(os.path.join(usd, "usda"))):
|
||||
if f.endswith(".usda"):
|
||||
cases.append({"name": "assimp/" + f, "path": os.path.join(usd, "usda", f), "files": files_under(os.path.join(usd, "usda"), f)})
|
||||
for d, f in [(os.path.join(usd, "usdc"), x) for x in sorted(os.listdir(os.path.join(usd, "usdc"))) if x.endswith(".usdc")] + [(os.path.join(src, "test", "models", "USD"), "MotionCaptureROM.usdc")]:
|
||||
dst = os.path.join(conv, f[:-5] + ".usda")
|
||||
pxr(ctx, {"mode": "convert", "src": os.path.join(d, f), "dst": dst})
|
||||
cases.append({"name": "assimp/" + f + " (usdcat)", "path": dst, "files": files_under(d, f)})
|
||||
# 4. Blender USD exports of glTF samples
|
||||
if shutil.which("blender"):
|
||||
bdir = os.path.join(tmp, "blender")
|
||||
os.makedirs(bdir)
|
||||
script = os.path.join(tmp, "blender_export.py")
|
||||
with open(script, "w") as f:
|
||||
f.write(BLENDER)
|
||||
groot = os.path.join(ctx.root, "tests", "fixtures", "gltf")
|
||||
for model, variant, main in GLTF_MODELS:
|
||||
d = os.path.join(groot, model, variant)
|
||||
if not os.path.isdir(d):
|
||||
continue
|
||||
main = main or [x for x in sorted(os.listdir(d)) if x.endswith((".gltf", ".glb"))][0]
|
||||
out = os.path.join(bdir, model, model + ".usda")
|
||||
os.makedirs(os.path.dirname(out), exist_ok=True)
|
||||
r = subprocess.run(["blender", "-b", "--factory-startup", "--python", script, "--", os.path.join(d, main), out], capture_output=True)
|
||||
if r.returncode == 0 and os.path.exists(out):
|
||||
cases.append({"name": "blender/" + model, "path": out, "files": files_under(os.path.dirname(out), model + ".usda")})
|
||||
refs = pxr(ctx, {"mode": "metrics", "paths": [c["path"] for c in cases if "expect" not in c]})
|
||||
k = 0
|
||||
for c in cases:
|
||||
if "expect" not in c:
|
||||
c["ref"] = refs[k]
|
||||
k += 1
|
||||
c["data"] = open(c["path"], "rb").read()
|
||||
del c["path"]
|
||||
ctx.emit("usda_cases", cases)
|
||||
|
||||
# 5. parse-only: OpenUSD's schema layers
|
||||
usdpkg = ctx.python(["openusd"], "import pxr, os; print(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(pxr.__file__)))))))").decode().strip()
|
||||
specs = []
|
||||
for root, _, fs in os.walk(usdpkg):
|
||||
for f in fs:
|
||||
if f.endswith(".usda") and ("usdGeom" in root or "usdShade" in root or "usdLux" in root or "usdSkel" in root):
|
||||
specs.append(os.path.join(root, f))
|
||||
specs = sorted(specs)[:8]
|
||||
counts = pxr(ctx, {"mode": "specs", "paths": specs})
|
||||
ctx.emit("usda_specs", [{"name": os.path.relpath(p, usdpkg), "data": open(p, "rb").read(), "prims": n} for p, n in zip(specs, counts)])
|
||||
|
||||
# 6. pxr reads our writer's output
|
||||
exe = shutil.which("luau")
|
||||
cmd = [exe, "tools/fixtures/_usda_encode.luau"] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau", "tools/fixtures/_usda_encode.luau"]
|
||||
res = subprocess.run(cmd, cwd=ctx.root, capture_output=True, check=True)
|
||||
xdir = os.path.join(tmp, "ours")
|
||||
os.makedirs(xdir)
|
||||
mains = []
|
||||
for line in res.stdout.decode().split("\n"):
|
||||
if "\t" in line:
|
||||
name, hexdata = line.split("\t", 1)
|
||||
p = os.path.join(xdir, name)
|
||||
os.makedirs(os.path.dirname(p), exist_ok=True)
|
||||
with open(p, "wb") as f:
|
||||
f.write(bytes.fromhex(hexdata.strip()))
|
||||
if name.endswith(".usda") and "/" not in name:
|
||||
mains.append(name)
|
||||
xrefs = pxr(ctx, {"mode": "metrics", "paths": [os.path.join(xdir, n) for n in mains]})
|
||||
ctx.emit("usda_xcheck", [{"name": n, "case": int(n[5:].split(".")[0]), "ref": r} for n, r in zip(mains, xrefs)])
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
Reference in new issue
Block a user