diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index ea1c2fd..eb004e0 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -8,7 +8,9 @@ WindowManager.brokkr_mesh_polish_result, as the polish operators do. What a placed part is lives on its object as three ID properties: kit_kit, kit_part and kit_params. The mesh is derived from them (set_params rebuilds it), and socket frames are derived again at every report: nothing else in -the scene stores them. Placement, materials and export are Brokkr's own rows (setObjectTransform, assignMaterial, +the scene stores them. Two things would give a part a second owner and are refused: a mesh datablock shared with +another object (set_params), and a world transform that scales, mirrors or shears (set_params and report: a +part's size is its params). Placement, materials and export are Brokkr's own rows (setObjectTransform, assignMaterial, exportGltf). """ bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0), @@ -66,10 +68,19 @@ def sync_bevel(obj, width: float) -> None: modifier.width = width +RIGID = 1e-5 # how far a world matrix's 3x3 may stand from a rotation + + def kit_part_of(obj): - """(part, stored params) of a placed part, read from its ID properties.""" + """(part, stored params) of a placed part, read from its ID properties. Refuses a part whose world transform is + not rigid: its socket frames would not be frames, and its size would have a second owner.""" if PART not in obj: raise Refused(f"{obj.name!r} is not a kit part (it has no {PART} property); place_part makes one.") + turn = np.array(obj.matrix_world)[:3, :3] + if np.abs(turn.T @ turn - np.eye(3)).max() > RIGID or np.linalg.det(turn) < 0: + scale = ", ".join(f"{s:.4g}" for s in obj.matrix_world.to_scale()) + raise Refused(f"{obj.name!r} is scaled, mirrored or sheared in the world (scale {scale}): a kit part's size is its params. " + "Set its scale, and its parents', to 1 (setObjectTransform) and resize it with set_params.") try: stored = json.loads(obj.get(PARAMS, "{}")) except ValueError: @@ -85,6 +96,22 @@ def part_report(obj, part, built) -> dict: "sockets": core.socket_rows(built.sockets, np.array(obj.matrix_world))} +def carried_materials(mesh, old, new): + """Per-face material indices for a rebuilt mesh, or None when there is nothing to carry: each shape of the part + keeps the index most of its faces had (the lowest on a tie), since faces do not survive a change of segments + or counts but shapes do. A mesh that is no longer the old build (edited by hand) carries nothing.""" + if old is None or len(mesh.polygons) != len(old.counts): + return None + index = np.zeros(len(old.counts), dtype=np.int32) + mesh.polygons.foreach_get("material_index", index) + if not index.any(): + return None + carried = np.zeros(len(new.counts), dtype=np.int32) + for shape in np.unique(old.shape): + carried[new.shape == shape] = np.bincount(index[old.shape == shape]).argmax() + return carried + + def bounded(report: dict, advice: str) -> dict: size = len(json.dumps(report, separators=(",", ":"))) if size > REPORT_LIMIT: @@ -119,7 +146,7 @@ class BROKKR_KITBASH_OT_place_part(PolishOperator): class BROKKR_KITBASH_OT_set_params(PolishOperator): """Change params of a placed kit part and rebuild its mesh in place: its transform, parent, modifiers and - material slots stay, and the Bevel width follows""" + material slots stay, each shape keeps its faces' material, and the Bevel width follows""" bl_idname = "brokkr_kitbash.set_params" bl_label = "Set Kit Part Params" object_name: bpy.props.StringProperty(name="Object") @@ -129,9 +156,20 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator): def work(self, context): obj = mesh_object(self.object_name) part, stored = kit_part_of(obj) + if obj.data.users > 1: + raise Refused(f"{obj.name!r} shares its mesh {obj.data.name!r} with {obj.data.users - 1} other user(s): rebuilding it would change " + "them while their params stay. Give it its own mesh (place_part a new part) and set that; nothing changed.") built = core.build(part, core.resolve_params(part, core.parse_params(self.params), stored)) + try: + old = core.build(part, stored) + except core.KitError: # stored params an edited kit no longer admits: nothing to map faces by + old = None + materials = carried_materials(obj.data, old, built) obj.data.clear_geometry() write_mesh(obj.data, built) + if materials is not None: + obj.data.polygons.foreach_set("material_index", materials) + obj.data.update() sync_bevel(obj, built.bevel) obj[PARAMS] = json.dumps(built.params) return part_report(obj, part, built) diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 41e010a..b570c13 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -45,7 +45,7 @@ }, { "name": "brokkr_kitbash.set_params", - "doc": "Change params of a placed kit part and rebuild its mesh in place; transform, parent, modifiers and materials stay. Reports as place_part.", + "doc": "Change params of a placed kit part and rebuild its mesh in place; transform, parent, modifiers and materials stay. Refuses a mesh another object shares and a scaled part. Reports as place_part.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -93,7 +93,7 @@ }, { "name": "brokkr_kitbash.report", - "doc": "Placed kit parts as the scene has them: kit, part, params, faces, shells and each socket's world 4x4.", + "doc": "Placed kit parts as the scene has them: kit, part, params, faces, shells and each socket's world 4x4. Refuses a part scaled in the world: resize with set_params.", "changesScene": false, "editModeSafe": true, "result": "brokkr_mesh_polish_result", diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index 0d6b0c8..a9b0c6b 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -40,6 +40,16 @@ class KitError(ValueError): """The kit document, a param or a build breaks a rule of the format; the message names where.""" +def finite(value: Any) -> bool: + """A number (not a bool) a float can hold: an integer too large for one is not finite.""" + if isinstance(value, bool) or not isinstance(value, (int, float)): + return False + try: + return math.isfinite(float(value)) + except OverflowError: + return False + + # --- expressions --------------------------------------------------------------------------------------------- class Expr: @@ -50,8 +60,11 @@ class Expr: self.source, self.tree, self.where = source, tree, where def value(self, env: dict[str, float]) -> float: - result = self.source if self.tree is None else _walk(self.tree, env, self) - if not math.isfinite(result): + try: + result = self.source if self.tree is None else _walk(self.tree, env, self) + except OverflowError: # an integer literal no float holds + result = math.inf + if not finite(result): raise KitError(f"{self.where}: {self.source!r} is not a finite number") return float(result) @@ -60,8 +73,8 @@ def parse(value: Any, names, where: str) -> Expr: """The Expr for a numeric field: a finite number, or a string of + - * /, unary minus, parentheses, min(a,b), max(a,b), numbers and the names given. Anything else is refused here, before any build.""" if isinstance(value, (int, float)) and not isinstance(value, bool): - if not math.isfinite(value): - raise KitError(f"{where}: {value!r} is not a finite number") + if not finite(value): + raise KitError(f"{where}: {str(value)[:40]} is not a finite number") return Expr(value, None, where) if not isinstance(value, str): raise KitError(f"{where} must be a number or an expression string, not {type(value).__name__}") @@ -150,7 +163,7 @@ def _name(value: Any, where: str, seen: set) -> str: def _number(value: Any, where: str) -> float: - if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + if not finite(value): raise KitError(f"{where} must be a finite number") return value @@ -166,7 +179,7 @@ ZERO = [Expr(0.0, None, "zero")] * 3 def _shape(shape: Any, names, where: str, inside_repeat: bool = False) -> dict: kind = shape.get("shape") if isinstance(shape, dict) else None - if kind not in SHAPES: + if not isinstance(kind, str) or kind not in SHAPES: raise KitError(f"{where}: unknown shape {kind!r}; shapes are {', '.join(SHAPES)}") where = f"{where} ({kind})" required, optional = SHAPES[kind] @@ -248,10 +261,10 @@ def check_kit(document: Any) -> dict: s_name = _name(socket.get("name") if isinstance(socket, dict) else None, f"{where} socket {s_index}", socket_names) s_where = f"{where} socket {s_name!r}" _keys(socket, s_where, ("name", "type", "size", "at", "z", "y")) - if socket["type"] not in types: + if not isinstance(socket["type"], str) or socket["type"] not in types: raise KitError(f"{s_where}: type {socket['type']!r} is not one of the kit's socketTypes ({', '.join(types) or 'none'})") for key in ("z", "y"): - if socket[key] not in AXES: + if not isinstance(socket[key], str) or socket[key] not in AXES: raise KitError(f"{s_where}: {key} must be one of {', '.join(AXES)}") if socket["z"][1] == socket["y"][1]: raise KitError(f"{s_where}: z ({socket['z']}) and y ({socket['y']}) lie on the same axis") @@ -328,7 +341,7 @@ def resolve_params(part: dict, given: dict, base: dict | None = None) -> dict: for param in part["params"]: name = param["name"] value = merged.get(name, param["default"]) - if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + if not finite(value): raise KitError(f"{here} param {name!r} must be a finite number") if not param["min"] <= value <= param["max"]: raise KitError(f"{here} param {name!r} = {value} is outside [{param['min']}, {param['max']}] (bounds included)") @@ -344,13 +357,15 @@ def resolve_params(part: dict, given: dict, base: dict | None = None) -> dict: class Built(NamedTuple): """A part at given params, in the part's frame, metres. Face i has counts[i] corners, listed in order in - faces (quads and n-gon caps, wound outward); smooth[i] marks tube sides to shade smooth. Each socket is + faces (quads and n-gon caps, wound outward); smooth[i] marks tube sides to shade smooth; shape[i] is the index, + in the part's shapes list, of the shape the face belongs to (every copy of a repeat shares one). Each socket is {'name', 'type', 'size', 'matrix'} with matrix the 4x4 frame: column 2 the outward normal, column 1 up, column 0 = y cross z, column 3 the origin.""" V: np.ndarray faces: np.ndarray counts: np.ndarray smooth: np.ndarray + shape: np.ndarray shell_count: int sockets: list bevel: float @@ -427,15 +442,22 @@ def build(part: dict, params: dict | None = None) -> Built: """The part at these params (resolve_params fills and checks them). The same part and params give byte-identical arrays.""" env = resolve_params(part, params or {}) - shells = [] - for shape in part["shapes"]: - if shape["shape"] == "repeat": - count = _whole(shape["count"], env, COPIES) - step = np.array([e.value(env) for e in shape["step"]]) - V, faces, counts, smooth = _placed(shape["of"], env) - shells += [(V + k * step, faces, counts, smooth) for k in range(count)] - else: - shells.append(_placed(shape, env)) + here = f"kit {part['kit']!r} part {part['name']!r}" + shells, owner = [], [] + with np.errstate(over="ignore", invalid="ignore"): # a huge value is refused below, not warned about + for index, shape in enumerate(part["shapes"]): + if shape["shape"] == "repeat": + count = _whole(shape["count"], env, COPIES) + step = np.array([e.value(env) for e in shape["step"]]) + V, faces, counts, smooth = _placed(shape["of"], env) + made = [(V + k * step, faces, counts, smooth) for k in range(count)] + else: + made = [_placed(shape, env)] + for shell in made: + if not np.isfinite(shell[0]).all(): + raise KitError(f"{here} shape {index} ({shape['shape']}): its vertices are not finite at these params") + shells += made + owner += [index] * len(made) offsets = np.cumsum([0] + [len(s[0]) for s in shells[:-1]]) sockets = [] for socket in part["sockets"]: @@ -454,6 +476,7 @@ def build(part: dict, params: dict | None = None) -> Built: faces=np.concatenate([s[1] + o for s, o in zip(shells, offsets)]).astype(np.int32), counts=np.concatenate([s[2] for s in shells]).astype(np.int32), smooth=np.concatenate([s[3] for s in shells]).astype(bool), + shape=np.concatenate([np.full(len(s[2]), o) for s, o in zip(shells, owner)]).astype(np.int32), shell_count=len(shells), sockets=sockets, bevel=bevel, params=env) diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index a893abf..8ce9c2c 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -19,6 +19,11 @@ Who owns what: - In the scene, an object's `kit_kit`, `kit_part` and `kit_params` ID properties own what that part is. Its mesh is derived from them: `set_params` rebuilds it, and an edit made to the mesh by hand is lost at the next `set_params`. Socket frames are derived at every report and stored nowhere. +- Two things would give a part a second owner, and are refused. `set_params` refuses an object whose mesh + datablock another object uses (a linked duplicate): rebuilding it would change the other while its params stay. + `set_params` and `report` refuse a part whose world transform scales, mirrors or shears, its parents' + included: a part's size is its params, and a socket's frame is a rotation and an origin. Set scale to 1 and + resize with `set_params`. This add-on places and re-parameterises parts. Mating sockets, booleans and baking are not here. @@ -88,8 +93,9 @@ Every numeric field of a shape or socket, and `bevel`, is a number or a string o An expression is parsed once and walked against that list when the kit is checked; an attribute, subscript, power, comparison, any other call, a keyword argument, a lambda or a string is refused there, naming the part and -field. Nothing in a kit is run as Python. Division by zero and a `count` or `segments` that is not whole are -refused when the part is built, naming the expression. +field. Nothing in a kit is run as Python. Division by zero, a result that is not a finite number, and a `count` +or `segments` that is not whole are refused when the part is built, naming the expression; so is a shape whose +vertices overflow. ## The actions @@ -97,7 +103,7 @@ refused when the part is built, naming the expression. | --- | --- | --- | | `brokkr_kitbash.describe` | `kit` (default `mechanical`), `part` (default: all) | Parts with their params (type, min, max, default, doc) and sockets in the part frame at default params. Changes nothing. | | `brokkr_kitbash.place_part` | `kit`, `part`, `object_name`, `params` | A new mesh object at the origin: the part's mesh, a `Kit Bevel` modifier when the part has a bevel, and the three ID properties. Refuses a name an object already has. | -| `brokkr_kitbash.set_params` | `object_name`, `params` | Overlays `params` on the stored ones and rebuilds the mesh in the same datablock: transform, parent, modifiers and material slots stay, and the Bevel width follows. | +| `brokkr_kitbash.set_params` | `object_name`, `params` | Overlays `params` on the stored ones and rebuilds the mesh in the same datablock: transform, parent, modifiers and material slots stay, and the Bevel width follows. Per-face materials are carried by shape: each shape of the part keeps the material most of its faces had, whatever the new face count. | | `brokkr_kitbash.report` | `object_name` (default: every kit part) | Each part as the scene has it: kit, part, params, faces, shells, and each socket's world frame. Changes nothing. | `params` is `name=value; name=value`; a param left out takes the part's default (`place_part`) or keeps its stored diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index 7ab51e5..410cab3 100644 --- a/surfaces/blender/tests/live/kitbash.py +++ b/surfaces/blender/tests/live/kitbash.py @@ -142,8 +142,8 @@ check("set_params overlays the stored params, and the Bevel width follows the pa # --- report: sockets in the world ------------------------------------------------------------------------------------------- send("setObjectTransform", targetObjectName="P_pipe_fitting", location=[-2.0, 0.5, 1.0], rotationEuler=[1.1, 0.4, -0.7]) +receipt, reported = send("brokkr_kitbash.report") # straight after the move, before anything here updates the view layer: the frames are already the moved ones bpy.context.view_layer.update() -receipt, reported = send("brokkr_kitbash.report") worst, listed = 0.0, [] for entry in (reported or {}).get("parts", []): obj = bpy.data.objects[entry["object"]] @@ -161,9 +161,29 @@ check("report of the parented, rotated tank carries its parent's and its own tra and np.abs(np.array(single["parts"][0]["sockets"][2]["matrix"]) - tank_world @ core.build(kit["parts"]["tank"], wide["params"]).sockets[2]["matrix"]).max() < 1e-6 and np.abs(tank_world[:3, 3] - [1.0, 2.0, 3.0]).max() < 1e-6, single) +# --- per-face materials ride on the part's shapes ---------------------------------------------------------------------------- +strut = bpy.data.objects["P_strut"] +send("assignMaterial", targetObjectName="P_strut", materialName="Strut Paint", color=[0.35, 0.35, 0.35]) +strut.data.materials.append(bpy.data.materials.new("Pin Steel")) +PINS = 2 # the strut's third shape: the repeat of two pins +was = core.build(kit["parts"]["strut"]) +strut.data.polygons.foreach_set("material_index", np.where(was.shape == PINS, 1, 0).astype(np.int32)) +receipt, _ = send("brokkr_kitbash.set_params", object_name="P_strut", params="segments=12; length=1.2") +now = core.build(kit["parts"]["strut"], {"segments": 12, "length": 1.2}) +index = np.zeros(len(strut.data.polygons), dtype=np.int32) +strut.data.polygons.foreach_get("material_index", index) +check("set_params with other segments keeps each shape's material: the pins stay Pin Steel, the rest Strut Paint", receipt["status"] == "accepted" + and len(now.counts) != len(was.counts) and index.tolist() == np.where(now.shape == PINS, 1, 0).tolist() and int(index.sum()) == 2 * (12 + 2) + and [s.material.name for s in strut.material_slots] == ["Strut Paint", "Pin Steel"], [receipt["message"], int(index.sum()), len(index)]) + # --- refusals leave the scene as it was -------------------------------------------------------------------------------------- bpy.ops.mesh.primitive_cube_add() bpy.context.active_object.name = "Plain" +twin = bpy.data.objects["P_vent"].copy() # a linked duplicate: one mesh, two objects, each with its own kit_params +twin.name = "P_vent_twin" +bpy.context.scene.collection.objects.link(twin) +send("setObjectTransform", targetObjectName="P_radiator_stack", scale=[2.0, 2.0, 2.0]) +send("setObjectTransform", targetObjectName="P_actuator", scale=[-1.0, 1.0, 1.0]) def scene_state(): @@ -185,6 +205,12 @@ refusals = [ ("set_params out of range", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "length=0.1"}, "is outside [0.6, 2.0]"), ("set_params with a repeated key", "brokkr_kitbash.set_params", {"object_name": "P_tank", "params": "length=1; length=1.2"}, "'length' is given twice"), ("report of a plain mesh", "brokkr_kitbash.report", {"object_name": "Plain"}, "is not a kit part"), + ("set_params on a mesh a linked duplicate shares", "brokkr_kitbash.set_params", {"object_name": "P_vent", "params": "slats=9"}, "shares its mesh 'P_vent' with 1 other user"), + ("set_params on the linked duplicate", "brokkr_kitbash.set_params", {"object_name": "P_vent_twin", "params": "slats=9"}, "shares its mesh 'P_vent' with 1 other user"), + ("report of a scaled part", "brokkr_kitbash.report", {"object_name": "P_radiator_stack"}, "'P_radiator_stack' is scaled, mirrored or sheared in the world (scale 2, 2, 2)"), + ("set_params on a scaled part", "brokkr_kitbash.set_params", {"object_name": "P_radiator_stack", "params": "fins=5"}, "is scaled, mirrored or sheared"), + ("report of a mirrored part", "brokkr_kitbash.report", {"object_name": "P_actuator"}, "'P_actuator' is scaled, mirrored or sheared"), + ("report of every part while one is scaled", "brokkr_kitbash.report", {}, "is scaled, mirrored or sheared"), ("describe of an unknown part", "brokkr_kitbash.describe", {"part": "wing"}, "has no part 'wing'"), ] for label, action, fields, expected in refusals: @@ -192,6 +218,15 @@ for label, action, fields, expected in refusals: check(f"refused, scene unchanged: {label}", receipt["status"] != "accepted" and expected in str(receipt["message"]) and scene_state() == state, [receipt["status"], receipt["message"]]) +bpy.data.objects.remove(twin) +send("setObjectTransform", targetObjectName="P_radiator_stack", scale=[1.0, 1.0, 1.0]) +send("setObjectTransform", targetObjectName="P_actuator", scale=[1.0, 1.0, 1.0]) +receipt, alone = send("brokkr_kitbash.set_params", object_name="P_vent", params="slats=9") +check("with the duplicate gone the vent's mesh is its own again and set_params rebuilds it", receipt["status"] == "accepted" and alone + and alone["params"]["slats"] == 9 and len(bpy.data.objects["P_vent"].data.polygons) == len(core.build(kit["parts"]["vent"], {"slats": 9}).counts), receipt["message"]) +receipt, whole = send("brokkr_kitbash.report") +check("with scale back at 1 every part reports again", receipt["status"] == "accepted" and whole and len(whole["parts"]) == 9, receipt["message"]) + # --- export --------------------------------------------------------------------------------------------------------------- receipt, _ = send("exportGltf", filepath="kit.glb", extras=False, yUp=True, applyModifiers=True, selection=[f"P_{n}" for n in names]) glb = WORK / "kit.glb" diff --git a/surfaces/blender/tests/live/kitbash.result.json b/surfaces/blender/tests/live/kitbash.result.json index 2097f87..ab893bc 100644 --- a/surfaces/blender/tests/live/kitbash.result.json +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -191,6 +191,11 @@ "ok": true, "detail": null }, + { + "name": "set_params with other segments keeps each shape's material: the pins stay Pin Steel, the rest Strut Paint", + "ok": true, + "detail": null + }, { "name": "refused, scene unchanged: an unknown kit", "ok": true, @@ -251,11 +256,51 @@ "ok": true, "detail": null }, + { + "name": "refused, scene unchanged: set_params on a mesh a linked duplicate shares", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on the linked duplicate", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: report of a scaled part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on a scaled part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: report of a mirrored part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: report of every part while one is scaled", + "ok": true, + "detail": null + }, { "name": "refused, scene unchanged: describe of an unknown part", "ok": true, "detail": null }, + { + "name": "with the duplicate gone the vent's mesh is its own again and set_params rebuilds it", + "ok": true, + "detail": null + }, + { + "name": "with scale back at 1 every part reports again", + "ok": true, + "detail": null + }, { "name": "exportGltf of all nine parts succeeds", "ok": true, @@ -278,16 +323,16 @@ ], "placed": { "nozzle": { - "faces": 1024, - "shells": 21, + "faces": 1312, + "shells": 24, "bevel": 0.0024, "sockets": [ "mount" ] }, "tank": { - "faces": 636, - "shells": 16, + "faces": 740, + "shells": 20, "bevel": 0.00176, "sockets": [ "port_a", diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index c0b0bcd..5481efd 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -150,6 +150,34 @@ class ExpressionTests(unittest.TestCase): core.build(core.part(kit, "p")) self.assertEqual(float(np.ptp(core.build(core.part(kit, "p"), {"a": 3}).V[:, 0])), 0.5) + def test_a_value_no_float_holds_is_refused_by_name(self): + """Mutant N4 (finite check dropped in Expr.value): 1e308*a at a=10 is inf and is no longer refused there.""" + part = core.part(core.check_kit(document([{"shape": "box", "size": ["1e308*a", 1, "a*" + "9" * 400]}], [param("a", 0, 10, 0)])), "p") + with self.assertRaisesRegex(core.KitError, r"part 'p' shape 0 \(box\) size\[0\]: '1e308\*a' is not a finite number"): + core.build(part, {"a": 10}) + with self.assertRaisesRegex(core.KitError, r"size\[2\]: 'a\*9+' is not a finite number"): # an integer literal no float holds + core.build(part, {"a": 1e-300}) + for doc, message in ((document([{"shape": "box", "size": [10 ** 400, 1, 1]}]), r"size\[0\]: 1000\d+ is not a finite number"), + (document(params=[param("a", 0, 10 ** 400, 1)]), r"param 'a' max must be a finite number")): + with self.assertRaisesRegex(core.KitError, message): + core.check_kit(doc) + with self.assertRaisesRegex(core.KitError, r"param 'a' must be a finite number"): + core.resolve_params(part, {"a": 10 ** 400}) + far = core.part(core.check_kit(document([{"shape": "box", "size": [1, 1, 1]}, {"shape": "box", "size": [1e308, 1, 1], "at": [1.5e308, 0, 0]}])), "p") + with self.assertRaisesRegex(core.KitError, r"part 'p' shape 1 \(box\): its vertices are not finite"): # each number finite, their sum not + core.build(far) + + def test_a_socket_size_is_above_zero_and_a_bevel_is_not_negative(self): + """Mutants N8 (socket size <= 0 allowed) and N9 (negative bevel allowed).""" + socket = {"name": "s", "type": "mount", "size": "a-1", "at": [0, 0, 0], "z": "+z", "y": "+y"} + part = core.part(core.check_kit(document(params=[param("a")], sockets=[socket], bevel="2-a")), "p") + self.assertEqual((core.build(part, {"a": 2}).sockets[0]["size"], core.build(part, {"a": 2}).bevel), (1.0, 0.0)) + for a in (1.0, 0.5): + with self.assertRaisesRegex(core.KitError, r"part 'p' socket 's' size is -?0\.\d: a socket's size must be above 0"): + core.build(part, {"a": a}) + with self.assertRaisesRegex(core.KitError, r"part 'p' bevel is -1\.0: a bevel is 0 or more"): + core.build(part, {"a": 3}) + @unittest.skipIf(np is None, "numpy is not installed") class CheckKitTests(unittest.TestCase): @@ -175,6 +203,10 @@ class CheckKitTests(unittest.TestCase): (document([{**box, "size": ["width", 1, 1]}], [param("a")]), r"part 'p' shape 0 \(box\) size\[0\]: 'width' names 'width'"), (document(params=[param("min")]), r"part 'p' param 0: 'min' is not a name"), (document(bevel="a.b"), r"part 'p' bevel: 'a\.b' uses Attribute"), + (document(sockets=[{**socket, "type": ["mount"]}]), r"part 'p' socket 's': type \['mount'\] is not one of"), # unhashable where a name belongs + (document(sockets=[{**socket, "z": {}}]), r"part 'p' socket 's': z must be one of"), + (document([{"shape": ["box"], "size": [1, 1, 1]}]), r"part 'p' shape 0: unknown shape \['box'\]"), + (document(sockets=[{**socket, "at": [0, 0, 10 ** 400]}]), r"part 'p' socket 's' at\[2\]: 1000\d+ is not a finite number"), ] for doc, message in cases: with self.assertRaisesRegex(core.KitError, message): @@ -199,7 +231,8 @@ class CheckKitTests(unittest.TestCase): class ShapeTests(unittest.TestCase): def test_tubes_are_closed_oriented_and_hold_their_volume(self): """tube-closed-oriented. Mutants M3 (inner wall not reversed) and M4 (solid tube without its top cap) break - the edge census; M5 (r0 and r1 swapped) puts the z=0 ring at r1.""" + the edge census; M5 (r0 and r1 swapped) puts the z=0 ring at r1; N10 (inner0 and inner1 swapped) puts the + z=0 inner ring at inner1, which volume and the census cannot see.""" for n in (3, 32): solid = built([{"shape": "tube", "r0": 0.5, "r1": 0.3, "length": 2.0, "segments": n}]) hollow = built([{"shape": "tube", "r0": 0.5, "r1": 0.3, "inner0": 0.2, "inner1": 0.1, "length": 2.0, "segments": n, "smooth": True}]) @@ -211,6 +244,9 @@ class ShapeTests(unittest.TestCase): low = b.V[np.abs(b.V[:, 2]) < 1e-12] self.assertTrue(np.allclose(np.linalg.norm(low[:n, :2], axis=1), 0.5, atol=1e-12)) self.assertEqual(float(b.V[:, 2].max()), 2.0) + for rows_, radius, z in ((slice(2 * n, 3 * n), 0.2, 0.0), (slice(3 * n, 4 * n), 0.1, 2.0)): + self.assertTrue(np.allclose(np.linalg.norm(hollow.V[rows_, :2], axis=1), radius, atol=1e-12)) + self.assertTrue((hollow.V[rows_, 2] == z).all()) self.assertEqual(solid.smooth.tolist(), [False] * (n + 2)) self.assertEqual(hollow.smooth.tolist(), [True] * (2 * n) + [False] * (2 * n)) # both walls smooth, both end rings flat tube = {"shape": "tube", "r0": 1, "r1": 1, "length": 1, "segments": 8} @@ -246,6 +282,14 @@ class ShapeTests(unittest.TestCase): with self.assertRaisesRegex(core.KitError, "count is .*whole number from 1 to 256"): built([shape], [param("n", 0, 300, 4), param("a")], {"n": count}) + def test_every_face_names_its_shape(self): + """What set_params carries per-face materials by: a repeat's copies share their shape's index.""" + b = built([{"shape": "box", "size": [1, 1, 1]}, + {"shape": "repeat", "count": 3, "step": [2, 0, 0], "of": {"shape": "box", "size": [1, 1, 1]}}, + {"shape": "tube", "r0": 1, "r1": 1, "length": 1, "segments": 8}]) + self.assertEqual(b.shape.tolist(), [0] * 6 + [1] * 18 + [2] * 10) + self.assertEqual((b.shape.dtype, b.shell_count), (np.int32, 5)) + def test_sockets_are_right_handed_frames(self): socket = {"name": "s", "type": "mount", "size": "2*a", "at": ["a", 2, 3], "z": "+x", "y": "+z"} kit = core.check_kit(document(params=[param("a")], sockets=[socket]))