# 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 rosetta" ] } 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"}