ws-3d3: codecs/model/Vrml (VRML97 / X3D classic parser, X3D XML adapter, node graph -> Scene builder, writer) + model/vrml (.wrl read / write) + model/x3d (.x3d / .x3dv read / write; .x3db UNSUPPORTED); tests against VTK and assimp
This commit is contained in:
1 parent
4c74171631
commit
76128bf381
20 files changed
+4906
-1
No files matched your search
@@ -0,0 +1,54 @@
|
||||
-- tools/fixtures/_vrml_encode: run by tools/fixtures/vrml.py and x3d.py (luau CLI, repo root): decodes every VRML /
|
||||
-- X3D case and glTF sample with our readers and writes it back with our writers, printing "<file>\t<hex>" lines for
|
||||
-- VTK (.wrl) and assimp (.x3d) to read back. Files: case_<i>.wrl, gltf_<i>.wrl, xcase_<i>.x3d, xgltf_<i>.x3d.
|
||||
local Vrml = require("@formats/model/vrml")
|
||||
local X3d = require("@formats/model/x3d")
|
||||
local Gltf = require("@formats/model/gltf")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Cases = require("@tests/gen/vrml_cases")
|
||||
local GltfCases = require("@tests/gen/vrml_gltf")
|
||||
local ok, X3dCases = pcall(require, "@tests/gen/x3d_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
|
||||
|
||||
local function both(scene: any, wrl: string, x3d: string)
|
||||
local a = Vrml.encode(scene)
|
||||
if a then
|
||||
print(wrl .. "\t" .. hex(a))
|
||||
end
|
||||
local b = X3d.encode(scene)
|
||||
if b then
|
||||
print(x3d .. "\t" .. hex(b))
|
||||
end
|
||||
end
|
||||
|
||||
for i, c in Cases do
|
||||
local scene = Vrml.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files, triangulate = false })
|
||||
if scene then
|
||||
both(scene, string.format("case_%d.wrl", i), string.format("wcase_%d.x3d", i))
|
||||
end
|
||||
end
|
||||
for i, c in GltfCases do
|
||||
local scene = Gltf.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files })
|
||||
if scene then
|
||||
both(scene, string.format("gltf_%d.wrl", i), string.format("xgltf_%d.x3d", i))
|
||||
end
|
||||
end
|
||||
if ok and type(X3dCases) == "table" then
|
||||
for i, c in X3dCases do
|
||||
local scene = X3d.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files, triangulate = false })
|
||||
if scene then
|
||||
both(scene, string.format("xcase_%d.wrl", i), string.format("xcase_%d.x3d", i))
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,241 @@
|
||||
# Shared helpers for tools/fixtures/vrml.py and x3d.py: VTK (nixpkgs python3 vtk) as the VRML97 reference reader and
|
||||
# as a writer of more .wrl / .x3d inputs, assimp's X3D reader for .x3d, and the hand-written feature files.
|
||||
# vtk_read(ctx, paths) -> [ { actors, polys, lines, verts, points, min, max } | { failed } ] (vtkVRMLImporter)
|
||||
# vtk_export(ctx, outdir, gltf_paths) -> [ (name, wrl path, x3d path) ] (vtkVRMLExporter / vtkX3DExporter scenes)
|
||||
# FEATURES: { name: VRML97 text } covering PROTO, DEF / USE, Switch, LOD, primitives, per-face colours, separate
|
||||
# indices, ElevationGrid, Extrusion, ROUTE animation, lights, viewpoints, Inline, PixelTexture
|
||||
import json
|
||||
|
||||
VTK_READ = r"""
|
||||
import json, os, sys, vtk
|
||||
vtk.vtkObject.GlobalWarningDisplayOff()
|
||||
|
||||
def read(p):
|
||||
imp = vtk.vtkVRMLImporter(); imp.SetFileName(p)
|
||||
rw = vtk.vtkRenderWindow(); rw.SetOffScreenRendering(1); imp.SetRenderWindow(rw)
|
||||
imp.Update()
|
||||
acts = imp.GetRenderer().GetActors(); acts.InitTraversal()
|
||||
out = {"actors": 0, "polys": 0, "lines": 0, "verts": 0, "points": 0}
|
||||
lo, hi = [1e30] * 3, [-1e30] * 3
|
||||
for i in range(acts.GetNumberOfItems()):
|
||||
a = acts.GetNextActor()
|
||||
m = a.GetMapper()
|
||||
if not m:
|
||||
continue
|
||||
m.Update()
|
||||
d = m.GetInput()
|
||||
if d is None or d.GetNumberOfPoints() == 0:
|
||||
continue
|
||||
out["actors"] += 1
|
||||
out["polys"] += d.GetNumberOfPolys() + d.GetNumberOfStrips()
|
||||
out["lines"] += d.GetNumberOfLines()
|
||||
out["verts"] += d.GetNumberOfVerts()
|
||||
out["points"] += d.GetNumberOfPoints()
|
||||
# tight world bounds: every point through the actor's matrix (GetBounds boxes the local bounds)
|
||||
mat = a.GetMatrix()
|
||||
pts = d.GetPoints()
|
||||
for j in range(d.GetNumberOfPoints()):
|
||||
p = pts.GetPoint(j)
|
||||
w = mat.MultiplyPoint((p[0], p[1], p[2], 1.0))
|
||||
for k in range(3):
|
||||
lo[k] = min(lo[k], w[k]); hi[k] = max(hi[k], w[k])
|
||||
if out["actors"]:
|
||||
out["min"], out["max"] = lo, hi
|
||||
return out
|
||||
|
||||
# one child process per file: vtkVRMLImporter crashes on some valid files
|
||||
res = []
|
||||
for p in json.loads(sys.stdin.read()):
|
||||
r, w = os.pipe()
|
||||
pid = os.fork()
|
||||
if pid == 0:
|
||||
os.close(r)
|
||||
try:
|
||||
data = json.dumps(read(p))
|
||||
except Exception:
|
||||
data = json.dumps({"failed": True})
|
||||
os.write(w, data.encode())
|
||||
os._exit(0)
|
||||
os.close(w)
|
||||
chunks = []
|
||||
while True:
|
||||
b = os.read(r, 65536)
|
||||
if not b:
|
||||
break
|
||||
chunks.append(b)
|
||||
os.close(r)
|
||||
_, status = os.waitpid(pid, 0)
|
||||
try:
|
||||
res.append(json.loads(b"".join(chunks).decode()) if status == 0 else {"failed": True, "crashed": True})
|
||||
except ValueError:
|
||||
res.append({"failed": True})
|
||||
print("RESULT " + json.dumps(res))
|
||||
"""
|
||||
|
||||
VTK_EXPORT = r"""
|
||||
import json, os, sys, vtk
|
||||
vtk.vtkObject.GlobalWarningDisplayOff()
|
||||
args = json.loads(sys.stdin.read())
|
||||
out, gltfs = args["out"], args["gltf"]
|
||||
made = []
|
||||
|
||||
def export(ren, name):
|
||||
rw = vtk.vtkRenderWindow(); rw.SetOffScreenRendering(1); rw.AddRenderer(ren)
|
||||
ren.ResetCamera()
|
||||
w = vtk.vtkVRMLExporter(); w.SetRenderWindow(rw); w.SetFileName(os.path.join(out, name + ".wrl")); w.Write()
|
||||
x = vtk.vtkX3DExporter(); x.SetRenderWindow(rw); x.SetFileName(os.path.join(out, name + ".x3d")); x.SetBinary(0); x.Write()
|
||||
made.append(name)
|
||||
|
||||
def actor(src, pos=(0, 0, 0), scale=(1, 1, 1), rot=(0, 0, 0), color=None, scalars=False):
|
||||
m = vtk.vtkPolyDataMapper(); m.SetInputConnection(src.GetOutputPort())
|
||||
if not scalars:
|
||||
m.ScalarVisibilityOff()
|
||||
a = vtk.vtkActor(); a.SetMapper(m); a.SetPosition(*pos); a.SetScale(*scale)
|
||||
a.RotateX(rot[0]); a.RotateY(rot[1]); a.RotateZ(rot[2])
|
||||
if color:
|
||||
a.GetProperty().SetColor(*color)
|
||||
return a
|
||||
|
||||
# 1. primitives as polygon meshes, transformed, coloured, one with point scalars
|
||||
ren = vtk.vtkRenderer()
|
||||
s = vtk.vtkSphereSource(); s.SetThetaResolution(16); s.SetPhiResolution(8)
|
||||
ren.AddActor(actor(s, (1, 2, 3), (2, 2, 2), (30, 0, 0), (0.9, 0.2, 0.1)))
|
||||
c = vtk.vtkConeSource(); c.SetResolution(12)
|
||||
ren.AddActor(actor(c, (-3, 0, 1), (1, 3, 1), (0, 45, 10), (0.2, 0.8, 0.3)))
|
||||
cube = vtk.vtkCubeSource(); cube.SetXLength(2); cube.SetYLength(1); cube.SetZLength(0.5)
|
||||
ren.AddActor(actor(cube, (0, -2, 0), (1, 1, 1), (0, 0, 20), (0.3, 0.3, 0.9)))
|
||||
keep = [vtk.vtkSphereSource(), vtk.vtkSphereSource(), vtk.vtkCubeSource()]
|
||||
el = vtk.vtkElevationFilter(); el.SetInputConnection(keep[0].GetOutputPort()); el.SetLowPoint(0, -0.5, 0); el.SetHighPoint(0, 0.5, 0)
|
||||
ren.AddActor(actor(el, (4, 4, 0), scalars=True))
|
||||
light = vtk.vtkLight(); light.SetPosition(5, 5, 5); light.SetFocalPoint(0, 0, 0); light.SetColor(1, 0.9, 0.8)
|
||||
ren.AddLight(light)
|
||||
export(ren, "vtk_shapes")
|
||||
|
||||
# 2. lines and points
|
||||
ren = vtk.vtkRenderer()
|
||||
ls = vtk.vtkLineSource(); ls.SetPoint1(0, 0, 0); ls.SetPoint2(3, 1, 2); ls.SetResolution(5)
|
||||
ren.AddActor(actor(ls, (1, 0, 0), color=(1, 1, 0)))
|
||||
pts = vtk.vtkPointSource(); pts.SetNumberOfPoints(40); pts.SetRadius(2); pts.SetCenter(0, 5, 0)
|
||||
ren.AddActor(actor(pts))
|
||||
ren.AddActor(actor(keep[2], (0, 0, -4)))
|
||||
export(ren, "vtk_lines_points")
|
||||
|
||||
# 3. a textured plane (PixelTexture) and a strip mesh
|
||||
ren = vtk.vtkRenderer()
|
||||
pl = vtk.vtkPlaneSource(); pl.SetResolution(3, 2)
|
||||
img = vtk.vtkImageCanvasSource2D(); img.SetScalarTypeToUnsignedChar(); img.SetNumberOfScalarComponents(3); img.SetExtent(0, 7, 0, 3, 0, 0)
|
||||
img.SetDrawColor(200, 30, 30); img.FillBox(0, 7, 0, 3); img.SetDrawColor(20, 30, 200); img.FillBox(0, 3, 0, 1); img.Update()
|
||||
tex = vtk.vtkTexture(); tex.SetInputConnection(img.GetOutputPort())
|
||||
a = actor(pl, (0, 0, 1), (4, 2, 1)); a.SetTexture(tex)
|
||||
ren.AddActor(a)
|
||||
strip = vtk.vtkStripper(); strip.SetInputConnection(keep[1].GetOutputPort())
|
||||
ren.AddActor(actor(strip, (0, 3, 0)))
|
||||
export(ren, "vtk_texture_strips")
|
||||
|
||||
# 4. glTF sample models through VTK's glTF importer
|
||||
for g in gltfs:
|
||||
try:
|
||||
imp = vtk.vtkGLTFImporter(); imp.SetFileName(g)
|
||||
rw = vtk.vtkRenderWindow(); rw.SetOffScreenRendering(1); imp.SetRenderWindow(rw); imp.Update()
|
||||
name = "vtk_gltf_" + os.path.splitext(os.path.basename(g))[0]
|
||||
export(imp.GetRenderer(), name)
|
||||
except Exception:
|
||||
pass
|
||||
print("RESULT " + json.dumps(made))
|
||||
"""
|
||||
|
||||
|
||||
def vtk_xform_ok(data):
|
||||
"""False when vtkVRMLImporter's transforms are wrong for the file: it ignores center and scaleOrientation"""
|
||||
import re
|
||||
return not re.search(rb"\b(center|scaleOrientation)\s+[-+\d.]", data)
|
||||
|
||||
|
||||
def _run(ctx, code, arg):
|
||||
out = ctx.python(["vtk"], code, input=json.dumps(arg).encode()).decode("utf-8", "replace")
|
||||
for line in out.split("\n"):
|
||||
if line.startswith("RESULT "):
|
||||
return json.loads(line[7:])
|
||||
raise RuntimeError("vtk script printed no result")
|
||||
|
||||
|
||||
def vtk_read(ctx, paths):
|
||||
return _run(ctx, VTK_READ, paths) if paths else []
|
||||
|
||||
|
||||
def vtk_export(ctx, outdir, gltfs):
|
||||
return _run(ctx, VTK_EXPORT, {"out": outdir, "gltf": gltfs})
|
||||
|
||||
|
||||
FEATURES = {
|
||||
"feat_proto_use.wrl": """#VRML V2.0 utf8
|
||||
PROTO Brick [ field SFVec3f size 1 1 1 field SFColor col 1 0 0 exposedField SFVec3f where 0 0 0 ] {
|
||||
Transform { translation IS where children Shape {
|
||||
appearance Appearance { material Material { diffuseColor IS col } }
|
||||
geometry Box { size IS size } } }
|
||||
}
|
||||
DEF A Brick { size 2 1 1 col 0 1 0 where 0 0 0 }
|
||||
Brick { where 3 0 0 }
|
||||
Transform { translation 0 3 0 children [ DEF S Shape { geometry IndexedFaceSet {
|
||||
coord DEF C Coordinate { point [ 0 0 0, 1 0 0, 1 1 0, 0 1 0 ] } coordIndex [ 0 1 2 3 -1 ] } } ] }
|
||||
Transform { translation 0 5 0 rotation 0 0 1 1.5708 children USE S }
|
||||
""",
|
||||
"feat_indices.wrl": """#VRML V2.0 utf8
|
||||
# separate normal / colour / texture indices, per-face colours, ccw FALSE, solid FALSE
|
||||
Shape {
|
||||
appearance Appearance { material Material { diffuseColor 0.5 0.5 0.5 transparency 0.25 shininess 0.5 specularColor 1 1 1 } }
|
||||
geometry IndexedFaceSet {
|
||||
solid FALSE ccw FALSE
|
||||
coord Coordinate { point [ 0 0 0, 2 0 0, 2 2 0, 0 2 0, 0 0 2, 2 0 2 ] }
|
||||
coordIndex [ 0 1 2 3 -1, 0 4 5 1 -1 ]
|
||||
normal Normal { vector [ 0 0 1, 0 -1 0 ] }
|
||||
normalPerVertex FALSE normalIndex [ 0 1 ]
|
||||
color Color { color [ 1 0 0, 0 0 1 ] }
|
||||
colorPerVertex FALSE
|
||||
texCoord TextureCoordinate { point [ 0 0, 1 0, 1 1, 0 1 ] }
|
||||
texCoordIndex [ 0 1 2 3 -1, 3 2 1 0 -1 ]
|
||||
}
|
||||
}
|
||||
Shape { geometry IndexedFaceSet {
|
||||
coord Coordinate { point [ 5 0 0, 6 0 0, 6 1 0, 5 1 0 ] }
|
||||
coordIndex [ 0 1 2 -1 0 2 3 ]
|
||||
color Color { color [ 1 0 0, 0 1 0, 0 0 1, 1 1 1 ] } colorIndex [ 3 2 1 -1 0 1 2 -1 ] } }
|
||||
""",
|
||||
"feat_primitives.wrl": """#VRML V2.0 utf8
|
||||
Transform { translation -4 0 0 children Shape { geometry Box { size 1 2 3 } } }
|
||||
Transform { translation 0 0 0 children Shape { geometry Sphere { radius 1.5 } } }
|
||||
Transform { translation 4 0 0 children Shape { geometry Cone { bottomRadius 1 height 3 } } }
|
||||
Transform { translation 8 0 0 scale 2 1 1 children Shape { geometry Cylinder { radius 0.5 height 4 } } }
|
||||
""",
|
||||
"feat_grid_extrusion.wrl": """#VRML V2.0 utf8
|
||||
Shape { geometry ElevationGrid { xDimension 4 zDimension 3 xSpacing 1 zSpacing 2
|
||||
height [ 0 1 0 1, 1 2 1 0, 0 0 1 3 ] } }
|
||||
Transform { translation 6 0 0 children Shape { geometry Extrusion {
|
||||
crossSection [ 1 1, 1 -1, -1 -1, -1 1, 1 1 ] spine [ 0 0 0, 0 1 0, 1 2 0, 2 2 0 ] scale [ 1 1, 0.5 0.5, 0.5 0.5, 1 1 ] } } }
|
||||
""",
|
||||
"feat_scene.wrl": """#VRML V2.0 utf8
|
||||
WorldInfo { title "feature scene" info [ "made for formats-luau" ] }
|
||||
DEF Cam Viewpoint { position 0 1 8 orientation 0 1 0 0.3 fieldOfView 0.9 description "front" }
|
||||
DEF Sun DirectionalLight { direction 0 -1 -1 intensity 0.8 color 1 1 0.9 }
|
||||
DEF Bulb PointLight { location 1 2 3 radius 10 }
|
||||
DEF Spot SpotLight { location 0 5 0 direction 0 -1 0 cutOffAngle 0.6 beamWidth 0.4 }
|
||||
DEF Sw Switch { whichChoice 1 choice [
|
||||
Shape { geometry Box { } }
|
||||
Transform { translation 0 2 0 children Shape { geometry Sphere { radius 0.5 } } } ] }
|
||||
LOD { range [ 10 ] level [ Shape { geometry Box { size 0.5 0.5 0.5 } } Shape { geometry Sphere { } } ] }
|
||||
DEF Mover Transform { center 1 0 0 scaleOrientation 0 0 1 0.5 scale 1 2 1 children [
|
||||
Shape { geometry IndexedLineSet { coord Coordinate { point [ 0 0 0, 1 0 0, 1 1 0 ] } coordIndex [ 0 1 2 -1 ] color Color { color [ 1 0 0, 0 1 0, 0 0 1 ] } } }
|
||||
Shape { geometry PointSet { coord Coordinate { point [ 0 0 1, 1 0 1 ] } } } ] }
|
||||
DEF Clock TimeSensor { cycleInterval 4 loop TRUE }
|
||||
DEF Path PositionInterpolator { key [ 0 0.5 1 ] keyValue [ 0 0 0, 0 2 0, 0 0 0 ] }
|
||||
DEF Turn OrientationInterpolator { key [ 0 1 ] keyValue [ 0 1 0 0, 0 1 0 3.14 ] }
|
||||
ROUTE Clock.fraction_changed TO Path.set_fraction
|
||||
ROUTE Clock.fraction_changed TO Turn.set_fraction
|
||||
ROUTE Path.value_changed TO Mover.set_translation
|
||||
ROUTE Turn.value_changed TO Mover.set_rotation
|
||||
Shape { appearance Appearance { texture PixelTexture { image 2 2 3 0xFF0000 0x00FF00 0x0000FF 0xFFFFFF } } geometry Box { } }
|
||||
Inline { url [ "part.wrl" ] }
|
||||
""",
|
||||
}
|
||||
# the Inline target of feat_scene.wrl
|
||||
INLINE = {"part.wrl": "#VRML V2.0 utf8\nTransform { translation 0 -3 0 children Shape { geometry Box { size 4 0.2 4 } } }\n"}
|
||||
@@ -0,0 +1,99 @@
|
||||
# VRML97 fixtures (tools/fixtures.py): assimp's WRL test models (test/models/WRL, read from the nixpkgs assimp source,
|
||||
# never committed; assimp itself is built without its VRML reader), scenes and glTF sample models written by VTK's
|
||||
# vtkVRMLExporter, and the hand-written feature files of tools/fixtures/_vrml_ref.py, with VTK's vtkVRMLImporter as
|
||||
# the reference (polygons, lines, world bounds). Then our encoder's output (tools/fixtures/_vrml_encode.luau) read back
|
||||
# by VTK.
|
||||
# tests/gen/vrml_cases.luau { name, data, files = { name -> bytes }, vtk, primitives (bool: tessellated shapes) }
|
||||
# tests/gen/vrml_gltf.luau glTF sample models for the writer round trips: { name, data, files }
|
||||
# tests/gen/vrml_xcheck.luau { name, case?, gltf?, vtk }
|
||||
import importlib.util, os, re
|
||||
|
||||
INPUTS = ["src/Formats/codecs/model/Vrml", "src/Formats/model/vrml", "tests/fixtures/gltf", "tools/fixtures/_vrml_ref.py",
|
||||
"tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py", "tools/fixtures/_vrml_encode.luau"]
|
||||
|
||||
GLTF = ["Box", "BoxTextured", "BoxVertexColors", "Cameras", "MeshPrimitiveModes", "SimpleMeshes", "AnimatedTriangle", "InterpolationTest",
|
||||
"NegativeScaleTest", "TextureCoordinateTest", "MultiUVTest"]
|
||||
|
||||
|
||||
def load(ctx, name):
|
||||
spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
def primitives(data):
|
||||
return bool(re.search(rb"\b(Box|Sphere|Cone|Cylinder|Extrusion|ElevationGrid|Text)\s*\{|<(Box|Sphere|Cone|Cylinder|Extrusion|ElevationGrid|Text)\b", data))
|
||||
|
||||
|
||||
def gltf_picks(ctx):
|
||||
gl = os.path.join(ctx.root, "tests", "fixtures", "gltf")
|
||||
picks = []
|
||||
for model in GLTF:
|
||||
d0 = os.path.join(gl, model)
|
||||
if not os.path.isdir(d0):
|
||||
continue
|
||||
for variant in ("glTF", "glTF-Embedded", "glTF-Binary"):
|
||||
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, "path": os.path.join(d, mains[0]), "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
|
||||
return picks
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
M = load(ctx, "_model_ref")
|
||||
Fbx = load(ctx, "fbx")
|
||||
R = load(ctx, "_vrml_ref")
|
||||
tmp = M.tempdir()
|
||||
cases = []
|
||||
src = os.path.join(Fbx.assimp_src(ctx), "test", "models", "WRL")
|
||||
for f in sorted(os.listdir(src)):
|
||||
if f.lower().endswith(".wrl"):
|
||||
files = {}
|
||||
if f == "HelloWorld.wrl":
|
||||
files["earth-topo.png"] = open(os.path.join(src, "earth-topo.png"), "rb").read()
|
||||
cases.append({"name": "assimp/" + f, "path": os.path.join(src, f), "files": files})
|
||||
picks = gltf_picks(ctx)
|
||||
for name in R.vtk_export(ctx, tmp, [p["path"] for p in picks if p["path"].endswith((".gltf", ".glb"))]):
|
||||
cases.append({"name": "vtk/" + name + ".wrl", "path": os.path.join(tmp, name + ".wrl"), "files": {}})
|
||||
for name, text in sorted(R.FEATURES.items()):
|
||||
p = os.path.join(tmp, name)
|
||||
with open(p, "w") as f:
|
||||
f.write(text)
|
||||
cases.append({"name": "feature/" + name, "path": p, "files": dict(R.INLINE)})
|
||||
for name, text in R.INLINE.items():
|
||||
with open(os.path.join(tmp, name), "w") as f:
|
||||
f.write(text)
|
||||
refs = R.vtk_read(ctx, [c["path"] for c in cases])
|
||||
for c, v in zip(cases, refs):
|
||||
c["data"] = open(c["path"], "rb").read()
|
||||
c["vtk"] = v
|
||||
c["primitives"] = primitives(c["data"])
|
||||
c["vtkTransforms"] = R.vtk_xform_ok(c["data"])
|
||||
del c["path"]
|
||||
ctx.emit("vrml_cases", cases)
|
||||
for p in picks:
|
||||
del p["path"]
|
||||
ctx.emit("vrml_gltf", picks)
|
||||
|
||||
# VTK reads our output
|
||||
ours = M.luau_encode(ctx, "tools/fixtures/_vrml_encode.luau")
|
||||
xtmp = M.tempdir()
|
||||
names = sorted(n for n in ours if n.endswith(".wrl"))
|
||||
for name, data in ours.items():
|
||||
with open(os.path.join(xtmp, name), "wb") as f:
|
||||
f.write(data)
|
||||
refs = R.vtk_read(ctx, [os.path.join(xtmp, n) for n in names])
|
||||
out = []
|
||||
for n, v in zip(names, refs):
|
||||
e = {"name": n, "vtk": v, "vtkTransforms": R.vtk_xform_ok(ours[n])}
|
||||
m = re.match(r"(case|gltf)_(\d+)\.wrl$", n)
|
||||
if m:
|
||||
e[m.group(1)] = int(m.group(2))
|
||||
out.append(e)
|
||||
ctx.emit("vrml_xcheck", out)
|
||||
@@ -0,0 +1,135 @@
|
||||
# X3D fixtures (tools/fixtures.py): assimp's X3D / X3DV / X3DB test models (test/models/X3D*, read from the nixpkgs
|
||||
# assimp source, never committed), scenes and glTF sample models written by VTK's vtkX3DExporter, glTF sample models
|
||||
# written by assimp's X3D exporter, and hand-written feature files (below), with assimp's X3D reader as the reference
|
||||
# (`assimp info -r`: meshes, faces, materials; world bounds from its PreTransformVertices export). Then our encoder's
|
||||
# X3D output (tools/fixtures/_vrml_encode.luau) read back by assimp.
|
||||
# tests/gen/x3d_cases.luau { name, data, files = { name -> bytes }, assimp, primitives (bool) }
|
||||
# tests/gen/x3d_xcheck.luau { name, case? / gltf? / wcase?, assimp }
|
||||
import importlib.util, os, re, subprocess
|
||||
|
||||
INPUTS = ["src/Formats/codecs/model/Vrml", "src/Formats/model/x3d", "src/Formats/model/vrml", "tests/fixtures/gltf",
|
||||
"tools/fixtures/_vrml_ref.py", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py", "tools/fixtures/vrml.py",
|
||||
"tools/fixtures/_vrml_encode.luau"]
|
||||
|
||||
FEATURES = {
|
||||
"feat_sets.x3d": """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<X3D profile="Interchange" version="3.3"><Scene>
|
||||
<Transform translation="0 0 0"><Shape><Appearance><Material diffuseColor="1 0 0"/></Appearance>
|
||||
<IndexedTriangleSet index="0 1 2 0 2 3" solid="false"><Coordinate point="0 0 0 1 0 0 1 1 0 0 1 0"/>
|
||||
<ColorRGBA color="1 0 0 1 0 1 0 1 0 0 1 0.5 1 1 1 1"/></IndexedTriangleSet></Shape></Transform>
|
||||
<Transform translation="2 0 0"><Shape><TriangleFanSet fanCount="5"><Coordinate point="0 0 0 1 0 0 1 1 0 0 1 0 -1 1 0"/></TriangleFanSet></Shape></Transform>
|
||||
<Transform translation="4 0 0"><Shape><IndexedTriangleStripSet index="0 1 2 3 -1 4 5 6"><Coordinate point="0 0 0 1 0 0 0 1 0 1 1 0 0 2 0 1 2 0 0 3 0"/></IndexedTriangleStripSet></Shape></Transform>
|
||||
<Transform translation="6 0 0"><Shape><IndexedQuadSet index="0 1 2 3"><Coordinate point="0 0 0 1 0 0 1 1 0 0 1 0"/></IndexedQuadSet></Shape></Transform>
|
||||
<Transform translation="8 0 0"><Shape><TriangleSet><Coordinate point="0 0 0 1 0 0 0 1 0 0 0 1 1 0 1 0 1 1"/></TriangleSet></Shape></Transform>
|
||||
<Transform translation="0 3 0"><Shape><LineSet vertexCount="3 2"><Coordinate point="0 0 0 1 0 0 1 1 0 2 2 2 3 3 3"/></LineSet></Shape></Transform>
|
||||
</Scene></X3D>
|
||||
""",
|
||||
"feat_proto.x3d": """<?xml version="1.0" encoding="UTF-8"?>
|
||||
<X3D profile="Immersive" version="3.3"><head><meta name="title" content="protos"/><unit category="length" name="centimetre" conversionFactor="0.01"/></head>
|
||||
<Scene>
|
||||
<ProtoDeclare name="Post"><ProtoInterface>
|
||||
<field name="height" type="SFFloat" accessType="initializeOnly" value="2"/>
|
||||
<field name="where" type="SFVec3f" accessType="inputOutput" value="0 0 0"/>
|
||||
<field name="look" type="SFNode" accessType="inputOutput"><Appearance><Material diffuseColor="0 0 1"/></Appearance></field>
|
||||
</ProtoInterface>
|
||||
<ProtoBody><Transform><IS><connect nodeField="translation" protoField="where"/></IS>
|
||||
<Shape><IS><connect nodeField="appearance" protoField="look"/></IS>
|
||||
<Cylinder radius="0.1"><IS><connect nodeField="height" protoField="height"/></IS></Cylinder></Shape></Transform></ProtoBody>
|
||||
</ProtoDeclare>
|
||||
<ProtoInstance name="Post" DEF="P1"><fieldValue name="where" value="1 0 0"/></ProtoInstance>
|
||||
<ProtoInstance name="Post"><fieldValue name="where" value="-1 0 0"/><fieldValue name="height" value="4"/></ProtoInstance>
|
||||
<Transform DEF="Spin"><Shape><Appearance><PhysicalMaterial baseColor="0.5 0.5 0.5" metallic="0.25" roughness="0.75"/></Appearance>
|
||||
<Box size="1 1 1"/></Shape></Transform>
|
||||
<TimeSensor DEF="Clock" cycleInterval="2" loop="true"/>
|
||||
<OrientationInterpolator DEF="Rot" key="0 0.5 1" keyValue="0 1 0 0 0 1 0 3.14159 0 1 0 6.28318"/>
|
||||
<ROUTE fromNode="Clock" fromField="fraction_changed" toNode="Rot" toField="set_fraction"/>
|
||||
<ROUTE fromNode="Rot" fromField="value_changed" toNode="Spin" toField="set_rotation"/>
|
||||
<OrthoViewpoint fieldOfView="-2 -1 2 1" position="0 0 5"/>
|
||||
<Shape><Appearance><UnlitMaterial emissiveColor="0 1 0"/></Appearance><PointSet><Coordinate point="0 5 0 1 5 0"/><Color color="1 0 0 0 1 0"/></PointSet></Shape>
|
||||
</Scene></X3D>
|
||||
""",
|
||||
"feat_classic.x3dv": """#X3D V3.3 utf8
|
||||
PROFILE Interchange
|
||||
COMPONENT Geometry2D:1
|
||||
META "title" "classic"
|
||||
UNIT length millimetre 0.001
|
||||
DEF Root Transform { translation 1 2 3 children [
|
||||
Shape { appearance Appearance { material Material { diffuseColor 0 1 0 } }
|
||||
geometry IndexedFaceSet { coord Coordinate { point [ 0 0 0 1 0 0 1 1 0 0 1 0 ] } coordIndex [ 0 1 2 3 -1 ]
|
||||
color ColorRGBA { color [ 1 0 0 1, 0 1 0 1, 0 0 1 1, 1 1 1 0.5 ] } } }
|
||||
Shape { geometry IndexedTriangleSet { index [ 0 1 2 ] coord Coordinate { point [ 0 0 1 1 0 1 0 1 1 ] } } }
|
||||
] }
|
||||
""",
|
||||
}
|
||||
|
||||
|
||||
def load(ctx, name):
|
||||
spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
def reference(ctx, M, Fbx, path, tmp):
|
||||
a = M.assimp_info(ctx, [path], raw=True)[0]
|
||||
if not a.get("failed"):
|
||||
a.pop("min", None)
|
||||
a.pop("max", None)
|
||||
a.update(Fbx.assimp_extra(ctx, path))
|
||||
a.update(Fbx.ptv_bounds(ctx, path, tmp))
|
||||
return a
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
M = load(ctx, "_model_ref")
|
||||
Fbx = load(ctx, "fbx")
|
||||
R = load(ctx, "_vrml_ref")
|
||||
V = load(ctx, "vrml")
|
||||
tmp = M.tempdir()
|
||||
cases = []
|
||||
root = os.path.join(Fbx.assimp_src(ctx), "test", "models")
|
||||
for sub in ("X3D", "X3DV", "X3DB"):
|
||||
d = os.path.join(root, sub)
|
||||
for f in sorted(os.listdir(d)):
|
||||
if f.lower().endswith((".x3d", ".x3dv", ".x3db")):
|
||||
files = {}
|
||||
if f.startswith("HelloWorld"):
|
||||
files["earth-topo.png"] = open(os.path.join(d, "earth-topo.png"), "rb").read()
|
||||
cases.append({"name": "assimp/%s/%s" % (sub, f), "path": os.path.join(d, f), "files": files})
|
||||
picks = V.gltf_picks(ctx)
|
||||
for name in R.vtk_export(ctx, tmp, [p["path"] for p in picks]):
|
||||
cases.append({"name": "vtk/" + name + ".x3d", "path": os.path.join(tmp, name + ".x3d"), "files": {}})
|
||||
for p in picks:
|
||||
out = os.path.join(tmp, "assimp_" + p["name"].split("/")[0] + ".x3d")
|
||||
try:
|
||||
ctx.nix("assimp", ["assimp", "export", p["path"], out, "-fx3d"])
|
||||
except subprocess.CalledProcessError:
|
||||
continue
|
||||
cases.append({"name": "assimp-export/" + os.path.basename(out), "path": out, "files": dict(p["files"])})
|
||||
for name, text in sorted(FEATURES.items()):
|
||||
path = os.path.join(tmp, name)
|
||||
with open(path, "w") as f:
|
||||
f.write(text)
|
||||
cases.append({"name": "feature/" + name, "path": path, "files": {}})
|
||||
for c in cases:
|
||||
c["data"] = open(c["path"], "rb").read()
|
||||
c["primitives"] = V.primitives(c["data"])
|
||||
c["assimp"] = reference(ctx, M, Fbx, c["path"], tmp) if c["path"].endswith(".x3d") else {"skip": True}
|
||||
del c["path"]
|
||||
ctx.emit("x3d_cases", cases)
|
||||
|
||||
# assimp reads our X3D output
|
||||
ours = M.luau_encode(ctx, "tools/fixtures/_vrml_encode.luau")
|
||||
xtmp = M.tempdir()
|
||||
out = []
|
||||
for name in sorted(n for n in ours if n.endswith(".x3d")):
|
||||
path = os.path.join(xtmp, name)
|
||||
with open(path, "wb") as f:
|
||||
# assimp 6 cannot read quoted MFString urls (url='"a.png"', which the X3D encoding requires)
|
||||
f.write(re.sub(rb'url=""([^&"]*)""', rb'url="\1"', ours[name]))
|
||||
e = {"name": name, "assimp": reference(ctx, M, Fbx, path, xtmp)}
|
||||
m = re.match(r"(xcase|xgltf|wcase)_(\d+)\.x3d$", name)
|
||||
if m:
|
||||
e[m.group(1)] = int(m.group(2))
|
||||
out.append(e)
|
||||
ctx.emit("x3d_xcheck", out)
|
||||
Reference in new issue
Block a user