Reads stage metadata, xform op stacks (every rotate order, orient, transform, pivots / !invert!, resetXformStack), time samples -> TRS animation, Mesh (all primvar interpolations + indices, GeomSubsets, holes, leftHanded), UsdPreviewSurface / UsdUVTexture / UsdTransform2d materials with inherited bindings, cameras, UsdLux lights, selected variants. USDC returns UNSUPPORTED. Writes Xform / Mesh / GeomSubset / Material / Camera / lights.
265 lines
11 KiB
Python
265 lines
11 KiB
Python
# 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)
|