3D modeling in Python, built for LLMs.
fix: a GLB holds only the root's tree, placed in metres (#11)
Alaa Ben Fatma3ef2b86bda79
diff --git a/src/sand3d/assembly.py b/src/sand3d/assembly.pyindex 553af5f..96cef96 100644--- a/src/sand3d/assembly.py+++ b/src/sand3d/assembly.py@@ -96,32 +96,27 @@ def export(root, path):returnlent = _lend_meshes()try:- if urdf.articulated(root):- coll = bpy.data.collections.new("s3d~export")- bpy.context.scene.collection.children.link(coll)- try:- state = urdf.glb_tree(root, coll)- except BaseException:- bpy.data.collections.remove(coll)- raise- dressed = materials.dressed() # asked before the tags come off: it reads them- tags = {m: m.pop(materials.TAG) for m in bpy.data.materials if materials.TAG in m} # extras: joints only- try:- bpy.ops.export_scene.gltf(filepath=str(path), export_format="GLB", collection=coll.name,- export_extras=True,- export_materials="EXPORT" if dressed else "NONE")- finally:- for m, tag in tags.items():- m[materials.TAG] = tag- urdf.undo(state, coll)- return- scale = tuple(root.scale)- root.scale = (_core.MM / 1000,) * 3+ name = root.name # the GLB's scene: the exporter names it after coll+ coll = bpy.data.collections.new("s3d~export") # the exporter writes this, not the whole scene+ bpy.context.scene.collection.children.link(coll)+ state = urdf.glb_tree(root, coll)+ dressed = materials.dressed() # asked before the tags come off: it reads them+ tags = {m: m.pop(materials.TAG) for m in bpy.data.materials if materials.TAG in m} # extras: joints only+ clash = bpy.data.collections.get(name) # a collection of the program's, lent its name meanwhiletry:- bpy.ops.export_scene.gltf(filepath=str(path), export_format="GLB",- export_materials="EXPORT" if materials.dressed() else "NONE")+ if clash is not None:+ clash.name = "s3d~export~lent"+ coll.name = name+ bpy.ops.export_scene.gltf(filepath=str(path), export_format="GLB", collection=coll.name,+ export_extras=True,+ export_materials="EXPORT" if dressed else "NONE")finally:- root.scale = scale # the program's model stays in its unit+ coll.name = "s3d~export"+ if clash is not None:+ clash.name = name+ for m, tag in tags.items():+ m[materials.TAG] = tag+ urdf.undo(state, coll)finally:_return_meshes(lent)diff --git a/src/sand3d/urdf.py b/src/sand3d/urdf.pyindex 049b177..b4d99c0 100644--- a/src/sand3d/urdf.py+++ b/src/sand3d/urdf.py@@ -377,26 +377,27 @@ def write_urdf(root, path):# ---------------------------------------------------------------- GLB, nested by the joints-def articulated(root):- """Whether `export(root, …)` writes something with joints."""- if not J.everything():- return False- return bool(Mechanism(root).bodies)--def glb_tree(root, coll):"""Temporary objects in `coll` that the glTF exporter writes for `root`: its parts attheir current pose, nested by the joints, a node per joint carrying it in its extras.The program's objects are renamed meanwhile, so the nodes keep their names; returns- what `undo` needs."""- mech = Mechanism(root)- mech.check()- k = mech.k+ what `undo` needs; on an error, undoes what it did before raising it."""renamed = []- for i, ob in enumerate(mech.members):- renamed.append((ob, ob.name))- for i, (ob, _) in enumerate(renamed):- ob.name = f"s3d~export~{i}"+ try:+ mech = Mechanism(root)+ mech.check()+ renamed += [(ob, ob.name) for ob in mech.members]+ for i, (ob, _) in enumerate(renamed):+ ob.name = f"s3d~export~{i}"+ _twins(mech, renamed, coll)+ except BaseException:+ undo((renamed, list(coll.objects)), coll)+ raise+ return renamed, list(coll.objects)+++def _twins(mech, renamed, coll):+ root, k = mech.root, mech.kmade = {}for ob, name in renamed:twin = bpy.data.objects.new(name, ob.data if ob.type == "MESH" else None)@@ -410,8 +411,7 @@ def glb_tree(root, coll):twin.matrix_basis = parent_world.inverted() @ own_world if parent_twin is not None else own_worldtop = made[root.as_pointer()]- top.matrix_basis = world[root.as_pointer()]- top.scale = (_metres(),) * 3+ top.matrix_basis = Matrix.Scale(_metres(), 4) @ world[root.as_pointer()] # the whole placement: offset, mirrorjointed = {c.as_pointer() for c in mech.bodies}for ob, _ in renamed:if ob is root:@@ -445,7 +445,6 @@ def glb_tree(root, coll):hang(twin, made[ob.parent.as_pointer()], world[ob.parent.as_pointer()], world[ob.as_pointer()])else:hang(twin, top, world[root.as_pointer()], world[ob.as_pointer()])- return renamed, list(coll.objects)def undo(state, coll):diff --git a/tests/golden/bpy-5.2.json b/tests/golden/bpy-5.2.jsonindex c9aab9b..c798fa0 100644--- a/tests/golden/bpy-5.2.json+++ b/tests/golden/bpy-5.2.json@@ -34,8 +34,8 @@"case:mechanism_posed": "387657250adb99c1","case:parts_seated": "37ef3a756eb8cfe1","case:assembly_layer": "8af7a0b9e624e741",- "case:export_glb": "c91b293f534c1519",- "case:export_articulated": "399a6ddc0bd4d9e2",+ "case:export_glb": "b86f969688b56f5a",+ "case:export_articulated": "0070ebad2b7f4ce5","case:export_usd": "ce602d8180c1f8a8","case:export_meshes": "49d47323e897e4ac","case:materials": "4c37230ee2cc72ee",diff --git a/tests/test_export_joints.py b/tests/test_export_joints.pyindex 9fdb111..3073da4 100644--- a/tests/test_export_joints.py+++ b/tests/test_export_joints.py@@ -7,6 +7,7 @@ import osimport structimport tempfileimport unittest+from unittest import mockimport xml.etree.ElementTree as ETfrom pathlib import Path@@ -367,6 +368,70 @@ class Glb(unittest.TestCase):self.assertEqual(sorted(n["name"] for n in nodes), ["b", "thing"])self.assertTrue(all("extras" not in n for n in nodes))+ def test_a_glb_holds_its_root_and_nothing_else(self):+ """Without joints the whole scene went out, every other object in the program's unit+ read as metres: a table built beside a chair came out 1000 times too large in the+ chair's GLB."""+ s3d.empty_scene()+ chair = s3d.group("chair", s3d.box("seat", 400, 400, 20))+ s3d.at(s3d.group("table", s3d.box("top", 1200, 800, 30)), x=1000)+ s3d.export(chair, self.path)+ self.assertEqual(sorted(n["name"] for n in glb_json(self.path)["nodes"]), ["chair", "seat"])++ def test_the_glb_scene_is_named_after_its_root(self):+ """A viewer shows the scene's name: the root's, not the exporter's temporary collection,+ and a collection of the program's that bears it keeps it."""+ s3d.empty_scene()+ chair = s3d.group("chair", s3d.box("seat", 400, 400, 20))+ own = bpy.data.collections.new("chair")+ bpy.context.scene.collection.children.link(own)+ s3d.export(chair, self.path)+ self.assertEqual([s["name"] for s in glb_json(self.path)["scenes"]], ["chair"])+ self.assertEqual([c.name for c in bpy.data.collections], ["chair"])+ self.assertIs(bpy.data.collections["chair"], own)++ def test_a_placed_or_mirrored_root_is_where_the_scene_has_it(self):+ """The root's scale was overwritten with the metre factor: its offset stayed in+ millimetres, 1000 times too far, and a mirror image came out turned instead."""+ to_gltf = Matrix(((1, 0, 0, 0), (0, 0, 1, 0), (0, -1, 0, 0), (0, 0, 0, 1))) # Z up to Y up+ metres = Matrix.Scale(0.001, 4)++ def local(n):+ t, q, s = n.get("translation", [0] * 3), n.get("rotation", [0, 0, 0, 1]), n.get("scale", [1] * 3)+ return Matrix.LocRotScale(Vector(t), Quaternion((q[3], q[0], q[1], q[2])), Vector(s))++ s3d.at(self.root, x=1000, rz=90)+ plain = s3d.transform(s3d.group("set", s3d.at(s3d.box("leg", 10, 20, 30), x=50, y=30)), x=1000, rz=30,+ mirror="x")+ arm = s3d.at(s3d.group("arm", s3d.box("rod", 10, 10, 200)), x=300, z=500)+ s3d.at(s3d.group("robot", arm), x=-2000, rz=45) # a sub-assembly, exported on its own+ for root in (self.root, plain, arm):+ before = _core.world(root)+ s3d.export(root, self.path)+ self.assertEqual(_core.world(root), before, "the model stays where it was")+ nodes = glb_json(self.path)["nodes"]+ parent = {c: i for i, n in enumerate(nodes) for c in n.get("children", [])}+ for i, n in enumerate(nodes):+ if "mesh" not in n:+ continue+ got, k = Matrix.Identity(4), i+ while k is not None:+ got, k = local(nodes[k]) @ got, parent.get(k)+ want = to_gltf @ metres @ _core.world(bpy.data.objects[n["name"]]) @ to_gltf.inverted()+ for a, b in zip(got, want):+ for x, y in zip(a, b):+ self.assertAlmostEqual(x, y, places=5, msg=(root.name, n["name"]))++ def test_an_export_that_fails_leaves_the_scene_as_it_was(self):+ """The program's objects are renamed while the GLB is written: an error midway left+ them renamed, beside the exporter's temporary objects."""+ before = sorted(o.name for o in bpy.data.objects)+ with mock.patch("sand3d.urdf._metres", side_effect=RuntimeError("midway")):+ with self.assertRaisesRegex(RuntimeError, "midway"):+ s3d.export(self.root, self.path)+ self.assertEqual(sorted(o.name for o in bpy.data.objects), before)+ self.assertEqual([c.name for c in bpy.data.collections], [])+if __name__ == "__main__":unittest.main()