Merge pull request 'brokkr_kitbash.shell takes a free cage (verts, tri/quad faces, creases, declared poles, mirror seam); cage export and scorer (cut kit-minimal-cage)' (#40) from nibu/kit-minimal-cage into main
This commit is contained in:
commit
eed171efad
10 changed files with 1282 additions and 32 deletions
|
|
@ -44,7 +44,7 @@ a cutter. The ribs object is a bake of the cage at that call, and kit_ribs on it
|
|||
nothing reads it to decide geometry, and ribs is its one writer. The one Manifold Boolean in the package is the hole
|
||||
cut inside ribs, on webs it built as closed shells that do not cross; a target's live Booleans stay Exact.
|
||||
|
||||
shell makes the cage that cut and ribs work on: a loft of rings with crease runs (core.sheet) under a Kit Subsurf
|
||||
shell makes the cage that cut and ribs work on: a loft of rings or a free cage, with creases (core.sheet), under a Kit Subsurf
|
||||
and a Kit Solidify. kit_shell on the object is the request, and it owns the cage mesh as kit_params owns a part's:
|
||||
shell is the one writer of the mesh, its crease attributes and those two modifiers, and calling it again on the
|
||||
object rewrites the mesh in place, leaving the object, its cutters, ribs, Booleans and material slots. shell
|
||||
|
|
@ -106,7 +106,7 @@ RIBS_LIMIT = 64 # planes in one ribs
|
|||
LONGERONS_LIMIT = 16 # longerons in one ribs
|
||||
SHELL = "kit_shell" # on a shell: the request its cage is derived from, as JSON; its presence admits a rebuild, and nothing reads it to decide geometry
|
||||
SUBSURF, SOLIDIFY = "Kit Subsurf", "Kit Solidify" # a shell's own modifiers, in that order, before any of its Booleans and the Kit Bevel
|
||||
SHELL_FACES_LIMIT = 262144 # faces of a shell's subdivided surface: cage quads times 4 to the levels
|
||||
SHELL_FACES_LIMIT = 262144 # faces of a shell's subdivided surface: core.subdivided_faces
|
||||
HOSE = "kit_hose" # on a hose: the request it was routed from, as JSON; its presence admits a rebuild, and another hose reads its two ends to know that it crosses the same pin
|
||||
HOSE_CLAMPS = 8 # clamps in one hose: each is one more leg to search
|
||||
HOSE_VOXELS = 2 ** 19 # voxels of one leg's search box: 1.8 s of capped nearest-face queries at 3.4 us each
|
||||
|
|
@ -1585,13 +1585,13 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator):
|
|||
|
||||
|
||||
class BROKKR_KITBASH_OT_shell(PolishOperator):
|
||||
"""Make a faceted, hollow armor shell from a loft of rings: a quad cage with crease runs and a creased rim, under
|
||||
a Subdivision and a Solidify; on an object that is already a shell, rebuild its cage in place under its cutters,
|
||||
"""Make a faceted, hollow armor shell from a cage, a loft of rings or a free cage of vertices and faces of 3 or 4
|
||||
sides, with creases and a creased rim, under a Subdivision and a Solidify; on an object that is already a shell, rebuild its cage in place under its cutters,
|
||||
ribs and Booleans"""
|
||||
bl_idname = "brokkr_kitbash.shell"
|
||||
bl_label = "Make A Shell"
|
||||
object_name: bpy.props.StringProperty(name="Object", description="The shell's name: a new object, or a shell to rebuild")
|
||||
sheet: bpy.props.StringProperty(name="Sheet", description="A JSON object {rings, closed, mirror, creases, rim, flip}: rings of [x, y, z] points in the shell's own frame")
|
||||
sheet: bpy.props.StringProperty(name="Sheet", description="A JSON object, a loft {rings, closed, mirror, creases, rim, flip} or a free cage {verts, faces, creases, corners, poles, mirror, rim, flip}, in the shell's own frame")
|
||||
thickness: bpy.props.FloatProperty(name="Thickness", default=0.05, min=0.0009, max=1.0, description="The wall's thickness")
|
||||
offset: bpy.props.FloatProperty(name="Offset", default=-1.0, min=-1.0, max=1.0, description="-1: the wall grows inward from the designed surface; 1: outward")
|
||||
levels: bpy.props.IntProperty(name="Levels", default=3, min=1, max=4, description="Subdivision levels")
|
||||
|
|
@ -1622,9 +1622,9 @@ class BROKKR_KITBASH_OT_shell(PolishOperator):
|
|||
except ValueError as error:
|
||||
raise Refused(f"sheet is not JSON ({error}); nothing changed.") from None
|
||||
built = core.sheet(document)
|
||||
cage_faces = len(built.counts)
|
||||
if cage_faces * 4 ** self.levels > SHELL_FACES_LIMIT:
|
||||
raise Refused(f"sheet: {cage_faces} cage quads at {self.levels} levels subdivide to {cage_faces * 4 ** self.levels} faces, over {SHELL_FACES_LIMIT}. "
|
||||
subdivided = core.subdivided_faces(built, self.levels)
|
||||
if subdivided > SHELL_FACES_LIMIT:
|
||||
raise Refused(f"sheet: {len(built.counts)} cage {'faces' if built.triangles else 'quads'} at {self.levels} levels subdivide to {subdivided} faces, over {SHELL_FACES_LIMIT}. "
|
||||
"Use fewer levels or a sparser sheet; nothing changed.")
|
||||
rebuilt = obj is not None
|
||||
if rebuilt:
|
||||
|
|
@ -1648,17 +1648,19 @@ 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)
|
||||
obj[SHELL] = json.dumps({"sheet": document, "thickness": self.thickness, "offset": self.offset, "levels": self.levels, "bevel": self.bevel})
|
||||
corners = built.V[built.faces.reshape(-1, 4)]
|
||||
facing = np.cross(corners[:, 2] - corners[:, 0], corners[:, 3] - corners[:, 1]).sum(axis=0) # twice the quads' vector areas, summed
|
||||
cancels = np.linalg.norm(facing) <= 1e-9 * np.linalg.norm(np.cross(corners[:, 2] - corners[:, 0], corners[:, 3] - corners[:, 1]), axis=1).sum()
|
||||
return {"object": obj.name, "rebuilt": rebuilt, "rings": built.rings, "points": built.points, "cageFaces": cage_faces, "creases": len(built.creases),
|
||||
"folded": self.folded_faces(context, obj, cage_faces * 4 ** self.levels) if self.count_folds else None,
|
||||
"corners": len(built.corners), "subdividedFaces": cage_faces * 4 ** self.levels,
|
||||
starts = np.cumsum(built.counts) - built.counts
|
||||
first, second, third, last = (built.V[built.faces[starts + k]] for k in (0, 1, 2, built.counts - 1))
|
||||
areas = np.where((built.counts == 3)[:, None], np.cross(second - first, third - first), np.cross(third - first, last - second)) # twice each face's vector area
|
||||
facing = areas.sum(axis=0)
|
||||
cancels = np.linalg.norm(facing) <= 1e-9 * np.linalg.norm(areas, axis=1).sum()
|
||||
return {"object": obj.name, "rebuilt": rebuilt, "rings": built.rings, "points": built.points, **core.cage_report(built),
|
||||
"folded": self.folded_faces(context, obj, subdivided) if self.count_folds else None,
|
||||
"subdividedFaces": subdivided,
|
||||
"facing": None if cancels else [round(float(v), 6) for v in facing / np.linalg.norm(facing)],
|
||||
"thickness": round(self.thickness, 6), "offset": round(self.offset, 6), "levels": self.levels, "children": sorted(child.name for child in obj.children)}
|
||||
|
||||
|
|
|
|||
|
|
@ -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 {\"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 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, points, cageFaces, creases, 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",
|
||||
|
|
@ -823,7 +823,7 @@
|
|||
"required": true,
|
||||
"minLength": 2,
|
||||
"maxLength": 32000,
|
||||
"doc": "the shell description, a JSON object: rings, closed, mirror, creases, rim, flip"
|
||||
"doc": "the shell description, a JSON object: a loft (rings, closed, mirror, creases, rim, flip) or a free cage (verts, faces, creases, corners, poles, mirror, rim, flip)"
|
||||
},
|
||||
{
|
||||
"name": "thickness",
|
||||
|
|
@ -847,7 +847,7 @@
|
|||
"minimum": 1,
|
||||
"maximum": 4,
|
||||
"default": 3,
|
||||
"doc": "subdivision levels; cage quads times 4 to the levels may not pass 262144"
|
||||
"doc": "subdivision levels; the subdivided faces (a quad 4 to the levels, a triangle three quarters of that) may not pass 262144"
|
||||
},
|
||||
{
|
||||
"name": "bevel",
|
||||
|
|
|
|||
|
|
@ -1024,19 +1024,27 @@ def spans(flags, lengths, closed: bool, bridge: float, clearance: float) -> list
|
|||
return kept
|
||||
|
||||
|
||||
# --- shells: a loft of rings and its creases -------------------------------------------------------------------
|
||||
# --- shells: a cage (a loft of rings, or free) and its creases --------------------------------------------------
|
||||
|
||||
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_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")
|
||||
|
||||
|
||||
class Sheet(NamedTuple):
|
||||
"""A shell's cage, in the shell's frame, metres: the five fields a mesh is written from (every face a quad,
|
||||
"""A shell's cage, in the shell's frame, metres: the five fields a mesh is written from (faces of 3 or 4 sides,
|
||||
shaded smooth, no sharp edge) and what a subdivision surface creases. creases is an (E, 2) array of vertex index
|
||||
pairs with weights (E,) in (0, 1]; corners (K,) are vertex indices with corner_weights (K,) in (0, 1]. Vertex
|
||||
i * points + j is ring i's point j, of rings rings of points points (2C - 1 when mirrored)."""
|
||||
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.
|
||||
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
|
||||
|
|
@ -1046,8 +1054,11 @@ class Sheet(NamedTuple):
|
|||
weights: np.ndarray
|
||||
corners: np.ndarray
|
||||
corner_weights: np.ndarray
|
||||
rings: int
|
||||
points: int
|
||||
rings: int | None
|
||||
points: int | None
|
||||
poles: np.ndarray
|
||||
triangles: int
|
||||
boundary: str
|
||||
|
||||
|
||||
def _index(value: Any, where: str, least: int, most: int) -> int:
|
||||
|
|
@ -1063,7 +1074,8 @@ def _weight(value: Any, where: str) -> float:
|
|||
|
||||
|
||||
def sheet(document: Any) -> Sheet:
|
||||
"""The cage of a shell description {rings, closed, mirror, creases, rim, flip}.
|
||||
"""The cage of a shell description, in one of two forms: a loft {rings, closed, mirror, creases, rim, flip}, or
|
||||
a free cage {verts, faces, creases, corners, poles, mirror, rim, flip} (see _cage). Exactly one of rings, verts.
|
||||
|
||||
rings: 2 to 64 rings of 2 to 64 [x, y, z] points, equal counts. Quad (i, j) is P[i][j], P[i][j+1], P[i+1][j+1],
|
||||
P[i+1][j], so its normal (P[i][j+1] - P[i][j]) x (P[i+1][j] - P[i][j]) faces out: seen from outside, a ring's
|
||||
|
|
@ -1075,6 +1087,11 @@ def sheet(document: Any) -> Sheet:
|
|||
may be the count: the edge back to point 0); {column, from, to, weight} a column's edges from ring `from` to
|
||||
ring `to`; {point: [ring, point], weight} one vertex. rim is the weight of every boundary edge no run names.
|
||||
An edge has one weight: two runs that give it different ones are refused."""
|
||||
if isinstance(document, dict) and ("rings" in document) == ("verts" in document):
|
||||
raise KitError("sheet states both rings and verts: a sheet is a loft of rings or a free cage of verts and faces, one of them" if "rings" in document else
|
||||
"sheet lacks 'rings' and 'verts': a sheet is a loft of rings or a free cage of verts and faces")
|
||||
if isinstance(document, dict) and "verts" in document:
|
||||
return _cage(document)
|
||||
_keys(document, "sheet", ("rings",), SHEET_KEYS)
|
||||
flags = {}
|
||||
for key in ("closed", "mirror", "flip"):
|
||||
|
|
@ -1178,7 +1195,210 @@ def sheet(document: Any) -> Sheet:
|
|||
pinned = sorted((key, weight) for key, (weight, _) in verts.items() if weight > 0)
|
||||
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)
|
||||
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, boundary="PRESERVE_CORNERS")
|
||||
|
||||
|
||||
def _cage_facts(vertices: int, faces, counts):
|
||||
"""What a cage's connectivity says: (edges, boundary, valences, poles). edges maps each (low, high) vertex pair
|
||||
to how many faces use it; boundary lists the pairs one face uses; valences (vertices,) counts each vertex's
|
||||
edges; poles are the vertices of irregular valence, ascending: not 4 off the boundary, not 2 or 3 on it."""
|
||||
edges: dict[tuple[int, int], int] = {}
|
||||
at = 0
|
||||
for count in counts:
|
||||
face = [int(v) for v in faces[at:at + count]]
|
||||
at += count
|
||||
for a, b in zip(face, face[1:] + face[:1]):
|
||||
key = (min(a, b), max(a, b))
|
||||
edges[key] = edges.get(key, 0) + 1
|
||||
boundary = sorted(key for key, used in edges.items() if used == 1)
|
||||
valences = np.zeros(vertices, dtype=np.int64)
|
||||
for a, b in edges:
|
||||
valences[a] += 1
|
||||
valences[b] += 1
|
||||
rim = np.zeros(vertices, dtype=bool)
|
||||
rim[[v for key in boundary for v in key]] = True
|
||||
poles = np.flatnonzero(np.where(rim, (valences != 2) & (valences != 3), valences != 4))
|
||||
return edges, boundary, valences, poles
|
||||
|
||||
|
||||
def cage_report(built: Sheet) -> dict:
|
||||
"""A cage's counts for a report, either form: cageVerts, cageFaces, triangles, creases, corners, poles (valence
|
||||
-> how many vertices, the irregular ones only) and closed (no boundary edge)."""
|
||||
_, boundary, valences, poles = _cage_facts(len(built.V), built.faces, built.counts)
|
||||
tally: dict[str, int] = {}
|
||||
for valence in sorted(int(valences[v]) for v in poles):
|
||||
tally[str(valence)] = tally.get(str(valence), 0) + 1
|
||||
return {"cageVerts": len(built.V), "cageFaces": len(built.counts), "triangles": built.triangles, "creases": len(built.creases),
|
||||
"corners": len(built.corners), "poles": tally, "closed": not boundary}
|
||||
|
||||
|
||||
def subdivided_faces(built: Sheet, levels: int) -> int:
|
||||
"""Faces of the cage after `levels` Catmull-Clark levels (1 or more): a quad gives 4^levels, a triangle three
|
||||
quads at the first level and so 3 * 4^(levels - 1)."""
|
||||
return (len(built.counts) - built.triangles) * 4 ** levels + built.triangles * 3 * 4 ** (levels - 1)
|
||||
|
||||
|
||||
def poles(document: Any) -> list[int]:
|
||||
"""The poles a free cage's faces make, by authored index, ascending: what its sheet.poles must state. For a
|
||||
reader of a cage someone else modelled (tools/cage_export.py); every other refusal of the free form stands."""
|
||||
return [int(v) for v in _cage(document, gate=False).poles if v < len(document["verts"])]
|
||||
|
||||
|
||||
def _cage(document: Any, gate: bool = True) -> Sheet:
|
||||
"""The cage of a free description {verts, faces, creases, corners, poles, mirror, rim, flip}.
|
||||
|
||||
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. 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. 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"):
|
||||
flags[key] = document.get(key, False)
|
||||
if not isinstance(flags[key], bool):
|
||||
raise KitError(f"sheet.{key} must be true or false, not {flags[key]!r}")
|
||||
mirror, flip = flags["mirror"], flags["flip"]
|
||||
rim = _weight(document.get("rim", 1.0), "sheet.rim")
|
||||
verts, faces = document["verts"], document["faces"]
|
||||
if not isinstance(verts, list) or not 4 <= len(verts) <= CAGE_VERTS:
|
||||
raise KitError(f"sheet.verts must be 4 to {CAGE_VERTS} vertices, not {len(verts) if isinstance(verts, list) else verts!r}")
|
||||
for i, point in enumerate(verts):
|
||||
if not isinstance(point, list) or len(point) != 3 or not all(finite(v) for v in point):
|
||||
raise KitError(f"sheet.verts[{i}] must be three finite numbers [x, y, z]")
|
||||
A = len(verts)
|
||||
if not isinstance(faces, list) or not faces:
|
||||
raise KitError("sheet.faces must be an array of faces, each 3 or 4 vertex indices")
|
||||
for f, face in enumerate(faces):
|
||||
if not isinstance(face, list) or len(face) not in (3, 4):
|
||||
raise KitError(f"sheet.faces[{f}] must be 3 or 4 vertex indices, not {len(face) if isinstance(face, list) else face!r}: a cage's faces are triangles and quads")
|
||||
for k, v in enumerate(face):
|
||||
_index(v, f"sheet.faces[{f}][{k}]", 0, A - 1)
|
||||
if len(set(face)) != len(face):
|
||||
raise KitError(f"sheet.faces[{f}] names vertex {next(v for v in face if face.count(v) > 1)} twice")
|
||||
used = {v for face in faces for v in face}
|
||||
if len(used) != A:
|
||||
raise KitError(f"sheet.verts[{min(set(range(A)) - used)}] is in no face: every vertex of a cage is used")
|
||||
V = np.array(verts, dtype=np.float64)
|
||||
seam = np.zeros(A, dtype=bool)
|
||||
if mirror:
|
||||
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")
|
||||
seen, directed = {}, {}
|
||||
for f, face in enumerate(faces):
|
||||
key = tuple(sorted(face))
|
||||
if key in seen:
|
||||
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 {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:
|
||||
area += 0.5 * np.linalg.norm(np.cross(corners[3] - corners[2], corners[1] - corners[2]))
|
||||
if area < SHEET_AREA:
|
||||
raise KitError(f"sheet.faces[{f}] has area {area:.3g} m2, under {SHEET_AREA:g}: a collapsed face. Move its vertices apart")
|
||||
for a, b in zip(face, face[1:] + face[:1]):
|
||||
directed.setdefault((a, b), []).append(f)
|
||||
for (a, b), users in sorted(directed.items()):
|
||||
both = users + directed.get((b, a), [])
|
||||
if len(both) > 2 and a < b or len(users) > 2:
|
||||
raise KitError(f"sheet.faces: the edge between vertices {min(a, b)} and {max(a, b)} is in {len(both)} faces ({', '.join(str(f) for f in sorted(both))}): a cage's edge is in at most two")
|
||||
if len(users) == 2:
|
||||
raise KitError(f"sheet.faces[{users[1]}] crosses the edge between vertices {a} and {b} the same way as sheet.faces[{users[0]}]: the two are wound against each other. Reverse one")
|
||||
if mirror and seam[a] and seam[b] and len(both) == 2:
|
||||
raise KitError(f"sheet.faces[{both[0]}] and sheet.faces[{both[1]}] share the edge between vertices {min(a, b)} and {max(a, b)}, which lies on the mirror plane: "
|
||||
"with their reflections that edge is in four faces (a fin on the plane)")
|
||||
twin = np.arange(A)
|
||||
if mirror:
|
||||
twin[~seam] = A + np.arange(int((~seam).sum()))
|
||||
V = np.concatenate([V, V[~seam] * (-1.0, 1.0, 1.0)])
|
||||
built = [list(face) for face in faces] + [[int(twin[v]) for v in reversed(face)] for face in faces]
|
||||
else:
|
||||
built = [list(face) for face in faces]
|
||||
if flip:
|
||||
built = [face[::-1] for face in built]
|
||||
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):
|
||||
raise KitError("sheet.poles must be an array of vertex indices")
|
||||
for k, v in enumerate(declared):
|
||||
_index(v, f"sheet.poles[{k}]", 0, A - 1)
|
||||
if v in declared[:k]:
|
||||
raise KitError(f"sheet.poles[{k}] names vertex {v} twice")
|
||||
computed = [int(v) for v in poles if v < A]
|
||||
where = lambda v: f"vertex {v} (valence {int(valences[v])}{', on the boundary' if any(v in key for key in boundary) else ''})" # noqa: E731
|
||||
undeclared, regular = [v for v in computed if v not in declared], [v for v in declared if v not in computed]
|
||||
if undeclared:
|
||||
raise KitError(f"sheet.poles lacks {', '.join(where(v) for v in undeclared)}: a pole is declared or the faces are changed. "
|
||||
"A vertex is a pole when its valence is not 4 off the boundary, or not 2 or 3 on it")
|
||||
if regular:
|
||||
raise KitError(f"sheet.poles[{declared.index(regular[0])}] names {where(regular[0])}, which is no pole; the regular ones named: {', '.join(str(v) for v in regular)}")
|
||||
|
||||
def state(table, key, weight, where, what):
|
||||
if key in table and table[key][0] != weight:
|
||||
raise KitError(f"{where} gives {what} weight {weight:g} that {table[key][1]} gives {table[key][0]:g}: {what} has one weight")
|
||||
table.setdefault(key, (weight, where))
|
||||
|
||||
edges, pinned = {}, {}
|
||||
for name, table, size in (("creases", edges, 3), ("corners", pinned, 2)):
|
||||
runs = document.get(name, [])
|
||||
if not isinstance(runs, list):
|
||||
raise KitError(f"sheet.{name} must be an array")
|
||||
for k, run in enumerate(runs):
|
||||
where_run = f"sheet.{name}[{k}]"
|
||||
if not isinstance(run, list) or len(run) != size:
|
||||
raise KitError(f"{where_run} must be {'[a, b, weight]: an edge by its two vertices' if size == 3 else '[vertex, weight]'}")
|
||||
ends = [_index(v, f"{where_run}[{i}]", 0, A - 1) for i, v in enumerate(run[:-1])]
|
||||
weight = _weight(run[-1], f"{where_run}[{size - 1}]")
|
||||
if size == 2:
|
||||
for v in {ends[0], int(twin[ends[0]])}:
|
||||
state(pinned, v, weight, where_run, "a point")
|
||||
continue
|
||||
key = (min(ends), max(ends))
|
||||
if key not in cage_edges:
|
||||
raise KitError(f"{where_run}: vertices {ends[0]} and {ends[1]} share no face's edge: a crease lies on an edge of the cage")
|
||||
for a, b in {key, tuple(sorted((int(twin[ends[0]]), int(twin[ends[1]]))))}:
|
||||
state(edges, (a, b), weight, where_run, "an edge")
|
||||
for key in boundary:
|
||||
edges.setdefault(key, (rim, "sheet.rim"))
|
||||
kept = sorted((key, weight) for key, (weight, _) in edges.items() if weight > 0)
|
||||
held = sorted((key, weight) for key, (weight, _) in pinned.items() if weight > 0)
|
||||
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()), boundary="ALL")
|
||||
|
||||
|
||||
# --- reports -------------------------------------------------------------------------------------------------
|
||||
|
|
|
|||
|
|
@ -450,8 +450,10 @@ and about 0.002 s with them frozen.
|
|||
## Making a shell
|
||||
|
||||
`shell` makes an armor plate the way one is modelled by hand: fit a sparse subdivision cage, crease the edges that
|
||||
are facets' borders, give it a wall, then cut into it. The cage is a **loft**: rings of points with equal counts,
|
||||
quads between neighbouring rings. The description is a JSON object, `sheet`:
|
||||
are facets' borders, give it a wall, then cut into it. The description is a JSON object, `sheet`, in one of two
|
||||
forms, both compiled by `core.sheet` into the same cage: a **loft** (`rings`), below, or a **free cage** (`verts`
|
||||
and `faces`, [A free cage](#a-free-cage)). A sheet states exactly one of `rings` and `verts`. The loft is rings of
|
||||
points with equal counts, quads between neighbouring rings:
|
||||
|
||||
| key | default | what it says |
|
||||
| --- | --- | --- |
|
||||
|
|
@ -550,14 +552,111 @@ the corner.
|
|||
Refused, each before anything is written and naming the field and index: a missing or unknown key; a non-finite
|
||||
number; fewer than 2 or more than 64 rings or points; rings of unequal counts; a quad under 1e-8 m2 (a collapsed
|
||||
corner); a mirrored ring that does not start on x = 0 or has a point behind it; `mirror` with `closed`; a run out
|
||||
of range or with `from` not under `to`; a weight outside 0 to 1; more than 262144 subdivided faces (cage quads
|
||||
times 4 to the `levels`).
|
||||
of range or with `from` not under `to`; a weight outside 0 to 1; more than 262144 subdivided faces (a quad gives
|
||||
4 to the `levels`, a triangle three quarters of that).
|
||||
|
||||
On the pauldron (25 cage quads, 1600 subdivided faces, 3360 with the wall), `shell` took 3.5 ms a call with
|
||||
Blender's own update after it, and one whole evaluation of the Subdivision and Solidify 1.7 ms. With six cutters
|
||||
(four panel lines, two insets) and ribs under it, a rebuild took 0.92 s, which is its one Boolean evaluation.
|
||||
Medians of 3, interleaved, Blender 5.3 on Starfire (`tests/live/kitbash_faceted.py`, `costs`).
|
||||
|
||||
### A free cage
|
||||
|
||||
A loft is a grid: every vertex off its boundary has four edges, so it cannot state a triangle, a pole, or a crease
|
||||
that ends inside the surface. A hull modelled by hand uses all three. The bar is the fewest cage vertices that
|
||||
hold the form, with creases doing the work: a dense cage that only looks smooth after subdivision is the failure.
|
||||
The free form states the cage directly:
|
||||
|
||||
| key | default | what it says |
|
||||
| --- | --- | --- |
|
||||
| `verts` | required | 4 to 256 `[x, y, z]` in the shell's own frame |
|
||||
| `faces` | required | each 3 or 4 vertex indices, counter-clockwise seen from outside |
|
||||
| `creases` | `[]` | `[a, b, w]`: the edge between vertices a and b, weight 0 to 1 |
|
||||
| `corners` | `[]` | `[vertex, w]`: a vertex held as a corner |
|
||||
| `poles` | `[]` | the vertices of irregular valence, by index: a gate, below |
|
||||
| `mirror` | `false` | the cage is authored on one side of x = 0 and reflected |
|
||||
| `rim` | `1` | the weight of every boundary edge no crease names |
|
||||
| `flip` | `false` | reverse every face |
|
||||
|
||||
```json
|
||||
{"verts": [[0, 0, 0.5], [1, 0, 0], [0, 1, 0], [-1, 0, 0], [0, -1, 0], [1, 0, -1], [0, 1, -1]],
|
||||
"faces": [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [2, 1, 5, 6]],
|
||||
"creases": [[0, 1, 1.0], [0, 3, 1.0]], "poles": [1, 2], "rim": 0}
|
||||
```
|
||||
|
||||
**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
|
||||
exactly the poles the faces make. An undeclared pole and a declared vertex that is none are both refused, naming
|
||||
the vertex and its valence. The list changes nothing in the mesh: it is there so that no pole is an accident,
|
||||
since a pole is where a subdivision surface pinches or flattens. Put one where a crease runs through it or a
|
||||
triangle stands beside it, and where the form turns anyway.
|
||||
|
||||
**Triangles.** A triangle subdivides to three quads, so after one level the surface is all quads, and the wall,
|
||||
`cut`, `ribs` and `count_folds` take it as any shell. Use one where a crease run ends: the two cage edges
|
||||
either side of the crease close onto a point instead of carrying a loop across the rest of the form. Faces of
|
||||
five or more sides are refused.
|
||||
|
||||
**Budget.** Two cages modelled by hand are the measure. A whole ship hull, 1 m long: 46 control vertices (29
|
||||
authored under a mirror), 25 faces a side of which 6 are triangles, 9 creased edges a side, every one at weight
|
||||
1, six poles, each on a crease or beside a triangle. A petal: 10 vertices, 4 quads and 6 triangles, 5 creased
|
||||
ridges at weight 1, an uncreased outline. In both the creases are full weight and stand only where the form
|
||||
truly breaks (turns of 40 to 170 degrees); the longest straight silhouette edges are single cage edges; the cage's
|
||||
vertices stand outside the form, as subdivision shrinks toward the inside. An armour plate should cost about what
|
||||
the petal does. Add a vertex only where the limit surface cannot otherwise reach the form, and say why.
|
||||
|
||||
**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 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.
|
||||
|
||||
**The report** carries, for both forms, `cageVerts`, `cageFaces`, `triangles`, `creases`, `corners`, `poles`
|
||||
(`{"3": 2, "5": 1}`: valence to how many vertices, on the cage as built) and `closed` (no boundary edge);
|
||||
`rings` and `points` are null on a free cage.
|
||||
|
||||
**What it gives up.** A free cage is authored by index, by hand or by an agent: nothing derives it from a
|
||||
silhouette, and a wrong index is caught only where it breaks a rule above, not where it merely makes a worse form.
|
||||
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
|
||||
(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
|
||||
|
||||
An armor plate is not a kit part: it is any mesh, usually one made by `shell`. `cut` cuts it, or a
|
||||
|
|
|
|||
340
surfaces/blender/tests/live/kitbash_cage.py
Normal file
340
surfaces/blender/tests/live/kitbash_cage.py
Normal file
|
|
@ -0,0 +1,340 @@
|
|||
"""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; 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>
|
||||
|
||||
Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses
|
||||
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
|
||||
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
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import traceback
|
||||
import types
|
||||
from pathlib import Path
|
||||
|
||||
import bmesh
|
||||
import bpy
|
||||
import numpy as np
|
||||
|
||||
SURFACE = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(SURFACE / "tools"))
|
||||
import private_dirs # noqa: E402
|
||||
|
||||
_refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind))
|
||||
if _refused:
|
||||
raise SystemExit(_refused)
|
||||
OUT = sys.argv[sys.argv.index("--") + 1]
|
||||
if not Path(OUT).is_absolute():
|
||||
raise SystemExit(f"{OUT!r} is not an absolute path")
|
||||
package = types.ModuleType("brokkr_bridge")
|
||||
package.__path__ = [str(SURFACE / "brokkr_bridge")]
|
||||
sys.modules["brokkr_bridge"] = package
|
||||
from brokkr_bridge import blender_target as bt # noqa: E402
|
||||
|
||||
import addon_utils # noqa: E402
|
||||
import cage_export # noqa: E402
|
||||
import cage_score # noqa: E402
|
||||
|
||||
core = cage_export.load_core()
|
||||
sys.path.append(str(SURFACE))
|
||||
bpy.ops.wm.read_factory_settings(use_empty=True)
|
||||
for module in ("brokkr_mesh_polish", "brokkr_kitbash"):
|
||||
addon_utils.enable(module, default_set=True)
|
||||
target = bt.BrokkrBlenderTarget(bpy)
|
||||
WORK = Path(tempfile.mkdtemp(prefix="brokkr-kitbash-cage-"))
|
||||
target.configure_action_dirs("", str(WORK))
|
||||
target.reload_host_actions()
|
||||
R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], "readings": {}}
|
||||
COUNT, SECTION = [0], ["setup"]
|
||||
# Degrees: the largest dihedral angle across an edge of the tent's subdivided surface off its boundary; it is on the
|
||||
# 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 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.
|
||||
TENT = {"verts": [[0.0, 0.0, 0.5], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [-1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [1.0, 0.0, -1.0], [0.0, 1.0, -1.0]],
|
||||
"faces": [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [2, 1, 5, 6]], "creases": [[0, 1, 1.0], [0, 3, 1.0]], "poles": [1, 2], "rim": 0.0}
|
||||
# Half a lozenge hull, mirrored: seam vertices 0 to 3 (one 4 mm off the plane), a nose and tail triangle each side.
|
||||
HULL = {"verts": [[0.0, -1.0, 0.0], [0.004, 0.0, 0.3], [0.0, 1.0, 0.0], [0.0, 0.0, -0.3], [0.6, 0.0, 0.0]],
|
||||
"faces": [[0, 4, 1], [1, 4, 2], [2, 4, 3], [3, 4, 0]], "creases": [[0, 4, 1.0], [4, 2, 1.0]], "mirror": True}
|
||||
LOFT = {"rings": [[[0.3 * j - 0.45, 0.02 * j * j, 0.3 * i] for j in range(4)] for i in range(3)], "flip": True}
|
||||
CUTS = [{"name": "TentLine", "part": "slab", "params": "gap=0.02; length=0.4; depth=0.03", "origin": [0.3, -0.35, 3.0], "direction": [0, 0, -1]}]
|
||||
|
||||
|
||||
def check(name, ok, detail=None):
|
||||
R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else json.loads(json.dumps(detail, default=str))})
|
||||
|
||||
|
||||
def section(name):
|
||||
SECTION[0] = name
|
||||
|
||||
|
||||
def send(action, **fields):
|
||||
COUNT[0] += 1
|
||||
receipt = target.run_intent(bpy.context, {"commandId": f"live-{COUNT[0]}", "requestedBy": "nibu/hands", "action": action, **fields})
|
||||
result = None
|
||||
if receipt.get("hostResult"):
|
||||
try:
|
||||
result = json.loads(receipt["hostResult"])
|
||||
except ValueError:
|
||||
result = None
|
||||
print("SEND", action, receipt["status"], str(receipt["message"])[:300], flush=True)
|
||||
return receipt, result
|
||||
|
||||
|
||||
def evaluated(obj, only=None):
|
||||
"""An object as Blender evaluates it, as a bmesh; with `only`, with just the modifiers of those names shown."""
|
||||
hidden = [m for m in obj.modifiers if only is not None and m.name not in only 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())
|
||||
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()
|
||||
bm.normal_update()
|
||||
return bm
|
||||
|
||||
|
||||
def sharpest(obj):
|
||||
bm = evaluated(obj, only=("Kit Subsurf",))
|
||||
worst = max(math.degrees(e.link_faces[0].normal.angle(e.link_faces[1].normal, 0.0)) for e in bm.edges if len(e.link_faces) == 2)
|
||||
bm.free()
|
||||
return worst
|
||||
|
||||
|
||||
def state():
|
||||
return {o.name: (sorted(k for k in o.keys() if k.startswith("kit_")), len(o.data.vertices) if o.type == "MESH" else None, [m.name for m in o.modifiers]) for o in bpy.data.objects}, sorted(m.name for m in bpy.data.meshes)
|
||||
|
||||
|
||||
try:
|
||||
# --- live-free-cage-shell: counts at each level ----------------------------------------------------------------
|
||||
section("free-cage-triangle-counts")
|
||||
for levels in (1, 2, 3):
|
||||
receipt, report = send("brokkr_kitbash.shell", object_name="Tent", sheet=json.dumps(TENT), thickness=0.04, levels=levels, count_folds=True)
|
||||
tent = bpy.data.objects.get("Tent")
|
||||
expected = 1 * 4 ** levels + 4 * 3 * 4 ** (levels - 1)
|
||||
bm = evaluated(tent, only=("Kit Subsurf",))
|
||||
faces, sides = len(bm.faces), {len(f.verts) for f in bm.faces}
|
||||
bm.free()
|
||||
wall = evaluated(tent, only=("Kit Subsurf", "Kit Solidify"))
|
||||
closed, walled = all(e.is_manifold for e in wall.edges), len(wall.faces)
|
||||
wall.free()
|
||||
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 + 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")}
|
||||
== {"rings": None, "points": None, "cageVerts": 7, "cageFaces": 5, "triangles": 4, "creases": 2, "corners": 0, "poles": {"4": 2}, "closed": False}, report)
|
||||
check("the cage mesh is core.sheet's, face for face, and kit_shell is the request",
|
||||
[tuple(p.vertices) for p in tent.data.polygons] == [tuple(f) for f in TENT["faces"]] and np.abs(np.array([v.co[:] for v in tent.data.vertices]) - built.V).max() < 1e-6
|
||||
and json.loads(tent["kit_shell"])["sheet"] == TENT, tent["kit_shell"])
|
||||
|
||||
# --- the creases reach the surface -----------------------------------------------------------------------------------
|
||||
section("free-cage-crisp")
|
||||
crisp = sharpest(tent)
|
||||
attribute = tent.data.attributes["crease_edge"]
|
||||
kept = [d.value for d in attribute.data]
|
||||
attribute.data.foreach_set("value", [0.0] * len(kept)) # K1: what the surface is when the creases are not written
|
||||
tent.data.update()
|
||||
soft = sharpest(tent)
|
||||
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 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)
|
||||
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 ----------------------------------------------------------------------------------------------------------
|
||||
section("free-cage-mirror")
|
||||
receipt, report = send("brokkr_kitbash.shell", object_name="Hull", sheet=json.dumps(HULL), thickness=0.01)
|
||||
hull = bpy.data.objects.get("Hull")
|
||||
bm = evaluated(hull, only=("Kit Subsurf",))
|
||||
check("a mirrored cage closes over its seam: 6 vertices from 5, 8 triangles, the vertex 4 mm off the plane snapped onto it, no boundary edge on the cage or its surface, and its poles reported",
|
||||
receipt["status"] == "accepted" and (report["cageVerts"], report["cageFaces"], report["triangles"], report["closed"], report["creases"], report["subdividedFaces"]) == (6, 8, 8, True, 4, 8 * 3 * 16)
|
||||
and abs(hull.data.vertices[1].co.x) < 1e-9 and all(e.is_manifold for e in bm.edges) and len(bm.faces) == 384 and report["poles"] == {}, report)
|
||||
bm.free()
|
||||
|
||||
# --- rebuild a loft as a free cage -------------------------------------------------------------------------------------
|
||||
section("free-cage-rebuild")
|
||||
receipt, _ = send("brokkr_kitbash.shell", object_name="Plate", sheet=json.dumps(LOFT), thickness=0.03)
|
||||
plate_obj = bpy.data.objects["Plate"]
|
||||
plate_obj.data.materials.append(bpy.data.materials.new("Khaki"))
|
||||
receipt, _ = send("brokkr_kitbash.cut_many", object_name="Plate", cuts=json.dumps([{"name": "PlateLine", "part": "slab", "params": "gap=0.02; length=0.3; depth=0.02", "origin": [0.0, 3.0, 0.3], "direction": [0, -1, 0]}]))
|
||||
before = (plate_obj.as_pointer(), plate_obj.data.as_pointer(), sorted(c.name for c in plate_obj.children), sorted(o.name for o in plate_obj.modifiers["Kit Difference"].collection.objects), [s.material.name for s in plate_obj.material_slots])
|
||||
loft = core.sheet(LOFT)
|
||||
quads = loft.faces.reshape(-1, 4).tolist()
|
||||
FREE = {"verts": [[round(c, 6) for c in v] for v in loft.V.tolist()], "faces": quads[:5] + [quads[5][:3], [quads[5][0], quads[5][2], quads[5][3]]], "poles": [7, 10], "creases": [[5, 6, 1.0]]} # the last quad split along its diagonal: two boundary vertices of valence 4
|
||||
receipt, report = send("brokkr_kitbash.shell", object_name="Plate", sheet=json.dumps(FREE), thickness=0.03)
|
||||
again = bpy.data.objects.get("Plate")
|
||||
after = (again.as_pointer(), again.data.as_pointer(), sorted(c.name for c in again.children), sorted(o.name for o in again.modifiers["Kit Difference"].collection.objects), [s.material.name for s in again.material_slots])
|
||||
bm = evaluated(again)
|
||||
check("a loft shell rebuilt in place as a free cage keeps its object, mesh datablock, cutter, Boolean and material slot; the report says rebuilt, 2 triangles and the cage's poles; the plate is still cut and closed",
|
||||
receipt["status"] == "accepted" and before == after and before[2:] == (["PlateLine"], ["PlateLine"], ["Khaki"]) and report["rebuilt"] is True and (report["triangles"], report["rings"], report["cageFaces"]) == (2, None, 7)
|
||||
and report["poles"] == {"4": 2} and report["children"] == ["PlateLine"] and sum(1 for e in bm.edges if not e.is_manifold) == 0 and len(bm.faces) > 2 * report["subdividedFaces"], [receipt["message"], report, before, after])
|
||||
bm.free()
|
||||
|
||||
# --- the gate refuses before it writes -------------------------------------------------------------------------------
|
||||
section("free-cage-refusals")
|
||||
for label, name, sheet, expected in (
|
||||
("an undeclared pole, on a shell", "Plate", {**FREE, "poles": [7]}, "sheet.poles lacks vertex 10 (valence 4, on the boundary)"),
|
||||
("a declared vertex that is no pole, on a new name", "New", {**TENT, "poles": [1, 2, 0]}, "sheet.poles[2] names vertex 0 (valence 4), which is no pole"),
|
||||
("rings with verts", "New", {**TENT, "rings": LOFT["rings"]}, "sheet states both rings and verts"),
|
||||
("a face of five sides", "New", {**TENT, "faces": TENT["faces"][:4] + [[2, 1, 5, 6, 3]]}, "sheet.faces[4] must be 3 or 4 vertex indices, not 5"),
|
||||
("two faces wound against each other", "Plate", {**FREE, "faces": FREE["faces"][:6] + [FREE["faces"][6][::-1]]}, "the two are wound against each other")):
|
||||
held = state()
|
||||
receipt, _ = send("brokkr_kitbash.shell", object_name=name, sheet=json.dumps(sheet))
|
||||
check(f"refused, scene unchanged: {label}", receipt["status"] != "accepted" and expected in str(receipt["message"]) and state() == held, [receipt["status"], receipt["message"]])
|
||||
check("no refusal made an object", "New" not in bpy.data.objects, None)
|
||||
|
||||
# --- export-score-roundtrip -----------------------------------------------------------------------------------------
|
||||
section("export-score-roundtrip")
|
||||
saved = str(WORK / "scratch.blend")
|
||||
probe = bpy.data.objects.new("Probe Cage", bpy.data.meshes.new("Probe Cage")) # a cage as a person leaves one: a mesh, a Mirror, creases on edges; made here, no one's file
|
||||
bpy.context.scene.collection.objects.link(probe)
|
||||
probe.data.from_pydata(HULL["verts"], [], HULL["faces"])
|
||||
probe.data.update(calc_edges=True)
|
||||
weights = probe.data.attributes.new("crease_edge", "FLOAT", "EDGE")
|
||||
for e in probe.data.edges:
|
||||
weights.data[e.index].value = 1.0 if tuple(sorted(e.vertices)) in ((0, 4), (2, 4)) else 0.0
|
||||
probe.modifiers.new("Mirror", "MIRROR")
|
||||
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 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, 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:
|
||||
R["ok"] = all(c["ok"] for c in R["checks"])
|
||||
R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())}
|
||||
Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8")
|
||||
for c in R["checks"]:
|
||||
print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True)
|
||||
print("READINGS", R["readings"], flush=True)
|
||||
sys.exit(0 if R["ok"] else 1)
|
||||
153
surfaces/blender/tests/live/kitbash_cage.result.json
Normal file
153
surfaces/blender/tests/live/kitbash_cage.result.json
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
{
|
||||
"blender": "5.3.0",
|
||||
"checks": [
|
||||
{
|
||||
"name": "a cage of 4 triangles and a quad at 1 levels: subdividedFaces is 4^L + 4 * 3 * 4^(L-1) and the evaluated surface has that many faces, all quads",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "at 1 levels the wall is closed, twice the surface and a rim, and count_folds counts none folded",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "a cage of 4 triangles and a quad at 2 levels: subdividedFaces is 4^L + 4 * 3 * 4^(L-1) and the evaluated surface has that many faces, all quads",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "at 2 levels the wall is closed, twice the surface and a rim, and count_folds counts none folded",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "a cage of 4 triangles and a quad at 3 levels: subdividedFaces is 4^L + 4 * 3 * 4^(L-1) and the evaluated surface has that many faces, all quads",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "at 3 levels the wall is closed, twice the surface and a rim, and count_folds counts none folded",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "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",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "the cage mesh is core.sheet's, face for face, and kit_shell is the request",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "the creased ridge stays an edge under subdivision: over 34.0 degrees, and under it with crease_edge cleared",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"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
|
||||
},
|
||||
{
|
||||
"name": "a mirrored cage closes over its seam: 6 vertices from 5, 8 triangles, the vertex 4 mm off the plane snapped onto it, no boundary edge on the cage or its surface, and its poles reported",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "a loft shell rebuilt in place as a free cage keeps its object, mesh datablock, cutter, Boolean and material slot; the report says rebuilt, 2 triangles and the cage's poles; the plate is still cut and closed",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: an undeclared pole, on a shell",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a declared vertex that is no pole, on a new name",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: rings with verts",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a face of five sides",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: two faces wound against each other",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "no refusal made an object",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"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": "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_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,
|
||||
"openRoundTripPct": 1.7e-05,
|
||||
"openRoundTripPctB1": 7.7,
|
||||
"scoreLiftedHausdorffPct": 3.3,
|
||||
"scoreSameHausdorffPct": 0.0
|
||||
},
|
||||
"ok": true
|
||||
}
|
||||
|
|
@ -214,7 +214,8 @@ try:
|
|||
and sorted(stored) == ["bevel", "levels", "offset", "sheet", "thickness"] and stored["sheet"] == PAULDRON
|
||||
and (stored["levels"], stored["offset"]) == (3, -1.0) and abs(stored["thickness"] - WALL) < 1e-7, [receipt["message"], stored])
|
||||
check("shell reports cage facts: rings, points, quads, creased edges, the subdivided count, an upward facing, no children",
|
||||
report and sorted(report) == ["cageFaces", "children", "corners", "creases", "facing", "folded", "levels", "object", "offset", "points", "rebuilt", "rings", "subdividedFaces", "thickness"]
|
||||
report and sorted(report) == ["cageFaces", "cageVerts", "children", "closed", "corners", "creases", "facing", "folded", "levels", "object", "offset", "points", "poles", "rebuilt", "rings", "subdividedFaces", "thickness", "triangles"]
|
||||
and (report["cageVerts"], report["triangles"], report["poles"], report["closed"]) == (36, 0, {}, False)
|
||||
and (report["object"], report["rebuilt"], report["rings"], report["points"], report["cageFaces"], report["creases"], report["corners"], report["subdividedFaces"], report["levels"],
|
||||
report["thickness"], report["offset"], report["children"]) == ("Pauldron", False, 6, 6, 25, 25, 0, 1600, 3, 0.06, -1.0, [])
|
||||
and report["facing"][2] > 0.5 and abs(np.linalg.norm(report["facing"]) - 1.0) < 1e-5, report)
|
||||
|
|
|
|||
|
|
@ -2003,6 +2003,143 @@ ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbas
|
|||
"brokkr_kitbash.shell", "brokkr_kitbash.hose"]
|
||||
|
||||
|
||||
class CageTests(unittest.TestCase):
|
||||
"""core.sheet's free form: a cage of vertices and faces of 3 or 4 sides. Exact arithmetic: each assertion is
|
||||
the built value and names the mutant it kills."""
|
||||
|
||||
@staticmethod
|
||||
def fan(quads: int, lift=0.2):
|
||||
"""`quads` quads round vertex 0, counter-clockwise seen from +z (their outside): 0 has valence `quads`."""
|
||||
ring = [[math.cos(k * math.pi / quads), math.sin(k * math.pi / quads), 0.0] for k in range(2 * quads)]
|
||||
return [[0.0, 0.0, lift]] + ring, [[0, 2 * k + 1, 2 * k + 2, (2 * k + 2) % (2 * quads) + 1] for k in range(quads)]
|
||||
|
||||
PYRAMID = ([[0.0, 0.0, 0.5], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [-1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [1.0, 0.0, -1.0], [0.0, 1.0, -1.0]],
|
||||
[[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [2, 1, 5, 6]]) # four triangles round an apex of valence 4, a quad hung under one edge
|
||||
|
||||
def refused(self, pattern, **sheet):
|
||||
with self.assertRaisesRegex(core.KitError, pattern):
|
||||
core.sheet(sheet)
|
||||
|
||||
def test_a_free_cage_stating_a_loft_is_the_loft(self):
|
||||
"""free-cage-grid-equals-loft. C1 (a second path that orders, winds or creases differently): the same Sheet,
|
||||
array for array, open and closed."""
|
||||
for extra in ({"creases": [{"ring": 1, "from": 0, "to": 3, "weight": 0.5}, {"column": 2, "from": 0, "to": 2, "weight": 0.25}], "rim": 0.75},
|
||||
{"closed": True, "creases": [{"ring": 1, "from": 0, "to": 4, "weight": 1.0}]}, {"flip": True, "rim": 0.0}):
|
||||
loft = core.sheet({"rings": SheetTests.rings(3, 4), **extra})
|
||||
runs = [[int(a), int(b), w] for (a, b), w in zip(loft.creases.tolist(), loft.weights.tolist())]
|
||||
free = core.sheet({"verts": loft.V.tolist(), "faces": loft.faces.reshape(-1, 4).tolist(), "creases": runs, "rim": 0.0})
|
||||
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()})
|
||||
self.assertEqual((free.creases.tolist(), free.weights.tolist()), (plain.creases.tolist(), plain.weights.tolist()))
|
||||
self.assertEqual(core.cage_report(free), {"cageVerts": 12, "cageFaces": 6, "triangles": 0, "creases": 10, "corners": 0, "poles": {}, "closed": False})
|
||||
|
||||
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_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 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)]
|
||||
self.assertTrue((np.cross(V[:, 1] - V[:, 0], V[:, 3] - V[:, 0])[:, 1] > 0).all()) # both halves face +y
|
||||
self.assertEqual(SheetTests.weights(built), {(2, 3): 0.75, (6, 7): 0.75})
|
||||
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 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
|
||||
left = core.sheet({"verts": [[-x, y, z] for x, y, z in verts[:1] + [[0.0, 0.0, 1.0]] + verts[2:]], "faces": [face[::-1] for face in faces], "mirror": True})
|
||||
self.assertEqual(left.V[6:, 0].tolist(), [0.5, 0.5, 1.0, 1.0]) # authored on -x, reflected to +x
|
||||
verts[5][0] = -1.0
|
||||
self.refused(r"sheet\.verts\[5\] has x = -1: a mirrored cage is authored on one side", verts=verts, faces=faces, mirror=True)
|
||||
|
||||
def test_triangles_are_counted_as_three_quads(self):
|
||||
"""free-cage-triangle-counts. C3 (every face counted as a quad): q quads and t triangles subdivide to
|
||||
q * 4^L + t * 3 * 4^(L-1) faces."""
|
||||
verts, faces = self.PYRAMID
|
||||
built = core.sheet({"verts": verts, "faces": faces, "poles": [1, 2]})
|
||||
self.assertEqual((built.counts.tolist(), built.triangles, len(built.faces)), ([3, 3, 3, 3, 4], 4, 16))
|
||||
self.assertEqual([core.subdivided_faces(built, levels) for levels in (1, 2, 3)], [4 * 3 + 4, 4 * 12 + 16, 4 * 48 + 64])
|
||||
self.assertEqual(core.cage_report(built), {"cageVerts": 7, "cageFaces": 5, "triangles": 4, "creases": 6, "corners": 0, "poles": {"4": 2}, "closed": False})
|
||||
loft = core.sheet({"rings": SheetTests.rings(3, 4)})
|
||||
self.assertEqual([core.subdivided_faces(loft, levels) for levels in (1, 3)], [24, 384])
|
||||
|
||||
def test_poles_are_declared_or_refused(self):
|
||||
"""free-cage-pole-gate. C4 (a gate that compares counts, or skips the check): the declared set must be the
|
||||
computed set, vertex for vertex."""
|
||||
for quads in (3, 5):
|
||||
verts, faces = self.fan(quads)
|
||||
self.refused(rf"sheet\.poles lacks vertex 0 \(valence {quads}\)", verts=verts, faces=faces)
|
||||
self.refused(rf"sheet\.poles lacks vertex 0 \(valence {quads}\)", verts=verts, faces=faces, poles=[1]) # one named, one computed: the count agrees, the set does not
|
||||
built = core.sheet({"verts": verts, "faces": faces, "poles": [0]})
|
||||
self.assertEqual((built.poles.tolist(), core.cage_report(built)["poles"]), ([0], {str(quads): 1}))
|
||||
verts, faces = self.fan(4) # valence 4 at the centre; the rim has valence 2 and 3: no pole anywhere
|
||||
self.assertEqual(core.sheet({"verts": verts, "faces": faces}).poles.tolist(), [])
|
||||
self.refused(r"sheet\.poles\[0\] names vertex 0 \(valence 4\), which is no pole", verts=verts, faces=faces, poles=[0])
|
||||
self.refused(r"sheet\.poles\[0\] names vertex 2 \(valence 2, on the boundary\), which is no pole", verts=verts, faces=faces, poles=[2])
|
||||
self.refused(r"sheet\.poles\[1\] names vertex 0 twice", verts=self.fan(3)[0], faces=self.fan(3)[1], poles=[0, 0])
|
||||
verts, faces = self.PYRAMID
|
||||
self.refused(r"sheet\.poles lacks vertex 1 \(valence 4, on the boundary\), vertex 2 \(valence 4, on the boundary\)", verts=verts, faces=faces)
|
||||
|
||||
def test_a_bad_cage_is_refused_by_field_and_index(self):
|
||||
"""free-cage-refusals. C5 (a check dropped): each fault is refused, naming where."""
|
||||
verts, faces = self.fan(4)
|
||||
ok = {"verts": verts, "faces": faces}
|
||||
self.refused(r"sheet\.verts\[9\] is in no face", **{**ok, "verts": verts + [[5.0, 5.0, 5.0]]})
|
||||
self.refused(r"sheet\.faces\[1\] must be 3 or 4 vertex indices, not 2", **{**ok, "faces": [faces[0], [0, 3]] + faces[1:]})
|
||||
self.refused(r"sheet\.faces\[0\] must be 3 or 4 vertex indices, not 5", **{**ok, "faces": [[0, 1, 2, 3, 4]] + faces[1:]})
|
||||
self.refused(r"sheet\.faces\[2\] names vertex 5 twice", **{**ok, "faces": faces[:2] + [[0, 5, 5, 7]] + faces[3:]})
|
||||
self.refused(r"sheet\.faces\[3\]\[2\] must be a whole number from 0 to 8, not 9", **{**ok, "faces": faces[:3] + [[0, 7, 9, 1]]})
|
||||
self.refused(r"sheet\.faces\[4\] has the vertices of sheet\.faces\[0\]: a duplicate face", **{**ok, "faces": faces + [[3, 2, 1, 0]]})
|
||||
wing = [[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 1.0], [1.0, 0.0, 0.0], [-1.0, 0.0, 0.0], [-1.0, 0.0, 1.0], [0.0, 1.0, 0.0], [0.0, 1.0, 1.0]]
|
||||
self.refused(r"the edge between vertices 0 and 1 is in 3 faces \(0, 1, 2\)", verts=wing, faces=[[0, 1, 2, 3], [1, 0, 4, 5], [0, 1, 7, 6]])
|
||||
self.refused(r"sheet\.faces\[1\] crosses the edge between vertices 0 and 1 the same way as sheet\.faces\[0\]", verts=wing[:6], faces=[[0, 1, 2, 3], [0, 1, 5, 4]])
|
||||
self.refused(r"sheet\.faces\[0\] and sheet\.faces\[1\] share the edge between vertices 0 and 1, which lies on the mirror plane",
|
||||
verts=wing[:4] + [[1.0, 1.0, 0.0], [1.0, 1.0, 1.0]], faces=[[0, 1, 2, 3], [1, 0, 4, 5]], mirror=True)
|
||||
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)
|
||||
self.refused(r"sheet\.verts must be 4 to 256 vertices, not 3", verts=verts[:3], faces=[[0, 1, 2]])
|
||||
self.refused(r"sheet\.verts\[2\] must be three finite numbers", **{**ok, "verts": verts[:2] + [[0.0, float("nan"), 0.0]] + verts[3:]})
|
||||
self.refused(r"sheet has no key 'closed'", closed=True, **ok)
|
||||
self.refused(r"sheet\.creases\[0\]: vertices 1 and 5 share no face's edge", creases=[[1, 5, 1.0]], **ok)
|
||||
self.refused(r"sheet\.creases\[1\] gives an edge weight 0\.5 that sheet\.creases\[0\] gives 1", creases=[[0, 1, 1.0], [1, 0, 0.5]], **ok)
|
||||
self.refused(r"sheet\.creases\[0\]\[2\] must be a number from 0 to 1, not 2", creases=[[0, 1, 2]], **ok)
|
||||
self.refused(r"sheet\.corners\[0\] must be \[vertex, weight\]", corners=[[0]], **ok)
|
||||
self.refused(r"sheet\.creases\[0\] must be \{ring, from, to, weight\}", rings=SheetTests.rings(), creases=[[0, 1, 1.0]]) # the loft keeps its own crease form
|
||||
self.refused(r"sheet has no key 'poles'", rings=SheetTests.rings(), poles=[])
|
||||
|
||||
|
||||
class HostFileTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.document = json.loads((SURFACE / "brokkr_kitbash" / "brokkr_actions.json").read_text(encoding="utf-8"))
|
||||
|
|
@ -2195,7 +2332,7 @@ class OwnershipTests(unittest.TestCase):
|
|||
self.assertEqual((shell.count("evaluable("), shell.count("folded_faces("), shell.count("self.count_folds")), (1, 1, 2))
|
||||
self.assertLess(shell.index("if self.count_folds:"), shell.index("with self.wall_alone(obj):"))
|
||||
self.assertLess(shell.index("with self.wall_alone(obj):"), shell.index("evaluable("))
|
||||
self.assertIn("self.folded_faces(context, obj, cage_faces * 4 ** self.levels) if self.count_folds else None", shell)
|
||||
self.assertIn("self.folded_faces(context, obj, subdivided) if self.count_folds else None", shell)
|
||||
self.assertLess(count.index("wall_alone(shell):"), count.index("evaluable("))
|
||||
self.assertEqual((count.count("evaluable("), count.count("to_mesh("), source.count("folded_faces("), source.count("wall_alone(")), (1, 1, 2, 3))
|
||||
self.assertLess(alone.index("finally:"), alone.index("modifier.show_viewport = True"))
|
||||
|
|
|
|||
88
surfaces/blender/tools/cage_export.py
Normal file
88
surfaces/blender/tools/cage_export.py
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
"""Write one object of a .blend as a free cage document, the form brokkr_kitbash.shell's sheet takes.
|
||||
|
||||
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tools/cage_export.py -- <copy.blend> <object> <out.json>
|
||||
|
||||
For reading a cage a person modelled by hand: its vertex budget, faces, creases and poles, and as the reference
|
||||
of tools/cage_score.py. <copy.blend> is a COPY of the file, made by whoever runs this: the script opens it, reads
|
||||
one mesh, writes <out.json> (an absolute path) and nothing else, and never saves a .blend. It refuses to start
|
||||
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 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
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import bpy
|
||||
|
||||
SURFACE = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def load_core():
|
||||
spec = importlib.util.spec_from_file_location("brokkr_kitbash_core_tool", SURFACE / "brokkr_kitbash" / "core.py")
|
||||
core = importlib.util.module_from_spec(spec)
|
||||
sys.modules[spec.name] = core
|
||||
spec.loader.exec_module(core)
|
||||
return core
|
||||
|
||||
|
||||
def export(obj, core) -> dict:
|
||||
"""The document of a mesh object's cage. Raises core.KitError when the cage is none core.sheet takes."""
|
||||
if obj.type != "MESH":
|
||||
raise core.KitError(f"{obj.name!r} is a {obj.type}, not a mesh")
|
||||
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]
|
||||
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 [],
|
||||
"corners": [[v.index, round(float(corners.data[v.index].value), 4)] for v in mesh.vertices if corners.data[v.index].value > 0] if corners else [],
|
||||
"mirror": bool(mirrors), "rim": 0.0}
|
||||
sheet["poles"] = core.poles(sheet)
|
||||
core.sheet(sheet)
|
||||
return {"object": obj.name, "modifiers": [[m.type, m.name] for m in obj.modifiers], "matrixWorld": core.rows(obj.matrix_world), "sheet": sheet}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import private_dirs
|
||||
refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind))
|
||||
if refused:
|
||||
raise SystemExit(f"cage_export: {refused}")
|
||||
arguments = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
|
||||
if len(arguments) != 3 or not Path(arguments[2]).is_absolute():
|
||||
raise SystemExit("usage: blender --background --factory-startup --python cage_export.py -- <copy.blend> <object> <absolute out.json>")
|
||||
blend, name, out = arguments
|
||||
core = load_core()
|
||||
bpy.ops.wm.open_mainfile(filepath=str(Path(blend).resolve()), load_ui=False, use_scripts=False)
|
||||
obj = bpy.data.objects.get(name)
|
||||
if obj is None:
|
||||
raise SystemExit(f"cage_export: {blend} has no object {name!r}; its meshes: {', '.join(sorted(o.name for o in bpy.data.objects if o.type == 'MESH'))}")
|
||||
try:
|
||||
document = export(obj, core)
|
||||
except core.KitError as error:
|
||||
raise SystemExit(f"cage_export: {name!r} is no free cage: {error}") from None
|
||||
Path(out).write_text(json.dumps(document, indent=1), encoding="utf-8")
|
||||
print("cage_export:", json.dumps({key: core.cage_report(core.sheet(document["sheet"]))[key] for key in ("cageVerts", "cageFaces", "triangles", "creases", "poles", "closed")}), flush=True)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
210
surfaces/blender/tools/cage_score.py
Normal file
210
surfaces/blender/tools/cage_score.py
Normal file
|
|
@ -0,0 +1,210 @@
|
|||
"""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>
|
||||
|
||||
Each input is a sheet (either form of brokkr_kitbash.shell's) or a cage_export.py document holding one. Both are
|
||||
built by brokkr_kitbash.shell through the add-on's own agent turn, at three levels, and read with their Kit
|
||||
Subsurf alone: the tool measures what the tool builds. <out.json> is an absolute path and the one file written;
|
||||
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. 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
|
||||
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
|
||||
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, 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())
|
||||
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()
|
||||
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):
|
||||
tree = BVHTree.FromPolygons([Vector(v) for v in V], [tuple(int(i) for i in t) for t in triangles])
|
||||
return np.array([tree.find_nearest(Vector(p))[3] for p in points])
|
||||
|
||||
|
||||
def silhouette(V, triangles, axis, low, scale):
|
||||
"""A PIXELS-square mask of the triangles seen along `axis`, in the frame (low, scale) both surfaces share."""
|
||||
keep = [k for k in range(3) if k != axis]
|
||||
P = (V[:, keep] - low[keep]) * scale
|
||||
mask = np.zeros((PIXELS, PIXELS), dtype=bool)
|
||||
for a, b, c in P[triangles]:
|
||||
x0, y0 = np.floor(np.minimum(np.minimum(a, b), c)).astype(int).clip(0, PIXELS - 1)
|
||||
x1, y1 = np.ceil(np.maximum(np.maximum(a, b), c)).astype(int).clip(0, PIXELS - 1)
|
||||
area = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
|
||||
if abs(area) < 1e-12:
|
||||
continue
|
||||
X, Y = np.meshgrid(np.arange(x0, x1 + 1) + 0.5, np.arange(y0, y1 + 1) + 0.5)
|
||||
u = ((b[0] - X) * (c[1] - Y) - (b[1] - Y) * (c[0] - X)) / area
|
||||
v = ((c[0] - X) * (a[1] - Y) - (c[1] - Y) * (a[0] - X)) / area
|
||||
mask[y0:y1 + 1, x0:x1 + 1] |= (u >= 0) & (v >= 0) & (u + v <= 1)
|
||||
return mask
|
||||
|
||||
|
||||
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."""
|
||||
built, reports = {}, {}
|
||||
try:
|
||||
for role, sheet in (("agent", agent), ("reference", reference)):
|
||||
name = f"Cage Score {role.title()}"
|
||||
receipt, report = send("brokkr_kitbash.shell", object_name=name, sheet=json.dumps(sheet), levels=LEVELS, thickness=0.001)
|
||||
if receipt["status"] != "accepted":
|
||||
raise SystemExit(f"cage_score: the {role} cage was refused: {receipt['message']}")
|
||||
reports[role] = {key: report[key] for key in COUNTS}
|
||||
built[role] = surface(bpy.data.objects[name])
|
||||
finally:
|
||||
for role in ("agent", "reference"):
|
||||
obj = bpy.data.objects.get(f"Cage Score {role.title()}")
|
||||
if obj is not None:
|
||||
mesh = obj.data
|
||||
bpy.data.objects.remove(obj)
|
||||
bpy.data.meshes.remove(mesh)
|
||||
(VA, TA, WA, SA), (VB, TB, WB, SB) = built["agent"], built["reference"]
|
||||
extent = float(np.ptp(VB, axis=0).max())
|
||||
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())
|
||||
overlap = {}
|
||||
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)
|
||||
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": {"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:
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import private_dirs
|
||||
refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind))
|
||||
if refused:
|
||||
raise SystemExit(f"cage_score: {refused}")
|
||||
arguments = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
|
||||
if len(arguments) != 3 or not Path(arguments[2]).is_absolute():
|
||||
raise SystemExit("usage: blender --background --factory-startup --python cage_score.py -- <agent.json> <reference.json> <absolute out.json>")
|
||||
sheets = []
|
||||
for path in arguments[:2]:
|
||||
document = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
sheets.append(document["sheet"] if "sheet" in document else document)
|
||||
package = types.ModuleType("brokkr_bridge")
|
||||
package.__path__ = [str(SURFACE / "brokkr_bridge")]
|
||||
sys.modules["brokkr_bridge"] = package
|
||||
blender_target = importlib.import_module("brokkr_bridge.blender_target")
|
||||
import addon_utils
|
||||
sys.path.append(str(SURFACE))
|
||||
bpy.ops.wm.read_factory_settings(use_empty=True)
|
||||
for module in ("brokkr_mesh_polish", "brokkr_kitbash"):
|
||||
addon_utils.enable(module, default_set=True)
|
||||
target = blender_target.BrokkrBlenderTarget(bpy)
|
||||
target.configure_action_dirs("", str(Path(arguments[2]).parent))
|
||||
target.reload_host_actions()
|
||||
count = [0]
|
||||
|
||||
def send(action, **fields):
|
||||
count[0] += 1
|
||||
receipt = target.run_intent(bpy.context, {"commandId": f"cage-score-{count[0]}", "requestedBy": "tools/cage_score", "action": action, **fields})
|
||||
return receipt, json.loads(receipt["hostResult"]) if receipt.get("hostResult") else None
|
||||
|
||||
result = score(sheets[0], sheets[1], send)
|
||||
Path(arguments[2]).write_text(json.dumps(result, indent=1), encoding="utf-8")
|
||||
print("cage_score:", json.dumps(result), flush=True)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Loading…
Reference in a new issue