diff --git a/surfaces/blender/brokkr_rig/__init__.py b/surfaces/blender/brokkr_rig/__init__.py index 1302b3d..b153ccd 100644 --- a/surfaces/blender/brokkr_rig/__init__.py +++ b/surfaces/blender/brokkr_rig/__init__.py @@ -33,6 +33,8 @@ 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") +OPEN_SHEET_WARN = 0.042 # the share of the mesh one chain may hold before tendrils warns: the geometric mean of the lace leviathan (0.0227) and the skeletal hull (0.0774), docs/rig.md +SPINE_THICK = 0.04 # shape diameter, as a share of the longest side, a triangle needs to take a spine seed GRAVITY_DOWN = (0.0, 0.0, -1.0) # Blender world; the exporter hook turns it into glTF world @@ -115,6 +117,44 @@ def write_weights(obj, names: list, ids: np.ndarray, idx: np.ndarray, w: np.ndar groups[b].add([vertex], weight, "REPLACE") +SOURCE = ("rig_src_i0", "rig_src_i1", "rig_src_i2", "rig_src_i3", "rig_src_w0", "rig_src_w1", "rig_src_w2", "rig_src_w3") + + +def write_source(obj, names: list, ids: np.ndarray, idx: np.ndarray, w: np.ndarray): + """Keep the body's own weights on the mesh (eight point attributes and the bone names they index), so tendrils, + which rewrite the vertex groups, always start again from them: a rerun is a function of its inputs.""" + for name in SOURCE: + if name in obj.data.attributes: + obj.data.attributes.remove(obj.data.attributes[name]) + for slot in range(4): + for prefix, column in (("rig_src_i", idx[ids, slot]), ("rig_src_w", w[ids, slot])): + attribute = obj.data.attributes.new(f"{prefix}{slot}", "FLOAT", "POINT") + attribute.data.foreach_set("value", column.astype(np.float32)) + obj["rig_src_bones"] = json.dumps(names) + + +def read_source(obj, names: list, ids: np.ndarray, count: int) -> np.ndarray: + """Dense body weights (welded vertices, names) from write_source; Refused when body has not run or a bone it + named is gone.""" + if "rig_src_bones" not in obj or SOURCE[0] not in obj.data.attributes: + raise Refused(f"Object {obj.name!r} has no body weights: run brokkr_rig.body first.") + kept = json.loads(obj["rig_src_bones"]) + missing = [n for n in kept if n not in names] + if missing: + raise Refused(f"Body bone {missing[0]!r} is gone from the armature: run brokkr_rig.body again.") + column = [names.index(n) for n in kept] + n = len(obj.data.vertices) + own = np.zeros((n, len(names))) + for slot in range(4): + i, v = np.empty(n, dtype=np.float32), np.empty(n, dtype=np.float32) + obj.data.attributes[f"rig_src_i{slot}"].data.foreach_get("value", i) + obj.data.attributes[f"rig_src_w{slot}"].data.foreach_get("value", v) + np.add.at(own, (np.arange(n), np.array(column)[i.astype(np.int64)]), v.astype(np.float64)) + out = np.zeros((count, len(names))) + out[ids] = own + return out + + 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} @@ -222,7 +262,11 @@ class BROKKR_RIG_OT_body(PolishOperator): 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]])] + sd = shape_diameter(w) # the spine's seeds take body surface: a triangle with a thin vertex is a tendril or a sheet + solid = (sd[w.TW] >= SPINE_THICK * w.length).all(axis=1) + pool = np.flatnonzero(solid) if solid.any() else np.arange(len(w.TW)) + nearest_solid = lambda point: int(pool[np.argmin(((centroid[pool] - np.asarray(point)) ** 2).sum(axis=1))]) # noqa: E731 + placed = [(nearest_solid(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 @@ -269,13 +313,23 @@ class BROKKR_RIG_OT_body(PolishOperator): bone.parent = edits[names[int(np.argmin([core.segment_distance(head[None], a, b)[0] for a, b in spine]))]] else: arm = existing + cleared = 0 + if existing is not None: # chains hang on the old weights: they go, and tendrils runs again + with edit_mode(context, arm) as edits: + for old in [e for e in edits if CHAIN in e]: + edits.remove(old) + cleared += 1 + for bone in arm.data.bones: + if COLLIDERS in bone: + del bone[COLLIDERS] write_weights(obj, bones, w.ids, idx, weight) + write_source(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, + return {"object": obj.name, "armature": arm.name, "created": existing is None, "chainBonesCleared": cleared, "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), @@ -309,13 +363,7 @@ class BROKKR_RIG_OT_tendrils(PolishOperator): 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))] + Wb = read_source(obj, body_names, w.ids, w.count) bidx, bw = core.top4(Wb) scale, band = w.length, self.band * w.length sd = shape_diameter(w) @@ -345,13 +393,13 @@ class BROKKR_RIG_OT_tendrils(PolishOperator): 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 + stiffness, hit = core.joint_params(spring.sd, self.stiffness, self.stiffness_tip_ratio, self.hit_scale) 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[STIFFNESS] = float(stiffness[k]) bone[DRAG], bone[GRAVITY] = self.drag, self.gravity_power - bone[HIT] = float(0.5 * spring.sd[k] * self.hit_scale) + bone[HIT] = float(hit[k]) 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] @@ -359,7 +407,19 @@ class BROKKR_RIG_OT_tendrils(PolishOperator): 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})) + on_chain = (found.ring >= 0) & np.isin(found.tree[np.maximum(found.ring, 0)], [c.tree for c in kept]) + kept_trees = [c.tree for c in kept] + trees = found.tree[found.ring[on_chain]] + open_share = float(np.bincount(trees).max() / w.count) if on_chain.any() else 0.0 # the biggest chain's share of the mesh + ring_of = np.where(found.ring >= 0, found.tree[np.maximum(found.ring, 0)], -1) + a, b = ring_of[w.E[:, 0]], ring_of[w.E[:, 1]] + fused = int(((a >= 0) & (b >= 0) & (a != b) & np.isin(a, [c.tree for c in kept]) & np.isin(b, [c.tree for c in kept])).sum()) + warnings = [] + if open_share >= OPEN_SHEET_WARN: + warnings.append(f"one chain holds {open_share:.0%} of the mesh: a plate of a hull may have become a chain; " + "raise tau or fold_bands, or rig a mesh whose tendrils are tubes") return {"object": obj.name, "armature": arm.name, "bodyVertices": int(found.body.sum()), "chains": len(springs), + "chainVertexShare": float(on_chain.mean()), "largestChainShare": open_share, "fusedContacts": fused, "warnings": warnings, "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)), @@ -389,7 +449,7 @@ class BROKKR_RIG_OT_colliders(PolishOperator): 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} + made = {"capsules": 0, "spheres": 0, "shrunk": 0, "dropped": 0, "skipped": 0, "shrinks": [], "shrunkMax": 0.0} for bone in body: if COLLIDERS in bone: del bone[COLLIDERS] @@ -408,6 +468,8 @@ class BROKKR_RIG_OT_colliders(PolishOperator): cleared = core.clear_radius(radius, joints, hit, offset, end) if cleared < radius: made["shrunk"] += 1 + made["shrinks"].append({"bone": bone.name, "before": round(float(radius), 6), "after": round(float(max(cleared, 0.0)), 6)}) + made["shrunkMax"] = round(max(made["shrunkMax"], float(1.0 - max(cleared, 0.0) / radius)), 4) if cleared <= 0: made["dropped"] += 1 continue diff --git a/surfaces/blender/brokkr_rig/core.py b/surfaces/blender/brokkr_rig/core.py index 5dde1d9..35c8ba9 100644 --- a/surfaces/blender/brokkr_rig/core.py +++ b/surfaces/blender/brokkr_rig/core.py @@ -347,3 +347,12 @@ def clear_radius(radius: float, joints: np.ndarray, hit: np.ndarray, a: np.ndarr if not len(joints): return radius return min(radius, float((segment_distance(joints, a, b) - hit).min())) + + +# --- spring parameters ----------------------------------------------------------------------------------- + +def joint_params(sd: np.ndarray, stiffness: float, tip_ratio: float, hit_scale: float) -> tuple[np.ndarray, np.ndarray]: + """(stiffness, hit radius) per joint of a spring whose joints' median shape diameters are sd: stiffness tapers + linearly from the root's value to tip_ratio times it at the tip; the hit radius is half the diameter times hit_scale.""" + last = len(sd) - 1 + return stiffness * (1.0 + (tip_ratio - 1.0) * np.arange(last + 1) / last), 0.5 * np.asarray(sd) * hit_scale diff --git a/surfaces/blender/docs/rig.md b/surfaces/blender/docs/rig.md index 1b3a0b9..cf85323 100644 --- a/surfaces/blender/docs/rig.md +++ b/surfaces/blender/docs/rig.md @@ -48,22 +48,29 @@ 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 +`spine` seeded at the surface nearest each spine joint and the tail point, among triangles whose three vertices have +a shape diameter of at least 0.04 of the longest side (a tendril or a sheet never takes a spine seed); 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. +Chain bones an earlier `tendrils` left on that armature are removed (the report says how many: `chainBonesCleared`), +because they hang on the old weights; run `tendrils` again. 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. +`smooth_rounds` Laplacian rounds over the welded vertex graph, the top 4 kept and normalised. They are also kept on +the mesh (point attributes `rig_src_*` and the object property `rig_src_bones`), because `tendrils` rewrites the +vertex groups. ### 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 +Needs `body` first, and starts from the body's weights kept on the mesh, so a run depends only on the mesh and its +knobs, never on earlier runs. 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. @@ -82,22 +89,30 @@ joint per ring at its centroid, its parent the ring it touches one band nearer. `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. +The report counts chains, spring bones, rigid branches, veins folded, shells attached and unreached vertices, and +gauges the rig: `chainVertexShare`, `largestChainShare` (the biggest chain's share of the mesh) and `fusedContacts` +(mesh edges joining two different chains). `warnings` says when one chain holds 4.2% of the mesh or more, which +is what a hull plate that became a chain looks like (the lace leviathan reads 2.3%, the skeletal and mantle hulls +7.7% and 11.2%; the bound is the geometric mean of the first two). An open sheet reads shape diameter 0, so on a +hull the builder succeeds; read the warning. ### 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. +shrunk until every spring joint past the first stands at least its hit radius outside it at rest. The report lists +each shrink (`shrinks`: bone, before, after) and the largest fraction (`shrunkMax`): where tendrils lie on the +body at rest the rule fits colliders to the gaps between them (the leviathan's spine_07 shrinks by 91%). 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. +is absorbed before the fold rule sees it. Seeds on a smooth surface split by distance alone. A fused generated +mesh joins tendrils that touch: the edges between two chains stretch when the chains move apart (the leviathan has +132 such edges; `fusedContacts` counts them). ## A recipe diff --git a/surfaces/blender/tests/live/rig.py b/surfaces/blender/tests/live/rig.py index 54bc1a4..26de79f 100644 --- a/surfaces/blender/tests/live/rig.py +++ b/surfaces/blender/tests/live/rig.py @@ -186,10 +186,28 @@ if tendrils: receipt, colliders = send("brokkr_rig.colliders", object_name="Whale") check("colliders accepted", receipt["status"] == "accepted", receipt["message"]) R["colliders"] = colliders + + +def skin_state(): + """Every vertex's (group name, weight) pairs and every chain bone's properties, exactly as stored.""" + groups = [g.name for g in whale.vertex_groups] + weights = [sorted((groups[e.group], e.weight) for e in v.groups) for v in whale.data.vertices] + props = {b.name: [b[k] for k in ("rig_chain", "rig_index", "rig_stiffness", "rig_drag", "rig_gravity", "rig_hit_radius")] + for b in arm.data.bones if "rig_chain" in b} + return weights, props + + +first = skin_state() +send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.06, dilate=0.02) +other = skin_state() 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]) +check("tendrils with other knobs changes the skin", other != first, None) +check("tendrils, other knobs, then the first knobs again restores the weights and bone properties exactly", skin_state() == first, None) +check("the tendrils report says what it sees", tendrils and {"warnings", "largestChainShare", "chainVertexShare", "fusedContacts"} <= set(tendrils) + and len(tendrils["warnings"]) == 1 and "one chain holds" in tendrils["warnings"][0], tendrils) # five chains hold 13% each at most: hull-like by the gauge receipt, colliders = send("brokkr_rig.colliders", object_name="Whale") +check("the colliders report lists each shrink", colliders and len(colliders["shrinks"]) == colliders["shrunk"] + and all(x["after"] < x["before"] for x in colliders["shrinks"]), colliders) R["colliders"] = colliders # --- export: the five attributes, weights, extension, structure ---------------------------------------------------- @@ -204,6 +222,12 @@ if ext and tendrils and colliders: 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"])]) +check("the extension is not required", "VRMC_springBone" not in gltf.get("extensionsRequired", []), gltf.get("extensionsRequired")) +if ext: + check("stiffness tapers from the root's 3 to the tip's 1.5 and hit radii are half a tube's diameter or less", + all(abs(s["joints"][0]["stiffness"] - 3.0) < 1e-6 and abs(s["joints"][-1]["stiffness"] - 1.5) < 1e-6 + and all(0 <= j["hitRadius"] <= 0.016 for j in s["joints"]) for s in ext["springs"]), + [[j["stiffness"] for j in ext["springs"][0]["joints"]], [j["hitRadius"] for j in ext["springs"][0]["joints"]]]) 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]) @@ -265,6 +289,23 @@ 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", {}))) +# --- body again on its own armature: the chains go, nothing is left weighing nothing; colliders alone export no springs +chain_bones = sum(1 for b in arm.data.bones if "rig_chain" in b) +receipt, rebody = send("brokkr_rig.body", object_name="Whale", armature_name=arm.name, seeds="jaw=0,0.45,0.05") +check("body again clears the chain bones it would orphan", + rebody and rebody["chainBonesCleared"] == chain_bones > 0 and not any("rig_chain" in b for b in arm.data.bones), rebody) +send("exportGltf", filepath="cleared.glb", extras=False, yUp=True, applyModifiers=True) +cleared_json, _, _ = glb_json(WORK / "cleared.glb") +check("an armature with no chains exports no springs", "VRMC_springBone" not in cleared_json.get("extensions", {}), None) +receipt, lone = send("brokkr_rig.colliders", object_name="Whale") +send("exportGltf", filepath="colliders_only.glb", extras=False, yUp=True, applyModifiers=True) +only_json, _, _ = glb_json(WORK / "colliders_only.glb") +check("colliders without chains export no VRMC_springBone", lone and lone["capsules"] > 0 and "VRMC_springBone" not in only_json.get("extensions", {}) + and "VRMC_springBone" not in only_json.get("extensionsUsed", []), lone) +receipt, rerun = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band=0.04, dilate=0.01) +check("tendrils after the second body rebuilds the same chains", rerun and tendrils and rerun["chains"] == tendrils["chains"] + and rerun["springBones"] == tendrils["springBones"], [rerun, tendrils]) + 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"]: diff --git a/surfaces/blender/tests/live/rig.result.json b/surfaces/blender/tests/live/rig.result.json index 3cbaafd..e00bb76 100644 --- a/surfaces/blender/tests/live/rig.result.json +++ b/surfaces/blender/tests/live/rig.result.json @@ -113,6 +113,12 @@ "armature": "Whale.rig", "bodyVertices": 913, "chains": 5, + "chainVertexShare": 0.36351875808538164, + "largestChainShare": 0.13389391979301424, + "fusedContacts": 0, + "warnings": [ + "one chain holds 13% of the mesh: a plate of a hull may have become a chain; raise tau or fold_bands, or rig a mesh whose tendrils are tubes" + ], "springBones": 50, "branchesRigid": 1, "veinsFolded": 10, @@ -130,45 +136,81 @@ "detail": "Operator brokkr_rig.colliders finished." }, { - "name": "tendrils run again on the same rig gives the same chains", + "name": "tendrils with other knobs changes the skin", "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 - } - ] + "detail": null + }, + { + "name": "tendrils, other knobs, then the first knobs again restores the weights and bone properties exactly", + "ok": true, + "detail": null + }, + { + "name": "the tendrils report says what it sees", + "ok": true, + "detail": { + "object": "Whale", + "armature": "Whale.rig", + "bodyVertices": 913, + "chains": 5, + "chainVertexShare": 0.36351875808538164, + "largestChainShare": 0.13389391979301424, + "fusedContacts": 0, + "warnings": [ + "one chain holds 13% of the mesh: a plate of a hull may have become a chain; raise tau or fold_bands, or rig a mesh whose tendrils are tubes" + ], + "springBones": 50, + "branchesRigid": 1, + "veinsFolded": 10, + "shellsAttached": 1, + "unreachedVertices": 42, + "rings": 59, + "shapeDiameterMedian": 0.15453927963972092, + "tau": 0.05000000074505806, + "band": 0.03999999910593033 + } + }, + { + "name": "the colliders report lists each shrink", + "ok": true, + "detail": { + "capsules": 6, + "spheres": 1, + "shrunk": 4, + "dropped": 0, + "skipped": 0, + "shrinks": [ + { + "bone": "spine_01", + "before": 0.155853, + "after": 0.070036 + }, + { + "bone": "spine_02", + "before": 0.148599, + "after": 0.053107 + }, + { + "bone": "spine_03", + "before": 0.166193, + "after": 0.056984 + }, + { + "bone": "spine_04", + "before": 0.106817, + "after": 0.074496 + } + ], + "shrunkMax": 0.6571, + "object": "Whale", + "armature": "Whale.rig", + "springJoints": 45 + } }, { "name": "exportGltf accepted", "ok": true, - "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-rig-live-hx2wf__p\\whale.glb (301168 bytes)." + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-rig-live-237ky4n3\\whale.glb (301188 bytes)." }, { "name": "VRMC_springBone is in extensions and extensionsUsed", @@ -185,6 +227,37 @@ 7 ] }, + { + "name": "the extension is not required", + "ok": true, + "detail": null + }, + { + "name": "stiffness tapers from the root's 3 to the tip's 1.5 and hit radii are half a tube's diameter or less", + "ok": true, + "detail": [ + [ + 3, + 2.7857142857142856, + 2.5714285714285716, + 2.357142857142857, + 2.142857142857143, + 1.9285714285714284, + 1.7142857142857142, + 1.5 + ], + [ + 0.0059821512550115585, + 0.005849682260304689, + 0.005868155509233475, + 0.005716879619285464, + 0.00568680465221405, + 0.005836397642269731, + 0.005983717972412705, + 0.005983717972412705 + ] + ] + }, { "name": "mesh primitives carry exactly the five attributes", "ok": true, @@ -258,6 +331,126 @@ "name": "a scene with no rig springs exports no VRMC_springBone", "ok": true, "detail": [] + }, + { + "name": "body again clears the chain bones it would orphan", + "ok": true, + "detail": { + "object": "Whale", + "armature": "Whale.rig", + "created": false, + "chainBonesCleared": 50, + "spine": [ + "spine_00", + "spine_01", + "spine_02", + "spine_03", + "spine_04", + "spine_05" + ], + "parts": [ + { + "name": "jaw", + "root": [ + -0.160415, + 0.128395, + 0.030328 + ], + "tail": [ + -0.170113, + 0.140889, + 0.055153 + ], + "triangles": 140 + } + ], + "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 + } + }, + { + "name": "an armature with no chains exports no springs", + "ok": true, + "detail": null + }, + { + "name": "colliders without chains export no VRMC_springBone", + "ok": true, + "detail": { + "capsules": 6, + "spheres": 1, + "shrunk": 0, + "dropped": 0, + "skipped": 0, + "shrinks": [], + "shrunkMax": 0.0, + "object": "Whale", + "armature": "Whale.rig", + "springJoints": 0 + } + }, + { + "name": "tendrils after the second body rebuilds the same chains", + "ok": true, + "detail": [ + { + "object": "Whale", + "armature": "Whale.rig", + "bodyVertices": 913, + "chains": 5, + "chainVertexShare": 0.36351875808538164, + "largestChainShare": 0.13389391979301424, + "fusedContacts": 0, + "warnings": [ + "one chain holds 13% of the mesh: a plate of a hull may have become a chain; raise tau or fold_bands, or rig a mesh whose tendrils are tubes" + ], + "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, + "chainVertexShare": 0.36351875808538164, + "largestChainShare": 0.13389391979301424, + "fusedContacts": 0, + "warnings": [ + "one chain holds 13% of the mesh: a plate of a hull may have become a chain; raise tau or fold_bands, or rig a mesh whose tendrils are tubes" + ], + "springBones": 50, + "branchesRigid": 1, + "veinsFolded": 10, + "shellsAttached": 1, + "unreachedVertices": 42, + "rings": 59, + "shapeDiameterMedian": 0.15453927963972092, + "tau": 0.05000000074505806, + "band": 0.03999999910593033 + } + ] } ], "hostErrors": [], @@ -313,6 +506,7 @@ "object": "Whale", "armature": "Whale.rig", "created": true, + "chainBonesCleared": 0, "spine": [ "spine_00", "spine_01", @@ -360,6 +554,12 @@ "armature": "Whale.rig", "bodyVertices": 913, "chains": 5, + "chainVertexShare": 0.36351875808538164, + "largestChainShare": 0.13389391979301424, + "fusedContacts": 0, + "warnings": [ + "one chain holds 13% of the mesh: a plate of a hull may have become a chain; raise tau or fold_bands, or rig a mesh whose tendrils are tubes" + ], "springBones": 50, "branchesRigid": 1, "veinsFolded": 10, @@ -376,6 +576,29 @@ "shrunk": 4, "dropped": 0, "skipped": 0, + "shrinks": [ + { + "bone": "spine_01", + "before": 0.155853, + "after": 0.070036 + }, + { + "bone": "spine_02", + "before": 0.148599, + "after": 0.053107 + }, + { + "bone": "spine_03", + "before": 0.166193, + "after": 0.056984 + }, + { + "bone": "spine_04", + "before": 0.106817, + "after": 0.074496 + } + ], + "shrunkMax": 0.6571, "object": "Whale", "armature": "Whale.rig", "springJoints": 45 diff --git a/surfaces/blender/tests/test_rig.py b/surfaces/blender/tests/test_rig.py index 35bcf2b..21755b0 100644 --- a/surfaces/blender/tests/test_rig.py +++ b/surfaces/blender/tests/test_rig.py @@ -40,9 +40,10 @@ if np is not None: BAND, TAU = 0.25, 0.1 -def tube_graph(vein: bool = True): +def tube_graph(vein: bool = True, perm=None): """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 + three along y, a short vein of two stations off the body (vein=True also adds a lone far + ring joined by one long edge and a detached shell). 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 = [], [], [] @@ -74,11 +75,28 @@ def tube_graph(vein: bool = True): 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} + lone, shell = [], [] + if vein: + a = len(V) + V.extend([(-0.1, 0.9, 0.0), (-0.1, 0.9, 0.01)]) + sd.extend([0.01, 0.01]) + E.extend([(a, a + 1), (body[1], a), (body[1] + 1, a + 1)]) + lone = [a] + b = len(V) + V.extend([(0.3, 0.0, 0.6), (0.3, 0.0, 0.61)]) + sd.extend([0.01, 0.01]) + E.append((b, b + 1)) + shell = [b] + V, E, sd = np.array(V), np.array(E), np.array(sd) + if perm is not None: # the same graph with its vertices numbered another way + V2, sd2 = np.empty_like(V), np.empty_like(sd) + V2[perm], sd2[perm] = V, sd + V, E, sd = V2, perm[E], sd2 + return V, E, sd, {"body": body, "trunk": trunk, "branch": branch, "vein": veins, "lone": lone, "shell": shell} -def extract(fold_bands=1.5, min_joints=1, vein=True): - V, E, sd, at_ = tube_graph(vein) +def extract(fold_bands=1.5, min_joints=1, vein=True, perm=None): + V, E, sd, at_ = tube_graph(vein, perm) return V, E, sd, at_, core.extract(V, E, sd, TAU, BAND, 0.0, fold_bands, min_joints) @@ -130,14 +148,51 @@ class RingTests(unittest.TestCase): @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])): + for bands, folded in ((0.0, [False] * 3), (1.5, [False, False, True]), (4.0, [True] * 3)): # trunk, a far lone ring, a vein *_, 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 + self.assertEqual(sorted(c.folded for c in f.chains), [False, True, True]) # the vein has two rings, the lone ring one + + + @unittest.skipIf(np is None, "numpy") + def test_the_main_path_is_the_tallest_subtree_however_the_vertices_are_numbered(self): + """Dies if the main path is the shortest subtree, or the lowest ring id.""" + for seed in range(8): + perm = np.random.default_rng(seed).permutation(len(tube_graph(False)[0])) + V, E, sd, s, f = extract(vein=False, perm=perm) + leaf = f.chains[0].rings[-1] + self.assertIn(int(perm[s["trunk"][8]]), np.flatnonzero(f.ring == leaf).tolist(), seed) class WeightTests(unittest.TestCase): + @unittest.skipIf(np is None, "numpy") + def test_a_detached_shell_rides_the_nearest_spring_bone(self): + """Dies if the shell takes the farthest bone, or any other than the nearest.""" + V, E, sd, s, f = extract() + springs = core.plan(V, sd, f, BAND) + trunk = [sp for sp in springs if np.linalg.norm(sp.pos[0] - V[s["trunk"][0]]) < 0.2][0] + 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) + every = np.concatenate([sp.pos for sp in springs]) + owner = np.concatenate([start[c] + np.arange(len(sp.pos)) for c, sp in enumerate(springs)]) + centre = V[s["shell"][0]:s["shell"][0] + 2].mean(axis=0) + near = int(owner[np.argmin(np.linalg.norm(every - centre, axis=1))]) + far = int(owner[np.argmax(np.linalg.norm(every - centre, axis=1))]) + self.assertNotEqual(near, far) + for v in (s["shell"][0], s["shell"][0] + 1): + self.assertEqual((int(idx[v, 0]), float(w[v, 0])), (near, 1.0)) + self.assertIn(near, range(start[springs.index(trunk)], start[springs.index(trunk)] + len(trunk.pos))) + + @unittest.skipIf(np is None, "numpy") + def test_stiffness_tapers_to_the_tip_ratio_and_the_hit_radius_is_half_the_diameter(self): + """Dies if the taper runs tip to root, or the hit radius is a diameter.""" + stiffness, hit = core.joint_params(np.array([0.02, 0.04, 0.06, 0.0]), 3.0, 0.5, 1.0) + self.assertTrue(np.allclose(stiffness, [3.0, 2.5, 2.0, 1.5])) + self.assertTrue(np.allclose(hit, [0.01, 0.02, 0.03, 0.0])) + self.assertTrue(np.allclose(core.joint_params(np.array([0.02, 0.04]), 3.0, 0.5, 2.0)[1], [0.02, 0.04])) + @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)."""