From 7de1e25e609f2ad41fae577cae33cdb7f229c93b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 02:17:45 +0100 Subject: [PATCH] brokkr_mesh_polish: repair and cut_parts turn no face; orient keeps the hierarchy; the tests pin the operators Soul falsified PR 22: repair's unconditional recalc_face_normals reversed 4,565 of 23,341 and 15,735 of 28,426 triangles on two further Tripo hulls, which a single-sided material culls. repair now leaves every winding alone; recalc_normals is opt-in and reports windingFlipped. cut_parts no longer recalculates either. Custom shading normals are carried through weld, fill and cut as plain directions and set back, new faces are shaded by their own direction, and delight reads those shading normals instead of winding-derived ones. audit: windingAgainstNormals, and uvMirroredTriangles (texture parity against the shading normals) in place of uvFlippedTriangles, which changed whenever a winding did. orient: object_name scopes it to a root and its descendants; parents and pivots are kept. cut_parts: a mesh with no material keeps a bare first slot, so only caps take the cap material. Tests: 13 more unit tests and 18 more live checks (43 with BROKKR_POLISH_HULLS). The live sphere is now torn, half inside out under outward custom normals. Soul's 26 mutants and 11 of this batch's own all die. Co-Authored-By: Claude Fable 5.2 --- .../blender/brokkr_mesh_polish/__init__.py | 148 ++++- .../brokkr_mesh_polish/brokkr_actions.json | 6 +- surfaces/blender/brokkr_mesh_polish/core.py | 20 +- surfaces/blender/tests/live/mesh_polish.py | 259 +++++++- .../tests/live/mesh_polish.result.json | 585 ++++++++++++++++-- surfaces/blender/tests/test_mesh_polish.py | 115 +++- 6 files changed, 1017 insertions(+), 116 deletions(-) diff --git a/surfaces/blender/brokkr_mesh_polish/__init__.py b/surfaces/blender/brokkr_mesh_polish/__init__.py index af1916c..473550d 100644 --- a/surfaces/blender/brokkr_mesh_polish/__init__.py +++ b/surfaces/blender/brokkr_mesh_polish/__init__.py @@ -45,15 +45,17 @@ def mesh_objects(name: str) -> list: def arrays(obj) -> dict: - """World-space triangle arrays of a mesh object: V, T, UV (per corner, or None), N (vertex normals), - polygon (the polygon each triangle came from).""" + """World-space triangle arrays of a mesh object: V, T, UV (per corner, or None), CN (per corner, the + normals the mesh is shaded with: its custom normals when it has them), N (per vertex, the mean of its + corners' CN) and polygon (the polygon each triangle came from). The normals never come from the winding + alone when the mesh carries custom normals, so a shell wound inside out still reads as it is drawn.""" mesh = obj.data mesh.calc_loop_triangles() count = len(mesh.loop_triangles) V = np.empty(len(mesh.vertices) * 3, dtype=np.float32) mesh.vertices.foreach_get("co", V) - N = np.empty(len(mesh.vertices) * 3, dtype=np.float32) - mesh.vertex_normals.foreach_get("vector", N) + corner = np.empty(len(mesh.loops) * 3, dtype=np.float32) + mesh.corner_normals.foreach_get("vector", corner) T = np.empty(count * 3, dtype=np.int32) mesh.loop_triangles.foreach_get("vertices", T) L = np.empty(count * 3, dtype=np.int32) @@ -62,14 +64,18 @@ def arrays(obj) -> dict: mesh.loop_triangles.foreach_get("polygon_index", P) world = np.array(obj.matrix_world, dtype=np.float64) V = V.reshape(-1, 3).astype(np.float64) @ world[:3, :3].T + world[:3, 3] - N = N.reshape(-1, 3).astype(np.float64) @ np.linalg.inv(world[:3, :3]) + corner = corner.reshape(-1, 3).astype(np.float64) @ np.linalg.inv(world[:3, :3]) + corner /= np.maximum(np.linalg.norm(corner, axis=1, keepdims=True), 1e-30) + CN = corner[L.reshape(-1, 3)] + N = np.zeros((len(V), 3)) + np.add.at(N, T.reshape(-1), CN.reshape(-1, 3)) N /= np.maximum(np.linalg.norm(N, axis=1, keepdims=True), 1e-30) UV = None if mesh.uv_layers.active is not None: flat = np.empty(len(mesh.loops) * 2, dtype=np.float32) mesh.uv_layers.active.uv.foreach_get("vector", flat) UV = flat.reshape(-1, 2).astype(np.float64)[L.reshape(-1, 3)] - return {"V": V, "T": T.reshape(-1, 3).astype(np.int64), "UV": UV, "N": N, "polygon": P} + return {"V": V, "T": T.reshape(-1, 3).astype(np.int64), "UV": UV, "N": N, "CN": CN, "polygon": P} def merged(objects: list) -> dict: @@ -78,6 +84,7 @@ def merged(objects: list) -> dict: offsets = np.cumsum([0] + [len(p["V"]) for p in parts[:-1]]) uv = None if any(p["UV"] is None for p in parts) else np.concatenate([p["UV"] for p in parts]) return {"V": np.concatenate([p["V"] for p in parts]), "N": np.concatenate([p["N"] for p in parts]), + "CN": np.concatenate([p["CN"] for p in parts]), "T": np.concatenate([p["T"] + o for p, o in zip(parts, offsets)]), "UV": uv} @@ -198,7 +205,14 @@ def upsample(field: np.ndarray, height: int, width: int) -> np.ndarray: def pin_uvs(bm, faces) -> None: """Give each new face (a filled hole, a cap) one UV point, taken from an old face beside it, so it shows that texel's colour and takes no area of the texture: a face made by filling has no place in the UV map, - and corners copied from several islands would smear the atlas across it and overlap everything.""" + and corners copied from several islands would smear the atlas across it and overlap everything. The fill + also copies its neighbours' stashed shading normals onto the new corners; those are cleared, so the new + face is shaded by its own direction.""" + kept = bm.loops.layers.float_vector.get(KEPT_NORMAL) + if kept is not None: + for face in faces: + for loop in face.loops: + loop[kept] = (0.0, 0.0, 0.0) layer = bm.loops.layers.uv.active if layer is None: return @@ -218,6 +232,41 @@ def pin_uvs(bm, faces) -> None: loop[layer].uv = anchor +KEPT_NORMAL = "polish_kept_normal" + + +def stash_normals(mesh, bm) -> bool: + """Copy the mesh's custom shading normals onto the bmesh's face corners, as plain vectors, so they survive + edits. Blender stores a custom normal against the automatic normal of its corner; welding or cutting + changes the automatic normals, and the stored ones would then be read as different directions.""" + if "custom_normal" not in mesh.attributes: + return False + flat = np.empty(len(mesh.loops) * 3, dtype=np.float32) + mesh.corner_normals.foreach_get("vector", flat) + normals = flat.reshape(-1, 3) + layer = bm.loops.layers.float_vector.new(KEPT_NORMAL) + for face in bm.faces: + for loop in face.loops: + loop[layer] = normals[loop.index] + return True + + +def restore_normals(mesh, keep: bool = True) -> None: + """Set the stashed vectors back as the mesh's custom normals (a new face's zero vector means automatic), + or with keep False only drop the stash.""" + attribute = mesh.attributes.get(KEPT_NORMAL) + if attribute is None: + return + flat = np.empty(len(mesh.loops) * 3, dtype=np.float32) + attribute.data.foreach_get("vector", flat) + mesh.attributes.remove(attribute) + if keep: + stale = mesh.attributes.get("custom_normal") + if stale is not None: # else a zero vector would keep the stale value instead of meaning automatic + mesh.attributes.remove(stale) + mesh.normals_split_custom_set(flat.reshape(-1, 3).tolist()) + + def cap_surface(): """The dark, rough material of cut faces and joints: what shows in the gap when a part swings away.""" material = bpy.data.materials.get(CAP_MATERIAL) @@ -261,7 +310,7 @@ class BROKKR_MESH_POLISH_OT_audit(PolishOperator): data = arrays(obj) nodes = base_color_nodes(obj) size = max(nodes[0].image.size) if nodes else 0 - entry = core.audit(data["V"], data["T"], data["UV"], size, raster=self.raster) + entry = core.audit(data["V"], data["T"], data["UV"], size, raster=self.raster, CN=data["CN"]) entry["baseColorImage"] = nodes[0].image.name if nodes else "" entry["baseColorSize"] = list(nodes[0].image.size) if nodes else [0, 0] entry["customNormals"] = "custom_normal" in obj.data.attributes @@ -271,7 +320,7 @@ class BROKKR_MESH_POLISH_OT_audit(PolishOperator): class BROKKR_MESH_POLISH_OT_repair(PolishOperator): """Weld coincident vertices (UV seams keep their UVs), drop degenerate and loose geometry, drop shells - below an area share, close small holes, make normals consistent and recompute shading from a sharp angle""" + below an area share, close small holes; on request rewind faces outward or recompute shading from a sharp angle""" bl_idname = "brokkr_mesh_polish.repair" bl_label = "Repair Mesh" object_name: bpy.props.StringProperty(name="Object") @@ -281,20 +330,26 @@ class BROKKR_MESH_POLISH_OT_repair(PolishOperator): description="Delete shells holding less than this share of the surface; 0 keeps all") fill_holes_sides: bpy.props.IntProperty(name="Fill Holes", default=0, min=0, max=1000, description="Close holes of up to this many edges; 0 leaves holes") + recalc_normals: bpy.props.BoolProperty(name="Recalculate Normals", default=False, + description="Rewind each shell so Blender judges it to face outward. Off leaves every face's winding as it is. On an open or intersecting shell the judgement can be wrong, and a face it turns is culled by a single-sided material: read windingFlipped in the report") sharp_angle: bpy.props.FloatProperty(name="Sharp Angle", default=0.0, min=0.0, max=180.0, description="Degrees; above 0, generated custom normals are dropped and edges sharper than this shade hard") def work(self, context): obj = mesh_object(self.object_name) mesh = obj.data - before = core.audit(arrays(obj)["V"], arrays(obj)["T"], None) + start = arrays(obj) + before = core.audit(start["V"], start["T"], None, CN=start["CN"]) bm = bmesh.new() bm.from_mesh(mesh) + stash_normals(mesh, bm) diagonal = (Vector(obj.bound_box[6]) - Vector(obj.bound_box[0])).length counts = {"vertices": len(bm.verts)} + faces = len(bm.faces) if self.weld_fraction > 0: bmesh.ops.remove_doubles(bm, verts=bm.verts[:], dist=diagonal * self.weld_fraction) counts["welded"] = counts.pop("vertices") - len(bm.verts) + counts["facesCollapsedByWeld"] = faces - len(bm.faces) faces = len(bm.faces) bmesh.ops.dissolve_degenerate(bm, edges=bm.edges[:], dist=diagonal * 1e-7) counts["degenerateFacesRemoved"] = faces - len(bm.faces) @@ -323,26 +378,39 @@ class BROKKR_MESH_POLISH_OT_repair(PolishOperator): counts["holesFilled"] = len(filled["faces"]) pin_uvs(bm, filled["faces"]) bmesh.ops.triangulate(bm, faces=[f for f in filled["faces"] if len(f.verts) > 3]) - bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:]) + counts["windingFlipped"] = 0 + if self.recalc_normals: + was = [face.normal.copy() for face in bm.faces] + bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:]) + bm.normal_update() + counts["windingFlipped"] = sum(1 for face, normal in zip(bm.faces, was) if face.normal.dot(normal) < 0) bm.to_mesh(mesh) bm.free() + # Custom normals are stored against each face's own normal: a face that was turned would carry its + # custom normal turned with it, so they cannot outlive a rewind. + drop_custom = self.sharp_angle > 0 or counts["windingFlipped"] > 0 + counts["customNormalsDropped"] = bool(drop_custom and "custom_normal" in mesh.attributes) + if drop_custom and "custom_normal" in mesh.attributes: + mesh.attributes.remove(mesh.attributes["custom_normal"]) + restore_normals(mesh, keep=not drop_custom) if self.sharp_angle > 0: - if "custom_normal" in mesh.attributes: - mesh.attributes.remove(mesh.attributes["custom_normal"]) mesh.polygons.foreach_set("use_smooth", [True] * len(mesh.polygons)) mesh.set_sharp_from_angle(angle=math.radians(self.sharp_angle)) mesh.update() - after = core.audit(arrays(obj)["V"], arrays(obj)["T"], None) + end = arrays(obj) + after = core.audit(end["V"], end["T"], None, CN=end["CN"]) + keys = ("triangles", "vertices", "boundaryEdges", "nonManifoldEdges", "shells", "windingAgainstNormals") return {"object": obj.name, "changes": counts, - "before": {k: before[k] for k in ("triangles", "vertices", "boundaryEdges", "nonManifoldEdges", "shells")}, - "after": {k: after[k] for k in ("triangles", "vertices", "boundaryEdges", "nonManifoldEdges", "shells")}} + "before": {k: before[k] for k in keys}, "after": {k: after[k] for k in keys}} class BROKKR_MESH_POLISH_OT_orient(PolishOperator): - """Turn every mesh in the scene, as one rigid body, onto its principal axes (longest on Y, shortest on Z), - centre it at the origin, scale its longest side to a length, and bake that into the mesh data""" + """Turn an object and everything parented under it (or the whole scene), as one rigid body, onto its + principal axes (longest on Y, shortest on Z), centre it at the origin and scale its longest side to a length. + Rotation and scale are baked into the mesh data; every object keeps its parent and its pivot point""" bl_idname = "brokkr_mesh_polish.orient" bl_label = "Orient Meshes" + object_name: bpy.props.StringProperty(name="Object", description="The root of what to turn: it and its descendants; every object in the scene when empty") length: bpy.props.FloatProperty(name="Length", default=0.0, min=0.0, max=1e6, description="Longest side after scaling, in scene units; 0 keeps the size") flip_forward: bpy.props.BoolProperty(name="Flip Forward", description="Turn half a turn about Z: swap bow and stern") @@ -352,7 +420,17 @@ class BROKKR_MESH_POLISH_OT_orient(PolishOperator): description="Off keeps the current axes and only applies the turns, centre and scale") def work(self, context): - objects = mesh_objects("") + if self.object_name: + top = bpy.data.objects.get(self.object_name) + if top is None: + raise Refused(f"No object named {self.object_name!r}.") + members = [top] + list(top.children_recursive) + else: + members = list(context.scene.objects) + objects = [o for o in members if o.type == "MESH"] + if not objects: + raise Refused("There is no mesh to orient.") + context.view_layer.update() data = merged(objects) centre, rotation = core.principal_frame(data["V"], data["T"]) if self.principal: @@ -371,15 +449,20 @@ class BROKKR_MESH_POLISH_OT_orient(PolishOperator): middle = (low + high) / 2.0 frame = Matrix.Translation(Vector(-middle * scale)) @ Matrix.Diagonal((scale, scale, scale, 1.0)) \ @ Matrix([list(row) + [0.0] for row in rotation] + [[0, 0, 0, 1]]) @ Matrix.Translation(Vector(-centre)) - originals = {o.name: frame @ o.matrix_world for o in objects} - for obj in objects: - if obj.data.users > 1: - obj.data = obj.data.copy() - obj.data.transform(originals[obj.name]) - obj.data.update() - for obj in objects: - obj.parent = None - obj.matrix_world = Matrix.Identity(4) + def depth(obj): + return 0 if obj.parent is None else 1 + depth(obj.parent) + + world = {o.name: o.matrix_world.copy() for o in members} + for obj in sorted(members, key=depth): # parents first: a child's new place is set against its parent's + target = frame @ world[obj.name] + pivot = Matrix.Translation(target.translation) + if obj.type == "MESH": + if obj.data.users > 1: + obj.data = obj.data.copy() + obj.data.transform(pivot.inverted() @ target) + obj.data.update() + obj.matrix_world = pivot if obj.type in ("MESH", "EMPTY") else target + context.view_layer.update() final = (local - middle) * scale return {"objects": [o.name for o in objects], "scale": scale, "extent": [round(float(x), 6) for x in (high - low) * scale], @@ -413,7 +496,7 @@ class BROKKR_MESH_POLISH_OT_delight(PolishOperator): covered = owner >= 0 if covered.sum() < 64: raise Refused("The UV map covers too little of the texture to fit lighting.") - normals = core.interpolate(owner, bary, N[T])[covered] + normals = core.interpolate(owner, bary, data["CN"])[covered] normals /= np.maximum(np.linalg.norm(normals, axis=1, keepdims=True), 1e-30) sky = core.interpolate(owner, bary, occlusion[T][..., None])[covered][:, 0] pixels = read_pixels(image) @@ -536,6 +619,7 @@ class BROKKR_MESH_POLISH_OT_cut_parts(PolishOperator): world = obj.matrix_world.copy() bm = bmesh.new() bm.from_mesh(mesh) + stash_normals(mesh, bm) diagonal = (Vector(obj.bound_box[6]) - Vector(obj.bound_box[0])).length bmesh.ops.remove_doubles(bm, verts=bm.verts[:], dist=diagonal * 1e-5) bmesh.ops.triangulate(bm, faces=[f for f in bm.faces if len(f.verts) > 3]) @@ -568,8 +652,8 @@ class BROKKR_MESH_POLISH_OT_cut_parts(PolishOperator): for edge in bm.edges: edge[was_open] = int(edge.is_boundary) cap_material = cap_surface() - cap_slot = len(mesh.materials) - materials = list(mesh.materials) + [cap_material] + materials = (list(mesh.materials) or [None]) + [cap_material] # a bare mesh keeps a bare first slot: only caps are dark + cap_slot = len(materials) - 1 collection = obj.users_collection[0] if obj.users_collection else context.scene.collection made, report = [], [] for index, name in enumerate(names): @@ -593,11 +677,11 @@ class BROKKR_MESH_POLISH_OT_cut_parts(PolishOperator): for face in caps: face.material_index = cap_slot face.smooth = False - bmesh.ops.recalc_face_normals(piece, faces=piece.faces[:]) new_mesh = bpy.data.meshes.new(f"{obj.name}.{name}") root_world = world @ Vector(root_local) if index else world.translation.copy() piece.to_mesh(new_mesh) piece.free() + restore_normals(new_mesh) for material in materials: new_mesh.materials.append(material) new_obj = bpy.data.objects.new(f"{obj.name}.{name}", new_mesh) diff --git a/surfaces/blender/brokkr_mesh_polish/brokkr_actions.json b/surfaces/blender/brokkr_mesh_polish/brokkr_actions.json index d2950b7..c161dcd 100644 --- a/surfaces/blender/brokkr_mesh_polish/brokkr_actions.json +++ b/surfaces/blender/brokkr_mesh_polish/brokkr_actions.json @@ -14,7 +14,7 @@ }, { "name": "brokkr_mesh_polish.repair", - "doc": "Weld coincident vertices, drop degenerate and loose geometry and small shells, close small holes, fix normals.", + "doc": "Weld coincident vertices, drop degenerate and loose geometry and small shells, close small holes; windings are left alone unless recalc_normals.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -23,16 +23,18 @@ {"name": "weld_fraction", "type": "number", "minimum": 0, "maximum": 0.01, "default": 0.0001, "doc": "weld distance as a share of the bounding diagonal"}, {"name": "min_shell_area", "type": "number", "minimum": 0, "maximum": 0.5, "default": 0, "doc": "delete shells below this share of the surface; 0 keeps all"}, {"name": "fill_holes_sides", "type": "integer", "minimum": 0, "maximum": 1000, "default": 0, "doc": "close holes of up to this many edges"}, + {"name": "recalc_normals", "type": "boolean", "default": false, "doc": "rewind each shell to face outward as Blender judges it; off leaves every winding as it is. Can turn faces wrongly on open shells: read windingFlipped"}, {"name": "sharp_angle", "type": "number", "minimum": 0, "maximum": 180, "default": 0, "doc": "degrees; above 0 drops generated custom normals and shades edges sharper than this hard"} ] }, { "name": "brokkr_mesh_polish.orient", - "doc": "Turn all meshes as one body onto their principal axes (long on Y, short on Z), centre, scale, and bake it in.", + "doc": "Turn an object and its descendants (or the scene) as one body onto its principal axes (long on Y, short on Z), centre, scale; parents and pivots are kept.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", "fields": [ + {"name": "object_name", "type": "string", "maxLength": 63, "doc": "the root of what to turn, with its descendants; every object in the scene when absent"}, {"name": "length", "type": "number", "minimum": 0, "maximum": 1000000, "default": 0, "doc": "longest side after scaling; 0 keeps the size"}, {"name": "flip_forward", "type": "boolean", "default": false, "doc": "half a turn about Z"}, {"name": "roll_quarter_turns", "type": "integer", "minimum": 0, "maximum": 3, "default": 0, "doc": "quarter turns about the long axis"}, diff --git a/surfaces/blender/brokkr_mesh_polish/core.py b/surfaces/blender/brokkr_mesh_polish/core.py index 0ae197a..9031425 100644 --- a/surfaces/blender/brokkr_mesh_polish/core.py +++ b/surfaces/blender/brokkr_mesh_polish/core.py @@ -111,13 +111,24 @@ def weighted_quantile(values: np.ndarray, weights: np.ndarray, q: float) -> floa return float(values[order][min(np.searchsorted(cumulative, q * cumulative[-1]), len(values) - 1)]) +def winding_against(V: np.ndarray, T: np.ndarray, CN: np.ndarray) -> np.ndarray: + """True for each triangle whose corner order faces away from its own shading normals CN (m,3,3): the + triangle is drawn from behind, and a single-sided material culls it.""" + a, b, c = V[T[:, 0]], V[T[:, 1]], V[T[:, 2]] + return (np.cross(b - a, c - a) * CN.sum(axis=1)).sum(axis=1) < 0 + + def audit(V: np.ndarray, T: np.ndarray, UV: np.ndarray | None, texture_size: int = 0, - weld_fraction: float = 1e-5, raster: int = 1024) -> dict: + weld_fraction: float = 1e-5, raster: int = 1024, CN: np.ndarray | None = None) -> dict: """The measurements a polish pass is judged by. Lengths are in the mesh's own units. Topology is counted after welding positions within weld_fraction of the bounding diagonal. UV overlap is the share of covered texels (on a raster x raster grid) that more than one triangle covers. Texel density is - texels per unit length for a texture_size texture, area-weighted over triangles; its spread is p95 / p5.""" + texels per unit length for a texture_size texture, area-weighted over triangles; its spread is p95 / p5. + With CN, the per-corner shading normals, windingAgainstNormals counts triangles wound away from them, and + uvMirroredTriangles counts triangles whose texture reads mirrored on the surface as shaded: negative UV + area on a triangle wound with its normals, or positive on one wound against them. Without CN the winding is + taken as right, so uvMirroredTriangles is the triangles of negative UV area.""" V = np.asarray(V, dtype=np.float64) T = np.asarray(T, dtype=np.int64) extent = V.max(axis=0) - V.min(axis=0) if len(V) else np.zeros(3) @@ -128,6 +139,9 @@ def audit(V: np.ndarray, T: np.ndarray, UV: np.ndarray | None, texture_size: int "extent": [round(float(x), 6) for x in extent], "surfaceArea": float(areas.sum()), "degenerateTriangles": int((areas <= 1e-14 * diagonal * diagonal).sum())} report.update(edge_census(TW)) + against = winding_against(V, T, np.asarray(CN, dtype=np.float64)) & (areas > 0) if CN is not None else np.zeros(len(T), dtype=bool) + if CN is not None: + report["windingAgainstNormals"] = int(against.sum()) shells = triangle_components(TW) _, shell_sizes = np.unique(shells, return_counts=True) report["shells"] = int(len(shell_sizes)) @@ -141,7 +155,7 @@ def audit(V: np.ndarray, T: np.ndarray, UV: np.ndarray | None, texture_size: int covered = int((cover > 0).sum()) report.update({ "uvIslands": uv_islands(TW, UV), - "uvFlippedTriangles": int((signed < 0).sum()), + "uvMirroredTriangles": int(((signed < 0) ^ against)[np.abs(signed) >= 1e-12].sum()), "uvZeroAreaTriangles": int((np.abs(signed) < 1e-12).sum()), "uvOutsideUnitTriangles": int(((UV < -1e-6) | (UV > 1 + 1e-6)).any(axis=(1, 2)).sum()), "uvCoverage": covered / float(raster * raster), diff --git a/surfaces/blender/tests/live/mesh_polish.py b/surfaces/blender/tests/live/mesh_polish.py index 4284585..5659698 100644 --- a/surfaces/blender/tests/live/mesh_polish.py +++ b/surfaces/blender/tests/live/mesh_polish.py @@ -5,7 +5,8 @@ and does what its doc says to real bpy meshes and images. Not part of the unitte Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses without them). Every action is sent through BrokkrBlenderTarget.run_intent, as tools/run_intents.py sends it. -Writes .result.json and exits 1 when a check failed. +With BROKKR_POLISH_HULLS= it also repairs each and checks that no face was +turned. Writes .result.json and exits 1 when a check failed. """ import json import math @@ -17,13 +18,15 @@ from pathlib import Path import bmesh import bpy import numpy as np -from mathutils import Matrix - -for _name in ("BLENDER_USER_CONFIG", "BLENDER_USER_EXTENSIONS", "BLENDER_USER_SCRIPTS"): - if not os.environ.get(_name): - raise SystemExit(f"{_name} is not set: run this in private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories") +from mathutils import Matrix, Vector SURFACE = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(SURFACE / "tools")) +import private_dirs # noqa: E402 + +_refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind)) +if _refused: + raise SystemExit(_refused) OUT = sys.argv[sys.argv.index("--") + 1] package = types.ModuleType("brokkr_bridge") package.__path__ = [str(SURFACE / "brokkr_bridge")] @@ -40,6 +43,7 @@ target.reload_host_actions() R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], "hostRows": [row["name"] for row in target.host_actions()[0]]} COUNT = [0] +RATIO_BOUND, DEFICIT_BOUND, SHADE_BOUND = 1.906, 0.136, 0.684 # each derived where it is used def check(name, ok, detail=None): @@ -92,58 +96,184 @@ def pixels_of(obj): check("host file admitted", not R["hostErrors"] and len(R["hostRows"]) == 7, R["hostErrors"] or R["hostRows"]) -# --- audit and repair: a sphere torn into loose faces is welded back into one closed shell ----------------------- +# --- audit and repair: a generator's sphere, torn at every edge, half its faces wound inside out under outward +# --- custom normals, is welded back into one closed shell with no face turned and its shading normals intact ------ size = 256 -rows = (np.arange(size) + 0.5) / size # v: 0 at the south pole, 1 at the north pole of Blender's UV sphere +rows = np.clip(((np.arange(size) + 0.5) / size - 0.1) / 0.8, 0.0, 1.0) # latitude: 0 at the south pole, 1 at the north baked = np.repeat((0.8 * (0.2 + 0.8 * rows))[:, None, None], size, axis=1) * np.ones((1, 1, 3)) -sphere = new_object("Ball", lambda bm: bmesh.ops.create_uvsphere(bm, u_segments=48, v_segments=24, radius=1.0, calc_uvs=True), - new_image("ball_bake", baked.astype(np.float32))) + + +def ball(bm): + bmesh.ops.create_uvsphere(bm, u_segments=48, v_segments=24, radius=1.0, calc_uvs=True) + layer = bm.loops.layers.uv.active + for face in bm.faces: # the island sits inside the texture with a margin, as a generator's atlas does + for loop in face.loops: + loop[layer].uv = loop[layer].uv * 0.8 + Vector((0.1, 0.1)) + + +sphere = new_object("Ball", ball, new_image("ball_bake", baked.astype(np.float32))) sphere.data.polygons.foreach_set("use_smooth", [True] * len(sphere.data.polygons)) torn = bmesh.new() torn.from_mesh(sphere.data) bmesh.ops.split_edges(torn, edges=torn.edges[:]) +inside_out = [f for f in torn.faces if f.calc_center_median().x > 0] +reversed_faces, reversed_triangles = len(inside_out), sum(len(f.verts) - 2 for f in inside_out) +bmesh.ops.reverse_faces(torn, faces=inside_out) torn.to_mesh(sphere.data) torn.free() +sphere.data.normals_split_custom_set([tuple(sphere.data.vertices[loop.vertex_index].co.normalized()) for loop in sphere.data.loops]) + + +def polygon_normals(mesh): + flat = np.empty(len(mesh.polygons) * 3, dtype=np.float32) + mesh.polygons.foreach_get("normal", flat) + return flat.reshape(-1, 3) + + +def shading_error(mesh): + """The worst angle, in degrees, between a corner's shading normal and the sphere's own outward direction.""" + flat = np.empty(len(mesh.loops) * 3, dtype=np.float32) + mesh.corner_normals.foreach_get("vector", flat) + outward = np.array([mesh.vertices[loop.vertex_index].co.normalized() for loop in mesh.loops]) + return float(np.degrees(np.arccos(np.clip((flat.reshape(-1, 3) * outward).sum(axis=1), -1, 1))).max()) + + receipt, before = send("brokkr_mesh_polish.audit", object_name="Ball") check("audit: accepted, no undo step", receipt["status"] == "accepted" and not receipt.get("undoLabel"), receipt["message"]) check("audit: welded topology sees one closed shell in the torn sphere", before["Ball"]["shells"] == 1 and before["Ball"]["boundaryEdges"] == 0 and before["Ball"]["nonManifoldEdges"] == 0, before["Ball"]) check("audit: texture and UV facts", before["Ball"]["baseColorSize"] == [size, size] and before["Ball"]["uvOverlap"] < 0.02 - and before["Ball"]["texelDensityMedian"] > 0, before["Ball"]) -torn_vertices = len(sphere.data.vertices) -receipt, repaired = send("brokkr_mesh_polish.repair", object_name="Ball", sharp_angle=30) + and before["Ball"]["texelDensityMedian"] > 0 and 0.55 < before["Ball"]["uvCoverage"] < 0.64, before["Ball"]) # an 0.8 x 0.8 island less the pole gaps +check("audit: counts the triangles wound against their shading normals, and none of them as a mirrored texture", + reversed_triangles > 1000 and before["Ball"]["windingAgainstNormals"] == reversed_triangles + and before["Ball"]["uvMirroredTriangles"] == 0, [reversed_triangles, before["Ball"].get("windingAgainstNormals"), before["Ball"].get("uvMirroredTriangles")]) +torn_vertices, normals_before = len(sphere.data.vertices), polygon_normals(sphere.data) +receipt, repaired = send("brokkr_mesh_polish.repair", object_name="Ball") check("repair: accepted as one undo step", receipt["status"] == "accepted" and "repair" in receipt.get("undoLabel", ""), receipt) check("repair: welds the torn vertices", repaired["changes"]["welded"] == torn_vertices - len(sphere.data.vertices) and len(sphere.data.vertices) == 48 * 23 + 2, repaired) -edges = [e for e in sphere.data.edges] -check("repair: every edge has two faces again", sum(1 for _ in edges) == 48 * 23 + 48 * 24, len(edges)) +check("repair: every edge has two faces again", len(sphere.data.edges) == 48 * 23 + 48 * 24, len(sphere.data.edges)) +normals_after = polygon_normals(sphere.data) +turned = int(((normals_before * normals_after).sum(axis=1) < 0).sum()) if len(normals_before) == len(normals_after) else -1 +R["winding"] = {"reversedTriangles": reversed_triangles, "turnedByDefaultRepair": turned, "shadingErrorDegrees": shading_error(sphere.data)} +check("repair: by default turns no face (a single-sided material would cull a turned one)", + turned == 0 and repaired["changes"]["windingFlipped"] == 0 + and repaired["after"]["windingAgainstNormals"] == repaired["before"]["windingAgainstNormals"] == reversed_triangles, [turned, repaired]) +check("repair: the shading normals survive the weld", "custom_normal" in sphere.data.attributes and R["winding"]["shadingErrorDegrees"] < 0.5 + and not repaired["changes"]["customNormalsDropped"], R["winding"]) -# --- delight: a bake that darkens with latitude is levelled ------------------------------------------------------ -receipt, lit = send("brokkr_mesh_polish.delight", object_name="Ball", clusters=1, fit_size=256, occlusion_rays=8) +# --- delight: a bake that darkens with latitude is levelled, reading the shading normals, not the windings -------- +receipt, lit = send("brokkr_mesh_polish.delight", object_name="Ball", clusters=1, fit_size=128, occlusion_rays=8, max_gain=8) after_pixels, after_image = pixels_of(sphere) column = after_pixels[:, size // 2, 0] -# top/bottom brightness of the stored texture, rows at v = 0.9 and v = 0.1 -ratio_before = float(baked[int(size * 0.9), 0, 0] / baked[int(size * 0.1), 0, 0]) -ratio_after = float(column[int(size * 0.9)] / column[int(size * 0.1)]) -R["delight"] = {"report": lit, "ratioBefore": ratio_before, "ratioAfter": ratio_after} -check("delight: accepted, new packed image on the material", receipt["status"] == "accepted" and after_image.name == "ball_bake.delit" - and after_image.packed_file is not None, receipt["message"]) +north, south = int(size * (0.1 + 0.8 * 0.9)), int(size * (0.1 + 0.8 * 0.1)) # rows at latitude 0.9 and 0.1 +ratio_before = float(baked[north, 0, 0] / baked[south, 0, 0]) +ratio_after = float(column[north] / column[south]) +# On the island's left border the gain field meets texels no triangle covers. With the field filled outward the +# border reads as the middle of the row does; left unfilled, the neutral gain of the uncovered texels bleeds in. +border = int(math.ceil(size * 0.1)) +deficit = float(np.median(1.0 - after_pixels[south - 8:south + 8, border, 0] / after_pixels[south - 8:south + 8, size // 2, 0])) +R["delight"] = {"report": lit, "ratioBefore": ratio_before, "ratioAfter": ratio_after, "borderDeficit": deficit} +check("delight: accepted, new packed image on the material, in the old image's colour space", receipt["status"] == "accepted" + and after_image.name == "ball_bake.delit" and after_image.packed_file is not None + and after_image.colorspace_settings.name == "Non-Color", [receipt["message"], after_image.colorspace_settings.name]) check("delight: finds the baked light", lit["explainedByLight"]["before"] > 0.5 and lit["before"]["upDownLuminanceRatio"] > 2.0, lit) -# bound: shipped ratioAfter 1.12, the no-op mutant leaves 3.29: sqrt(1.12 * 3.29) = 1.92 -check("delight: levels top against bottom", ratio_before > 1.92 * 1.2 and ratio_after < 1.92 / 1.2, [ratio_before, ratio_after]) +# bound: shipped ratioAfter 1.114; a no-op leaves 3.261 and so do normals taken from the windings (the inside-out half +# cancels the light the fit could find): sqrt(1.114 * 3.261) = 1.906 +check("delight: levels top against bottom", ratio_before > RATIO_BOUND * 1.2 and ratio_after < RATIO_BOUND / 1.2, [ratio_before, ratio_after]) +# bound: shipped deficit 0.000, an unfilled gain field leaves 0.164; the shipped reading being zero, the bound sits 1.2 under the mutant: 0.136 +check("delight: the gain reaches the island's border unweakened", abs(deficit) < DEFICIT_BOUND, deficit) -# --- orient: a turned slab is laid along Y, thin on Z, centred, scaled ------------------------------------------ +receipt, rewound = send("brokkr_mesh_polish.repair", object_name="Ball", recalc_normals=True, sharp_angle=30) +check("repair: recalc_normals rewinds the inside-out half and says how many faces it turned", + receipt["status"] == "accepted" and rewound["changes"]["windingFlipped"] == reversed_faces + and rewound["changes"]["customNormalsDropped"] and "custom_normal" not in sphere.data.attributes + and rewound["after"]["windingAgainstNormals"] == 0, rewound) + +# --- repair: only holes up to the size asked are filled, and only shells below the share asked are dropped ----- +def holey(bm): + bmesh.ops.create_grid(bm, x_segments=6, y_segments=6, size=3.0, calc_uvs=True) # 36 quads, each 1 x 1 + at = lambda face: (round(face.calc_center_median().x, 1), round(face.calc_center_median().y, 1)) + small = [f for f in bm.faces if at(f) == (1.5, 1.5)] # one quad inside: a 4-edge hole + large = [f for f in bm.faces if at(f)[0] in (-1.5, -0.5) and at(f)[1] in (-1.5, -0.5)] # a 2 x 2 block: an 8-edge hole + bmesh.ops.delete(bm, geom=small + large, context="FACES") + bm.faces.new([bm.verts.new(co) for co in ((9.0, 9.0, 0.0), (9.2, 9.0, 0.0), (9.0, 9.2, 0.0))]) # a far chip: 0.02 of area against 31 + + +sheet = new_object("Sheet", holey) +flipped_sheet = bmesh.new() # the generator's sheet faces down: a fill must follow it, whichever way Blender would guess +flipped_sheet.from_mesh(sheet.data) +bmesh.ops.reverse_faces(flipped_sheet, faces=flipped_sheet.faces[:]) +flipped_sheet.to_mesh(sheet.data) +flipped_sheet.free() +TILT = (0.6, 0.0, -0.8) # the generator's shading normals lean: the old faces must keep them, a fill must not borrow them +sheet.data.normals_split_custom_set([TILT] * len(sheet.data.loops)) +receipt, mended = send("brokkr_mesh_polish.repair", object_name="Sheet", fill_holes_sides=4, min_shell_area=0.01) +R["mend"] = mended +check("repair: fills the 4-edge hole, leaves the 8-edge hole and the rim, drops the chip", + receipt["status"] == "accepted" and mended["changes"]["holesFilled"] == 1 and mended["changes"]["shellsRemoved"] == 1 + and mended["after"]["shells"] == 1 and mended["after"]["boundaryEdges"] == 24 + 8, mended) +facing = polygon_normals(sheet.data)[:, 2] +check("repair: a filled hole is wound as the faces around it", len(facing) == 31 * 1 + 2 and bool((facing < -0.9).all()), [len(facing), float(facing.max())]) +shading = np.empty(len(sheet.data.loops) * 3, dtype=np.float32) +sheet.data.corner_normals.foreach_get("vector", shading) +shading = shading.reshape(-1, 3) +fill_loops = [i for polygon in sheet.data.polygons if abs(polygon.center.x - 1.5) < 0.4 and abs(polygon.center.y - 1.5) < 0.4 for i in polygon.loop_indices] +old_loops = [i for i in range(len(shading)) if i not in set(fill_loops)] +check("repair: old faces keep their shading normals through the weld and the fill; the fill is shaded by its own direction", + len(fill_loops) == 6 and np.allclose(shading[old_loops], TILT, atol=1e-3) and np.allclose(shading[fill_loops], (0.0, 0.0, -1.0), atol=1e-3), + [len(fill_loops), shading[fill_loops].tolist()[:2], shading[old_loops[0]].tolist()]) +bpy.data.objects.remove(sheet) + +# --- delight: darkness that follows occlusion is levelled --------------------------------------------------------- +def pair(bm): + layer = bm.loops.layers.uv.active + for side in (-1.0, 1.0): # two unit spheres 0.1 apart: their facing sides occlude each other + made = bmesh.ops.create_uvsphere(bm, u_segments=32, v_segments=16, radius=1.0, calc_uvs=True, matrix=Matrix.Translation((side * 1.05, 0, 0))) + for face in {f for v in made["verts"] for f in v.link_faces}: + for loop in face.loops: + loop[layer].uv = Vector((loop[layer].uv.x * 0.5 + (0.0 if side < 0 else 0.5), loop[layer].uv.y)) + + +import brokkr_mesh_polish as polish # noqa: E402 the fixture's bake uses the add-on's own occlusion, so the light is exactly what it can explain + +twins = new_object("Twins", pair, new_image("twins_bake", np.ones((size, size, 3), dtype=np.float32))) +twins.data.polygons.foreach_set("use_smooth", [True] * len(twins.data.polygons)) +twin = polish.arrays(twins) +twin_sky = polish.ambient_occlusion(twin["V"], twin["T"], twin["N"], 64, 0.35 * float(np.linalg.norm(twin["V"].max(axis=0) - twin["V"].min(axis=0)))) +owner, bary, _ = polish.core.rasterize(twin["UV"], size) +sky_map = polish.core.interpolate(owner, bary, twin_sky[twin["T"]][..., None])[..., 0] +occluded, open_sky = (owner >= 0) & (sky_map < 0.6), (owner >= 0) & (sky_map > 0.95) +twin_bake = np.where((owner >= 0)[..., None], 0.8 * np.clip(sky_map, 0.05, 1.0)[..., None], 0.5) * np.ones((1, 1, 3)) +flat = np.ones((size, size, 4), dtype=np.float32) +flat[..., :3] = twin_bake +bpy.data.images["twins_bake"].pixels.foreach_set(flat.reshape(-1)) +receipt, unshadowed = send("brokkr_mesh_polish.delight", object_name="Twins", clusters=1, fit_size=256, occlusion_rays=64, max_gain=8) +twin_after, _ = pixels_of(twins) +shade_before = float(np.median(twin_bake[..., 0][occluded]) / np.median(twin_bake[..., 0][open_sky])) +shade_after = float(np.median(twin_after[..., 0][occluded]) / np.median(twin_after[..., 0][open_sky])) +R["occlusion"] = {"report": unshadowed, "occludedTexels": int(occluded.sum()), "shadeBefore": shade_before, "shadeAfter": shade_after} +# bound: shipped shadeAfter 1.000; with occlusion ignored (a sky of 1 everywhere) it stays 0.468: sqrt(1.000 * 0.468) = 0.684 +check("delight: lifts occluded surface to the level of open surface", receipt["status"] == "accepted" and occluded.sum() > 500 + and shade_before < SHADE_BOUND / 1.2 and shade_after > SHADE_BOUND * 1.2, R["occlusion"]) +bpy.data.objects.remove(twins) + +# --- orient: a turned slab is laid along Y, thin on Z, centred, scaled; nothing outside it moves ----------------- slab = new_object("Slab", lambda bm: bmesh.ops.create_cube(bm, size=1.0, matrix=Matrix.Diagonal((3.0, 1.0, 0.5, 1.0)))) slab.matrix_world = Matrix.Translation((4, 5, 6)) @ Matrix.Rotation(math.radians(37), 4, (0.3, 0.5, 0.8)) -sphere.hide_viewport = True -bpy.context.scene.collection.objects.unlink(sphere) # orient turns every mesh in the scene as one body -receipt, oriented = send("brokkr_mesh_polish.orient", length=12.0) +sphere.location = (20, 0, 0) +bpy.context.view_layer.update() +receipt, oriented = send("brokkr_mesh_polish.orient", object_name="Slab", length=12.0) corners = np.array([slab.matrix_world @ v.co for v in slab.data.vertices]) extent = corners.max(axis=0) - corners.min(axis=0) check("orient: long on Y, thin on Z, scaled to the length, centred", receipt["status"] == "accepted" and np.allclose(extent, [4.0, 12.0, 2.0], atol=1e-3) and np.allclose((corners.max(axis=0) + corners.min(axis=0)) / 2, 0, atol=1e-4), [list(map(float, extent)), oriented]) check("orient: reports the mirror error of a symmetric body as small", max(oriented["mirrorError"].values()) < 0.05, oriented["mirrorError"]) +check("orient: an object outside the named root is not touched", oriented["objects"] == ["Slab"] + and np.allclose(sphere.matrix_world.translation, [20, 0, 0]) and abs(max(v.co.length for v in sphere.data.vertices) - 1.0) < 1e-5, oriented["objects"]) +receipt, _ = send("brokkr_mesh_polish.orient", object_name="Nobody") +check("orient: an unknown root is refused", receipt["status"] == "failed", receipt["message"]) bpy.data.objects.remove(slab) # --- cut_parts: a knob fused to a block is cut off at the crease, capped, and rooted at its cut ----------------- @@ -177,11 +307,54 @@ if receipt["status"] == "accepted": check("cut_parts: both sides of the cut are capped (closed shells)", all(closed[name]["boundaryEdges"] == 0 and closed[name]["shells"] == 1 for name in ("Block.body", "Block.knob")), {name: [closed[name]["boundaryEdges"], closed[name]["shells"]] for name in ("Block.body", "Block.knob")}) - check("cut_parts: caps carry the cap material and a joint sits at the root", "Polish Cap" in [m.name for m in knob.data.materials] + capped = {o.name: sum(1 for polygon in o.data.polygons if getattr(o.data.materials[polygon.material_index], "name", "") == "Polish Cap") for o in (body, knob)} + check("cut_parts: exactly the cap faces carry the cap material", capped["Block.knob"] == part["Block.knob"]["capTriangles"] > 0 + and capped["Block.body"] == part["Block.body"]["capTriangles"] > 0, capped) + cap_normals = {o.name: [polygon.normal.z for polygon in o.data.polygons + if getattr(o.data.materials[polygon.material_index], "name", "") == "Polish Cap"] for o in (body, knob)} + check("cut_parts: each cap faces out of its own part, and no old face was turned", + all(z < -0.9 for z in cap_normals["Block.knob"]) and all(z > 0.9 for z in cap_normals["Block.body"]) + and closed["Block.body"]["windingAgainstNormals"] == 0 and closed["Block.knob"]["windingAgainstNormals"] == 0, cap_normals) + check("cut_parts: a joint sits at the root", "Polish Cap" in [getattr(m, "name", "") for m in knob.data.materials] and np.allclose(bpy.data.objects[part["Block.knob"]["joint"]].matrix_world.translation, [0, 0, 1], atol=1e-5), part["Block.knob"].get("joint")) + # orient after the cut: the body and what hangs from it turn as one; the knob keeps its parent and its pivot + receipt, turned_parts = send("brokkr_mesh_polish.orient", object_name="Block.body", length=6.0) + pivot = knob.matrix_world.translation + reach = max(abs((knob.matrix_world @ v.co).y) for v in knob.data.vertices) + R["orientParts"] = {"report": turned_parts, "knobPivot": list(pivot), "knobReach": reach, "parent": knob.parent.name if knob.parent else None} + # the 2 x 2 x 3 body-and-knob is laid along Y and doubled: the cut centre (0, 0, 1), half a unit above the middle, lands 1 along Y + check("orient: after a cut the parts keep their parent and their pivot at the cut", receipt["status"] == "accepted" and knob.parent == body + and abs(abs(pivot.y) - 1.0) < 1e-4 and abs(pivot.x) < 1e-4 and abs(pivot.z) < 1e-4 and abs(reach - 3.0) < 1e-4 + and np.allclose(np.array(knob.matrix_world.to_3x3()), np.eye(3), atol=1e-6), R["orientParts"]) receipt, _ = send("brokkr_mesh_polish.cut_parts", object_name="Block.body", seeds="only=0,0,-1") check("cut_parts: one part is refused with nothing changed", receipt["status"] == "failed" and "Block.body" in bpy.data.objects, receipt["message"]) + +# --- cut_parts through: a seed on one face of a thin plate also holds the face behind it ----------------------- +def plate_body(bm): + bmesh.ops.create_cube(bm, size=2.0, matrix=Matrix.Diagonal((1.0, 1.0, 0.05, 1.0))) # 2 x 2 x 0.1 + bmesh.ops.subdivide_edges(bm, edges=bm.edges[:], cuts=7, use_grid_fill=True) + bmesh.ops.triangulate(bm, faces=bm.faces[:]) + + +def underside(name): + """Triangles of the part that face down and are surface, not cap.""" + part_object = bpy.data.objects[name] + return sum(1 for polygon in part_object.data.polygons + if polygon.normal.z < -0.9 and getattr(part_object.data.materials[polygon.material_index], "name", "") != "Polish Cap") + + +R["through"] = {} +for label, through in (("without", 0.0), ("with", 0.1)): + new_object("Plate", plate_body) + # by distance alone (no crease cost) the underside's middle is nearer the body's seed, at an underside corner, + # than the lid's seed on top, which must go round the rim; a ray inward from the lid's seed finds it at once + receipt, _ = send("brokkr_mesh_polish.cut_parts", object_name="Plate", seeds="body=-0.9,-0.9,-0.05; lid=0,0,0.05", crease_cost=0, through=through) + R["through"][label] = underside("Plate.lid") if receipt["status"] == "accepted" else None + for leftover in [o for o in bpy.data.objects if o.name.startswith("Plate")]: + bpy.data.objects.remove(leftover) +check("cut_parts: through seeds the far face of a thin part", R["through"]["without"] == 0 and (R["through"]["with"] or 0) >= 8, R["through"]) + # --- pick and scrub_markings: lettering on one panel is found from a camera and painted out ---------------------- panel = np.full((128, 128, 3), [0.1, 0.35, 0.4], dtype=np.float32) panel += np.random.default_rng(0).normal(0, 0.01, panel.shape).astype(np.float32) @@ -194,16 +367,16 @@ def plate(bm): sign = new_object("Sign", plate, new_image("sign_paint", panel)) # 4 x 2, flat on z = 0, u along x -sign.location = (0, 0, 5) +sign.location = (40, 0, 5) # clear of the block bpy.context.view_layer.update() camera = bpy.data.objects.new("Eye", bpy.data.cameras.new("Eye")) bpy.context.scene.collection.objects.link(camera) camera.data.type = "ORTHO" camera.data.ortho_scale = 4.0 -camera.location = (0, 0, 9) +camera.location = (40, 0, 9) receipt, picked = send("brokkr_mesh_polish.pick", camera_name="Eye", u=0.25, v=0.5, resolution_x=400, resolution_y=200) check("pick: names the surface point under (u, v) of a picture of that shape", receipt["status"] == "accepted" and picked["hit"] - and picked["object"] == "Sign" and np.allclose(picked["point"], [-1.0, 0.0, 5.0], atol=1e-4), picked) + and picked["object"] == "Sign" and np.allclose(picked["point"], [39.0, 0.0, 5.0], atol=1e-4), picked) receipt, missed = send("brokkr_mesh_polish.pick", camera_name="Eye", u=0.5, v=0.99, resolution_x=200, resolution_y=400) check("pick: off the surface is a miss, not an error", receipt["status"] == "accepted" and missed == {"hit": False}, missed) @@ -227,6 +400,26 @@ check("scrub_markings: a sphere off the surface is refused", receipt["status"] = receipt, _ = send("brokkr_mesh_polish.delight", object_name="Sign", max_gain=9) check("a bound miss is denied by Brokkr's table before the operator runs", receipt["status"] == "denied", receipt["message"]) +# --- real generated hulls, when a directory of .glb files is given: repair must turn none of their faces --------- +HULLS = os.environ.get("BROKKR_POLISH_HULLS", "") +R["hulls"] = {} +for path in sorted(Path(HULLS).glob("*.glb")) if HULLS else []: + known = set(bpy.data.objects.keys()) + bpy.ops.import_scene.gltf(filepath=str(path)) + for hull in [o for o in bpy.data.objects if o.name not in known and o.type == "MESH"]: + was = polygon_normals(hull.data) + _, raw = send("brokkr_mesh_polish.audit", object_name=hull.name) + against = raw[hull.name]["windingAgainstNormals"] + receipt, mended = send("brokkr_mesh_polish.repair", object_name=hull.name) + now = polygon_normals(hull.data) + turned = int(((was * now).sum(axis=1) < 0).sum()) if len(was) == len(now) else None + R["hulls"][path.name] = {"polygons": len(was), "polygonsAfter": len(now), "turned": turned, "againstBefore": against, + "againstAfter": mended["after"]["windingAgainstNormals"], "changes": mended["changes"]} + check(f"hull {path.name}: repair turns no face and keeps the shading normals' sides", receipt["status"] == "accepted" + and mended["changes"]["windingFlipped"] == 0 and turned in (0, None) # None: faces were removed, so indices no longer pair + and 0 <= against - mended["after"]["windingAgainstNormals"] <= len(was) - len(now), R["hulls"][path.name]) + bpy.data.objects.remove(hull) + R["ok"] = all(c["ok"] for c in R["checks"]) Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") for c in R["checks"]: diff --git a/surfaces/blender/tests/live/mesh_polish.result.json b/surfaces/blender/tests/live/mesh_polish.result.json index 9f3bae1..afe1e82 100644 --- a/surfaces/blender/tests/live/mesh_polish.result.json +++ b/surfaces/blender/tests/live/mesh_polish.result.json @@ -37,26 +37,27 @@ "boundaryEdges": 0, "nonManifoldEdges": 0, "collapsedTriangles": 0, + "windingAgainstNormals": 1104, "shells": 1, "shellTriangles": [ 2208 ], "uvIslands": 1, - "uvFlippedTriangles": 0, + "uvMirroredTriangles": 0, "uvZeroAreaTriangles": 0, "uvOutsideUnitTriangles": 0, - "uvCoverage": 0.95831298828125, + "uvCoverage": 0.6139068603515625, "uvOverlap": 0.0, - "texelDensityMedian": 61.97425923665604, - "texelDensityP5": 57.66165269744736, - "texelDensityP95": 113.44982327717632, - "texelDensitySpread": 1.9675090457856172, + "texelDensityMedian": 49.579448658498315, + "texelDensityP5": 46.12933107377486, + "texelDensityP95": 90.75985098993894, + "texelDensitySpread": 1.9675085000644446, "baseColorImage": "ball_bake", "baseColorSize": [ 256, 256 ], - "customNormals": false + "customNormals": true } }, { @@ -77,28 +78,38 @@ "boundaryEdges": 0, "nonManifoldEdges": 0, "collapsedTriangles": 0, + "windingAgainstNormals": 1104, "shells": 1, "shellTriangles": [ 2208 ], "uvIslands": 1, - "uvFlippedTriangles": 0, + "uvMirroredTriangles": 0, "uvZeroAreaTriangles": 0, "uvOutsideUnitTriangles": 0, - "uvCoverage": 0.95831298828125, + "uvCoverage": 0.6139068603515625, "uvOverlap": 0.0, - "texelDensityMedian": 61.97425923665604, - "texelDensityP5": 57.66165269744736, - "texelDensityP95": 113.44982327717632, - "texelDensitySpread": 1.9675090457856172, + "texelDensityMedian": 49.579448658498315, + "texelDensityP5": 46.12933107377486, + "texelDensityP95": 90.75985098993894, + "texelDensitySpread": 1.9675085000644446, "baseColorImage": "ball_bake", "baseColorSize": [ 256, 256 ], - "customNormals": false + "customNormals": true } }, + { + "name": "audit: counts the triangles wound against their shading normals, and none of them as a mirrored texture", + "ok": true, + "detail": [ + 1104, + 1104, + 0 + ] + }, { "name": "repair: accepted as one undo step", "ok": true, @@ -113,8 +124,8 @@ "note": "", "undoLabel": "Brokkr test/driver: brokkr_mesh_polish.repair live-2", "lookPath": "", - "hostResult": "{\"object\":\"Ball\",\"changes\":{\"welded\":3406,\"degenerateFacesRemoved\":0,\"looseEdgesRemoved\":0,\"looseVertsRemoved\":0,\"shellsRemoved\":0,\"holesFilled\":0},\"before\":{\"triangles\":2208,\"vertices\":4512,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1},\"after\":{\"triangles\":2208,\"vertices\":1106,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1}}", - "observedAt": "2026-12-01T00:06:45.524772+00:00" + "hostResult": "{\"object\":\"Ball\",\"changes\":{\"welded\":3406,\"facesCollapsedByWeld\":0,\"degenerateFacesRemoved\":0,\"looseEdgesRemoved\":0,\"looseVertsRemoved\":0,\"shellsRemoved\":0,\"holesFilled\":0,\"windingFlipped\":0,\"customNormalsDropped\":false},\"before\":{\"triangles\":2208,\"vertices\":4512,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1,\"windingAgainstNormals\":1104},\"after\":{\"triangles\":2208,\"vertices\":1106,\"boundaryEdges\":0,\"nonManifoldEdges\":0,\"shells\":1,\"windingAgainstNormals\":1104}}", + "observedAt": "2026-12-01T01:10:29.202522+00:00" } }, { @@ -124,25 +135,30 @@ "object": "Ball", "changes": { "welded": 3406, + "facesCollapsedByWeld": 0, "degenerateFacesRemoved": 0, "looseEdgesRemoved": 0, "looseVertsRemoved": 0, "shellsRemoved": 0, - "holesFilled": 0 + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false }, "before": { "triangles": 2208, "vertices": 4512, "boundaryEdges": 0, "nonManifoldEdges": 0, - "shells": 1 + "shells": 1, + "windingAgainstNormals": 1104 }, "after": { "triangles": 2208, "vertices": 1106, "boundaryEdges": 0, "nonManifoldEdges": 0, - "shells": 1 + "shells": 1, + "windingAgainstNormals": 1104 } } }, @@ -152,9 +168,58 @@ "detail": 2256 }, { - "name": "delight: accepted, new packed image on the material", + "name": "repair: by default turns no face (a single-sided material would cull a turned one)", "ok": true, - "detail": "Operator brokkr_mesh_polish.delight finished." + "detail": [ + 0, + { + "object": "Ball", + "changes": { + "welded": 3406, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 0, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + }, + "before": { + "triangles": 2208, + "vertices": 4512, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "shells": 1, + "windingAgainstNormals": 1104 + }, + "after": { + "triangles": 2208, + "vertices": 1106, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "shells": 1, + "windingAgainstNormals": 1104 + } + } + ] + }, + { + "name": "repair: the shading normals survive the weld", + "ok": true, + "detail": { + "reversedTriangles": 1104, + "turnedByDefaultRepair": 0, + "shadingErrorDegrees": 0.03426402062177658 + } + }, + { + "name": "delight: accepted, new packed image on the material, in the old image's colour space", + "ok": true, + "detail": [ + "Operator brokkr_mesh_polish.delight finished.", + "Non-Color" + ] }, { "name": "delight: finds the baked light", @@ -166,22 +231,22 @@ "Ball" ], "explainedByLight": { - "before": 0.9722586649734903, - "after": 0.005096664890544278 + "before": 0.9718638595466577, + "after": 0.0005166823179215685 }, "before": { - "upDownLuminanceRatio": 2.5686425388668988, + "upDownLuminanceRatio": 2.562451830544031, "occlusionCorrelation": 0.0 }, "after": { - "upDownLuminanceRatio": 1.0190418174045521, + "upDownLuminanceRatio": 1.0166067038538378, "occlusionCorrelation": 0.0 }, "gain": { - "min": 0.9849698054726783, - "median": 1.454503966956526, - "max": 3.0, - "clamped": 0.05147808358817533 + "min": 0.9857558709602762, + "median": 1.457103285957073, + "max": 3.0649151172981792, + "clamped": 0.0 } } }, @@ -189,10 +254,149 @@ "name": "delight: levels top against bottom", "ok": true, "detail": [ - 3.2905027932960893, - 1.119760513305664 + 3.2607489597780868, + 1.1137723922729492 ] }, + { + "name": "delight: the gain reaches the island's border unweakened", + "ok": true, + "detail": 0.0 + }, + { + "name": "repair: recalc_normals rewinds the inside-out half and says how many faces it turned", + "ok": true, + "detail": { + "object": "Ball", + "changes": { + "welded": 0, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 0, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 576, + "customNormalsDropped": true + }, + "before": { + "triangles": 2208, + "vertices": 1106, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "shells": 1, + "windingAgainstNormals": 1104 + }, + "after": { + "triangles": 2208, + "vertices": 1106, + "boundaryEdges": 0, + "nonManifoldEdges": 0, + "shells": 1, + "windingAgainstNormals": 0 + } + } + }, + { + "name": "repair: fills the 4-edge hole, leaves the 8-edge hole and the rim, drops the chip", + "ok": true, + "detail": { + "object": "Sheet", + "changes": { + "welded": 0, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 0, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 1, + "holesFilled": 1, + "windingFlipped": 0, + "customNormalsDropped": false + }, + "before": { + "triangles": 63, + "vertices": 51, + "boundaryEdges": 39, + "nonManifoldEdges": 0, + "shells": 2, + "windingAgainstNormals": 0 + }, + "after": { + "triangles": 64, + "vertices": 48, + "boundaryEdges": 32, + "nonManifoldEdges": 0, + "shells": 1, + "windingAgainstNormals": 0 + } + } + }, + { + "name": "repair: a filled hole is wound as the faces around it", + "ok": true, + "detail": [ + 33, + -1.0 + ] + }, + { + "name": "repair: old faces keep their shading normals through the weld and the fill; the fill is shaded by its own direction", + "ok": true, + "detail": [ + 6, + [ + [ + 0.0, + 0.0, + -1.0 + ], + [ + 0.0, + 0.0, + -1.0 + ] + ], + [ + 0.6000571846961975, + 7.155610326492479e-09, + -0.7999570965766907 + ] + ] + }, + { + "name": "delight: lifts occluded surface to the level of open surface", + "ok": true, + "detail": { + "report": { + "image": "twins_bake", + "newImage": "twins_bake.delit", + "objects": [ + "Twins" + ], + "explainedByLight": { + "before": 0.9999597575085393, + "after": 0.028075104342772272 + }, + "before": { + "upDownLuminanceRatio": 1.0000084632254227, + "occlusionCorrelation": 0.983967648279407 + }, + "after": { + "upDownLuminanceRatio": 0.9999964767503613, + "occlusionCorrelation": 0.40471079036691976 + }, + "gain": { + "min": 0.9999809983875252, + "median": 1.0000990920451596, + "max": 5.493916964800697, + "clamped": 0.0 + } + }, + "occludedTexels": 2209, + "shadeBefore": 0.42187492665834836, + "shadeAfter": 1.0 + } + }, { "name": "orient: long on Y, thin on Z, scaled to the length, centred", "ok": true, @@ -229,6 +433,18 @@ "Z": 1.962464589014781e-09 } }, + { + "name": "orient: an object outside the named root is not touched", + "ok": true, + "detail": [ + "Slab" + ] + }, + { + "name": "orient: an unknown root is refused", + "ok": true, + "detail": "Error: No object named 'Nobody'." + }, { "name": "cut fixture is one closed skin", "ok": true, @@ -247,12 +463,13 @@ "boundaryEdges": 0, "nonManifoldEdges": 0, "collapsedTriangles": 0, + "windingAgainstNormals": 0, "shells": 1, "shellTriangles": [ 28 ], "uvIslands": 1, - "uvFlippedTriangles": 0, + "uvMirroredTriangles": 0, "uvZeroAreaTriangles": 28, "uvOutsideUnitTriangles": 0, "uvCoverage": 0.0, @@ -312,15 +529,76 @@ } }, { - "name": "cut_parts: caps carry the cap material and a joint sits at the root", + "name": "cut_parts: exactly the cap faces carry the cap material", + "ok": true, + "detail": { + "Block.body": 2, + "Block.knob": 2 + } + }, + { + "name": "cut_parts: each cap faces out of its own part, and no old face was turned", + "ok": true, + "detail": { + "Block.body": [ + 1.0, + 1.0 + ], + "Block.knob": [ + -1.0, + -1.0 + ] + } + }, + { + "name": "cut_parts: a joint sits at the root", "ok": true, "detail": "Block.knob.joint" }, + { + "name": "orient: after a cut the parts keep their parent and their pivot at the cut", + "ok": true, + "detail": { + "report": { + "objects": [ + "Block.body", + "Block.knob", + "Block.knob.joint" + ], + "scale": 1.9999999986467376, + "extent": [ + 5.656854, + 6.0, + 5.656854 + ], + "mirrorError": { + "X": 1.8120748396336225e-08, + "Y": 0.1508370330678463, + "Z": 1.8363068583553207e-08 + } + }, + "knobPivot": [ + 1.407290284305418e-09, + 1.0, + -1.8218171415895767e-09 + ], + "knobReach": 3.0, + "parent": "Block.body" + } + }, { "name": "cut_parts: one part is refused with nothing changed", "ok": true, "detail": "Error: Cutting needs seeds for at least two parts." }, + { + "name": "cut_parts: through seeds the far face of a thin part", + "ok": true, + "detail": { + "without": 0, + "with": 93 + } + }, { "name": "pick: names the surface point under (u, v) of a picture of that shape", "ok": true, @@ -328,7 +606,7 @@ "hit": true, "object": "Sign", "point": [ - -1.0, + 39.0, 0.0, 5.0 ], @@ -375,6 +653,72 @@ "name": "a bound miss is denied by Brokkr's table before the operator runs", "ok": true, "detail": "max_gain must be between 1 and 8." + }, + { + "name": "hull fourth.glb: repair turns no face and keeps the shading normals' sides", + "ok": true, + "detail": { + "polygons": 28426, + "polygonsAfter": 28420, + "turned": null, + "againstBefore": 388, + "againstAfter": 387, + "changes": { + "welded": 6437, + "facesCollapsedByWeld": 2, + "degenerateFacesRemoved": 4, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + } + } + }, + { + "name": "hull sub.glb: repair turns no face and keeps the shading normals' sides", + "ok": true, + "detail": { + "polygons": 10406, + "polygonsAfter": 10406, + "turned": 0, + "againstBefore": 64, + "againstAfter": 64, + "changes": { + "welded": 2454, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 0, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + } + } + }, + { + "name": "hull third.glb: repair turns no face and keeps the shading normals' sides", + "ok": true, + "detail": { + "polygons": 23341, + "polygonsAfter": 23340, + "turned": null, + "againstBefore": 189, + "againstAfter": 189, + "changes": { + "welded": 3810, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 1, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + } + } } ], "hostErrors": [], @@ -387,6 +731,11 @@ "brokkr_mesh_polish.cut_parts", "brokkr_mesh_polish.pick" ], + "winding": { + "reversedTriangles": 1104, + "turnedByDefaultRepair": 0, + "shadingErrorDegrees": 0.03426402062177658 + }, "delight": { "report": { "image": "ball_bake", @@ -395,26 +744,87 @@ "Ball" ], "explainedByLight": { - "before": 0.9722586649734903, - "after": 0.005096664890544278 + "before": 0.9718638595466577, + "after": 0.0005166823179215685 }, "before": { - "upDownLuminanceRatio": 2.5686425388668988, + "upDownLuminanceRatio": 2.562451830544031, "occlusionCorrelation": 0.0 }, "after": { - "upDownLuminanceRatio": 1.0190418174045521, + "upDownLuminanceRatio": 1.0166067038538378, "occlusionCorrelation": 0.0 }, "gain": { - "min": 0.9849698054726783, - "median": 1.454503966956526, - "max": 3.0, - "clamped": 0.05147808358817533 + "min": 0.9857558709602762, + "median": 1.457103285957073, + "max": 3.0649151172981792, + "clamped": 0.0 } }, - "ratioBefore": 3.2905027932960893, - "ratioAfter": 1.119760513305664 + "ratioBefore": 3.2607489597780868, + "ratioAfter": 1.1137723922729492, + "borderDeficit": 0.0 + }, + "mend": { + "object": "Sheet", + "changes": { + "welded": 0, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 0, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 1, + "holesFilled": 1, + "windingFlipped": 0, + "customNormalsDropped": false + }, + "before": { + "triangles": 63, + "vertices": 51, + "boundaryEdges": 39, + "nonManifoldEdges": 0, + "shells": 2, + "windingAgainstNormals": 0 + }, + "after": { + "triangles": 64, + "vertices": 48, + "boundaryEdges": 32, + "nonManifoldEdges": 0, + "shells": 1, + "windingAgainstNormals": 0 + } + }, + "occlusion": { + "report": { + "image": "twins_bake", + "newImage": "twins_bake.delit", + "objects": [ + "Twins" + ], + "explainedByLight": { + "before": 0.9999597575085393, + "after": 0.028075104342772272 + }, + "before": { + "upDownLuminanceRatio": 1.0000084632254227, + "occlusionCorrelation": 0.983967648279407 + }, + "after": { + "upDownLuminanceRatio": 0.9999964767503613, + "occlusionCorrelation": 0.40471079036691976 + }, + "gain": { + "min": 0.9999809983875252, + "median": 1.0000990920451596, + "max": 5.493916964800697, + "clamped": 0.0 + } + }, + "occludedTexels": 2209, + "shadeBefore": 0.42187492665834836, + "shadeAfter": 1.0 }, "cut": { "body": "Block.body", @@ -456,6 +866,37 @@ } ] }, + "orientParts": { + "report": { + "objects": [ + "Block.body", + "Block.knob", + "Block.knob.joint" + ], + "scale": 1.9999999986467376, + "extent": [ + 5.656854, + 6.0, + 5.656854 + ], + "mirrorError": { + "X": 1.8120748396336225e-08, + "Y": 0.1508370330678463, + "Z": 1.8363068583553207e-08 + } + }, + "knobPivot": [ + 1.407290284305418e-09, + 1.0, + -1.8218171415895767e-09 + ], + "knobReach": 3.0, + "parent": "Block.body" + }, + "through": { + "without": 0, + "with": 93 + }, "scrub": { "report": { "object": "Sign", @@ -467,5 +908,61 @@ "inkInsideBefore": 192, "inkInsideAfter": 0 }, + "hulls": { + "fourth.glb": { + "polygons": 28426, + "polygonsAfter": 28420, + "turned": null, + "againstBefore": 388, + "againstAfter": 387, + "changes": { + "welded": 6437, + "facesCollapsedByWeld": 2, + "degenerateFacesRemoved": 4, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + } + }, + "sub.glb": { + "polygons": 10406, + "polygonsAfter": 10406, + "turned": 0, + "againstBefore": 64, + "againstAfter": 64, + "changes": { + "welded": 2454, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 0, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + } + }, + "third.glb": { + "polygons": 23341, + "polygonsAfter": 23340, + "turned": null, + "againstBefore": 189, + "againstAfter": 189, + "changes": { + "welded": 3810, + "facesCollapsedByWeld": 0, + "degenerateFacesRemoved": 1, + "looseEdgesRemoved": 0, + "looseVertsRemoved": 0, + "shellsRemoved": 0, + "holesFilled": 0, + "windingFlipped": 0, + "customNormalsDropped": false + } + } + }, "ok": true } \ No newline at end of file diff --git a/surfaces/blender/tests/test_mesh_polish.py b/surfaces/blender/tests/test_mesh_polish.py index 7205f81..9f0b4ef 100644 --- a/surfaces/blender/tests/test_mesh_polish.py +++ b/surfaces/blender/tests/test_mesh_polish.py @@ -37,6 +37,7 @@ def load(name: str, path: Path): turntable = load("turntable_recipe", SURFACE / "tools" / "turntable_recipe.py") +private_dirs = load("private_dirs", SURFACE / "tools" / "private_dirs.py") core = load("brokkr_mesh_polish_core", SURFACE / "brokkr_mesh_polish" / "core.py") if np is not None else None @@ -83,6 +84,23 @@ class TopologyTests(unittest.TestCase): self.assertEqual(report["shells"], 2) self.assertEqual(report["shellTriangles"], [4, 4]) + def test_a_triangle_the_weld_collapses_adds_no_edges(self): + V, T = quad_strip(3) + sliver = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1.0, 1.0, 0.0]]) # two corners weld into one + _, TW = core.weld(np.concatenate([V, sliver]), np.concatenate([T, [[len(V), len(V) + 1, len(V) + 2]]]), 1e-6) + census = core.edge_census(TW) + self.assertEqual((census["collapsedTriangles"], census["boundaryEdges"], census["nonManifoldEdges"]), (1, 8, 0)) + + def test_winding_against_shading_normals_is_counted_per_triangle(self): + V, T = quad_strip(3) # every triangle faces +z + up = np.tile([0.0, 0.0, 1.0], (len(T), 3, 1)) + self.assertEqual(int(core.winding_against(V, T, up).sum()), 0) + mixed = T.copy() + mixed[:2] = mixed[:2, ::-1] # two triangles wound the other way, their shading normals still up + self.assertEqual(core.winding_against(V, mixed, up).tolist(), [True, True, False, False, False, False]) + self.assertEqual(core.audit(V, mixed, None, CN=up)["windingAgainstNormals"], 2) + self.assertNotIn("windingAgainstNormals", core.audit(V, mixed, None)) + def test_components_follow_long_chains(self): pairs = np.array([[i, i + 1] for i in range(999)]) self.assertEqual(len(np.unique(core.components(1000, pairs[::-1]))), 1) @@ -101,7 +119,34 @@ class UvTests(unittest.TestCase): self.assertLess(report["uvOverlap"], 0.02) # only texel centres exactly on the shared diagonal self.assertAlmostEqual(report["texelDensityMedian"], 1024.0, places=3) self.assertAlmostEqual(report["texelDensitySpread"], 1.0, places=6) - self.assertEqual((report["uvIslands"], report["uvFlippedTriangles"]), (1, 0)) + self.assertEqual((report["uvIslands"], report["uvMirroredTriangles"]), (1, 0)) + + def test_a_seam_in_uv_space_makes_two_islands_of_one_surface(self): + apart = self.SQUARE_UV * 0.4 + apart[1] += 0.5 # the second triangle's UVs moved away: the 3D edge is shared, the UV edge is not + self.assertEqual(core.audit(self.SQUARE_V, self.SQUARE_T, apart, 1024, raster=64)["uvIslands"], 2) + self.assertEqual(core.audit(self.SQUARE_V, self.SQUARE_T, self.SQUARE_UV * 0.4, 1024, raster=64)["uvIslands"], 1) + + def test_texel_density_is_weighted_by_surface_area(self): + # one large triangle at 1024 texels per unit and four tiny ones at 4096: by count the median is 4096, by area 1024 + tiny = np.array([[0, 0, 0], [0.01, 0, 0], [0, 0.01, 0]], dtype=float) + V = np.concatenate([self.SQUARE_V[[0, 1, 2]] * 0.5] + [tiny + [2 + i, 0, 0] for i in range(4)]) + T = np.arange(15).reshape(5, 3) + UV = np.concatenate([self.SQUARE_UV[:1] * 0.5] + [tiny[None, :, :2] * 4 + [0.6 + 0.05 * i, 0.6] for i in range(4)]) + report = core.audit(V, T, UV, texture_size=1024, raster=64) + self.assertAlmostEqual(report["texelDensityMedian"], 1024.0, places=3) + self.assertAlmostEqual(report["texelDensityP95"], 1024.0, places=3) + + def test_mirrored_texture_is_judged_against_the_shading_normals_not_the_winding(self): + up = np.tile([0.0, 0.0, 1.0], (2, 3, 1)) + wound_back = self.SQUARE_T[:, ::-1] + uv_back = self.SQUARE_UV[:, ::-1] # the same texel at each vertex, listed in the reversed corner order + report = core.audit(self.SQUARE_V, wound_back, uv_back, 1024, raster=64, CN=up) + self.assertEqual((report["windingAgainstNormals"], report["uvMirroredTriangles"]), (2, 0)) # culled, but not mirrored + mirrored = self.SQUARE_UV.copy() + mirrored[..., 0] = 1 - mirrored[..., 0] + report = core.audit(self.SQUARE_V, self.SQUARE_T, mirrored, 1024, raster=64, CN=up) + self.assertEqual((report["windingAgainstNormals"], report["uvMirroredTriangles"]), (0, 2)) # drawn, and mirrored def test_two_triangles_on_the_same_texels_overlap(self): stacked = np.array([self.SQUARE_UV[0], self.SQUARE_UV[0]]) @@ -111,7 +156,7 @@ class UvTests(unittest.TestCase): def test_a_mirrored_island_counts_as_flipped_and_half_the_area_doubles_nothing_but_density(self): mirrored = self.SQUARE_UV.copy() mirrored[..., 0] = 1 - mirrored[..., 0] - self.assertEqual(core.audit(self.SQUARE_V, self.SQUARE_T, mirrored, 1024, raster=64)["uvFlippedTriangles"], 2) + self.assertEqual(core.audit(self.SQUARE_V, self.SQUARE_T, mirrored, 1024, raster=64)["uvMirroredTriangles"], 2) half = core.audit(self.SQUARE_V, self.SQUARE_T, self.SQUARE_UV * 0.5, 1024, raster=64) self.assertAlmostEqual(half["texelDensityMedian"], 512.0, places=3) self.assertAlmostEqual(half["uvCoverage"], 0.25, places=2) @@ -138,6 +183,22 @@ class OrientTests(unittest.TestCase): self.assertLess(extent[2], 1e-9) self.assertAlmostEqual(float(np.linalg.det(R)), 1.0, places=9) + def test_principal_frame_is_a_rotation_for_a_shape_and_for_its_mirror_image(self): + rng = np.random.default_rng(4) + V = rng.random((60, 3)) * [5.0, 2.0, 1.0] + T = rng.integers(0, 60, size=(40, 3)) + T = T[(T[:, 0] != T[:, 1]) & (T[:, 1] != T[:, 2]) & (T[:, 0] != T[:, 2])] + determinants = [float(np.linalg.det(core.principal_frame(V * flip, T)[1])) for flip in ([1, 1, 1], [-1, 1, 1], [1, -1, 1], [1, 1, -1])] + self.assertTrue(np.allclose(determinants, 1.0), determinants) # never a reflection: it would turn the mesh inside out + + def test_mirror_error_is_about_the_axis_asked(self): + rng = np.random.default_rng(1) + half = rng.random((400, 3)) + about_y = np.concatenate([half, half * [1, -1, 1]]) + [0.7, 0.0, 0.3] # a mirror across y = 0 only + self.assertEqual(core.mirror_error(about_y, 1), 0.0) + self.assertGreater(core.mirror_error(about_y, 0), 0.05) + self.assertGreater(core.mirror_error(about_y, 2), 0.05) + def test_mirror_error_tells_a_symmetric_cloud_from_a_lopsided_one(self): rng = np.random.default_rng(1) half = rng.random((400, 3)) @@ -321,6 +382,16 @@ class TextureFillTests(unittest.TestCase): outside = np.zeros((40, 40), dtype=bool) self.assertFalse(core.marking_mask(panel, outside, 0.25, 1).any()) + def test_marking_mask_judges_against_the_median_so_heavy_lettering_does_not_move_the_panel_colour(self): + panel = np.full((40, 40, 3), [0.1, 0.35, 0.4], dtype=np.float32) + panel[:, ::3] = [0.95, 0.9, 0.3] # a third of the region is lettering: the mean colour is 0.3 from the panel + region = np.ones((40, 40), dtype=bool) + mask = core.marking_mask(panel, region, 0.25, 0) + self.assertTrue(np.array_equal(mask, np.repeat((np.arange(40) % 3 == 0)[None, :], 40, axis=0))) + + def test_srgb_known_values(self): + self.assertTrue(np.allclose(core.srgb_to_linear(np.array([0.0, 0.04045, 0.5, 1.0])), [0.0, 0.0031308, 0.21404, 1.0], atol=2e-5)) + def test_box_blur_keeps_a_flat_field_and_spreads_a_point(self): flat = np.full((9, 9), 0.5) self.assertTrue(np.allclose(core.box_blur(flat, 2), 0.5)) @@ -360,6 +431,46 @@ class HostFileTests(unittest.TestCase): at.validate({**envelope, "action": "brokkr_mesh_polish.cut_parts", "object_name": "Hull"}, host) # seeds required +class PrivateDirsTests(unittest.TestCase): + """The guard a driver script runs before it touches Blender's user folders.""" + HOME = str(Path("/home/her")) + APPDATA = str(Path("/users/her/AppData/Roaming")) + + def environ(self, **changes): + base = {"BLENDER_USER_CONFIG": "/scratch/bl/cfg", "BLENDER_USER_EXTENSIONS": "/scratch/bl/ext", + "BLENDER_USER_SCRIPTS": "/scratch/bl/scripts", "APPDATA": self.APPDATA} + base.update(changes) + return {k: v for k, v in base.items() if v is not None} + + def test_scratch_directories_pass(self): + self.assertIsNone(private_dirs.refusal(self.environ(), self.HOME)) + used = {"CONFIG": "/scratch/bl/cfg", "EXTENSIONS": "/scratch/bl/ext", "SCRIPTS": "/scratch/bl/scripts"} + self.assertIsNone(private_dirs.refusal(self.environ(), self.HOME, lambda kind: used[kind])) + + def test_an_unset_or_empty_variable_is_refused(self): + for name in private_dirs.VARIABLES: + for value in (None, ""): + self.assertIn(name, private_dirs.refusal(self.environ(**{name: value}), self.HOME)) + + def test_a_variable_pointing_into_her_own_blender_folders_is_refused(self): + own = [str(Path(self.APPDATA) / "Blender Foundation" / "Blender" / "5.3" / "extensions"), + str(Path(self.APPDATA) / "Blender Foundation"), + str(Path(self.HOME) / ".config" / "blender" / "5.3" / "scripts"), + str(Path(self.HOME) / "Library" / "Application Support" / "Blender" / "5.3" / "config")] + for folder in own: + for name in private_dirs.VARIABLES: + refused = private_dirs.refusal(self.environ(**{name: folder}), self.HOME) + self.assertIsNotNone(refused, folder) + self.assertIn("own Blender folder", refused) + beside = str(Path(self.APPDATA) / "Blender Foundation Scratch") # a sibling that only shares a prefix + self.assertIsNone(private_dirs.refusal(self.environ(BLENDER_USER_EXTENSIONS=beside), self.HOME)) + + def test_a_blender_that_is_not_using_the_variables_is_refused(self): + hers = str(Path(self.APPDATA) / "Blender Foundation" / "Blender" / "5.3") + self.assertIn("refusing to touch it", private_dirs.refusal(self.environ(), self.HOME, lambda kind: hers)) + self.assertIn("refusing", private_dirs.refusal(self.environ(), self.HOME, lambda kind: "")) + + class TurntableRecipeTests(unittest.TestCase): def test_every_pose_looks_at_the_origin_with_z_up(self): for azimuth in (0, 45, 90, 200, 315):