brokkr_kitbash free cage: boundary smoothed as a hand-modelled cage's (Sheet.boundary; All on a free cage, Keep Corners on a loft); the seam relative to extent and read before the side; a pinched vertex refused by its fans; flip and the quad's area pinned

cage_export writes vertices as authored (core.sheet owns the seam) and refuses a Subdivision at Keep Corners.
cage_score: distance each way with area-weighted mean and Hausdorff; crease agreement read off the surfaces'
sharp edges (miss, spur) in place of the cage-tag chamfer; cost = fit + complexity after Hoppe et al. 1994.
Live kitbash_cage: the open-plate round trip with its bound, the cost ranking on a creased box, exact wall
counts, bounds compared as they stand (lodur:ruling:deterministic-bound-margin).
Fix batch h2 for aetheria-release:verdict:cut-kit-minimal-cage.s1.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-03 03:49:11 +01:00
commit 1755ffaada
9 changed files with 321 additions and 118 deletions

View file

@ -1648,7 +1648,7 @@ class BROKKR_KITBASH_OT_shell(PolishOperator):
context.scene.collection.objects.link(obj)
smooth = obj.modifiers.get(SUBSURF) or obj.modifiers.new(SUBSURF, "SUBSURF")
smooth.levels = smooth.render_levels = self.levels
smooth.subdivision_type, smooth.boundary_smooth, smooth.use_creases = "CATMULL_CLARK", "PRESERVE_CORNERS", True
smooth.subdivision_type, smooth.boundary_smooth, smooth.use_creases = "CATMULL_CLARK", built.boundary, True
wall = obj.modifiers.get(SOLIDIFY) or obj.modifiers.new(SOLIDIFY, "SOLIDIFY")
wall.thickness, wall.offset, wall.use_even_offset, wall.use_rim = self.thickness, self.offset, True, True
sync_bevel(obj, self.bevel)

View file

@ -804,7 +804,7 @@
},
{
"name": "brokkr_kitbash.shell",
"doc": "Make a faceted, hollow armor shell: the cage that cut, cut_many and ribs work on. sheet is a JSON object in one of two forms, a loft of rings or a free cage; exactly one of rings and verts. The loft: {\"rings\": 2 to 64 rings of 2 to 64 [x, y, z] points with equal counts, in the shell's own frame; \"closed\": each ring joins back to its first point (false); \"mirror\": each ring is authored from its point 0 on x = 0 toward +x and mirrored across x (false; not with closed); \"creases\": [{\"ring\": i, \"from\": a, \"to\": b, \"weight\": w} | {\"column\": j, \"from\": a, \"to\": b, \"weight\": w} | {\"point\": [i, j], \"weight\": w}], runs of ring or column edges and single points, weights 0 to 1, 1 a hard facet edge; \"rim\": the weight of every boundary edge no run names (1); \"flip\": reverse every face (false)}. Quads lie between neighbouring rings; the surface faces out where, seen from outside, a ring's points run left to right and the rings run upward. The free cage, for a form a few vertices and creases hold: {\"verts\": 4 to 256 [x, y, z]; \"faces\": each 3 or 4 vertex indices, counter-clockwise seen from outside; \"creases\": [[a, b, w]], an edge by its two vertices, weight 0 to 1; \"corners\": [[vertex, w]]; \"poles\": the vertex indices of irregular valence (not 4 off the boundary, not 2 or 3 on it); \"mirror\": every vertex is authored on one side of x = 0, one within 0.005 m of it is on the seam (snapped to x = 0 and shared), the others are reflected with their faces, creases, corners and poles (false); \"rim\" and \"flip\" as on the loft}. The pole gate: poles must equal the poles the faces make, or the sheet is refused naming each undeclared pole and each declared vertex that is none, with its valence. A free cage is also refused for a vertex in no face, a repeated index, a duplicate or collapsed face, an edge in three faces, two faces wound against each other, a crease on no edge, and a face or shared edge lying on the mirror plane. A triangle subdivides to three quads. The cage is subdivided (Kit Subsurf, creases kept) and given a wall (Kit Solidify, rim filled). On an object that is already a shell the cage is rebuilt in place: the object, its cutters, ribs, Booleans and material slots stay, and ribs are stale until run again. A thickness the cage cannot hold is not refused: the wall folds over itself beside a tight crease or rim corner, and a cut there is unsound. count_folds evaluates the wall alone (Kit Subsurf and Kit Solidify, no Boolean; 4 ms on a plate of 1600 subdivided faces) and counts the folded inner faces; nothing else in the report reads an evaluated mesh, and no figure of the cage bounds the fold. Refuses before it writes anything, naming the field and index. Reports object, rebuilt, rings and points (null on a free cage), cageVerts, cageFaces, triangles, creases, poles ({valence: how many vertices}, on the cage as built), closed (no boundary edge), folded (null unless count_folds: then the number of the wall's inner faces that fold over, counted on the evaluated wall; 0 is a wall with no folded face, which an Exact Boolean can still fail on just short of a fold: read nonManifoldEdges after cutting), corners, subdividedFaces, facing, thickness, offset, levels and children.",
"doc": "Make a faceted, hollow armor shell: the cage that cut, cut_many and ribs work on. sheet is a JSON object in one of two forms, a loft of rings or a free cage; exactly one of rings and verts. The loft: {\"rings\": 2 to 64 rings of 2 to 64 [x, y, z] points with equal counts, in the shell's own frame; \"closed\": each ring joins back to its first point (false); \"mirror\": each ring is authored from its point 0 on x = 0 toward +x and mirrored across x (false; not with closed); \"creases\": [{\"ring\": i, \"from\": a, \"to\": b, \"weight\": w} | {\"column\": j, \"from\": a, \"to\": b, \"weight\": w} | {\"point\": [i, j], \"weight\": w}], runs of ring or column edges and single points, weights 0 to 1, 1 a hard facet edge; \"rim\": the weight of every boundary edge no run names (1); \"flip\": reverse every face (false)}. Quads lie between neighbouring rings; the surface faces out where, seen from outside, a ring's points run left to right and the rings run upward. The free cage, for a form a few vertices and creases hold: {\"verts\": 4 to 256 [x, y, z]; \"faces\": each 3 or 4 vertex indices, counter-clockwise seen from outside; \"creases\": [[a, b, w]], an edge by its two vertices, weight 0 to 1; \"corners\": [[vertex, w]]; \"poles\": the vertex indices of irregular valence (not 4 off the boundary, not 2 or 3 on it); \"mirror\": every vertex is authored on one side of x = 0, one within 0.005 of the cage's largest extent of it is on the seam (snapped to x = 0 and shared), the others are reflected with their faces, creases, corners and poles (false); \"rim\" and \"flip\" as on the loft}. The pole gate: poles must equal the poles the faces make, or the sheet is refused naming each undeclared pole and each declared vertex that is none, with its valence. A free cage is also refused for a vertex in no face, a repeated index, a duplicate or collapsed face, an edge in three faces, two faces wound against each other, a pinched vertex (its faces meet only at it), a crease on no edge, and a face or shared edge lying on the mirror plane. A triangle subdivides to three quads. The cage is subdivided (Kit Subsurf, creases kept; a loft's boundary keeps its corners, a free cage's is smoothed through every vertex, Boundary Smooth All, so pin a corner with corners) and given a wall (Kit Solidify, rim filled). On an object that is already a shell the cage is rebuilt in place: the object, its cutters, ribs, Booleans and material slots stay, and ribs are stale until run again. A thickness the cage cannot hold is not refused: the wall folds over itself beside a tight crease or rim corner, and a cut there is unsound. count_folds evaluates the wall alone (Kit Subsurf and Kit Solidify, no Boolean; 4 ms on a plate of 1600 subdivided faces) and counts the folded inner faces; nothing else in the report reads an evaluated mesh, and no figure of the cage bounds the fold. Refuses before it writes anything, naming the field and index. Reports object, rebuilt, rings and points (null on a free cage), cageVerts, cageFaces, triangles, creases, poles ({valence: how many vertices}, on the cage as built), closed (no boundary edge), folded (null unless count_folds: then the number of the wall's inner faces that fold over, counted on the evaluated wall; 0 is a wall with no folded face, which an Exact Boolean can still fail on just short of a fold: read nonManifoldEdges after cutting), corners, subdividedFaces, facing, thickness, offset, levels and children.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",

View file

@ -1029,7 +1029,7 @@ def spans(flags, lengths, closed: bool, bridge: float, clearance: float) -> list
SHEET_LIMIT = 64 # rings in a sheet, and authored points in a ring
SHEET_AREA = 1e-8 # square metres: a cage quad under this is a collapsed corner
MIRROR_EPS = 1e-6 # metres a mirrored ring's point 0 may stand off x = 0, and any of its points behind it
SEAM_EPS = 5e-3 # metres from x = 0 within which a mirrored free cage's vertex is on the seam: snapped to 0 and shared
SEAM_REL = 5e-3 # of a mirrored free cage's largest authored extent: a vertex that near x = 0 is on the seam, snapped to 0 and shared
CAGE_VERTS = 256 # authored vertices in a free cage
SHEET_KEYS = ("closed", "mirror", "creases", "rim", "flip")
CAGE_KEYS = ("creases", "corners", "poles", "mirror", "rim", "flip")
@ -1041,7 +1041,10 @@ class Sheet(NamedTuple):
pairs with weights (E,) in (0, 1]; corners (K,) are vertex indices with corner_weights (K,) in (0, 1]. On a loft
vertex i * points + j is ring i's point j, of rings rings of points points (2C - 1 when mirrored); on a free
cage rings and points are None, the authored vertices keep their indices and a mirror's reflections follow them.
poles (P,) are the cage's vertices of irregular valence, as built; triangles is how many faces have 3 sides."""
poles (P,) are the cage's vertices of irregular valence, as built; triangles is how many faces have 3 sides.
boundary is the Subdivision's Boundary Smooth, by Blender's name: PRESERVE_CORNERS on a loft (a boundary vertex
of two edges stays a corner), ALL on a free cage (the boundary is smoothed through it unless a corner pins it),
which is how a cage modelled by hand is set."""
V: np.ndarray
faces: np.ndarray
counts: np.ndarray
@ -1055,6 +1058,7 @@ class Sheet(NamedTuple):
points: int | None
poles: np.ndarray
triangles: int
boundary: str
def _index(value: Any, where: str, least: int, most: int) -> int:
@ -1192,7 +1196,7 @@ def sheet(document: Any) -> Sheet:
return Sheet(V=V.copy(), faces=quads.ravel().astype(np.int32), counts=np.full(len(quads), 4, dtype=np.int32), smooth=np.ones(len(quads), dtype=bool),
sharp=NO_SHARP, creases=np.array([key for key, _ in kept], dtype=np.int64).reshape(-1, 2), weights=np.array([w for _, w in kept], dtype=np.float64),
corners=np.array([key for key, _ in pinned], dtype=np.int64), corner_weights=np.array([w for _, w in pinned], dtype=np.float64), rings=R, points=N,
poles=np.zeros(0, dtype=np.int64), triangles=0)
poles=np.zeros(0, dtype=np.int64), triangles=0, boundary="PRESERVE_CORNERS")
def _cage_facts(vertices: int, faces, counts):
@ -1246,12 +1250,15 @@ def _cage(document: Any, gate: bool = True) -> Sheet:
verts: 4 to 256 [x, y, z]. faces: 3 or 4 vertex indices each, wound so the normal (counter-clockwise seen from
outside) faces out; flip reverses every face. creases: [a, b, weight], an edge by its two vertices; corners:
[vertex, weight]. rim is the weight of every boundary edge no crease names. mirror: every vertex is authored on
one side of x = 0; one within SEAM_EPS of it is on the seam, snapped to x = 0 and shared; the others are
[vertex, weight]. rim is the weight of every boundary edge no crease names. The boundary is smoothed through
every vertex (Sheet.boundary ALL): a boundary vertex of two edges is a corner only where corners pins it or its
edges are creased apart. mirror: every vertex is authored on one side of x = 0; one within SEAM_REL of the
authored vertices' largest extent of it is on the seam, snapped to x = 0 and shared; the others are
reflected (vertex len(verts) + k is the k-th of them), each face gets a reversed twin, and creases, corners and
poles land on both halves. poles: the vertices of irregular valence on the cage as built (not 4 off the
boundary, not 2 or 3 on it), by authored index. The list is a gate, not a setting: it must equal what the
faces make, so a pole is never an accident."""
faces make, so a pole is never an accident. A vertex's faces are one fan, each joined to the next by an edge at
the vertex: one whose faces meet only at it (a pinched vertex) is refused."""
_keys(document, "sheet", ("verts", "faces"), CAGE_KEYS)
flags = {}
for key in ("mirror", "flip"):
@ -1282,12 +1289,13 @@ def _cage(document: Any, gate: bool = True) -> Sheet:
V = np.array(verts, dtype=np.float64)
seam = np.zeros(A, dtype=bool)
if mirror:
if (V[:, 0] < -MIRROR_EPS).any() and (V[:, 0] > MIRROR_EPS).any():
side = 1.0 if (V[:, 0] > MIRROR_EPS).sum() >= (V[:, 0] < -MIRROR_EPS).sum() else -1.0
near = SEAM_REL * float(np.ptp(V, axis=0).max())
seam = np.abs(V[:, 0]) <= near
V[seam, 0] = 0.0 # the seam first: a seam vertex may stand a hair on either side
if (V[:, 0] < 0).any() and (V[:, 0] > 0).any():
side = 1.0 if (V[:, 0] > 0).sum() >= (V[:, 0] < 0).sum() else -1.0
worst = int((V[:, 0] * side).argmin())
raise KitError(f"sheet.verts[{worst}] has x = {V[worst, 0]:.6g}: a mirrored cage is authored on one side of x = 0, and the others stand on the {'+' if side > 0 else '-'}x side")
seam = np.abs(V[:, 0]) <= SEAM_EPS
V[seam, 0] = 0.0
seen, directed = {}, {}
for f, face in enumerate(faces):
key = tuple(sorted(face))
@ -1295,7 +1303,7 @@ def _cage(document: Any, gate: bool = True) -> Sheet:
raise KitError(f"sheet.faces[{f}] has the vertices of sheet.faces[{seen[key]}]: a duplicate face")
seen[key] = f
if mirror and all(seam[v] for v in face):
raise KitError(f"sheet.faces[{f}] lies on the mirror plane (every vertex within {SEAM_EPS:g} m of x = 0): its reflection is itself")
raise KitError(f"sheet.faces[{f}] lies on the mirror plane (every vertex within {near:.3g} m of x = 0, {SEAM_REL:g} of the cage's extent): its reflection is itself")
corners = V[face]
area = 0.5 * np.linalg.norm(np.cross(corners[1] - corners[0], corners[-1] - corners[0]))
if len(face) == 4:
@ -1325,6 +1333,22 @@ def _cage(document: Any, gate: bool = True) -> Sheet:
counts = np.array([len(face) for face in built], dtype=np.int32)
flat = np.array([v for face in built for v in face], dtype=np.int32)
cage_edges, boundary, valences, poles = _cage_facts(len(V), flat, counts)
fans: dict[int, list[tuple[set[int], list[int]]]] = {} # each vertex's faces, grouped while they share an edge at it
for f, face in enumerate(built):
for k, v in enumerate(face):
spokes, members, apart = {face[k - 1], face[(k + 1) % len(face)]}, [f], []
for others, theirs in fans.get(v, []):
if others & spokes:
spokes, members = spokes | others, members + theirs
else:
apart.append((others, theirs))
fans[v] = apart + [(spokes, members)]
pinched = min((v for v, parts in fans.items() if len(parts) > 1), default=None)
if pinched is not None:
named = lambda f: str(f) if f < len(faces) else f"{f - len(faces)} mirrored" # noqa: E731
raise KitError(f"sheet.verts[{pinched}] is pinched: its faces meet only at it, in {len(fans[pinched])} fans (faces "
f"{' | '.join(', '.join(named(f) for f in sorted(theirs)) for _, theirs in sorted(fans[pinched], key=lambda part: min(part[1])))}). "
"A vertex's faces are one fan: join them by a face, or give each fan its own vertex")
declared = document.get("poles", []) if gate else [int(v) for v in poles if v < A]
if not isinstance(declared, list):
@ -1374,7 +1398,7 @@ def _cage(document: Any, gate: bool = True) -> Sheet:
return Sheet(V=V, faces=flat, counts=counts, smooth=np.ones(len(counts), dtype=bool), sharp=NO_SHARP,
creases=np.array([key for key, _ in kept], dtype=np.int64).reshape(-1, 2), weights=np.array([w for _, w in kept], dtype=np.float64),
corners=np.array([key for key, _ in held], dtype=np.int64), corner_weights=np.array([w for _, w in held], dtype=np.float64),
rings=None, points=None, poles=poles, triangles=int((counts == 3).sum()))
rings=None, points=None, poles=poles, triangles=int((counts == 3).sum()), boundary="ALL")
# --- reports -------------------------------------------------------------------------------------------------

View file

@ -584,11 +584,19 @@ The free form states the cage directly:
"creases": [[0, 1, 1.0], [0, 3, 1.0]], "poles": [1, 2], "rim": 0}
```
**Mirror.** Every vertex stands on one side of x = 0 (either side, all the same). One within 0.005 m of the
plane is on the seam: it is snapped to x = 0 and shared by both halves. The others are reflected (the k-th of
them is vertex `len(verts) + k`), each face gets a reversed twin, and creases, corners and poles land on both
halves. A vertex 0.006 m off the plane is not on the seam: the cage is open there. A face lying on the plane,
and an edge on the plane that two authored faces share (a fin), are refused.
**Boundary.** A free cage's open boundary is smoothed through every vertex (Kit Subsurf at Boundary Smooth All),
as the hand-modelled cages are set: an uncreased outline is a soft curve and a plate's tip is round. A boundary
vertex is a corner only where `corners` pins it at weight 1 or its two edges are creased apart by the form. A loft
keeps its corners (Keep Corners), as it always has. With the outline uncreased the two settings differ by 7.7% of
extent on a 3 m plate, so the setting is the form's and not a taste.
**Mirror.** Every vertex off the seam stands on one side of x = 0 (either side, all the same). One within 0.005
of the cage's largest authored extent of the plane (5 mm on a 1 m hull) is on the seam, on whichever side it
strays: it is snapped to x = 0 and shared by both halves, so a cage reads the same at any scale. The others are
reflected (the k-th of them is vertex `len(verts) + k`), each face gets a reversed twin, and creases, corners and
poles land on both halves. A vertex further off the plane is not on the seam: the cage is open there, and a face
that then meets its reflection at one vertex alone is refused as pinched. A face lying on the plane, and an edge
on the plane that two authored faces share (a fin), are refused.
**The pole gate.** A vertex's valence is the number of cage edges at it, on the cage as built (after the
mirror). A pole is a vertex whose valence is not 4 off the boundary, or not 2 or 3 on it. `poles` must list
@ -613,7 +621,8 @@ the petal does. Add a vertex only where the limit surface cannot otherwise reach
**Refused**, before anything is written and naming the field and index: fewer than 4 or more than 256 vertices;
a vertex in no face; a face of other than 3 or 4 indices, with a repeated or out-of-range index, with another
face's vertices, or under 1e-8 m2; an edge in three faces; two faces crossing an edge the same way (wound
against each other); a crease on no cage edge; two weights for one edge or point; a mirrored cage with vertices
against each other); a pinched vertex, whose faces meet only at it and are not one fan, naming the fans; a crease
on no cage edge; two weights for one edge or point; a mirrored cage with vertices
on both sides; the pole gate. `closed` and the loft's crease runs belong to the loft and are refused here, as
`poles`, `corners` and `verts` are on a loft.
@ -626,10 +635,27 @@ silhouette, and a wrong index is caught only where it breaks a rule above, not w
There are no pentagons. A loft remains the shorter description of anything that is a grid.
**Reading and scoring a cage.** `tools/cage_export.py` writes an object of a `.blend` copy as a free cage document
(seam snapped, creases from `crease_edge`, poles computed); it writes only that document and never saves the
`.blend`. `tools/cage_score.py` builds two documents through `shell` and reports, raw and with no pass bar, each
one's counts, the distance between their level-3 limit surfaces (median, 95th centile and worst, as a share of
the reference's largest extent), silhouette overlap from +x, +y and +z, and how far apart their creased curves run.
(vertices as authored, creases from `crease_edge`, poles computed); it writes only that document and never saves
the `.blend`. `shell` builds that document as the object's own Subdivision draws it: an open plate with an
uncreased outline to 2e-5% of its extent, a mirrored hull to 0.28% (its seam snap). A Subdivision at Keep Corners
is refused, saying how to state the corners.
`tools/cage_score.py` builds two documents through `shell` and reports, with no pass bar and every figure a share
of the reference's largest extent: each one's counts; the distance between their level-3 surfaces, whose vertices
lie on the limit surface, each way and together (area-weighted mean, Hausdorff, median, 95th centile); silhouette
overlap along x, y and z; and `crease`, where each surface is sharp (level-3 edges turning 30 degrees or more,
read off the surface, not off the crease weights): `missPct`, how far the reference's sharp features lie from the
agent's, and `spurPct`, the reverse; 100 when one side has them and the other none. The headline is `cost`, after
the energy of Hoppe et al., *Piecewise Smooth Surface Reconstruction* (1994), fit plus complexity:
`fit = meanPct + hausdorffPct + (missPct + spurPct) / 2`, `complexity = 0.01 * cageVerts + 0.002 * creases` of the
agent's cage, a sharp edge a fifth of a vertex as in the paper. Lower is better; a cage against itself costs its
complexity. On the 46-vertex hull: itself 0.50, every vertex 0.5% off 1.26, one vertex moved 5% 1.56, nine more
edges creased 5.49, every edge creased 16.2, no crease 16.6. The median and the silhouettes cannot make that
order: a moved vertex leaves the median at 0 and every silhouette at 1, and the creaseless cage has the lower
median of the two. What the cost gives up: the three fit terms are summed at weight 1 and the vertex price is a
chosen 0.01, knobs and not measurements; the Hausdorff term is one point, so one stray vertex costs as much as
a broad error of the same size; and sharpness is a 30 degree threshold, so a crease softer than that is not a
feature to it.
## Cutting a shell

View file

@ -1,8 +1,9 @@
"""Live proof, in a background Blender, of brokkr_kitbash.shell's free cage through run_intent: a cage of triangles
and quads with declared poles becomes a shell whose subdivided face count is the reported one at each level, takes a
wall, counts folds and is cut; a mirrored cage closes over its seam; a loft shell is rebuilt in place as a free cage
under its cutters; the pole gate refuses without writing; and tools/cage_export.py and tools/cage_score.py read a
cage back and score it. Not part of the unittest run: it needs Blender.
under its cutters; the pole gate refuses without writing; tools/cage_export.py reads a cage back, an open one
included, as its maker's Subdivision draws it; and tools/cage_score.py ranks a near copy, a moved vertex, an
over-creased and a creaseless cage in that order. Not part of the unittest run: it needs Blender.
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_cage.py -- <out>
@ -10,7 +11,8 @@ Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USE
without them). <out> is an absolute path; writes <out>.result.json and exits 1 when a check failed.
Bounds follow lodur:ruling:deterministic-bound-margin: each sits at the geometric mean of the shipped reading and
the least claimed mutant's, both written beside it; the result file carries the readings. The checks run inside
its mutant's, both written beside it, and is compared as it stands; an order between two readings asks 1.2
between them; the result file carries the readings. The checks run inside
one try: an uncaught error is a failed check that names its section, and the result file is always written.
"""
import importlib.util
@ -61,11 +63,16 @@ COUNT, SECTION = [0], ["setup"]
# creased ridge. Shipped 71; least claimed mutant 16 (K1, the free form's creases not written to crease_edge: the
# ridge subdivides smooth), read here by clearing the attribute; the geometric mean, separation 2.1 each side.
CRISP = 34.0
# Per cent of the reference's extent: cage_score's median surface distance between the tent and the tent with its apex
# moved 5% of the extent. Shipped (a cage against itself) 0, read as 5e-6 (1e-7 m, what a float32 mesh is good to, of
# a 2 m extent); least claimed mutant 0.68 (the moved apex); the geometric mean, separation 370 each side. The moved
# apex's silhouette reads IoU 0.95 along y, under 1: checked as a strict inequality, not bounded.
SAME = 1.8e-3
# Per cent of the reference's extent: cage_score's Hausdorff distance. Shipped (the tent against itself) 0, read as
# 5e-5 (the reading is rounded to 1e-4); the mutant is one stated move, the apex lifted 5% of the extent, 3.3; the
# geometric mean, separation 260 each side. A smaller move is not claimed.
SAME = 1.3e-2
# Per cent of extent: the worst distance, both ways, between an open plate as Blender's Subdivision at Boundary Smooth
# All draws it and as shell builds cage_export's document of it. Shipped 1.7e-5; mutant B1 (the shell's Kit Subsurf at
# Keep Corners, read here by setting it) 7.7; the geometric mean, separation 670 each side. A closed cage does not tell
# the two apart, and a hand-modelled hull's own round trip is 0.28 (its seam snap): the open plate stands inside that.
OPEN = 1.1e-2
# A tent: four triangles round an apex of valence 4 with two ridges creased, and a quad hung under one edge: 7
# vertices, vertices 1 and 2 boundary poles of valence 4.
@ -145,7 +152,7 @@ try:
check(f"a cage of 4 triangles and a quad at {levels} levels: subdividedFaces is 4^L + 4 * 3 * 4^(L-1) and the evaluated surface has that many faces, all quads",
receipt["status"] == "accepted" and report["subdividedFaces"] == expected == faces and sides == {4}, [receipt["message"], expected, faces, sides])
check(f"at {levels} levels the wall is closed, twice the surface and a rim, and count_folds counts none folded",
closed and walled > 2 * expected and report["folded"] == 0, [closed, walled, report and report["folded"]])
closed and walled == 2 * expected + 6 * 2 ** levels and report["folded"] == 0, [closed, walled, report and report["folded"]]) # the tent's boundary is 6 cage edges
built = core.sheet(TENT)
check("the report carries the cage's facts: 7 vertices, 5 faces of which 4 triangles, 2 creases, two poles of valence 4, open; rings and points null",
report and {k: report[k] for k in ("rings", "points", "cageVerts", "cageFaces", "triangles", "creases", "corners", "poles", "closed")}
@ -165,16 +172,15 @@ try:
attribute.data.foreach_set("value", kept)
tent.data.update()
R["readings"].update({"crispDegrees": crisp, "crispDegreesK1": soft})
check(f"the creased ridge stays an edge under subdivision: over {CRISP} degrees, and under it with crease_edge cleared", crisp > CRISP * 1.2 and soft < CRISP / 1.2, [crisp, soft])
check(f"the creased ridge stays an edge under subdivision: over {CRISP} degrees, and under it with crease_edge cleared", crisp > CRISP and soft < CRISP, [crisp, soft])
# --- cut -------------------------------------------------------------------------------------------------------------
section("live-free-cage-shell")
receipt, cut = send("brokkr_kitbash.cut_many", object_name="Tent", cuts=json.dumps(CUTS))
plate = evaluated(tent)
uncut = 2 * (4 ** 3 + 12 * 4 ** 2)
check("cut_many cuts a free-cage shell: the Boolean stands after the wall, the plate has more faces than the wall and no non-manifold edge",
receipt["status"] == "accepted" and [m.name for m in tent.modifiers] == ["Kit Subsurf", "Kit Solidify", "Kit Difference"] and len(plate.faces) > uncut + 20
and sum(1 for e in plate.edges if not e.is_manifold) == 0, [receipt["message"], len(plate.faces), sum(1 for e in plate.edges if not e.is_manifold)])
check("cut_many cuts a free-cage shell: the Boolean stands after the wall, the plate has more faces than the wall it was cut from (a Boolean that cut nothing leaves as many) and no non-manifold edge",
receipt["status"] == "accepted" and [m.name for m in tent.modifiers] == ["Kit Subsurf", "Kit Solidify", "Kit Difference"] and len(plate.faces) > walled
and sum(1 for e in plate.edges if not e.is_manifold) == 0, [receipt["message"], len(plate.faces), walled, sum(1 for e in plate.edges if not e.is_manifold)])
plate.free()
# --- mirror ----------------------------------------------------------------------------------------------------------
@ -233,24 +239,95 @@ try:
probe.modifiers.new("Subdivision", "SUBSURF")
document = cage_export.export(probe, core)
exported = document["sheet"]
check("cage_export reads a mirrored, creased mesh as the free cage it is: the seam snapped, the creases by vertex pair, mirror set, rim 0, the poles computed, and core.sheet takes it",
exported["verts"][1] == [0.0, 0.0, 0.3] and exported["faces"] == HULL["faces"] and exported["creases"] == [[0, 4, 1.0], [2, 4, 1.0]] and exported["mirror"] is True
check("cage_export reads a mirrored, creased mesh as the free cage it is: the vertices as authored and the seam snapped when built, the creases by vertex pair, mirror set, rim 0, the poles computed, and core.sheet takes it",
exported["verts"][1] == [0.004, 0.0, 0.3] and core.sheet(exported).V[1].tolist() == [0.0, 0.0, 0.3] and exported["faces"] == HULL["faces"] and exported["creases"] == [[0, 4, 1.0], [2, 4, 1.0]] and exported["mirror"] is True
and exported["rim"] == 0.0 and exported["poles"] == [] and document["modifiers"] == [["MIRROR", "Mirror"], ["SUBSURF", "Subdivision"]]
and np.array_equal(core.sheet(exported).faces, core.sheet(HULL).faces), document)
bpy.data.objects.remove(probe)
# an open plate as a person leaves one: a bulge, one creased ridge, an uncreased outline, Subdivision at Boundary Smooth All
grid = [[i - 1.5, j - 1.5, 0.4 * math.cos(i - 1.5) * math.cos(j - 1.5)] for i in range(4) for j in range(4)]
open_plate = bpy.data.objects.new("Open Plate", bpy.data.meshes.new("Open Plate"))
bpy.context.scene.collection.objects.link(open_plate)
open_plate.data.from_pydata(grid, [], [[4 * i + j, 4 * i + 4 + j, 4 * i + 5 + j, 4 * i + 1 + j] for i in range(3) for j in range(3)])
open_plate.data.update(calc_edges=True)
weights = open_plate.data.attributes.new("crease_edge", "FLOAT", "EDGE")
for e in open_plate.data.edges:
weights.data[e.index].value = 1.0 if all(v // 4 == 1 for v in e.vertices) else 0.0
by_hand = open_plate.modifiers.new("Subdivision", "SUBSURF")
by_hand.levels, by_hand.boundary_smooth = 3, "ALL"
bm = evaluated(open_plate)
VH = np.array([v.co[:] for v in bm.verts])
TH = np.array([[f.verts[0].index, f.verts[k].index, f.verts[k + 1].index] for f in bm.faces for k in (1, 2)])
bm.free()
document = cage_export.export(open_plate, core)
receipt, report = send("brokkr_kitbash.shell", object_name="Open Shell", sheet=json.dumps(document["sheet"]), levels=3, thickness=0.001)
shell_obj = bpy.data.objects["Open Shell"]
worst = {}
for mode in ("ALL", "PRESERVE_CORNERS"): # the second is B1
kept, shell_obj.modifiers["Kit Subsurf"].boundary_smooth = shell_obj.modifiers["Kit Subsurf"].boundary_smooth, mode
VS, TS, _, _ = cage_score.surface(shell_obj)
worst[mode] = float(max(cage_score.nearest(VS, VH, TH).max(), cage_score.nearest(VH, VS, TS).max()) / np.ptp(VH, axis=0).max() * 100.0)
shell_obj.modifiers["Kit Subsurf"].boundary_smooth = kept
R["readings"].update({"openRoundTripPct": worst["ALL"], "openRoundTripPctB1": worst["PRESERVE_CORNERS"]})
check(f"an open cage round-trips: shell builds cage_export's document of a plate with an uncreased outline as its Subdivision (Boundary Smooth All) draws it, under {OPEN}% of extent, and over it at Keep Corners",
receipt["status"] == "accepted" and kept == "ALL" and report["closed"] is False and document["sheet"]["corners"] == [] and worst["ALL"] < OPEN < worst["PRESERVE_CORNERS"], [receipt["message"], worst])
by_hand.boundary_smooth = "PRESERVE_CORNERS"
try:
cage_export.export(open_plate, core)
said = None
except core.KitError as error:
said = str(error)
check("cage_export refuses a Subdivision at Keep Corners, saying how to state the corners", said is not None and "Boundary Smooth Keep Corners" in said and "vertex crease of 1" in said, said)
bpy.data.objects.remove(shell_obj)
bpy.data.objects.remove(open_plate)
# --- score-ranks ---------------------------------------------------------------------------------------------------
section("score-ranks")
tent_document = {**TENT, "rim": 1.0}
held = state()
same = cage_score.score(tent_document, tent_document, send)
check("cage_score of a cage against itself: equal counts, distance 0, every silhouette IoU 1, crease chamfer 0, and its two shells removed again",
same["agent"] == same["reference"] and same["agent"]["cageVerts"] == 7 and same["distance"]["maxPct"] < SAME / 1.2 and set(same["silhouetteIoU"].values()) == {1.0}
and same["creaseChamferPct"] == 0.0 and state() == held, same)
moved = {**tent_document, "verts": [[0.0, 0.0, 0.5 + 0.05 * 2.0]] + TENT["verts"][1:]} # the apex lifted 5% of the 2 m extent
apart = cage_score.score(moved, tent_document, send)
R["readings"].update({"scoreSameMedianPct": same["distance"]["medianPct"], "scoreMovedMedianPct": apart["distance"]["medianPct"], "scoreMovedIoUy": apart["silhouetteIoU"]["y"],
"scoreMovedChamferPct": apart["creaseChamferPct"]})
check("cage_score of the cage with one vertex moved 5% of the extent: distance above the bound, a silhouette under 1, a crease chamfer above 0, the counts still equal",
apart["distance"]["medianPct"] > SAME * 1.2 and apart["distance"]["maxPct"] > 1.0 and min(apart["silhouetteIoU"].values()) < 1.0 and apart["creaseChamferPct"] > 0.0
and apart["agent"] == apart["reference"] and abs(apart["extent"] - same["extent"]) < 1e-9, apart)
check("cage_score of a cage against itself: equal counts, distance 0, every silhouette IoU 1, no sharp feature missed or spurious, the cost its complexity alone, and its two shells removed again",
same["agent"] == same["reference"] and same["agent"]["cageVerts"] == 7 and same["distance"]["hausdorffPct"] < SAME and set(same["silhouetteIoU"].values()) == {1.0}
and (same["crease"]["missPct"], same["crease"]["spurPct"]) == (0.0, 0.0) and same["crease"]["agentSharp"] == same["crease"]["referenceSharp"] > 0
and same["cost"]["complexity"] == round(7 * cage_score.C_REP + 8 * cage_score.C_SHARP, 4) and abs(same["cost"]["total"] - same["cost"]["complexity"]) < SAME and state() == held, same)
lifted = cage_score.score({**tent_document, "verts": [[0.0, 0.0, 0.5 + 0.05 * 2.0]] + TENT["verts"][1:]}, tent_document, send) # the apex lifted 5% of the 2 m extent
R["readings"].update({"scoreSameHausdorffPct": same["distance"]["hausdorffPct"], "scoreLiftedHausdorffPct": lifted["distance"]["hausdorffPct"]})
check("cage_score of the tent with its apex lifted 5% of the extent: Hausdorff distance above the bound, a silhouette under 1, the counts and the extent still the reference's",
lifted["distance"]["hausdorffPct"] > SAME and min(lifted["silhouetteIoU"].values()) < 1.0 and lifted["agent"] == lifted["reference"] and abs(lifted["extent"] - same["extent"]) < 1e-9, lifted)
# A box of 26 vertices and 24 quads, its lid's outline creased: the reference. Four agents against it.
points = [(x, y, z) for x in (-1, 0, 1) for y in (-1, 0, 1) for z in (-1, 0, 1) if (x, y, z) != (0, 0, 0)]
at = {point: k for k, point in enumerate(points)}
quads = []
for axis in range(3):
for side in (-1, 1):
for a in (-1, 0):
for b in (-1, 0):
quad = []
for da, db in ((0, 0), (1, 0), (1, 1), (0, 1)):
point = [0, 0, 0]
point[axis], point[(axis + 1) % 3], point[(axis + 2) % 3] = side, a + da, b + db
quad.append(at[tuple(point)])
quads.append(quad if side > 0 else quad[::-1])
cage_edges = sorted({tuple(sorted((q[k], q[k - 1]))) for q in quads for k in range(4)})
BOX = {"verts": [[0.6 * x, 1.0 * y, 0.4 * z] for x, y, z in points], "faces": quads,
"creases": [[a, b, 1.0] for a, b in cage_edges if points[a][2] == points[b][2] == 1 and (0, 0, 1) not in (points[a], points[b])]}
BOX["poles"] = core.poles(BOX)
shaken = (np.array(BOX["verts"]) + np.random.default_rng(7).normal(size=(26, 3)) * 0.005 * 2.0 / math.sqrt(3)).round(6).tolist()
agents = {"Self": BOX, "Near": {**BOX, "verts": shaken}, # every vertex off by 0.5% of the 2 m extent
"Moved": {**BOX, "verts": [[v[0], v[1] + 0.05 * 2.0, v[2]] if k == at[(1, 1, 1)] else v for k, v in enumerate(BOX["verts"])]}, # one vertex, 5% of the extent
"Over": {**BOX, "creases": [[a, b, 1.0] for a, b in cage_edges]}, # every edge creased: the box as a polyhedron
"Bare": {**BOX, "creases": []}} # no crease: a smooth blob
read = {label: cage_score.score(agent, BOX, send) for label, agent in agents.items()}
cost = {label: reading["cost"]["total"] for label, reading in read.items()}
R["readings"].update({f"cost{label}": value for label, value in cost.items()})
R["readings"].update({"costMovedHausdorffPct": read["Moved"]["distance"]["hausdorffPct"], "costBareMissPct": read["Bare"]["crease"]["missPct"], "costOverSpurPct": read["Over"]["crease"]["spurPct"]})
check("the cost ranks: the reference itself is cheapest, and a near copy (every vertex 0.5% off) beats a creaseless cage, each by 1.2 or more",
len(BOX["creases"]) == 8 and cost["Self"] * 1.2 < cost["Near"] and cost["Near"] * 1.2 < cost["Bare"] and read["Bare"]["crease"]["missPct"] > read["Near"]["crease"]["missPct"], [cost, read["Bare"]["crease"]])
check("one vertex moved 5% of the extent registers: its Hausdorff distance is over the bound and its cost 1.2 over the reference's own, though the median and the silhouettes barely see it",
read["Moved"]["distance"]["hausdorffPct"] > SAME and cost["Self"] * 1.2 < cost["Moved"], read["Moved"])
check("an over-creased cage costs more than the reference, by its spurious sharp features and its sharp edges' price",
cost["Self"] * 1.2 < cost["Over"] and read["Over"]["crease"]["spurPct"] > 0.0 and read["Over"]["cost"]["complexity"] > read["Self"]["cost"]["complexity"], read["Over"])
except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, not a missing result file
check(f"no uncaught error in section: {SECTION[0]}", False, traceback.format_exc().splitlines()[-6:])
finally:

View file

@ -47,7 +47,7 @@
"detail": null
},
{
"name": "cut_many cuts a free-cage shell: the Boolean stands after the wall, the plate has more faces than the wall and no non-manifold edge",
"name": "cut_many cuts a free-cage shell: the Boolean stands after the wall, the plate has more faces than the wall it was cut from (a Boolean that cut nothing leaves as many) and no non-manifold edge",
"ok": true,
"detail": null
},
@ -92,29 +92,62 @@
"detail": null
},
{
"name": "cage_export reads a mirrored, creased mesh as the free cage it is: the seam snapped, the creases by vertex pair, mirror set, rim 0, the poles computed, and core.sheet takes it",
"name": "cage_export reads a mirrored, creased mesh as the free cage it is: the vertices as authored and the seam snapped when built, the creases by vertex pair, mirror set, rim 0, the poles computed, and core.sheet takes it",
"ok": true,
"detail": null
},
{
"name": "cage_score of a cage against itself: equal counts, distance 0, every silhouette IoU 1, crease chamfer 0, and its two shells removed again",
"name": "an open cage round-trips: shell builds cage_export's document of a plate with an uncreased outline as its Subdivision (Boundary Smooth All) draws it, under 0.011% of extent, and over it at Keep Corners",
"ok": true,
"detail": null
},
{
"name": "cage_score of the cage with one vertex moved 5% of the extent: distance above the bound, a silhouette under 1, a crease chamfer above 0, the counts still equal",
"name": "cage_export refuses a Subdivision at Keep Corners, saying how to state the corners",
"ok": true,
"detail": null
},
{
"name": "cage_score of a cage against itself: equal counts, distance 0, every silhouette IoU 1, no sharp feature missed or spurious, the cost its complexity alone, and its two shells removed again",
"ok": true,
"detail": null
},
{
"name": "cage_score of the tent with its apex lifted 5% of the extent: Hausdorff distance above the bound, a silhouette under 1, the counts and the extent still the reference's",
"ok": true,
"detail": null
},
{
"name": "the cost ranks: the reference itself is cheapest, and a near copy (every vertex 0.5% off) beats a creaseless cage, each by 1.2 or more",
"ok": true,
"detail": null
},
{
"name": "one vertex moved 5% of the extent registers: its Hausdorff distance is over the bound and its cost 1.2 over the reference's own, though the median and the silhouettes barely see it",
"ok": true,
"detail": null
},
{
"name": "an over-creased cage costs more than the reference, by its spurious sharp features and its sharp edges' price",
"ok": true,
"detail": null
}
],
"hostErrors": [],
"readings": {
"costBare": 58.0,
"costBareMissPct": 100.0,
"costMoved": 3.4,
"costMovedHausdorffPct": 2.7,
"costNear": 1.2,
"costOver": 27.0,
"costOverSpurPct": 22.0,
"costSelf": 0.28,
"crispDegrees": 71.0,
"crispDegreesK1": 16.0,
"scoreMovedChamferPct": 0.46,
"scoreMovedIoUy": 0.95,
"scoreMovedMedianPct": 0.68,
"scoreSameMedianPct": 0.0
"openRoundTripPct": 1.7e-05,
"openRoundTripPctB1": 7.7,
"scoreLiftedHausdorffPct": 3.3,
"scoreSameHausdorffPct": 0.0
},
"ok": true
}

View file

@ -2031,6 +2031,7 @@ class CageTests(unittest.TestCase):
for field in ("V", "faces", "counts", "smooth", "creases", "weights", "corners", "corner_weights", "poles"):
self.assertEqual(getattr(free, field).tolist(), getattr(loft, field).tolist(), (field, extra))
self.assertEqual((free.rings, free.points, free.triangles, loft.triangles, len(loft.poles)), (None, None, 0, 0, 0))
self.assertEqual((free.boundary, loft.boundary), ("ALL", "PRESERVE_CORNERS")) # the one field the form decides: a free cage's boundary is smoothed as a hand-modelled cage's
self.assertEqual(core.cage_report(free), core.cage_report(loft))
plain = core.sheet({"rings": SheetTests.rings(3, 4)}) # rim defaults to 1 on the boundary edges of either form
free = core.sheet({"verts": plain.V.tolist(), "faces": plain.faces.reshape(-1, 4).tolist()})
@ -2039,12 +2040,19 @@ class CageTests(unittest.TestCase):
def test_a_mirrored_cage_shares_its_seam(self):
"""free-cage-mirror. C2 (the seam duplicated: an open cage; the reflected faces not reversed): seam vertices
within SEAM_EPS are snapped and shared, the rest reflected, and creases, corners and poles land on both halves."""
within SEAM_REL of the extent are snapped and shared, the rest reflected, and creases, corners and poles land
on both halves. S1 (the seam distance in metres, not of the extent): the same cage at 1% and at 100 times builds alike."""
verts = [[0.0, 0.0, 0.0], [0.004, 0.0, 1.0], [0.5, 0.0, 0.0], [0.5, 0.0, 1.0], [1.0, 0.2, 0.0], [1.0, 0.2, 1.0]]
faces = [[0, 1, 3, 2], [2, 3, 5, 4]] # outside is +y
built = core.sheet({"verts": verts, "faces": faces, "mirror": True, "creases": [[2, 3, 0.75]], "corners": [[4, 0.5], [0, 1.0]], "rim": 0.0})
self.assertEqual((len(built.V), built.counts.tolist()), (10, [4, 4, 4, 4]))
self.assertEqual(built.V[:2, 0].tolist(), [0.0, 0.0]) # 0.004 is inside SEAM_EPS: snapped
self.assertEqual(built.V[:2, 0].tolist(), [0.0, 0.0]) # 0.004 of an extent of 1 is inside SEAM_REL: snapped
for scale in (0.01, 100.0): # S1: at 1 cm an absolute 5 mm takes face 0 for the plane's; at 100 m it leaves vertex 1 off the seam
scaled = core.sheet({"verts": [[c * scale for c in v] for v in verts], "faces": faces, "mirror": True, "rim": 0.0})
self.assertEqual((len(scaled.V), scaled.V[:2, 0].tolist(), scaled.faces.tolist()), (10, [0.0, 0.0], built.faces.tolist()), scale)
turned = core.sheet({"verts": verts, "faces": faces, "mirror": True, "flip": True, "rim": 0.0}) # F1 (flip ignored on a free cage): every face reversed, the reflected ones too
self.assertEqual(turned.faces.reshape(-1, 4).tolist(), [[2, 3, 1, 0], [4, 5, 3, 2], [0, 1, 7, 6], [6, 7, 9, 8]])
self.assertEqual((turned.V.tolist(), SheetTests.weights(turned)), (built.V.tolist(), {}))
self.assertEqual(built.V[6:].tolist(), [[-0.5, 0.0, 0.0], [-0.5, 0.0, 1.0], [-1.0, 0.2, 0.0], [-1.0, 0.2, 1.0]])
self.assertEqual(built.faces.reshape(-1, 4).tolist(), [[0, 1, 3, 2], [2, 3, 5, 4], [6, 7, 1, 0], [8, 9, 7, 6]])
V = built.V[built.faces.reshape(-1, 4)]
@ -2053,10 +2061,12 @@ class CageTests(unittest.TestCase):
self.assertEqual((built.corners.tolist(), built.corner_weights.tolist()), ([0, 4, 8], [1.0, 0.5, 0.5]))
edges, boundary, _, _ = core._cage_facts(len(built.V), built.faces, built.counts)
self.assertEqual((edges[(0, 1)], (0, 1) in boundary, len(boundary)), (2, False, 10)) # the seam edge is interior
verts[1][0] = 0.006 # outside SEAM_EPS: reflected, not shared, and vertex 0 now joins four boundary edges
self.refused(r"sheet\.poles lacks vertex 0 \(valence 4, on the boundary\)", verts=verts, faces=faces, mirror=True)
apart = core.sheet({"verts": verts, "faces": faces, "mirror": True, "poles": [0]})
self.assertEqual((len(apart.V), apart.V[6].tolist(), apart.poles.tolist()), (11, [-0.006, 0.0, 1.0], [0]))
verts[1][0] = 0.006 # outside the seam: reflected, not shared, so face 0 and its reflection meet at vertex 0 alone
self.refused(r"sheet\.verts\[0\] is pinched: its faces meet only at it, in 2 fans \(faces 0 \| 0 mirrored\)", verts=verts, faces=faces, mirror=True, poles=[0])
verts[0][0] = 0.006 # both off the plane: two halves 12 mm apart, no vertex shared
apart = core.sheet({"verts": verts, "faces": faces, "mirror": True})
self.assertEqual((len(apart.V), apart.V[6:8].tolist(), apart.poles.tolist()), (12, [[-0.006, 0.0, 0.0], [-0.006, 0.0, 1.0]], []))
verts[0][0] = 0.0
fan_verts, fan_faces = self.fan(3)
aside = core.sheet({"verts": [[x + 2.0, y, z] for x, y, z in fan_verts], "faces": fan_faces, "mirror": True, "poles": [0]})
self.assertEqual((aside.poles.tolist(), core.cage_report(aside)["poles"]), ([0, 7], {"3": 2})) # a pole off the seam stands on both halves
@ -2111,6 +2121,11 @@ class CageTests(unittest.TestCase):
self.refused(r"sheet\.faces\[0\] lies on the mirror plane", verts=[[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 1.0, 1.0], [1.0, 0.0, 0.0]], faces=[[0, 1, 2], [0, 3, 1]], mirror=True)
self.refused(r"sheet\.faces\[1\] has area 0 m2, under 1e-08: a collapsed face",
verts=[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [2.0, 0.0, 0.0], [3.0, 0.0, 0.0]], faces=[[0, 1, 2], [1, 3, 4]])
self.refused(r"sheet\.faces\[0\] has area 0 m2, under 1e-08: a collapsed face", verts=[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [2.0, 0.0, 0.0], [3.0, 0.0, 0.0]], faces=[[0, 1, 2, 3]])
dart = core.sheet({"verts": [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [-1.0, 0.0, 0.0]], "faces": [[0, 1, 2, 3]]}) # Q1 (a quad's area read from its first corner alone): vertex 0 stands on the line from 3 to 1, and the quad has area 1
self.assertEqual((dart.counts.tolist(), dart.poles.tolist()), ([4], []))
self.refused(r"sheet\.verts\[2\] is pinched: its faces meet only at it, in 2 fans \(faces 0 \| 1\)\. A vertex's faces are one fan", # P1 (the fan check dropped): its valence 4 declared, it was taken
verts=[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0], [2.0, 1.0, 0.0], [2.0, 2.0, 0.0], [1.0, 2.0, 0.0]], faces=[[0, 1, 2, 3], [2, 4, 5, 6]], poles=[2])
self.refused(r"sheet states both rings and verts", rings=SheetTests.rings(), **ok)
self.refused(r"sheet lacks 'rings' and 'verts'", creases=[])
self.refused(r"sheet\.verts must be 4 to 256 vertices, not 257", verts=[[0.0, 0.0, float(k)] for k in range(257)], faces=faces)

View file

@ -8,11 +8,15 @@ one mesh, writes <out.json> (an absolute path) and nothing else, and never saves
unless BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS are private (tools/private_dirs.py).
The document: {"object", "modifiers" (type and name, as stacked), "matrixWorld", "sheet"}. sheet is the cage in
the object's own frame, before any modifier: verts, faces, creases from the crease_edge attribute, corners from
crease_vert, mirror true when the object carries a Mirror across x (any other Mirror is refused), the seam
snapped as core.sheet snaps it (a vertex within SEAM_EPS of x = 0 goes to 0), rim 0 (a boundary edge carries the
crease it was given and no more), and poles as the faces make them (core.poles). The sheet is what core.sheet
accepts: a cage it would refuse (a face of five sides, a fin on the mirror plane) is refused here with its reason.
the object's own frame, before any modifier: verts as authored (core.sheet snaps the seam when it builds), faces,
creases from the crease_edge attribute, corners from crease_vert, mirror true when the object carries a Mirror
across x (any other Mirror is refused), rim 0 (a boundary edge carries the crease it was given and no more), and
poles as the faces make them (core.poles). The sheet is what core.sheet accepts: a cage it would refuse (a face of
five sides, a fin on the mirror plane) is refused here with its reason.
A free cage's boundary is smoothed as Blender's Boundary Smooth: All smooths it (core.Sheet.boundary), the setting
of the hand-modelled cages this was made to read. A Subdivision set to Keep Corners draws another surface from the
same cage, so an object carrying one is refused, saying how to state its corners.
"""
import importlib.util
import json
@ -40,12 +44,12 @@ def export(obj, core) -> dict:
mirrors = [m for m in obj.modifiers if m.type == "MIRROR"]
if len(mirrors) > 1 or mirrors and (tuple(mirrors[0].use_axis) != (True, False, False) or mirrors[0].mirror_object is not None):
raise core.KitError(f"{obj.name!r} is mirrored otherwise than once across its own x: a free cage mirrors across x = 0 only")
kept = [m.name for m in obj.modifiers if m.type == "SUBSURF" and m.boundary_smooth != "ALL"]
if kept:
raise core.KitError(f"{obj.name!r} has its Subdivision {kept[0]!r} at Boundary Smooth Keep Corners, and a free cage smooths its boundary through every vertex: "
"set it to All and give each corner a vertex crease of 1, which draws the same surface")
mesh = obj.data
verts = [[round(float(c), 6) for c in v.co] for v in mesh.vertices]
if mirrors:
for point in verts:
if abs(point[0]) <= core.SEAM_EPS:
point[0] = 0.0
creases, corners = mesh.attributes.get("crease_edge"), mesh.attributes.get("crease_vert")
sheet = {"verts": verts, "faces": [list(p.vertices) for p in mesh.polygons],
"creases": sorted([*sorted(e.vertices), round(float(creases.data[e.index].value), 4)] for e in mesh.edges if creases.data[e.index].value > 0) if creases else [],

View file

@ -1,4 +1,5 @@
"""Read how close one free cage comes to another: an agent's cage against a reference, both in one frame.
"""Read how close one free cage comes to another, and what it spends to get there: an agent's cage against a
reference, both in one frame.
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tools/cage_score.py -- <agent.json> <reference.json> <out.json>
@ -8,68 +9,78 @@ Subsurf alone: the tool measures what the tool builds. <out.json> is an absolute
no .blend is saved. It refuses to start unless BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and
BLENDER_USER_SCRIPTS are private (tools/private_dirs.py).
The result is a reading with no pass bar:
The result is a reading with no pass bar. Every percentage is of the reference surface's largest extent.
agent, reference each cage's counts as shell reports them: cageVerts, cageFaces, triangles, creases, corners, poles, closed
extent the reference surface's largest extent, metres: the unit of every percentage
distance between the two level-3 surfaces, each one's vertices to the nearest point of the other, pooled:
medianPct, p95Pct, maxPct
extent the reference surface's largest extent, metres
distance between the two level-3 surfaces, whose vertices lie on the limit surface. Each one's vertices
to the nearest point of the other: agentToReference and referenceToAgent {meanPct, maxPct},
the mean weighted by each vertex's share of its surface's area. meanPct is the mean of the two
means, hausdorffPct the larger of the two maxima (one moved vertex shows here), medianPct and
p95Pct the pooled centiles.
silhouetteIoU orthographic silhouettes seen along x, y and z, 512 px across the two surfaces' common box:
intersection over union
creaseChamferPct the creased cage edges (rim included, where its weight is over 0) as they lie on each level-3
surface, sampled every 1% of extent: the mean distance from each curve's samples to the
other's, averaged both ways; null when either cage has no crease
crease where each surface is sharp, read off the surface and not off the cage's crease weights: the
level-3 edges between two faces that turn SHARP degrees or more, sampled every 1% of extent.
missPct is the mean distance from the reference's sharp samples to the agent's (a feature the
agent lacks), spurPct the reverse (a feature the reference lacks). A side with sharp samples
against one with none reads 100; two with none read 0. agentSharp and referenceSharp count the
sharp edges.
cost the headline, lower is better, after the energy of Hoppe et al., "Piecewise Smooth Surface
Reconstruction" (SIGGRAPH 1994), E = E_dist + c_rep * vertices + c_sharp * sharp edges: fit is
distance.meanPct + distance.hausdorffPct + the mean of crease.missPct and crease.spurPct;
complexity is C_REP per cage vertex and C_SHARP per creased cage edge of the agent, a sharp
edge a fifth of a vertex as in that paper; total is their sum. C_REP is the fit, in per cent
of extent, that one more cage vertex must buy.
"""
import importlib.util
import json
import math
import os
import sys
import types
from pathlib import Path
import bmesh
import bpy
import numpy as np
from mathutils import Vector
from mathutils.bvhtree import BVHTree
from mathutils.kdtree import KDTree
SURFACE = Path(__file__).resolve().parents[1]
LEVELS, PIXELS, SPACING = 3, 512, 0.01
SHARP = 30.0 # degrees between two level-3 faces at which their edge is a sharp feature
C_REP, C_SHARP = 0.01, 0.002 # per cent of extent: the price of a cage vertex, and of a creased cage edge
COUNTS = ("cageVerts", "cageFaces", "triangles", "creases", "corners", "poles", "closed")
def surface(obj):
"""(V, triangles, creased polylines) of a shell read with its Kit Subsurf alone. A creased cage edge is found on
the subdivided mesh as Blender lays it out: the cage's vertices keep their indices, then each cage edge's 2^L - 1
inner vertices follow in edge order; the chain is checked edge by edge against the mesh, not assumed."""
"""(V, triangles, area, sharp) of a shell read with its Kit Subsurf alone: area (len(V),) is each vertex's share
of the surface, sharp the (S, 2, 3) end points of the edges between two faces that turn SHARP degrees or more."""
hidden = [m for m in obj.modifiers if m.name != "Kit Subsurf" and m.show_viewport]
for m in hidden:
m.show_viewport = False
try:
bpy.context.view_layer.update()
owner = obj.evaluated_get(bpy.context.evaluated_depsgraph_get())
mesh = owner.to_mesh()
V = np.array([v.co[:] for v in mesh.vertices], dtype=np.float64)
triangles = np.array([[p.vertices[0], p.vertices[k], p.vertices[k + 1]] for p in mesh.polygons for k in range(1, len(p.vertices) - 1)], dtype=np.int64)
edges = {tuple(sorted(e.vertices)) for e in mesh.edges}
bm = bmesh.new()
bm.from_mesh(owner.to_mesh())
owner.to_mesh_clear()
finally:
for m in hidden:
m.show_viewport = True
bpy.context.view_layer.update()
cage, inner = obj.data, 2 ** obj.modifiers["Kit Subsurf"].levels - 1
weights = cage.attributes["crease_edge"].data
curves = []
for e in cage.edges:
if weights[e.index].value <= 0:
continue
between = [len(cage.vertices) + e.index * inner + k for k in range(inner)]
for chain in ([e.vertices[0], *between, e.vertices[1]], [e.vertices[0], *between[::-1], e.vertices[1]]):
if all(tuple(sorted(pair)) in edges for pair in zip(chain, chain[1:])):
curves.append(V[chain])
break
else:
raise SystemExit(f"cage_score: cage edge {tuple(e.vertices)} of {obj.name!r} is not where the subdivided mesh was expected to carry it; this Blender lays a Subdivision out otherwise")
return V, triangles, curves
bm.normal_update()
V = np.array([v.co[:] for v in bm.verts], dtype=np.float64)
triangles = np.array([[f.verts[0].index, f.verts[k].index, f.verts[k + 1].index] for f in bm.faces for k in range(1, len(f.verts) - 1)], dtype=np.int64)
area = np.zeros(len(V))
for f in bm.faces:
for v in f.verts:
area[v.index] += f.calc_area() / len(f.verts)
sharp = np.array([[e.verts[0].co[:], e.verts[1].co[:]] for e in bm.edges if len(e.link_faces) == 2 and math.degrees(e.calc_face_angle()) >= SHARP], dtype=np.float64).reshape(-1, 2, 3)
bm.free()
return V, triangles, area, sharp
def nearest(points, V, triangles):
@ -95,16 +106,23 @@ def silhouette(V, triangles, axis, low, scale):
return mask
def sampled(curves, step):
points = []
for curve in curves:
lengths = np.linalg.norm(np.diff(curve, axis=0), axis=1)
along = np.concatenate([[0.0], np.cumsum(lengths)])
at = np.linspace(0.0, along[-1], max(2, int(np.ceil(along[-1] / step)) + 1))
points.append(np.stack([np.interp(at, along, curve[:, k]) for k in range(3)], axis=1))
def sampled(segments, step):
"""Points along each segment, its ends included, no further apart than step."""
points = [a + (b - a) * np.linspace(0.0, 1.0, max(2, int(np.ceil(np.linalg.norm(b - a) / step)) + 1))[:, None] for a, b in segments]
return np.concatenate(points) if points else np.zeros((0, 3))
def apart(P, Q, extent):
"""The mean distance from P's points to the nearest of Q's, per cent of extent: 0 for no P, 100 for a P against no Q."""
if not len(P) or not len(Q):
return 100.0 if len(P) else 0.0
tree = KDTree(len(Q))
for k, q in enumerate(Q):
tree.insert(q, k)
tree.balance()
return float(np.mean([tree.find(p)[2] for p in P])) / extent * 100.0
def score(agent: dict, reference: dict, send) -> dict:
"""The reading of two sheets. send(action, **fields) -> (receipt, report) runs an intent; the two shells it
builds (Cage Score Agent, Cage Score Reference) are removed again."""
@ -124,9 +142,12 @@ def score(agent: dict, reference: dict, send) -> dict:
mesh = obj.data
bpy.data.objects.remove(obj)
bpy.data.meshes.remove(mesh)
(VA, TA, CA), (VB, TB, CB) = built["agent"], built["reference"]
(VA, TA, WA, SA), (VB, TB, WB, SB) = built["agent"], built["reference"]
extent = float(np.ptp(VB, axis=0).max())
d = np.concatenate([nearest(VA, VB, TB), nearest(VB, VA, TA)]) / extent * 100.0
to_reference, to_agent = nearest(VA, VB, TB) / extent * 100.0, nearest(VB, VA, TA) / extent * 100.0
pooled = np.concatenate([to_reference, to_agent])
means = float(np.average(to_reference, weights=WA)), float(np.average(to_agent, weights=WB))
mean, hausdorff = 0.5 * (means[0] + means[1]), float(pooled.max())
both = np.concatenate([VA, VB])
low = both.min(axis=0)
scale = (PIXELS - 1) / float(np.ptp(both, axis=0).max())
@ -134,14 +155,17 @@ def score(agent: dict, reference: dict, send) -> dict:
for axis, label in enumerate("xyz"):
a, b = silhouette(VA, TA, axis, low, scale), silhouette(VB, TB, axis, low, scale)
overlap[label] = round(float((a & b).sum() / max(1, (a | b).sum())), 4)
chamfer = None
if CA and CB:
SA, SB = sampled(CA, SPACING * extent), sampled(CB, SPACING * extent)
away = lambda P, Q: float(np.mean([np.linalg.norm(Q - p, axis=1).min() for p in P])) # noqa: E731
chamfer = round(0.5 * (away(SA, SB) + away(SB, SA)) / extent * 100.0, 4)
PA, PB = sampled(SA, SPACING * extent), sampled(SB, SPACING * extent)
miss, spur = apart(PB, PA, extent), apart(PA, PB, extent)
fit = mean + hausdorff + 0.5 * (miss + spur)
complexity = C_REP * reports["agent"]["cageVerts"] + C_SHARP * reports["agent"]["creases"]
return {"levels": LEVELS, "agent": reports["agent"], "reference": reports["reference"], "extent": round(extent, 6),
"distance": {"medianPct": round(float(np.median(d)), 4), "p95Pct": round(float(np.percentile(d, 95)), 4), "maxPct": round(float(d.max()), 4)},
"silhouetteIoU": overlap, "creaseChamferPct": chamfer}
"distance": {"meanPct": round(mean, 4), "hausdorffPct": round(hausdorff, 4), "medianPct": round(float(np.median(pooled)), 4), "p95Pct": round(float(np.percentile(pooled, 95)), 4),
"agentToReference": {"meanPct": round(means[0], 4), "maxPct": round(float(to_reference.max()), 4)},
"referenceToAgent": {"meanPct": round(means[1], 4), "maxPct": round(float(to_agent.max()), 4)}},
"silhouetteIoU": overlap,
"crease": {"sharpDegrees": SHARP, "missPct": round(miss, 4), "spurPct": round(spur, 4), "agentSharp": len(SA), "referenceSharp": len(SB)},
"cost": {"fit": round(fit, 4), "complexity": round(complexity, 4), "total": round(fit + complexity, 4), "cRep": C_REP, "cSharp": C_SHARP}}
def main() -> int: