diff --git a/surfaces/blender/brokkr_rig/__init__.py b/surfaces/blender/brokkr_rig/__init__.py new file mode 100644 index 0000000..1302b3d --- /dev/null +++ b/surfaces/blender/brokkr_rig/__init__.py @@ -0,0 +1,519 @@ +"""Rig a fused generated mesh for the spring-bone runtime: body bones and weights, tendril chains grown from the +mesh's own thickness, body colliders, and VRMC_springBone written by Blender's own glTF exporter. + +A host add-on for Brokkr beside brokkr_mesh_polish (it imports that package's operator base and arithmetic, and +nothing from Brokkr): brokkr_actions.json beside this file lists the operators agents may run (docs/rig.md). +The arithmetic is core.py (numpy, tested without Blender); this file is the bpy around it. Every operator writes +a JSON report to WindowManager.brokkr_mesh_polish_result, as the polish operators do. + +The rig lives in the scene as bones, vertex groups and bone ID properties. glTF2ExportUserExtension below reads +those properties when anything exports (Brokkr's exportGltf or File > Export) and writes VRMC_springBone into +the GLB; whether the result is acceptable is the runtime's own parse (SpringRigData.FromGlbJson), which this +add-on does not copy. +""" +bl_info = {"name": "Brokkr Rig", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0), + "category": "Rigging", "description": "Rig generated creatures for spring-bone tendrils; agent-callable through Brokkr."} + +import json +from types import SimpleNamespace + +import bpy +import numpy as np +from mathutils import Matrix, Vector +from mathutils.bvhtree import BVHTree + +try: + from brokkr_mesh_polish import RESULT, PolishOperator, Refused, arrays, mesh_object + from brokkr_mesh_polish import core as polish + MISSING = None +except ImportError as error: # register() says so; the classes below only need something to subclass + RESULT, PolishOperator, Refused, polish, MISSING = "brokkr_mesh_polish_result", bpy.types.Operator, RuntimeError, None, error + +from . import core + +CHAIN, INDEX, STIFFNESS, DRAG, GRAVITY, HIT, COLLIDERS = ("rig_chain", "rig_index", "rig_stiffness", "rig_drag", "rig_gravity", + "rig_hit_radius", "rig_colliders") +GRAVITY_DOWN = (0.0, 0.0, -1.0) # Blender world; the exporter hook turns it into glTF world + + +# --- the scene around the arithmetic --------------------------------------------------------------------- + +def armature_of(obj, name: str): + if name: + arm = bpy.data.objects.get(name) + if arm is None or arm.type != "ARMATURE": + raise Refused(f"No armature object named {name!r}.") + return arm + for modifier in obj.modifiers: + if modifier.type == "ARMATURE" and modifier.object is not None: + return modifier.object + raise Refused(f"Object {obj.name!r} has no Armature modifier: run brokkr_rig.body first or give armature_name.") + + +def welded(obj) -> SimpleNamespace: + """The mesh as the rig sees it: world positions and triangles welded over UV seams (ids maps each mesh vertex to its + welded vertex), the welded edge graph and per-vertex normals.""" + data = arrays(obj) + V, T = data["V"], data["T"] + diagonal = float(np.linalg.norm(V.max(axis=0) - V.min(axis=0))) + ids, TW = polish.weld(V, T, diagonal * 1e-5) + count = int(ids.max()) + 1 + Vw, N = np.zeros((count, 3)), np.zeros((count, 3)) + Vw[ids] = V + np.add.at(N, ids, data["N"]) + N /= np.maximum(np.linalg.norm(N, axis=1, keepdims=True), 1e-30) + return SimpleNamespace(V=V, ids=ids, Vw=Vw, TW=TW, N=N, E=core.welded_edges(TW), count=count, + diagonal=diagonal, length=float((V.max(axis=0) - V.min(axis=0)).max())) + + +class edit_mode: + """Edit Mode on an armature object for the length of the block; yields its edit bones.""" + + def __init__(self, context, arm): + self.context, self.arm = context, arm + + def __enter__(self): + self.context.view_layer.objects.active = self.arm + bpy.ops.object.mode_set(mode="EDIT") + return self.arm.data.edit_bones + + def __exit__(self, *_): + bpy.ops.object.mode_set(mode="OBJECT") + + +def spine_of(arm) -> list: + """The spine of an armature as the runtime finds it: from the first root, the child with the most descendants at + each step. Bones that belong to tendril chains are not part of the body.""" + bones = [b for b in arm.data.bones if CHAIN not in b] + kids = {b.name: [c for c in b.children if CHAIN not in c] for b in bones} + weight = {} + + def count(bone): + weight[bone.name] = 1 + sum(count(c) for c in kids[bone.name]) + return weight[bone.name] + + roots = [b for b in bones if b.parent is None or CHAIN in b.parent] + if not roots: + raise Refused(f"Armature {arm.name!r} has no body bones.") + for root in roots: + count(root) + spine, bone = [], roots[0] + while bone is not None: + spine.append(bone) + bone = max(kids[bone.name], key=lambda c: weight[c.name], default=None) + return spine + + +def write_weights(obj, names: list, ids: np.ndarray, idx: np.ndarray, w: np.ndarray): + """Replace the mesh's vertex groups with one per bone name; idx indexes names, (idx, w) per welded vertex.""" + obj.vertex_groups.clear() + groups = [obj.vertex_groups.new(name=name) for name in names] + wi, ww = idx[ids].tolist(), w[ids].tolist() + for vertex in range(len(ids)): + for b, weight in zip(wi[vertex], ww[vertex]): + if weight > 0: + groups[b].add([vertex], weight, "REPLACE") + + +def read_weights(obj, names: list, ids: np.ndarray, count: int) -> np.ndarray: + """Dense weights (welded vertices, names) of the mesh's vertex groups called names.""" + column = {obj.vertex_groups[n].index: i for i, n in enumerate(names) if n in obj.vertex_groups} + out = np.zeros((len(obj.data.vertices), len(names))) + for vertex in obj.data.vertices: + for entry in vertex.groups: + if entry.group in column: + out[vertex.index, column[entry.group]] = entry.weight + dense = np.zeros((count, len(names))) + dense[ids] = out + return dense + + +def shape_diameter(w: SimpleNamespace) -> np.ndarray: + """Per welded vertex, the median of five rays going inward (one along the reversed normal, four jittered inside a + cone, fixed seed) to the far side of the surface; a vertex whose rays find no back face (an open sheet) reads 0.""" + live = (w.TW[:, 0] != w.TW[:, 1]) & (w.TW[:, 1] != w.TW[:, 2]) & (w.TW[:, 0] != w.TW[:, 2]) + tree = BVHTree.FromPolygons([tuple(p) for p in w.Vw], [tuple(int(i) for i in t) for t in w.TW[live]]) + jitter = np.random.default_rng(0).normal(0.0, 0.35, (w.count, 4, 3)) + reach, lift = 0.5 * w.length, 1e-5 * w.length + out = np.zeros(w.count) + for i in range(w.count): + inward = -w.N[i] + hits = [] + for k in range(5): + way = inward if k == 0 else inward + jitter[i, k - 1] + way = way / max(float(np.linalg.norm(way)), 1e-30) + if way @ inward < 0.5: + continue + hit = tree.ray_cast(Vector(w.Vw[i] + way * lift), Vector(way), reach) + if hit[0] is not None: + hits.append(hit[3]) + out[i] = np.median(hits) if hits else 0.0 + return out + + +def rounded(values) -> list: + return [round(float(x), 6) for x in values] + + +# --- operators ------------------------------------------------------------------------------------------- + +class BROKKR_RIG_OT_body(PolishOperator): + """Give a mesh its body skeleton and weights: a spine along the long axis (root at the head end) and a bone + for each named seed region, or the weights alone against an armature that is already authored""" + bl_idname = "brokkr_rig.body" + bl_label = "Rig Body" + object_name: bpy.props.StringProperty(name="Object") + armature_name: bpy.props.StringProperty(name="Armature", description="An authored armature to weight against; empty makes .rig") + spine_bones: bpy.props.IntProperty(name="Spine Bones", default=8, min=2, max=32, description="Bones along the long axis of a new armature") + head: bpy.props.EnumProperty(name="Head", items=[("+y", "+Y", "The head is at the +Y end"), ("-y", "-Y", "The head is at the -Y end")], + default="+y", description="Which end of the long axis is the head: the spine's root, where the swim wave starts") + seeds: bpy.props.StringProperty(name="Seeds", maxlen=4000, + description="name=x,y,z; name=x,y,z ... world-space surface points: each name is a part with its own bone (a jaw, a fin); the spine takes the rest") + crease_cost: bpy.props.FloatProperty(name="Crease Cost", default=40.0, min=0.0, max=1000.0, + description="How strongly parts stop at concave creases; 0 splits by distance alone") + smooth_rounds: bpy.props.IntProperty(name="Smooth Rounds", default=3, min=0, max=64, description="Laplacian rounds over the weights") + + def work(self, context): + obj = mesh_object(self.object_name) + try: + seeds = polish.parse_seeds(self.seeds) if self.seeds.strip() else [] + except ValueError as error: + raise Refused(str(error)) from None + w = welded(obj) + _, frame = polish.principal_frame(w.Vw, w.TW) + axis = frame[0] / np.linalg.norm(frame[0]) + existing = bpy.data.objects.get(self.armature_name) if self.armature_name else None + if self.armature_name and (existing is None or existing.type != "ARMATURE"): + raise Refused(f"No armature object named {self.armature_name!r}.") + if existing is None: + if bpy.data.objects.get(f"{obj.name}.rig") is not None: + raise Refused(f"{obj.name}.rig exists: give armature_name={obj.name}.rig to weight against it.") + if (axis[1] < 0) == (self.head == "+y"): + axis = -axis + joints, u, length = core.spine_points(w.Vw, axis, self.spine_bones) + names = [f"spine_{i:02d}" for i in range(self.spine_bones)] + spine = [(joints[i], joints[i + 1]) for i in range(self.spine_bones)] + knots = np.arange(self.spine_bones) * (length / self.spine_bones) + others = [] # (name, head, tail) of bones the armature does not have yet; filled from the regions + wanted = [name for name, _ in seeds] + else: + matrix = np.array(existing.matrix_world) + body = spine_of(existing) + names = [b.name for b in body] + spine = [(matrix[:3, :3] @ np.array(b.head_local) + matrix[:3, 3], matrix[:3, :3] @ np.array(b.tail_local) + matrix[:3, 3]) for b in body] + if len(names) < 2: + raise Refused(f"Armature {existing.name!r} has a spine of {len(names)} bone: a spine needs 2 or more.") + if spine[0][0] @ axis < spine[-1][0] @ axis: + axis = -axis + top = w.Vw @ axis + u = top.max() - top + knots = top.max() - np.array([head @ axis for head, _ in spine]) + if np.any(np.diff(knots) <= 0): + raise Refused("The spine's bones do not run from the head end to the tail end of the mesh's long axis.") + others = [b for b in existing.data.bones if b.name not in names and CHAIN not in b] + known = {b.name for b in others} + for name, _ in seeds: + if name not in known: + raise Refused(f"Seed {name!r} names no bone of {existing.name!r} outside its spine.") + wanted = [b.name for b in others] + tails = {b.name: matrix[:3, :3] @ np.array(b.tail_local) + matrix[:3, 3] for b in others} + seeds = seeds + [(name, tail) for name, tail in tails.items()] + parts = ["spine"] + [n for n in dict.fromkeys(wanted) if n != "spine"] + pairs = polish.face_adjacency(w.TW) + centroid = w.Vw[w.TW].mean(axis=1) + nearest = lambda point: int(np.argmin(((centroid - np.asarray(point)) ** 2).sum(axis=1))) # noqa: E731 + placed = [(nearest(point), 0) for point in ([a for a, _ in spine] + [spine[-1][1]])] + placed += [(nearest(point), parts.index(name) if name in parts else 0) for name, point in seeds] + part, _ = polish.grow_parts(len(w.TW), pairs, polish.crease_costs(w.Vw, w.TW, pairs, self.crease_cost), placed) + part[part < 0] = 0 + areas = polish.triangle_areas(w.Vw, w.TW) + pa, pb, mids, lengths = core.cut_edges(w.Vw, w.TW, part) + region = [] + for p in range(1, len(parts)): + mine = part == p + if not mine.any(): + raise Refused(f"Part {parts[p]!r} came out empty: move its seed onto the surface.") + tail = (centroid[mine] * areas[mine][:, None]).sum(axis=0) / max(float(areas[mine].sum()), 1e-30) + cut = (pa == p) | (pb == p) + region.append((parts[p], polish.boundary_root(mids[cut], lengths[cut]), tail)) + if existing is None: + for name, head, tail in region: + if np.linalg.norm(tail - head) < 1e-4 * w.diagonal: + raise Refused(f"Part {name!r} has no length from its root to its centre: move its seed.") + # weights: spine bones along the axis, a region 1 on its bone, then the rounds + bones = names + [n for n in parts[1:]] + W = np.zeros((w.count, len(bones))) + W[:, :len(names)] = core.axial_weights(u, knots) + for p in range(1, len(parts)): + verts = np.unique(w.TW[part == p]) + W[verts] = 0.0 + W[verts, len(names) + p - 1] = 1.0 + idx, weight = core.top4(core.smooth(W, w.E, self.smooth_rounds)) + # the scene: bake the object's transform, make or keep the armature, skin + mesh = obj.data + mesh.transform(obj.matrix_world) + obj.parent = None + obj.matrix_world = Matrix.Identity(4) + collection = obj.users_collection[0] if obj.users_collection else context.scene.collection + if existing is None: + arm = bpy.data.objects.new(f"{obj.name}.rig", bpy.data.armatures.new(f"{obj.name}.rig")) + collection.objects.link(arm) + with edit_mode(context, arm) as edits: + for i, (head, tail) in enumerate(spine): + bone = edits.new(names[i]) + bone.head, bone.tail = Vector(head), Vector(tail) + bone.parent = edits[names[i - 1]] if i else None + for name, head, tail in region: + bone = edits.new(name) + bone.head, bone.tail = Vector(head), Vector(tail) + bone.parent = edits[names[int(np.argmin([core.segment_distance(head[None], a, b)[0] for a, b in spine]))]] + else: + arm = existing + write_weights(obj, bones, w.ids, idx, weight) + for modifier in [m for m in obj.modifiers if m.type == "ARMATURE"]: + obj.modifiers.remove(modifier) + obj.modifiers.new("Armature", "ARMATURE").object = arm + obj.parent = arm + obj.matrix_parent_inverse = arm.matrix_world.inverted() + return {"object": obj.name, "armature": arm.name, "created": existing is None, "spine": names, + "parts": [{"name": n, "root": rounded(h), "tail": rounded(t), "triangles": int((part == i + 1).sum())} + for i, (n, h, t) in enumerate(region)], + "head": rounded(spine[0][0]), "tail": rounded(spine[-1][1]), "axis": rounded(axis), + "vertices": int(len(mesh.vertices)), "weldedVertices": w.count} + + +class BROKKR_RIG_OT_tendrils(PolishOperator): + """Grow spring chains from the mesh's thin parts: skin each tendril to a chain of bones hung from the body and + mark the chains' stiffness, drag, gravity and hit radii for the exporter""" + bl_idname = "brokkr_rig.tendrils" + bl_label = "Rig Tendrils" + object_name: bpy.props.StringProperty(name="Object") + armature_name: bpy.props.StringProperty(name="Armature", description="Empty: the object's Armature modifier") + tau: bpy.props.FloatProperty(name="Tau", default=0.04, min=0.0, max=0.5, description="Shape diameter below which the surface is thin, as a share of the longest side") + band: bpy.props.FloatProperty(name="Band", default=0.04, min=0.0, max=0.5, description="Distance from the body one joint ring spans, as a share of the longest side") + dilate: bpy.props.FloatProperty(name="Dilate", default=0.04, min=0.0, max=0.5, description="How far the thick body is grown over its roots, as a share of the longest side") + fold_bands: bpy.props.FloatProperty(name="Fold Bands", default=1.5, min=0.0, max=10.0, description="A chain whose every vertex lies within this many bands of the body is a vein and folds into it") + min_joints: bpy.props.IntProperty(name="Min Joints", default=2, min=1, max=64, description="A chain with fewer rings than this folds into the body") + blend: bpy.props.FloatProperty(name="Blend", default=0.5, min=0.0, max=4.0, description="Bands over which weights blend between neighbouring bones and into the body") + stiffness: bpy.props.FloatProperty(name="Stiffness", default=3.0, min=0.0, max=1000.0, description="Rate (1 per second) a joint closes on its rest pose, at the root") + stiffness_tip_ratio: bpy.props.FloatProperty(name="Tip Ratio", default=0.5, min=0.0, max=10.0, description="Stiffness at the tip as a multiple of the root's") + drag: bpy.props.FloatProperty(name="Drag", default=0.3, min=0.0, max=1.0, description="Share of velocity a joint loses per substep") + gravity_power: bpy.props.FloatProperty(name="Gravity", default=0.0, min=0.0, max=100.0, description="Displacement per second along the world's down, in scene units") + hit_scale: bpy.props.FloatProperty(name="Hit Scale", default=1.0, min=0.0, max=10.0, description="Joint hit radius as a multiple of half the ring's median shape diameter") + + def work(self, context): + obj = mesh_object(self.object_name) + arm = armature_of(obj, self.armature_name) + w = welded(obj) + body_bones = [b for b in arm.data.bones if CHAIN not in b] + if not body_bones: + raise Refused(f"Armature {arm.name!r} has no body bones.") + body_names = [b.name for b in body_bones] + Wb = read_weights(obj, body_names, w.ids, w.count) + known = Wb.sum(axis=1) > 0 # a vertex a past run skinned to a chain has none: it takes the nearest one's + if not known.any(): + raise Refused("No vertex has weight on a body bone: run brokkr_rig.body first.") + if not known.all(): + near = core.dijkstra(core.graph(w.Vw, w.E), np.flatnonzero(known))[2] + Wb = Wb[np.where(known, np.arange(w.count), np.where(near >= 0, near, 0))] + bidx, bw = core.top4(Wb) + scale, band = w.length, self.band * w.length + sd = shape_diameter(w) + try: + found = core.extract(w.Vw, w.E, sd, self.tau * scale, band, self.dilate * scale, self.fold_bands, self.min_joints) + except ValueError as error: + raise Refused(str(error)) from None + springs = core.plan(w.Vw, sd, found, band) + for spring in springs: + spring.bone = body_names[int(np.argmax(Wb[spring.anchor].sum(axis=0)))] + idx, weight, start = core.tendril_weights(w.Vw, w.E, found, springs, bidx, bw, len(body_names), band, self.blend) + names = list(body_names) + for c, spring in enumerate(springs): + spring.names = [f"tendril_{c:03d}_{k:02d}" for k in range(len(spring.pos))] + names += spring.names + matrix = np.array(arm.matrix_world) + inverse = np.linalg.inv(matrix) + to_arm = lambda p: inverse[:3, :3] @ np.asarray(p) + inverse[:3, 3] # noqa: E731 + with edit_mode(context, arm) as edits: + for old in [e for e in edits if CHAIN in e]: + edits.remove(old) + for spring in springs: + for k, name in enumerate(spring.names): + head = spring.pos[k] + tail = spring.pos[k + 1] if k + 1 < len(spring.pos) else head + (head - spring.pos[k - 1]) * 0.5 + bone = edits.new(name) + bone.head, bone.tail = Vector(to_arm(head)), Vector(to_arm(tail)) + bone.parent = edits[spring.names[k - 1]] if k else edits[spring.bone] + for c, spring in enumerate(springs): + last = len(spring.names) - 1 + for k, name in enumerate(spring.names): + bone = arm.data.bones[name] + bone[CHAIN], bone[INDEX] = f"tendril_{c:03d}", k + bone[STIFFNESS] = self.stiffness * (1.0 + (self.stiffness_tip_ratio - 1.0) * k / last) + bone[DRAG], bone[GRAVITY] = self.drag, self.gravity_power + bone[HIT] = float(0.5 * spring.sd[k] * self.hit_scale) + arm.data["rig_gravity_dir"] = list(GRAVITY_DOWN) + write_weights(obj, names, w.ids, idx, weight) + kept = [c for c in found.chains if not c.folded] + lost = ~found.body & ~np.isfinite(found.d) + shells = len(np.unique(polish.components(w.count, w.E[lost[w.E[:, 0]] & lost[w.E[:, 1]]])[lost])) if lost.any() else 0 + branches = int(sum(1 for r in range(len(found.parent)) if not found.on_main[r] and found.parent[r] >= 0 + and found.on_main[found.parent[r]] and found.tree[r] in {c.tree for c in kept})) + return {"object": obj.name, "armature": arm.name, "bodyVertices": int(found.body.sum()), "chains": len(springs), + "springBones": int(sum(len(s.pos) for s in springs)), "branchesRigid": branches, + "veinsFolded": len(found.chains) - len(kept), "shellsAttached": shells, + "unreachedVertices": int(lost.sum()), "rings": int(len(found.parent)), + "shapeDiameterMedian": float(np.median(sd)), "tau": self.tau * scale, "band": band} + + +class BROKKR_RIG_OT_colliders(PolishOperator): + """Size body colliders for the spring chains: a capsule on each spine bone, a sphere on each other body bone, + shrunk until every spring joint past the first stands outside its hit radius at rest""" + bl_idname = "brokkr_rig.colliders" + bl_label = "Rig Colliders" + object_name: bpy.props.StringProperty(name="Object") + armature_name: bpy.props.StringProperty(name="Armature", description="Empty: the object's Armature modifier") + scale: bpy.props.FloatProperty(name="Scale", default=0.8, min=0.0, max=2.0, description="Collider radius as a multiple of the median radius of the body around it") + + def work(self, context): + obj = mesh_object(self.object_name) + arm = armature_of(obj, self.armature_name) + w = welded(obj) + matrix = np.array(arm.matrix_world) + world = lambda p: matrix[:3, :3] @ np.array(p) + matrix[:3, 3] # noqa: E731 + body = [b for b in arm.data.bones if CHAIN not in b] + spine = {b.name for b in spine_of(arm)} + Wb = read_weights(obj, [b.name for b in body], w.ids, w.count) + solid = Wb.sum(axis=1) >= 0.5 + heaviest = Wb.argmax(axis=1) + chain = [b for b in arm.data.bones if CHAIN in b and b[INDEX] >= 1] + joints = np.array([world(b.head_local) for b in chain]).reshape(-1, 3) + hit = np.array([b[HIT] for b in chain]) + made = {"capsules": 0, "spheres": 0, "shrunk": 0, "dropped": 0, "skipped": 0} + for bone in body: + if COLLIDERS in bone: + del bone[COLLIDERS] + for column, bone in enumerate(body): + head, tail = world(bone.head_local), world(bone.tail_local) + if bone.name in spine: + radius = core.capsule_radius(w.Vw[solid], head, tail, self.scale) + shape, offset, end = "capsule", head, tail + else: + mine = solid & (heaviest == column) + if not mine.any(): + made["skipped"] += 1 + continue + offset, radius = core.sphere_fit(w.Vw[mine], self.scale) + shape, end = "sphere", offset + cleared = core.clear_radius(radius, joints, hit, offset, end) + if cleared < radius: + made["shrunk"] += 1 + if cleared <= 0: + made["dropped"] += 1 + continue + entry = {"shape": shape, "offset": rounded(offset), "radius": float(cleared)} + if shape == "capsule": + entry["tail"] = rounded(end) + bone[COLLIDERS] = [entry] + made["capsules" if shape == "capsule" else "spheres"] += 1 + made.update({"object": obj.name, "armature": arm.name, "springJoints": len(chain)}) + return made + + +# --- the export hook: VRMC_springBone ---------------------------------------------------------------------- + +def _node_matrix(node) -> np.ndarray: + if getattr(node, "matrix", None): + return np.array(node.matrix, dtype=np.float64).reshape(4, 4).T + x, y, z, s = node.rotation if getattr(node, "rotation", None) else (0.0, 0.0, 0.0, 1.0) + rotation = np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * s), 2 * (x * z + y * s)], + [2 * (x * y + z * s), 1 - 2 * (x * x + z * z), 2 * (y * z - x * s)], + [2 * (x * z - y * s), 2 * (y * z + x * s), 1 - 2 * (x * x + y * y)]]) + scale = np.array(node.scale) if getattr(node, "scale", None) else np.ones(3) + local = np.eye(4) + local[:3, :3] = rotation * scale + local[:3, 3] = node.translation if getattr(node, "translation", None) else (0.0, 0.0, 0.0) + return local + + +def _spring_bone(gltf, export_settings) -> dict | None: + """The VRMC_springBone object for the armatures this export carries (those with brokkr_rig chains whose bones all + became nodes), or None when there are none.""" + nodes = gltf.nodes or [] + node_of = {node.name: i for i, node in enumerate(nodes)} + parent = {} + for i, node in enumerate(nodes): + for child in node.children or []: + parent[child if isinstance(child, int) else next(j for j, n in enumerate(nodes) if n is child)] = i + world = {} + + def matrix_of(i): + if i not in world: + world[i] = (matrix_of(parent[i]) if i in parent else np.eye(4)) @ _node_matrix(nodes[i]) + return world[i] + + yup = bool(export_settings.get("gltf_yup", True)) + swing = np.array([[1.0, 0, 0], [0, 0, 1.0], [0, -1.0, 0]]) if yup else np.eye(3) + local = lambda i, p: (np.linalg.inv(matrix_of(i)) @ np.append(swing @ np.asarray(p, dtype=np.float64), 1.0))[:3].tolist() # noqa: E731 + springs, colliders = [], [] + for arm in sorted((o for o in bpy.data.objects if o.type == "ARMATURE"), key=lambda o: o.name): + by_chain = {} + for bone in arm.data.bones: + if CHAIN in bone: + by_chain.setdefault(bone[CHAIN], []).append(bone) + gravity = (swing @ np.asarray(list(arm.data.get("rig_gravity_dir", GRAVITY_DOWN)), dtype=np.float64)).tolist() + for name in sorted(by_chain): + chain = sorted(by_chain[name], key=lambda b: b[INDEX]) + if not all(b.name in node_of for b in chain): + continue + springs.append({"name": name, "colliderGroups": [0], "joints": [ + {"node": node_of[b.name], "hitRadius": float(b[HIT]), "stiffness": float(b[STIFFNESS]), "gravityPower": float(b[GRAVITY]), + "gravityDir": gravity, "dragForce": float(b[DRAG])} for b in chain]}) + for bone in arm.data.bones: + if COLLIDERS in bone and bone.name in node_of: + for entry in bone[COLLIDERS]: + entry = entry.to_dict() if hasattr(entry, "to_dict") else entry + at = node_of[bone.name] + shape = {"offset": local(at, entry["offset"]), "radius": float(entry["radius"])} + if entry["shape"] == "capsule": + shape["tail"] = local(at, entry["tail"]) + colliders.append({"node": at, "shape": {entry["shape"]: shape}}) + if not springs: + return None + if not colliders: + springs = [{k: v for k, v in s.items() if k != "colliderGroups"} for s in springs] + return {"specVersion": "1.0", "colliders": colliders, + "colliderGroups": [{"name": "body", "colliders": list(range(len(colliders)))}] if colliders else [], "springs": springs} + + +class glTF2ExportUserExtension: + """Blender's glTF exporter finds this class on every enabled add-on and calls its hook once the nodes are final.""" + + def __init__(self): + from io_scene_gltf2.io.com.gltf2_io_extensions import Extension + self.Extension = Extension + + def gather_gltf_extensions_hook(self, gltf, export_settings): + spring = _spring_bone(gltf, export_settings) + if spring is None: + return + gltf.extensions = gltf.extensions or {} + gltf.extensions["VRMC_springBone"] = self.Extension(name="VRMC_springBone", extension=spring, required=False) + gltf.extensions_used = gltf.extensions_used or [] + if "VRMC_springBone" not in gltf.extensions_used: + gltf.extensions_used.append("VRMC_springBone") + + +classes = (BROKKR_RIG_OT_body, BROKKR_RIG_OT_tendrils, BROKKR_RIG_OT_colliders) + + +def register(): + if MISSING is not None or not hasattr(bpy.types.WindowManager, RESULT): + raise RuntimeError(f"brokkr_rig needs brokkr_mesh_polish enabled first ({MISSING or 'its result property is not registered'}).") + for cls in classes: + bpy.utils.register_class(cls) + + +def unregister(): + for cls in reversed(classes): + bpy.utils.unregister_class(cls) diff --git a/surfaces/blender/brokkr_rig/brokkr_actions.json b/surfaces/blender/brokkr_rig/brokkr_actions.json new file mode 100644 index 0000000..d258802 --- /dev/null +++ b/surfaces/blender/brokkr_rig/brokkr_actions.json @@ -0,0 +1,207 @@ +{ + "schema": "brokkr.blender.host_actions.v0", + "actions": [ + { + "name": "brokkr_rig.body", + "doc": "Skin a mesh to its body: a new spine along the long axis (root at the head end) with a bone per seed part, or an authored armature, weighted. Bakes the object's transform.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63 + }, + { + "name": "armature_name", + "type": "string", + "maxLength": 63, + "doc": "an authored armature to weight against, kept as it is; empty makes .rig" + }, + { + "name": "spine_bones", + "type": "integer", + "minimum": 2, + "maximum": 32, + "default": 8, + "doc": "bones along the long axis of a new armature" + }, + { + "name": "head", + "type": "string", + "enum": [ + "+y", + "-y" + ], + "default": "+y", + "doc": "which end of the long axis is the head, the spine's root" + }, + { + "name": "seeds", + "type": "string", + "maxLength": 4000, + "doc": "name=x,y,z; name=x,y,z ... world-space surface points; each name is a part with its own bone, the spine takes the rest" + }, + { + "name": "crease_cost", + "type": "number", + "minimum": 0, + "maximum": 1000, + "default": 40, + "doc": "how strongly parts stop at concave creases" + }, + { + "name": "smooth_rounds", + "type": "integer", + "minimum": 0, + "maximum": 64, + "default": 3, + "doc": "Laplacian rounds over the weights" + } + ] + }, + { + "name": "brokkr_rig.tendrils", + "doc": "Grow spring chains from the thin parts of a skinned mesh: one bone chain per tendril hung from a body bone, weights, and spring parameters for the exporter.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63 + }, + { + "name": "armature_name", + "type": "string", + "maxLength": 63, + "doc": "an armature object; the object's Armature modifier when absent" + }, + { + "name": "tau", + "type": "number", + "minimum": 0.001, + "maximum": 0.5, + "default": 0.04, + "doc": "shape diameter below which the surface is thin, as a share of the longest side" + }, + { + "name": "band", + "type": "number", + "minimum": 0.002, + "maximum": 0.5, + "default": 0.04, + "doc": "distance from the body one joint ring spans, as a share of the longest side" + }, + { + "name": "dilate", + "type": "number", + "minimum": 0, + "maximum": 0.5, + "default": 0.04, + "doc": "how far the thick body is grown over its roots, as a share of the longest side" + }, + { + "name": "fold_bands", + "type": "number", + "minimum": 0, + "maximum": 10, + "default": 1.5, + "doc": "a chain whose every vertex lies within this many bands of the body is a vein and folds into it" + }, + { + "name": "min_joints", + "type": "integer", + "minimum": 1, + "maximum": 64, + "default": 2, + "doc": "a chain with fewer rings than this folds into the body" + }, + { + "name": "blend", + "type": "number", + "minimum": 0, + "maximum": 4, + "default": 0.5, + "doc": "bands over which weights blend between neighbouring bones and into the body" + }, + { + "name": "stiffness", + "type": "number", + "minimum": 0.01, + "maximum": 1000, + "default": 3, + "doc": "rate (1 per second) a joint closes on its rest pose, at the root" + }, + { + "name": "stiffness_tip_ratio", + "type": "number", + "minimum": 0.01, + "maximum": 10, + "default": 0.5, + "doc": "stiffness at the tip as a multiple of the root's" + }, + { + "name": "drag", + "type": "number", + "minimum": 0, + "maximum": 1, + "default": 0.3, + "doc": "share of velocity a joint loses per substep" + }, + { + "name": "gravity_power", + "type": "number", + "minimum": 0, + "maximum": 100, + "default": 0, + "doc": "displacement per second along the world's down, in scene units" + }, + { + "name": "hit_scale", + "type": "number", + "minimum": 0, + "maximum": 10, + "default": 1, + "doc": "joint hit radius as a multiple of half the ring's median shape diameter" + } + ] + }, + { + "name": "brokkr_rig.colliders", + "doc": "Size body colliders for the spring chains: a capsule per spine bone, a sphere per other body bone, shrunk to clear every spring joint past the first.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63 + }, + { + "name": "armature_name", + "type": "string", + "maxLength": 63, + "doc": "an armature object; the object's Armature modifier when absent" + }, + { + "name": "scale", + "type": "number", + "minimum": 0.05, + "maximum": 2, + "default": 0.8, + "doc": "collider radius as a multiple of the median radius of the body around it" + } + ] + } + ] +} \ No newline at end of file diff --git a/surfaces/blender/brokkr_rig/core.py b/surfaces/blender/brokkr_rig/core.py new file mode 100644 index 0000000..5dde1d9 --- /dev/null +++ b/surfaces/blender/brokkr_rig/core.py @@ -0,0 +1,349 @@ +"""The arithmetic of the rig builder: numpy only, no bpy, so every rule here is tested without Blender. + +A mesh is welded positions V (n,3) and unique edges E (k,2) of the welded graph (mesh polish's weld, so a vertex +split at a UV seam is one vertex here). Skin weights are (idx, w): four bone indices and four weights per vertex. + +Tendril extraction is a level-set walk from a thick body: every vertex gets a geodesic distance from the body, +the distance is cut into bands, each band into connected rings, and a ring is one joint at its centroid whose +parent is the ring one band nearer. Each tree's root-to-deepest-leaf path is one spring; the rest of the tree +rides the path rigidly. +""" +from __future__ import annotations + +import heapq +from types import SimpleNamespace + +import numpy as np +from brokkr_mesh_polish.core import components + + +# --- graph ----------------------------------------------------------------------------------------------- + +def welded_edges(TW: np.ndarray) -> np.ndarray: + """Unique edges (k,2), low id first, of the welded triangles; triangles that collapsed in the weld add none.""" + live = (TW[:, 0] != TW[:, 1]) & (TW[:, 1] != TW[:, 2]) & (TW[:, 0] != TW[:, 2]) + tw = TW[live] + return np.unique(np.sort(np.concatenate([tw[:, [0, 1]], tw[:, [1, 2]], tw[:, [2, 0]]]), axis=1), axis=0) + + +def graph(V: np.ndarray, E: np.ndarray) -> tuple[list, list, list]: + """Adjacency in compressed rows: (start, target, length); the neighbours of v are target[start[v]:start[v + 1]].""" + length = np.linalg.norm(V[E[:, 0]] - V[E[:, 1]], axis=1) + source = np.concatenate([E[:, 0], E[:, 1]]) + order = np.argsort(source, kind="stable") + return (np.searchsorted(source[order], np.arange(len(V) + 1)).tolist(), + np.concatenate([E[:, 1], E[:, 0]])[order].tolist(), np.concatenate([length, length])[order].tolist()) + + +def dijkstra(g: tuple, sources: np.ndarray, limit: float = float("inf")) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """(distance, predecessor, origin) over the edge graph from several sources; distance is inf, predecessor + and origin -1, where no source reaches within limit.""" + start, target, length = g + n = len(start) - 1 + best = [float("inf")] * n + pred = [-1] * n + origin = [-1] * n + heap = [] + for s in sources.tolist(): + best[s], origin[s] = 0.0, s + heap.append((0.0, s)) + heapq.heapify(heap) + while heap: + cost, u = heapq.heappop(heap) + if cost > best[u]: + continue + for k in range(start[u], start[u + 1]): + w, reach = target[k], cost + length[k] + if reach < best[w] and reach <= limit: + best[w], pred[w], origin[w] = reach, u, origin[u] + heapq.heappush(heap, (reach, w)) + return np.asarray(best), np.asarray(pred, dtype=np.int64), np.asarray(origin, dtype=np.int64) + + +# --- weights --------------------------------------------------------------------------------------------- + +def top4(W: np.ndarray) -> tuple[np.ndarray, np.ndarray]: + """(idx, w) of a dense weight matrix (n,bones): the four heaviest per vertex, normalised to sum 1.""" + keep = min(4, W.shape[1]) + idx = np.argsort(-W, axis=1, kind="stable")[:, :keep] + w = np.take_along_axis(W, idx, axis=1) + total = w.sum(axis=1, keepdims=True) + w = np.where(total > 0, w / np.maximum(total, 1e-30), 0.0) + if keep < 4: + idx, w = np.pad(idx, ((0, 0), (0, 4 - keep))), np.pad(w, ((0, 0), (0, 4 - keep))) + return idx, w + + +def axial_weights(u: np.ndarray, knots: np.ndarray) -> np.ndarray: + """(n, len(knots)): bone i weighs 1 at knot i and falls linearly to 0 at knot i + 1, where bone i + 1 takes over; + before the first knot and past the last, one bone. knots increase.""" + count = len(knots) + W = np.zeros((len(u), count)) + at = np.clip(np.searchsorted(knots, u, side="right") - 1, 0, count - 1) + nxt = np.minimum(at + 1, count - 1) + span = knots[nxt] - knots[at] + t = np.where(span > 0, np.clip((u - knots[at]) / np.where(span > 0, span, 1.0), 0.0, 1.0), 0.0) + rows = np.arange(len(u)) + W[rows, at] += 1.0 - t + W[rows, nxt] += t + return W + + +def smooth(W: np.ndarray, E: np.ndarray, rounds: int) -> np.ndarray: + """Laplacian rounds over the vertex graph: each vertex takes half its own weights and half its neighbours' mean.""" + degree = np.maximum(np.bincount(E.reshape(-1), minlength=len(W)), 1)[:, None] + for _ in range(rounds): + near = np.zeros_like(W) + np.add.at(near, E[:, 0], W[E[:, 1]]) + np.add.at(near, E[:, 1], W[E[:, 0]]) + W = 0.5 * W + 0.5 * near / degree + return W + + +def spine_points(V: np.ndarray, axis: np.ndarray, count: int) -> tuple[np.ndarray, np.ndarray, float]: + """(joints (count + 1,3), u, length): count equal bones from the head end (the far end along axis) to the tail + end, each joint centred on the median of the vertices around it; u is every vertex's distance from the head + end along axis, length the extent.""" + a = V @ axis + head, tail = float(a.max()), float(a.min()) + u = head - a + length = head - tail + step = length / count + side = V - np.outer(a, axis) + joints = np.empty((count + 1, 3)) + for i in range(count + 1): + near = np.abs(u - i * step) <= step + joints[i] = axis * (head - i * step) + (np.median(side[near], axis=0) if near.any() else 0.0) + return joints, u, length + + +def cut_edges(V: np.ndarray, TW: np.ndarray, part: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """The welded edges whose two triangles lie in different parts: (part a, part b, midpoint, length).""" + count = len(TW) + edges = np.sort(np.concatenate([TW[:, [0, 1]], TW[:, [1, 2]], TW[:, [2, 0]]]), axis=1) + face = np.tile(np.arange(count), 3) + order = np.lexsort((edges[:, 1], edges[:, 0])) + edges, face = edges[order], face[order] + same = (edges[1:] == edges[:-1]).all(axis=1) + i, j, e = face[:-1][same], face[1:][same], edges[:-1][same] + cut = part[i] != part[j] + e = e[cut] + return part[i][cut], part[j][cut], (V[e[:, 0]] + V[e[:, 1]]) / 2.0, np.linalg.norm(V[e[:, 0]] - V[e[:, 1]], axis=1) + + +# --- tendril extraction ---------------------------------------------------------------------------------- + +def body_region(g: tuple, E: np.ndarray, sd: np.ndarray, tau: float, dilate: float) -> np.ndarray: + """The body: the largest connected set of vertices whose shape diameter is at least tau (a vertex in an open + sheet reads 0 and is thin), grown geodesically by dilate.""" + n = len(sd) + thick = sd >= tau + if not thick.any(): + raise ValueError("no vertex is thicker than tau: lower tau") + label = components(n, E[thick[E[:, 0]] & thick[E[:, 1]]]) + body = thick & (label == np.bincount(label[thick], minlength=n).argmax()) + if dilate > 0: + body = np.isfinite(dijkstra(g, np.flatnonzero(body), dilate)[0]) + return body + + +def extract(V: np.ndarray, E: np.ndarray, sd: np.ndarray, tau: float, band: float, dilate: float, + fold_bands: float, min_joints: int) -> SimpleNamespace: + """Rings, the joint tree and the chains. tau, band and dilate are lengths. + + Returns: body, d (distance from the body), origin (nearest body vertex), ring (per vertex, -1 off the rings), + and per ring: parent (-1 touches the body), band, centroid, dist (mean distance), size, tree, on_main, fork + (the main-path ring a branch ring rides), index (position on its main path). chains is a list of + SimpleNamespace(tree, rings, folded): rings is the main path, root first; a tree whose farthest vertex is + within fold_bands bands of the body, or whose main path has fewer than min_joints rings, is folded + (a vein lying on the body).""" + n = len(V) + g = graph(V, E) + body = body_region(g, E, sd, tau, dilate) + d, pred, origin = dijkstra(g, np.flatnonzero(body)) + free = ~body & np.isfinite(d) + band_of = np.where(free, np.floor(d / band), -1).astype(np.int64) + same = free[E[:, 0]] & free[E[:, 1]] & (band_of[E[:, 0]] == band_of[E[:, 1]]) + label = components(n, E[same]) + ids = np.unique(label[free]) + ring = np.full(n, -1, dtype=np.int64) + ring[free] = np.searchsorted(ids, label[free]) + R = len(ids) + r = ring[free] + size = np.bincount(r, minlength=R) + centroid = np.stack([np.bincount(r, weights=V[free][:, k], minlength=R) for k in range(3)], axis=1) / np.maximum(size, 1)[:, None] + dist = np.bincount(r, weights=d[free], minlength=R) / np.maximum(size, 1) + ring_band = np.zeros(R, dtype=np.int64) + ring_band[r] = band_of[free] + far = np.zeros(R) + np.maximum.at(far, r, d[free]) + # a ring hangs from the ring its nearest vertex was reached through: one band nearer, or the body + near = np.flatnonzero(free) + near = near[np.lexsort((near, d[near], ring[near]))] + first = near[np.unique(ring[near], return_index=True)[1]] + up = pred[first] + parent = np.where(body[up], -1, ring[up]) + # the main path of each tree: at each ring the child with the tallest subtree (then the most vertices, then the lowest id) + order = np.argsort(-ring_band, kind="stable") + height = np.ones(R, dtype=np.int64) + main = np.full(R, -1, dtype=np.int64) + for c in order.tolist(): + if main[c] >= 0: + height[c] = 1 + height[main[c]] + p = parent[c] + if p >= 0 and (main[p] < 0 or (height[c], size[c], -c) > (height[main[p]], size[main[p]], -main[p])): + main[p] = c + tree = np.arange(R) + on_main = np.zeros(R, dtype=bool) + fork = np.arange(R) + index = np.zeros(R, dtype=np.int64) + for c in order[::-1].tolist(): + p = parent[c] + if p < 0: + on_main[c] = True + continue + tree[c] = tree[p] + on_main[c] = on_main[p] and main[p] == c + fork[c] = c if on_main[c] else fork[p] + index[c] = index[p] + 1 if on_main[c] else 0 + reach = np.zeros(R) + np.maximum.at(reach, tree, far) + chains = [] + for root in np.flatnonzero(parent < 0).tolist(): + path = [root] + while main[path[-1]] >= 0: + path.append(int(main[path[-1]])) + chains.append(SimpleNamespace(tree=root, rings=path, folded=bool(reach[root] <= fold_bands * band or len(path) < min_joints))) + return SimpleNamespace(body=body, d=d, pred=pred, origin=origin, ring=ring, parent=parent, band=ring_band, centroid=centroid, + dist=dist, size=size, tree=tree, on_main=on_main, fork=fork, index=index, chains=chains) + + +def plan(V: np.ndarray, sd: np.ndarray, found: SimpleNamespace, band: float) -> list[SimpleNamespace]: + """The springs: for each kept chain its joints (a ring's centroid each, then the tip at the leaf ring's + farthest vertex), the distance of each from the body, the median shape diameter of each ring, and the + vertex of the body the chain's first ring leaves from. The tip stands at least a quarter band from the last + ring's centroid.""" + out = [] + for chain in found.chains: + if chain.folded: + continue + rings = chain.rings + pos = [found.centroid[r] for r in rings] + dist = [float(found.dist[r]) for r in rings] + leaf = np.flatnonzero(found.ring == rings[-1]) + tip = leaf[np.argmax(found.d[leaf])] + tip_pos, tip_dist = V[tip].copy(), float(found.d[tip]) + gap = 0.25 * band + if np.linalg.norm(tip_pos - pos[-1]) < gap: + way = pos[-1] - (pos[-2] if len(pos) > 1 else V[found.origin[leaf[0]]]) + way = way / np.linalg.norm(way) if np.linalg.norm(way) > 0 else np.array([0.0, 0.0, 1.0]) + tip_pos, tip_dist = pos[-1] + way * gap, max(tip_dist, dist[-1] + gap) + hit = [float(np.median(sd[found.ring == r])) for r in rings] + [float(np.median(sd[leaf]))] + out.append(SimpleNamespace(tree=chain.tree, rings=rings, pos=np.array(pos + [tip_pos]), dist=np.array(dist + [tip_dist]), + sd=np.array(hit), anchor=np.unique(found.origin[found.ring == rings[0]]))) + return out + + +def tendril_weights(V: np.ndarray, E: np.ndarray, found: SimpleNamespace, springs: list, body_idx: np.ndarray, + body_w: np.ndarray, bodies: int, band: float, blend: float) -> tuple[np.ndarray, np.ndarray, list]: + """(idx, w, start): skin weights over bodies body bones then every spring's bones, spring c owning bones + start[c] .. start[c] + len(pos) - 1 (its rings, then the tip). + + A vertex on a spring's main path, at distance x from the body, takes bone k, the last joint at or before x, + blending linearly from bone k - 1 over blend bands from joint k (a joint's distance is its ring's mean); + a branch ring rides the main-path bone at its fork; a vertex within blend bands of the body takes the body + weights of its nearest body vertex in the complement; a folded vein takes those body weights; a vertex the + distance never reaches takes, per shell, the nearest spring bone.""" + n = len(V) + start, at = [], bodies + for s in springs: + start.append(at) + at += len(s.pos) + chain_of = {s.tree: c for c, s in enumerate(springs)} + ring_joint = {} # ring -> (spring, joint index) on the main path + for c, s in enumerate(springs): + for k, r in enumerate(s.rings): + ring_joint[r] = (c, k) + reach = blend * band + out = [None] * n + for v in range(n): + if found.body[v]: + out[v] = {int(b): float(w) for b, w in zip(body_idx[v], body_w[v]) if w > 0} + continue + r = found.ring[v] + if r < 0: + continue + near = int(found.origin[v]) + c = chain_of.get(int(found.tree[r])) + if c is None: + out[v] = {int(b): float(w) for b, w in zip(body_idx[near], body_w[near]) if w > 0} + continue + s = springs[c] + if found.on_main[r]: + k = int(np.searchsorted(s.dist, found.d[v], side="right")) - 1 + if k <= 0: + mix = {start[c]: 1.0} + else: + t = min((found.d[v] - s.dist[k]) / reach, 1.0) if reach > 0 else 1.0 + mix = {start[c] + k: t, **({start[c] + k - 1: 1.0 - t} if k > 0 and t < 1.0 else {})} + else: + mix = {start[c] + ring_joint[int(found.fork[r])][1]: 1.0} + share = min(found.d[v] / reach, 1.0) if reach > 0 else 1.0 + row = {b: w * share for b, w in mix.items()} + if share < 1.0: + for b, w in zip(body_idx[near], body_w[near]): + row[int(b)] = row.get(int(b), 0.0) + float(w) * (1.0 - share) + out[v] = row + lost = [v for v in range(n) if out[v] is None] + if lost: + lost = np.asarray(lost) + bone_pos = np.concatenate([s.pos for s in springs]) if springs else np.zeros((0, 3)) + bone_id = np.concatenate([start[c] + np.arange(len(s.pos)) for c, s in enumerate(springs)]) if springs else np.zeros(0, dtype=int) + pairs = E[np.isin(E[:, 0], lost) & np.isin(E[:, 1], lost)] + shell = components(n, pairs) + for label in np.unique(shell[lost]): + members = lost[shell[lost] == label] + if len(bone_pos): + bone = int(bone_id[np.argmin(np.linalg.norm(bone_pos - V[members].mean(axis=0), axis=1))]) + for v in members.tolist(): + out[v] = {bone: 1.0} + else: + for v in members.tolist(): + out[v] = {int(b): float(w) for b, w in zip(body_idx[v], body_w[v]) if w > 0} + idx, w = np.zeros((n, 4), dtype=np.int64), np.zeros((n, 4)) + for v, row in enumerate(out): + top = sorted(row.items(), key=lambda item: (-item[1], item[0]))[:4] + total = sum(x for _, x in top) + for slot, (b, x) in enumerate(top): + idx[v, slot], w[v, slot] = b, x / total + return idx, w, start + + +# --- colliders ------------------------------------------------------------------------------------------- + +def segment_distance(P: np.ndarray, a: np.ndarray, b: np.ndarray) -> np.ndarray: + """Distance from each point of P (k,3) to the segment a-b (a point when a == b).""" + ab = b - a + along = np.clip(((P - a) @ ab) / max(float(ab @ ab), 1e-30), 0.0, 1.0) + return np.linalg.norm(P - (a + along[:, None] * ab), axis=1) + + +def capsule_radius(V: np.ndarray, head: np.ndarray, tail: np.ndarray, scale: float) -> float: + """The median distance from the axis head-tail of the vertices that project onto it, times scale (0 if none).""" + ab = tail - head + t = ((V - head) @ ab) / max(float(ab @ ab), 1e-30) + on = (t >= 0.0) & (t <= 1.0) + return float(np.median(segment_distance(V[on], head, tail)) * scale) if on.any() else 0.0 + + +def sphere_fit(V: np.ndarray, scale: float) -> tuple[np.ndarray, float]: + """(centre, radius): the centroid of the vertices and the median distance from it, times scale.""" + centre = V.mean(axis=0) + return centre, float(np.median(np.linalg.norm(V - centre, axis=1)) * scale) + + +def clear_radius(radius: float, joints: np.ndarray, hit: np.ndarray, a: np.ndarray, b: np.ndarray) -> float: + """radius shrunk until every joint (k,3) stands at least its hit radius outside the capsule a-b (a sphere when a == b).""" + if not len(joints): + return radius + return min(radius, float((segment_distance(joints, a, b) - hit).min())) diff --git a/surfaces/blender/docs/rig.md b/surfaces/blender/docs/rig.md new file mode 100644 index 0000000..1b3a0b9 --- /dev/null +++ b/surfaces/blender/docs/rig.md @@ -0,0 +1,123 @@ +# Rigging generated creatures for spring-bone tendrils + +`surfaces/blender/brokkr_rig` is a Blender add-on that rigs a fused generated mesh (Tripo and its kin: one skin, +body and tendrils welded together) for a spring-bone runtime. It is a host add-on in Brokkr's sense +(`install.md`, "Host add-on actions"), a sibling of `brokkr_mesh_polish`: it imports that package's operator base, +`Refused`, `mesh_object`, `arrays` and arithmetic (weld, components, face adjacency, crease costs, seed growing, +`principal_frame`, `boundary_root`) instead of copying them, and nothing from `brokkr_bridge`. Enable +`brokkr_mesh_polish` first; `brokkr_rig` refuses to register without it. `brokkr_actions.json` beside its +`__init__.py` lists the three operators agents may run; the arithmetic is `core.py` (numpy only, tested without +Blender). Every action writes a JSON report to `brokkr_mesh_polish_result`, returned in the receipt's `hostResult`. + +## The contract it produces, and who owns it + +The GLB the exporter writes has one skin over every bone, every node with translation and rotation at unit scale +and no matrix, mesh primitives with exactly `POSITION`, `NORMAL`, `TEXCOORD_0`, `JOINTS_0`, `WEIGHTS_0` (at most 4 +influences, weights summing to 1), and `VRMC_springBone` 1.0: each spring a linear chain whose first joint hangs +from a body bone, colliders only on body bones in one group `body` named by every spring. Stiffness is a rate in +1 per second, not VRM's unit. + +Whether a GLB is acceptable is **Aetheria's** `SpringRigData.FromGlbJson`, not this add-on, which ships no copy of +its refusals. Run the owner's code on the output with `SpringRigVerify.VerifyGlb` (Aetheria, batch mode): + +```text +SPRINGRIG_GLB= Unity -batchmode -projectPath \ + -executeMethod Aetheria.EditorTools.SpringRigVerify.VerifyGlb -logFile +``` + +(no `-nographics`, no `-quit`; one Unity batch instance at a time). It logs the rig's bone, body, chain, joint and +collider counts and exits 0 on PASS. + +## Export + +There is no export action of its own: Brokkr's `exportGltf` (or File > Export > glTF) writes the GLB, and the +add-on's `glTF2ExportUserExtension` hook writes `VRMC_springBone` into it, mapping bone names to node indices from +the exporter's final node list. It acts only when an exported armature carries `brokkr_rig` chains, so any other +export is untouched. Collider offsets and capsule tails are stored in Blender world space on the body bones and +composed into each collider node's local glTF frame at export from the exported nodes' translation, rotation and +scale; the gravity direction goes into glTF world. Both follow `export_yup`. + +## Actions + +### body + +`brokkr_rig.body` (`object_name`, `armature_name`, `spine_bones` 2-32, `head` `+y`/`-y`, `seeds`, `crease_cost`, +`smooth_rounds`). Bakes the object's transform into its mesh and parents it to the armature at identity, so no +node carries a scale. + +With no `armature_name` it makes `.rig`: a spine of equal bones along the principal axis, the root at the +head end (`head` names which end of world Y; the swim wave runs head to tail), and one bone per seed name. `seeds` +reads as in `cut_parts` (`name=x,y,z; ...`, several points may name one part). The spine is an implicit part named +`spine` seeded at the surface nearest each spine joint; a seed named `spine` adds to it. Each named part is grown +from its seeds along concave creases (`grow_parts`); its bone runs from the root of the part's cut +(`boundary_root`) to its centroid and hangs from the nearest spine bone. + +With an existing `armature_name` the armature is kept as it is: its spine is the first root's heaviest-child chain +(as the runtime derives it), every other body bone is seeded at the surface nearest its tail (`seeds` may add +points for a bone by name). The spine's bones must run from the head end to the tail end along the long axis. + +Weights: spine bones by axial projection, linear between neighbouring joints; a part's region 1 on its bone; then +`smooth_rounds` Laplacian rounds over the welded vertex graph, the top 4 kept and normalised. + +### tendrils + +`brokkr_rig.tendrils` (`object_name`, `armature_name`, `tau`, `band`, `dilate` as shares of the longest side, +`fold_bands`, `min_joints`, `blend`, `stiffness`, `stiffness_tip_ratio`, `drag`, `gravity_power`, `hit_scale`). +Needs `body` first. The mesh is welded; each vertex gets a shape diameter (median of five inward rays, fixed +seed; an open sheet with no back face reads 0). The body is the largest component thicker than `tau`, dilated by +`dilate`. Edge distance from the body is cut into bands of `band`; each band splits into connected rings, one +joint per ring at its centroid, its parent the ring it touches one band nearer. + +- A tree (everything hanging from one root ring) whose farthest vertex lies within `fold_bands` bands of the body + is a surface vein and folds into the body; so does a tree whose main path has fewer than `min_joints` rings. +- Each remaining tree's root-to-deepest-leaf path is one spring, ending in a tip joint at the leaf ring's farthest + vertex (the runtime gives a chain's last joint its parent's aimed rotation). Side branches cannot be springs of + their own (a spring's first joint must hang from a body bone), so their vertices weight rigidly to the main-path + bone at their fork. +- Vertices the distance never reaches (detached shells) weight rigidly, per shell, to the nearest spring bone. +- Weights: a vertex between joints k and k+1 goes to bone k, blending linearly from bone k-1 over `blend` bands + from joint k, and with the body weights of its nearest body vertex within `blend` bands of the body. +- Bones `tendril__`; joint 0 hangs from the body bone with most weight at its ring's body boundary. Bone + ID properties: `rig_chain`, `rig_index`, `rig_stiffness` (tapered from the root to the tip by + `stiffness_tip_ratio`), `rig_drag`, `rig_gravity`, `rig_hit_radius` (half the ring's median shape diameter times + `hit_scale`). Running it again replaces every earlier chain. + +The report counts chains, spring bones, rigid branches, veins folded, shells attached and unreached vertices. + +### colliders + +`brokkr_rig.colliders` (`object_name`, `armature_name`, `scale`). A capsule per spine bone from head to tail, +radius the median radial distance of the body vertices projecting onto it times `scale`; a sphere per other body +bone at the centroid of its heaviest vertices, radius the median distance times `scale`. Each radius is then +shrunk until every spring joint past the first stands at least its hit radius outside it at rest (`shrunk` counts +them). Stored as the bone's `rig_colliders` property list. + +## What it cannot do + +It does not judge a rig: acceptance is the runtime's parse. It does not simulate the springs (the report's +chain, joint and collider counts are what was built, not how it moves). It reads thickness from rays against the +mesh, so a mesh whose windings face inward needs `repair` and `recalc_normals` first. A vein the dilation reaches +is absorbed before the fold rule sees it. Seeds on a smooth surface split by distance alone. + +## A recipe + +```json +{"requestedBy": "nibu/hands", "importDir": "work", "outputDir": "work", + "hostAddons": ["brokkr_mesh_polish", "brokkr_rig"], "saveBlend": "work/whale.blend", + "intents": [ + {"action": "importGltf", "filepath": "whale.glb"}, + {"action": "brokkr_mesh_polish.audit"}, + {"action": "brokkr_mesh_polish.repair", "object_name": "whale_mesh"}, + {"action": "brokkr_mesh_polish.orient", "object_name": "whale_root", "length": 1.0}, + {"action": "brokkr_rig.body", "object_name": "whale_mesh", "spine_bones": 8, "head": "+y", "seeds": "jaw=0.2,0.4,0"}, + {"action": "brokkr_rig.tendrils", "object_name": "whale_mesh", "tau": 0.04, "band": 0.04, "dilate": 0.04}, + {"action": "brokkr_rig.colliders", "object_name": "whale_mesh"}, + {"action": "exportGltf", "filepath": "whale_rigged.glb"}]} +``` + +Pick seed points from a flat turntable with `brokkr_mesh_polish.pick`, and pick `head` by eye from a render. Run +the recipe with `tools/run_intents.py` under private `BLENDER_USER_*` directories (`mesh-polish.md`), then +`VerifyGlb` on `whale_rigged.glb`. + +The live proof is `tests/live/rig.py` (a synthetic whale through the same intents; `rig.result.json` is its last +run). diff --git a/surfaces/blender/tests/live/rig.py b/surfaces/blender/tests/live/rig.py new file mode 100644 index 0000000..54bc1a4 --- /dev/null +++ b/surfaces/blender/tests/live/rig.py @@ -0,0 +1,272 @@ +"""Live proof, in a background Blender, that the brokkr_rig rows are admitted by Brokkr as host actions and that a +synthetic whale (a capsule body, six tendrils of which one forks and one is a vein lying on the body, a detached +bead and a jaw seed) goes through run_intent: repair, orient, body, tendrils, colliders, exportGltf, and comes out +as a GLB the exporter hook has given VRMC_springBone. Not part of the unittest run: it needs Blender. + + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/rig.py -- + +Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses +without them). Writes .result.json and .glb (the synthetic whale's rig, for the runtime's own parse, +Aetheria SpringRigVerify.VerifyGlb) and exits 1 when a check failed. The acceptance is the runtime's parse, not +anything here: the structure checks below are what this builder promised, not the runtime's rules. +""" +import json +import math +import os +import struct +import sys +import tempfile +import time +import types +from pathlib import Path + +import bmesh +import bpy +import numpy as np +from mathutils import Matrix, Vector + +SURFACE = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(SURFACE / "tools")) +import private_dirs # noqa: E402 + +_refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind)) +if _refused: + raise SystemExit(_refused) +OUT = sys.argv[sys.argv.index("--") + 1] +package = types.ModuleType("brokkr_bridge") +package.__path__ = [str(SURFACE / "brokkr_bridge")] +sys.modules["brokkr_bridge"] = package +from brokkr_bridge import blender_target as bt # noqa: E402 + +import addon_utils # noqa: E402 + +sys.path.append(str(SURFACE)) +T0 = time.time() +bpy.ops.wm.read_factory_settings(use_empty=True) +for module in ("brokkr_mesh_polish", "brokkr_rig"): + addon_utils.enable(module, default_set=True) +target = bt.BrokkrBlenderTarget(bpy) +WORK = Path(tempfile.mkdtemp(prefix="brokkr-rig-live-")) +target.configure_action_dirs("", str(WORK)) +target.reload_host_actions() +R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], + "hostRows": [row["name"] for row in target.host_actions()[0]]} +COUNT = [0] +T0 = time.time() + + +def check(name, ok, detail=None): + R["checks"].append({"name": name, "ok": bool(ok), "detail": detail}) + + +def send(action, **fields): + COUNT[0] += 1 + receipt = target.run_intent(bpy.context, {"commandId": f"live-{COUNT[0]}", "requestedBy": "test/driver", "action": action, **fields}) + result = json.loads(receipt["hostResult"]) if receipt.get("hostResult") else None + print("SEND", f"{time.time() - T0:.1f}s", action, receipt["status"], str(receipt["message"])[:300], flush=True) + return receipt, result + + +def tube(start, end, radius=0.006, segments=6): + start, end = Vector(start), Vector(end) + along = end - start + matrix = Matrix.Translation((start + end) / 2) @ along.to_track_quat("Z", "Y").to_matrix().to_4x4() + return matrix, along.length, radius, segments + + +def make_whale(): + """Body: an ellipsoid 0.24 x 1.0 x 0.24. Tendrils are tubes whose first 0.03 lies inside the body, joined by an + exact union so the skin is fused as a generated mesh is; the bead is a separate shell.""" + body = bmesh.new() + bmesh.ops.create_uvsphere(body, u_segments=32, v_segments=24, radius=1.0, calc_uvs=True) + bmesh.ops.scale(body, vec=(0.12, 0.5, 0.12), verts=body.verts) + bm = bmesh.new() + inside = 0.03 + specs = [] + for y, tilt, length in ((-0.3, -0.4, 0.34), (-0.1, 0.4, 0.3), (0.1, -0.2, 0.36), (0.3, 0.3, 0.28)): + d = Vector((tilt, 0.0, -1.0)).normalized() + surface = Vector((0.0, y, -0.12 * math.sqrt(max(1.0 - (y / 0.5) ** 2, 0.0)))) + specs.append((surface - d * inside, surface + d * length)) + d = Vector((0.5, 0.2, -1.0)).normalized() # the forked one: a trunk with a side branch near its middle + surface = Vector((0.0, 0.0, -0.12)) + trunk = (surface - d * inside, surface + d * 0.4) + specs.append(trunk) + mid = surface + d * 0.2 + specs.append((mid - Vector((0.0, 0.01, 0.0)), mid + Vector((0.0, 0.18, -0.05)))) + specs.append((Vector((-0.02, -0.12, 0.125)), Vector((-0.02, 0.12, 0.125)))) # the vein lies along the top + for start, end in specs: + matrix, depth, radius, segments = tube(start, end, 0.015 if end.z > 0.1 else 0.006) + bmesh.ops.create_cone(bm, cap_ends=True, segments=segments, radius1=radius, radius2=radius, depth=depth, matrix=matrix) + bmesh.ops.subdivide_edges(bm, edges=[e for e in bm.edges if e.calc_length() > 0.05], cuts=15, use_grid_fill=True) + mesh = bpy.data.meshes.new("Whale") + body.to_mesh(mesh) + body.free() + mesh.uv_layers.new(name="UVMap") + tubes = bpy.data.meshes.new("WhaleTubes") + bm.to_mesh(tubes) + bm.free() + obj = bpy.data.objects.new("Whale", mesh) + other = bpy.data.objects.new("WhaleTubes", tubes) + for o in (obj, other): + bpy.context.scene.collection.objects.link(o) + mod = obj.modifiers.new("Union", "BOOLEAN") + mod.operation, mod.operand_type, mod.solver, mod.object, mod.use_self = "UNION", "OBJECT", "EXACT", other, True + bpy.context.view_layer.objects.active = obj + bpy.ops.object.modifier_apply(modifier="Union") + bpy.data.objects.remove(other) + bead = bmesh.new() + bmesh.ops.create_uvsphere(bead, u_segments=8, v_segments=6, radius=0.02, matrix=Matrix.Translation((0.3, 0.1, -0.3))) + mesh2 = bpy.data.meshes.new("Bead") + bead.to_mesh(mesh2) + bead.free() + both = bmesh.new() + both.from_mesh(obj.data) + both.from_mesh(mesh2) + both.to_mesh(obj.data) + both.free() + obj.data.uv_layers.new(name="UVMap") if not obj.data.uv_layers else None + bpy.data.meshes.remove(mesh2) + return obj + + +def glb_json(path): + blob = Path(path).read_bytes() + length = struct.unpack_from(" 0 + and arm.data.bones["jaw"].parent.name in body["spine"], body["parts"]) + head, tail = np.array(body["head"]), np.array(body["tail"]) + check("body: the root bone is at the +y end and the object's transform is baked", head[1] > tail[1] + and np.allclose(np.array(whale.matrix_world), np.eye(4), atol=1e-9) and arm.data.bones["spine_00"].parent is None, [head, tail]) +receipt, tendrils = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01) +check("tendrils accepted", receipt["status"] == "accepted", receipt["message"]) +R["tendrils"] = tendrils +if tendrils: + check("tendrils: five chains (the vein folded), the fork made one chain with a rigid branch, the bead attached", + tendrils["chains"] == 5 and tendrils["veinsFolded"] >= 1 and tendrils["branchesRigid"] >= 1 and tendrils["shellsAttached"] >= 1, tendrils) +receipt, colliders = send("brokkr_rig.colliders", object_name="Whale") +check("colliders accepted", receipt["status"] == "accepted", receipt["message"]) +R["colliders"] = colliders +receipt, again = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01) +check("tendrils run again on the same rig gives the same chains", again and tendrils and again["chains"] == tendrils["chains"] + and again["springBones"] == tendrils["springBones"], [again, tendrils]) +receipt, colliders = send("brokkr_rig.colliders", object_name="Whale") +R["colliders"] = colliders + +# --- export: the five attributes, weights, extension, structure ---------------------------------------------------- +receipt, _ = send("exportGltf", filepath="whale.glb", extras=False, yUp=True, applyModifiers=True) +check("exportGltf accepted", receipt["status"] == "accepted", receipt["message"]) +gltf, blob, bin_at = glb_json(WORK / "whale.glb") +ext = gltf.get("extensions", {}).get("VRMC_springBone") +check("VRMC_springBone is in extensions and extensionsUsed", ext is not None and "VRMC_springBone" in gltf.get("extensionsUsed", []), list(gltf.get("extensions", {}))) +if ext and tendrils and colliders: + check("the springs, joints and colliders are the built ones", len(ext["springs"]) == tendrils["chains"] + and sum(len(s["joints"]) for s in ext["springs"]) == tendrils["springBones"] + and len(ext["colliders"]) == colliders["capsules"] + colliders["spheres"] + and all(s["colliderGroups"] == [0] for s in ext["springs"]) and [g["name"] for g in ext["colliderGroups"]] == ["body"], + [len(ext["springs"]), len(ext["colliders"])]) +prims = [p for m in gltf["meshes"] for p in m["primitives"]] +check("mesh primitives carry exactly the five attributes", all(set(p["attributes"]) == {"POSITION", "NORMAL", "TEXCOORD_0", "JOINTS_0", "WEIGHTS_0"} for p in prims), + [sorted(p["attributes"]) for p in prims]) +worst_sum, worst_count = 0.0, 0 +for p in prims: + if "WEIGHTS_0" not in p["attributes"]: + check("every primitive is skinned", False, sorted(p["attributes"])) + continue + acc = gltf["accessors"][p["attributes"]["WEIGHTS_0"]] + view = gltf["bufferViews"][acc["bufferView"]] + W = np.frombuffer(blob, np.float32, acc["count"] * 4, bin_at + view.get("byteOffset", 0) + acc.get("byteOffset", 0)).reshape(-1, 4) + worst_sum = max(worst_sum, float(np.abs(W.sum(axis=1) - 1).max())) + worst_count = max(worst_count, int((W > 0).sum(axis=1).max())) +check("weights sum to 1 with at most four influences", worst_sum < 1e-5 and worst_count <= 4, [worst_sum, worst_count]) +nodes = gltf["nodes"] +parent = {c: i for i, n in enumerate(nodes) for c in n.get("children", [])} +check("no node carries a matrix and every scale is 1", all("matrix" not in n and all(abs(s - 1) < 1e-4 for s in n.get("scale", (1, 1, 1))) for n in nodes), None) +joints = gltf["skins"][0]["joints"] +check("one skin over every bone", len(gltf["skins"]) == 1 and len(joints) == len(arm.data.bones), [len(joints), len(arm.data.bones)]) +if ext: + in_spring = {j["node"] for s in ext["springs"] for j in s["joints"]} + linear = all(parent.get(s["joints"][0]["node"]) in set(joints) - in_spring and all(parent[s["joints"][k]["node"]] == s["joints"][k - 1]["node"] for k in range(1, len(s["joints"]))) + for s in ext["springs"]) + check("each spring is a linear chain, its first joint hung from a body bone, no bone in two springs", linear + and len(in_spring) == sum(len(s["joints"]) for s in ext["springs"]), None) + check("every segment has length", all(np.linalg.norm(nodes[j["node"]].get("translation", (0, 0, 0))) > 1e-6 for s in ext["springs"] for j in s["joints"][1:]), None) + check("colliders sit on body bones", all(c["node"] in set(joints) - in_spring for c in ext["colliders"]), None) + swing = np.array([[1.0, 0, 0], [0, 0, 1.0], [0, -1.0, 0]]) + where = [world_of(nodes, parent, j["node"])[:3, 3] for s in ext["springs"] for j in s["joints"]] + expect = [swing @ np.array(arm.matrix_world @ arm.data.bones[nodes[j["node"]]["name"]].head_local) for s in ext["springs"] for j in s["joints"]] + check("every joint's node stands where its bone's head is in the scene", np.allclose(where, expect, atol=1e-4), float(np.abs(np.array(where) - np.array(expect)).max())) +R["glb"] = {"nodes": len(nodes), "joints": len(joints), "springs": len(ext["springs"]) if ext else 0, "colliders": len(ext["colliders"]) if ext else 0} +Path(OUT + ".glb").write_bytes((WORK / "whale.glb").read_bytes()) + +# --- determinism, yUp, and a scene with no rig ------------------------------------------------------------------------ +send("exportGltf", filepath="again.glb", extras=False, yUp=True, applyModifiers=True) +a, b = glb_json(WORK / "whale.glb")[0], glb_json(WORK / "again.glb")[0] +check("two exports have identical JSON chunks", json.dumps(a, sort_keys=True) == json.dumps(b, sort_keys=True), None) +send("exportGltf", filepath="flat.glb", extras=False, yUp=False, applyModifiers=True) +flat, _, _ = glb_json(WORK / "flat.glb") +fext = flat.get("extensions", {}).get("VRMC_springBone") +if ext and fext: + nodes_f = flat["nodes"] + parent_f = {c: i for i, n in enumerate(nodes_f) for c in n.get("children", [])} + names = {n["name"]: i for i, n in enumerate(nodes)} + + def collider_world(gl, nd, par, c, key): + return (world_of(nd, par, c["node"]) @ np.append(c["shape"][list(c["shape"])[0]][key], 1.0))[:3] + + pairs = [(collider_world(gltf, nodes, parent, c, "offset"), collider_world(flat, nodes_f, parent_f, f, "offset")) + for c, f in zip(ext["colliders"], fext["colliders"])] + check("yUp false: a collider's node-local offset composes to the same scene point (up to the axis swing)", + bool(pairs) and all(np.allclose(up, swing @ flat_point, atol=1e-4) for up, flat_point in pairs), pairs[:1]) +bpy.ops.mesh.primitive_cube_add() +cube = bpy.context.active_object +cube.name = "Cube" +send("exportGltf", filepath="cube.glb", extras=False, yUp=True, applyModifiers=True, selection=["Cube"]) +cube_json, _, _ = glb_json(WORK / "cube.glb") +check("a scene with no rig springs exports no VRMC_springBone", "VRMC_springBone" not in cube_json.get("extensions", {}) + and "VRMC_springBone" not in cube_json.get("extensionsUsed", []), list(cube_json.get("extensions", {}))) + +R["ok"] = all(c["ok"] for c in R["checks"]) +Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") +for c in R["checks"]: + print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True) +sys.exit(0 if R["ok"] else 1) diff --git a/surfaces/blender/tests/live/rig.result.json b/surfaces/blender/tests/live/rig.result.json new file mode 100644 index 0000000..3cbaafd --- /dev/null +++ b/surfaces/blender/tests/live/rig.result.json @@ -0,0 +1,390 @@ +{ + "blender": "5.3.0", + "checks": [ + { + "name": "host file admitted", + "ok": true, + "detail": [ + "brokkr_mesh_polish.audit", + "brokkr_mesh_polish.repair", + "brokkr_mesh_polish.orient", + "brokkr_mesh_polish.delight", + "brokkr_mesh_polish.scrub_markings", + "brokkr_mesh_polish.cut_parts", + "brokkr_mesh_polish.pick", + "brokkr_rig.body", + "brokkr_rig.tendrils", + "brokkr_rig.colliders" + ] + }, + { + "name": "fixture: one fused shell and a detached bead", + "ok": true, + "detail": { + "Whale": { + "triangles": 3094, + "vertices": 1551, + "weldedVertices": 1549, + "extent": [ + 1.0, + 0.451844, + 0.615025 + ], + "surfaceArea": 0.6858676781563833, + "degenerateTriangles": 0, + "edges": 4635, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "collapsedTriangles": 4, + "windingAgainstNormals": 1, + "shells": 2, + "shellTriangles": [ + 3014, + 80 + ], + "uvIslands": 721, + "uvMirroredTriangles": 1, + "uvZeroAreaTriangles": 1508, + "uvOutsideUnitTriangles": 0, + "uvCoverage": 1.0, + "uvOverlap": 1.0, + "baseColorImage": "", + "baseColorSize": [ + 0, + 0 + ], + "customNormals": false + } + } + }, + { + "name": "repair accepted", + "ok": true, + "detail": "Operator brokkr_mesh_polish.repair finished." + }, + { + "name": "orient accepted", + "ok": true, + "detail": "Operator brokkr_mesh_polish.orient finished." + }, + { + "name": "body accepted", + "ok": true, + "detail": "Operator brokkr_rig.body finished." + }, + { + "name": "body: a spine of six, a jaw bone parented to a spine bone", + "ok": true, + "detail": [ + { + "name": "jaw", + "root": [ + -0.157115, + 0.175099, + 0.032488 + ], + "tail": [ + -0.15589, + 0.217733, + 0.04605 + ], + "triangles": 91 + } + ] + }, + { + "name": "body: the root bone is at the +y end and the object's transform is baked", + "ok": true, + "detail": [ + "[-0.183123 0.5 -0.039007]", + "[-0.16983 -0.5 -0.027336]" + ] + }, + { + "name": "tendrils accepted", + "ok": true, + "detail": "Operator brokkr_rig.tendrils finished." + }, + { + "name": "tendrils: five chains (the vein folded), the fork made one chain with a rigid branch, the bead attached", + "ok": true, + "detail": { + "object": "Whale", + "armature": "Whale.rig", + "bodyVertices": 913, + "chains": 5, + "springBones": 50, + "branchesRigid": 1, + "veinsFolded": 10, + "shellsAttached": 1, + "unreachedVertices": 42, + "rings": 59, + "shapeDiameterMedian": 0.15453927963972092, + "tau": 0.05000000074505806, + "band": 0.03999999910593033 + } + }, + { + "name": "colliders accepted", + "ok": true, + "detail": "Operator brokkr_rig.colliders finished." + }, + { + "name": "tendrils run again on the same rig gives the same chains", + "ok": true, + "detail": [ + { + "object": "Whale", + "armature": "Whale.rig", + "bodyVertices": 913, + "chains": 5, + "springBones": 50, + "branchesRigid": 1, + "veinsFolded": 10, + "shellsAttached": 1, + "unreachedVertices": 42, + "rings": 59, + "shapeDiameterMedian": 0.15453927963972092, + "tau": 0.05000000074505806, + "band": 0.03999999910593033 + }, + { + "object": "Whale", + "armature": "Whale.rig", + "bodyVertices": 913, + "chains": 5, + "springBones": 50, + "branchesRigid": 1, + "veinsFolded": 10, + "shellsAttached": 1, + "unreachedVertices": 42, + "rings": 59, + "shapeDiameterMedian": 0.15453927963972092, + "tau": 0.05000000074505806, + "band": 0.03999999910593033 + } + ] + }, + { + "name": "exportGltf accepted", + "ok": true, + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-rig-live-hx2wf__p\\whale.glb (301168 bytes)." + }, + { + "name": "VRMC_springBone is in extensions and extensionsUsed", + "ok": true, + "detail": [ + "VRMC_springBone" + ] + }, + { + "name": "the springs, joints and colliders are the built ones", + "ok": true, + "detail": [ + 5, + 7 + ] + }, + { + "name": "mesh primitives carry exactly the five attributes", + "ok": true, + "detail": [ + [ + "JOINTS_0", + "NORMAL", + "POSITION", + "TEXCOORD_0", + "WEIGHTS_0" + ] + ] + }, + { + "name": "weights sum to 1 with at most four influences", + "ok": true, + "detail": [ + 1.1920928955078125e-07, + 4 + ] + }, + { + "name": "no node carries a matrix and every scale is 1", + "ok": true, + "detail": null + }, + { + "name": "one skin over every bone", + "ok": true, + "detail": [ + 57, + 57 + ] + }, + { + "name": "each spring is a linear chain, its first joint hung from a body bone, no bone in two springs", + "ok": true, + "detail": null + }, + { + "name": "every segment has length", + "ok": true, + "detail": null + }, + { + "name": "colliders sit on body bones", + "ok": true, + "detail": null + }, + { + "name": "every joint's node stands where its bone's head is in the scene", + "ok": true, + "detail": 7.357579227540434e-07 + }, + { + "name": "two exports have identical JSON chunks", + "ok": true, + "detail": null + }, + { + "name": "yUp false: a collider's node-local offset composes to the same scene point (up to the axis swing)", + "ok": true, + "detail": [ + [ + "[-0.183123 -0.039007 -0.5 ]", + "[-0.183123 0.5 -0.039007]" + ] + ] + }, + { + "name": "a scene with no rig springs exports no VRMC_springBone", + "ok": true, + "detail": [] + } + ], + "hostErrors": [], + "hostRows": [ + "brokkr_mesh_polish.audit", + "brokkr_mesh_polish.repair", + "brokkr_mesh_polish.orient", + "brokkr_mesh_polish.delight", + "brokkr_mesh_polish.scrub_markings", + "brokkr_mesh_polish.cut_parts", + "brokkr_mesh_polish.pick", + "brokkr_rig.body", + "brokkr_rig.tendrils", + "brokkr_rig.colliders" + ], + "audit": { + "Whale": { + "triangles": 3094, + "vertices": 1551, + "weldedVertices": 1549, + "extent": [ + 1.0, + 0.451844, + 0.615025 + ], + "surfaceArea": 0.6858676781563833, + "degenerateTriangles": 0, + "edges": 4635, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "collapsedTriangles": 4, + "windingAgainstNormals": 1, + "shells": 2, + "shellTriangles": [ + 3014, + 80 + ], + "uvIslands": 721, + "uvMirroredTriangles": 1, + "uvZeroAreaTriangles": 1508, + "uvOutsideUnitTriangles": 0, + "uvCoverage": 1.0, + "uvOverlap": 1.0, + "baseColorImage": "", + "baseColorSize": [ + 0, + 0 + ], + "customNormals": false + } + }, + "body": { + "object": "Whale", + "armature": "Whale.rig", + "created": true, + "spine": [ + "spine_00", + "spine_01", + "spine_02", + "spine_03", + "spine_04", + "spine_05" + ], + "parts": [ + { + "name": "jaw", + "root": [ + -0.157115, + 0.175099, + 0.032488 + ], + "tail": [ + -0.15589, + 0.217733, + 0.04605 + ], + "triangles": 91 + } + ], + "head": [ + -0.183123, + 0.5, + -0.039007 + ], + "tail": [ + -0.16983, + -0.5, + -0.027336 + ], + "axis": [ + 0.0, + 1.0, + 0.0 + ], + "vertices": 1546, + "weldedVertices": 1546 + }, + "tendrils": { + "object": "Whale", + "armature": "Whale.rig", + "bodyVertices": 913, + "chains": 5, + "springBones": 50, + "branchesRigid": 1, + "veinsFolded": 10, + "shellsAttached": 1, + "unreachedVertices": 42, + "rings": 59, + "shapeDiameterMedian": 0.15453927963972092, + "tau": 0.05000000074505806, + "band": 0.03999999910593033 + }, + "colliders": { + "capsules": 6, + "spheres": 1, + "shrunk": 4, + "dropped": 0, + "skipped": 0, + "object": "Whale", + "armature": "Whale.rig", + "springJoints": 45 + }, + "glb": { + "nodes": 59, + "joints": 57, + "springs": 5, + "colliders": 7 + }, + "ok": true +} \ No newline at end of file diff --git a/surfaces/blender/tests/test_rig.py b/surfaces/blender/tests/test_rig.py new file mode 100644 index 0000000..35bcf2b --- /dev/null +++ b/surfaces/blender/tests/test_rig.py @@ -0,0 +1,266 @@ +"""Rig builder tests. No Blender: the arithmetic in brokkr_rig/core.py on a hand-built tube graph with one fork, the +host action file against Brokkr's own checker, and the shared cut-root formula. + +Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; skipped without it) +The operators and the exporter hook are exercised in a real Blender by tests/live/rig.py; the runtime's own parse +of the GLB is Aetheria's SpringRigVerify.VerifyGlb. + +Bounds follow lodur:ruling:deterministic-bound-margin: a deterministic reading is exact here, so each assertion is +the built value, and each names the mutant it kills. +""" +from __future__ import annotations + +import importlib +import importlib.util +import json +import re +import sys +import types +import unittest +from pathlib import Path + +SURFACE = Path(__file__).resolve().parents[1] +for name in ("brokkr_bridge", "brokkr_mesh_polish"): + package = types.ModuleType(name) + package.__path__ = [str(SURFACE / name)] + sys.modules.setdefault(name, package) +from brokkr_bridge import action_table as at # noqa: E402 + +try: + import numpy as np +except ImportError: # pragma: no cover + np = None + +if np is not None: + polish = importlib.import_module("brokkr_mesh_polish.core") + spec = importlib.util.spec_from_file_location("brokkr_rig_core", SURFACE / "brokkr_rig" / "core.py") + core = importlib.util.module_from_spec(spec) + spec.loader.exec_module(core) + +BAND, TAU = 0.25, 0.1 + + +def tube_graph(vein: bool = True): + """A body of three stations (thick), a trunk of nine stations along x that forks at station 5 into a branch of + three along y, and a short vein of two stations off the body. Every station is two vertices 0.01 apart, so a + ring is a handful of vertices. Distances from the body run .11 per trunk station: bands 0,0,1,1,2,2,3,3,3.""" + V, E, sd = [], [], [] + + def station(x, y, thick=False): + a = len(V) + V.extend([(x, y, 0.0), (x, y, 0.01)]) + sd.extend([1.0 if thick else 0.01] * 2) + E.append((a, a + 1)) + return a + + def join(a, b): + E.extend([(a, b), (a + 1, b + 1), (a, b + 1), (a + 1, b)]) + + body = [station(-0.2 + 0.1 * i, 0.0, True) for i in range(3)] + for a, b in zip(body, body[1:]): + join(a, b) + trunk, last = [], body[-1] + for k in range(1, 10): + trunk.append(station(0.11 * k, 0.0)) + join(last, trunk[-1]) + last = trunk[-1] + branch, last = [], trunk[4] + for k in range(1, 4): + branch.append(station(0.55, 0.11 * k)) + join(last, branch[-1]) + last = branch[-1] + veins, last = [], body[0] + for k in range(1, 3) if vein else (): + veins.append(station(-0.2, 0.11 * k)) + join(last, veins[-1]) + last = veins[-1] + return np.array(V), np.array(E), np.array(sd), {"body": body, "trunk": trunk, "branch": branch, "vein": veins} + + +def extract(fold_bands=1.5, min_joints=1, vein=True): + V, E, sd, at_ = tube_graph(vein) + return V, E, sd, at_, core.extract(V, E, sd, TAU, BAND, 0.0, fold_bands, min_joints) + + +class RingTests(unittest.TestCase): + @unittest.skipIf(np is None, "numpy") + def test_rings_make_the_tree(self): + """Dies if a ring's parent is taken from its own band.""" + V, E, sd, s, f = extract(vein=False) + self.assertEqual(int(f.body.sum()), 6) + trunk_rings = [int(f.ring[s["trunk"][i]]) for i in (0, 2, 4, 6)] + self.assertEqual([int(f.band[r]) for r in trunk_rings], [0, 1, 2, 3]) + self.assertEqual(len(f.parent), 5) + self.assertEqual([int(f.parent[r]) for r in trunk_rings], [-1, trunk_rings[0], trunk_rings[1], trunk_rings[2]]) + branch_ring = int(f.ring[s["branch"][2]]) + self.assertNotEqual(branch_ring, trunk_rings[3]) + self.assertEqual(int(f.parent[branch_ring]), trunk_rings[2]) + self.assertEqual(int(f.band[branch_ring]), 3) + self.assertEqual([int(r) for r in np.flatnonzero(f.parent < 0)], [trunk_rings[0]]) + for r in range(5): + self.assertNotEqual(int(f.band[f.parent[r]]) if f.parent[r] >= 0 else -1, int(f.band[r])) + + @unittest.skipIf(np is None, "numpy") + def test_main_path_and_tip(self): + """Dies without the tip or with the branch as a second spring.""" + V, E, sd, s, f = extract(vein=False) + self.assertEqual(len(f.chains), 1) + chain = f.chains[0] + trunk_rings = [int(f.ring[s["trunk"][i]]) for i in (0, 2, 4, 6)] + self.assertEqual(chain.rings, trunk_rings) + self.assertFalse(chain.folded) + branch_ring = int(f.ring[s["branch"][2]]) + self.assertFalse(bool(f.on_main[branch_ring])) + self.assertEqual(int(f.fork[branch_ring]), trunk_rings[2]) + springs = core.plan(V, sd, f, BAND) + self.assertEqual(len(springs), 1) + spring = springs[0] + self.assertEqual(len(spring.pos), 5) # four rings and the tip + tip = s["trunk"][8] + farthest = tip + int(np.argmax(f.d[[tip, tip + 1]])) + self.assertTrue(np.allclose(spring.pos[-1], V[farthest])) + self.assertGreater(float(np.linalg.norm(spring.pos[-1] - spring.pos[-2])), 0.0) + # the side branch's vertices weight 1 to the fork's bone + body_idx, body_w = np.zeros((len(V), 4), dtype=np.int64), np.zeros((len(V), 4)) + body_w[:, 0] = 1.0 + idx, w, start = core.tendril_weights(V, E, f, springs, body_idx, body_w, 1, BAND, 0.5) + for v in (s["branch"][1], s["branch"][2]): + self.assertEqual((int(idx[v, 0]), float(w[v, 0])), (start[0] + 2, 1.0)) + + @unittest.skipIf(np is None, "numpy") + def test_vein_folds(self): + """Dies with fold off or fold always on.""" + for bands, folded in ((0.0, [False, False]), (1.5, [True, False]), (4.0, [True, True])): + *_, f = extract(fold_bands=bands) + self.assertEqual(sorted(c.folded for c in f.chains), sorted(folded), bands) + *_, f = extract(min_joints=3) + self.assertEqual(sorted(c.folded for c in f.chains), [False, True]) # the vein has two rings + + +class WeightTests(unittest.TestCase): + @unittest.skipIf(np is None, "numpy") + def test_weights_partition(self): + """Dies if weights go to bone k + 1 (the joint the segment ends at).""" + V, E, sd, s, f = extract(vein=False) + springs = core.plan(V, sd, f, BAND) + body_idx, body_w = np.zeros((len(V), 4), dtype=np.int64), np.zeros((len(V), 4)) + body_w[:, 0] = 1.0 + idx, w, start = core.tendril_weights(V, E, f, springs, body_idx, body_w, 1, BAND, 0.5) + self.assertTrue(np.allclose(w.sum(axis=1), 1.0, atol=1e-6)) + self.assertLessEqual(int((w > 0).sum(axis=1).max()), 4) + self.assertTrue((idx[w > 0] < start[0] + len(springs[0].pos)).all()) + reach = 0.5 * BAND + D = springs[0].dist + for v in (s["trunk"][2], s["trunk"][3]): # outside the blend: bone k alone; inside: linear from bone k - 1 + d = f.d[v] + k = int(np.searchsorted(D, d, side="right")) - 1 + t = min((d - D[k]) / reach, 1.0) + got = {int(b): float(x) for b, x in zip(idx[v], w[v]) if x > 0} + if t >= 1.0: + self.assertEqual(got, {start[0] + k: 1.0}) + else: + self.assertAlmostEqual(got[start[0] + k], t, places=9) + self.assertAlmostEqual(got[start[0] + k - 1], 1.0 - t, places=9) + outside = [v for v in s["trunk"] if (lambda k: k >= 0 and (f.d[v] - D[k]) / reach >= 1.0)(int(np.searchsorted(D, f.d[v], side="right")) - 1)] + self.assertTrue(outside) + # a vertex at the body is the body's; one in the blend is part body + near = s["trunk"][0] + self.assertGreater(float(w[near][idx[near] == 0].sum()) if (idx[near] == 0).any() else 0.0, 0.0) + + @unittest.skipIf(np is None, "numpy") + def test_axial_weights_are_linear_between_knots_and_sum_to_one(self): + knots = np.array([0.0, 1.0, 3.0]) + W = core.axial_weights(np.array([-1.0, 0.0, 0.5, 1.0, 2.0, 3.0, 9.0]), knots) + self.assertTrue(np.allclose(W.sum(axis=1), 1.0)) + self.assertTrue(np.allclose(W[[0, 1, 3, 5, 6]], np.eye(3)[[0, 0, 1, 2, 2]])) + self.assertTrue(np.allclose(W[2], [0.5, 0.5, 0.0]) and np.allclose(W[4], [0.0, 0.5, 0.5])) + + @unittest.skipIf(np is None, "numpy") + def test_top4_keeps_the_heaviest_and_normalises(self): + idx, w = core.top4(np.array([[0.1, 0.5, 0.2, 0.15, 0.05]])) + self.assertEqual(sorted(idx[0].tolist()), [0, 1, 2, 3]) + self.assertAlmostEqual(float(w.sum()), 1.0, places=12) + self.assertAlmostEqual(float(w[0, 0]), 0.5 / 0.95, places=12) + + +class ColliderTests(unittest.TestCase): + @unittest.skipIf(np is None, "numpy") + def test_colliders_clear_rest(self): + """Dies without the shrink.""" + a, b = np.array([0.0, 0.0, 0.0]), np.array([1.0, 0.0, 0.0]) + joints = np.array([[0.5, 0.4, 0.0], [2.0, 0.0, 0.0]]) + hit = np.array([0.05, 0.05]) + radius = core.clear_radius(0.5, joints, hit, a, b) + self.assertAlmostEqual(radius, 0.35, places=12) + self.assertTrue((core.segment_distance(joints, a, b) - hit >= radius - 1e-12).all()) + self.assertFalse((core.segment_distance(joints, a, b) - hit >= 0.5).all()) + self.assertEqual(core.clear_radius(0.2, joints, hit, a, b), 0.2) # already clear: unchanged + self.assertAlmostEqual(core.clear_radius(1.0, joints[:1], hit[:1], a, a), float(np.linalg.norm([0.5, 0.4])) - 0.05, places=12) # a sphere + + @unittest.skipIf(np is None, "numpy") + def test_capsule_and_sphere_sizes(self): + ring = np.array([[np.cos(t), np.sin(t), z] for z in (0.2, 0.5, 0.8) for t in np.linspace(0, 6.2, 12)]) + self.assertAlmostEqual(core.capsule_radius(ring, np.array([0.0, 0.0, 0.0]), np.array([0.0, 0.0, 1.0]), 0.8), 0.8, places=9) + centre, radius = core.sphere_fit(ring[:12], 0.5) + self.assertTrue(np.allclose(centre[:2], ring[:12, :2].mean(axis=0))) + self.assertAlmostEqual(radius, 0.5 * float(np.median(np.linalg.norm(ring[:12] - centre, axis=1))), places=12) + + +class SharedRootTests(unittest.TestCase): + @unittest.skipIf(np is None, "numpy") + def test_boundary_root_equals_the_former_inline_formula(self): + mids = np.array([[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [2.0, 4.0, 0.0]]) + lengths = np.array([1.0, 1.0, 2.0]) + inline = (mids * lengths[:, None]).sum(axis=0) / lengths.sum() + self.assertTrue(np.array_equal(polish.boundary_root(mids, lengths), inline)) + self.assertTrue(np.array_equal(polish.boundary_root(np.zeros((0, 3)), np.zeros(0)), np.zeros(3))) + source = (SURFACE / "brokkr_mesh_polish" / "__init__.py").read_text(encoding="utf-8") + self.assertIn("core.boundary_root(mids, lengths)", source) + self.assertNotIn("(mids * lengths[:, None]).sum(axis=0) / lengths.sum() if len(cut)", source) + + +class HostFileTests(unittest.TestCase): + def setUp(self): + self.document = json.loads((SURFACE / "brokkr_rig" / "brokkr_actions.json").read_text(encoding="utf-8")) + + def test_brokkr_admits_the_file(self): + """rows-check: Brokkr's own host-file checker.""" + at.check_host(self.document, at.table()["charsets"]) + + def test_every_row_names_an_operator_and_property_the_add_on_defines(self): + source = (SURFACE / "brokkr_rig" / "__init__.py").read_text(encoding="utf-8") + for row in self.document["actions"]: + self.assertIn(f'bl_idname = "{row["name"]}"', source) + self.assertEqual(row.get("result"), "brokkr_mesh_polish_result") + body = source.split(f'bl_idname = "{row["name"]}"')[1].split("def work")[0] + for field in row["fields"]: + self.assertIn(f" {field['name']}: bpy.props.", body, f"{row['name']}.{field['name']}") + + def test_a_valid_intent_is_admitted_and_a_bound_miss_is_refused(self): + host = [{**row, "host": "brokkr_rig"} for row in self.document["actions"]] + envelope = {"schema": "brokkr.blender.command_intent.v0", "commandId": "t-1", "requestedBy": "test/driver"} + admitted = at.validate({**envelope, "action": "brokkr_rig.tendrils", "object_name": "Hull"}, host) + self.assertEqual(admitted["tau"], 0.04) + with self.assertRaises(at.IntentInvalid): + at.validate({**envelope, "action": "brokkr_rig.tendrils", "object_name": "Hull", "tau": 0.9}, host) + + +class OwnershipTests(unittest.TestCase): + """The negative patterns of the cut: the contract's refusals, a second exporter and the bridge stay out of brokkr_rig.""" + PATTERNS = (r"non-unit scale|first joint|named twice|not a skin joint", r"brokkr_bridge", r"export_scene\.gltf|struct\.pack") + + def sources(self): + return {p.name: p.read_text(encoding="utf-8") for p in (SURFACE / "brokkr_rig").glob("*.py")} + + def test_no_pattern_matches_the_package(self): + for pattern in self.PATTERNS: + for name, text in self.sources().items(): + self.assertIsNone(re.search(pattern, text), f"{pattern} in {name}") + + def test_the_patterns_bite(self): + for pattern, planted in zip(self.PATTERNS, ("Node 3 has a non-unit scale", "from brokkr_bridge import x", "struct.pack('