From d1d0dc7605fcb10ba5eed34644a11519ee134c30 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 18:56:56 +0100 Subject: [PATCH] brokkr_kitbash: sharp lathe points; a flat profile is refused to a tolerance; pins for the lip and the apply clamp A lathe profile point may be [r, z, "sharp"]: Built.sharp lists the ring edges of the marked points in every copy, and write_mesh sets sharp_edge on exactly those edges. check_kit refuses any other third item, a fourth, and a mark at an open profile's end. The reducer's two cone rings are sharp. _lathe refuses a closing area at or below FLAT (5.1e-10) of the square of the profile's largest coordinate, so a constant-z profile is refused whatever its digits (shipped least 6.1e-3, float noise 4.3e-17). test_no_lathe_profile_crosses_itself walks every lathe of the kit at every corner of its params: the nozzle lip fix is pinned. kitbash_assembly.py gives the Gap cutter two brass faces and asks that each face keeps its own slot. kitbash.md: the reducer mates a fitting only from small_r 0.03, and Boolean cost as ratios plus the times read through the add-on. Takes the five Low findings of verdict cut-kit-shape-vocabulary.s1 (cut kit-joints). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 8 ++- surfaces/blender/brokkr_kitbash/core.py | 57 +++++++++++----- .../brokkr_kitbash/kits/mechanical.v0.json | 4 +- surfaces/blender/docs/kitbash.md | 36 +++++++--- surfaces/blender/tests/live/kitbash.py | 15 ++++ .../blender/tests/live/kitbash.result.json | 55 +++++++++++++++ .../blender/tests/live/kitbash_assembly.py | 7 ++ .../tests/live/kitbash_assembly.result.json | 5 ++ surfaces/blender/tests/test_kitbash.py | 68 ++++++++++++++++++- 9 files changed, 224 insertions(+), 31 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 4b1ada6..5f77073 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -59,7 +59,8 @@ def kit_work(work): def write_mesh(mesh, built) -> None: - """The built part into an empty mesh datablock: vertices, n-gon faces, and flat shading on every face not marked smooth.""" + """The built part into an empty mesh datablock: vertices, n-gon faces, flat shading on every face not marked + smooth, and sharp_edge on exactly the edges built.sharp lists.""" mesh.vertices.add(len(built.V)) mesh.vertices.foreach_set("co", built.V.astype(np.float32).ravel()) mesh.loops.add(len(built.faces)) @@ -69,6 +70,11 @@ def write_mesh(mesh, built) -> None: sharp = mesh.attributes.get("sharp_face") or mesh.attributes.new("sharp_face", "BOOLEAN", "FACE") sharp.data.foreach_set("value", ~built.smooth) mesh.update(calc_edges=True) + ends = np.zeros(2 * len(mesh.edges), dtype=np.int32) + mesh.edges.foreach_get("vertices", ends) + key = lambda pairs: pairs.min(axis=1).astype(np.int64) * len(built.V) + pairs.max(axis=1) # noqa: E731 + crease = mesh.attributes.get("sharp_edge") or mesh.attributes.new("sharp_edge", "BOOLEAN", "EDGE") + crease.data.foreach_set("value", np.isin(key(ends.reshape(-1, 2)), key(built.sharp))) def sync_bevel(obj, width: float) -> None: diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index 0df5aef..489bac0 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -3,14 +3,16 @@ numpy and the standard library only, no Blender: tests/test_kitbash.py runs this file as it is. A kit is data (kits/.v0.json beside this file). A part is a list of shapes (tube, box, lathe, and a repeat of one of them, a step apart or turned about an axis) whose numbers may be expressions over the part's params, and a list of -sockets, each a frame on one of the part's flat faces. An expression is parsed with ast.parse and walked against a +sockets, each a frame on one of the part's flat faces. A lathe profile point may be marked sharp: its ring of edges +is then a crease (Built.sharp). An expression is parsed with ast.parse and walked against a whitelist; nothing in a kit is ever run as Python. kit = load_kit("mechanical") - built = build(part(kit, "tank"), {"length": 1.2}) # Built: V, faces, counts, smooth, shell_count, sockets + built = build(part(kit, "tank"), {"length": 1.2}) # Built: V, faces, counts, smooth, sharp, shell_count, sockets Two sockets mate through mate (the child's matrix under its parent), mate_refusal (what may mate) and residual -(how far a placed child stands from its mate). +(how far a placed child stands from its mate). closure_residual is how far two sockets stand from meeting as a pin, +whatever the roll: what closes a loop the tree of connections cannot state. Every refusal is a KitError whose message names the kit, part and field. """ @@ -223,11 +225,15 @@ def _shape(shape: Any, names, where: str, inside_repeat: bool = False) -> dict: profile = shape["profile"] if not isinstance(profile, list) or len(profile) < least: raise KitError(f"{where} profile must be an array of at least {least} [r, z] points{' (it is a loop)' if made['loop'] else ''}") - made["profile"] = [] + made["profile"], made["sharp"] = [], [] for i, point in enumerate(profile): - if not isinstance(point, list) or len(point) != 2: - raise KitError(f"{where} profile[{i}] must be [r, z]: two numbers or expressions") - made["profile"].append([parse(value, names, f"{where} profile[{i}][{c}]") for c, value in enumerate(point)]) + if not isinstance(point, list) or len(point) not in (2, 3) or (len(point) == 3 and point[2] != "sharp"): + raise KitError(f"{where} profile[{i}] must be [r, z] or [r, z, \"sharp\"]: two numbers or expressions, and the mark") + if len(point) == 3 and not made["loop"] and i in (0, len(profile) - 1): + raise KitError(f"{where} profile[{i}] is marked sharp at an end of an open profile: an end is a flat cap or a pole, " + "and has no ring to crease") + made["profile"].append([parse(value, names, f"{where} profile[{i}][{c}]") for c, value in enumerate(point[:2])]) + made["sharp"].append(len(point) == 3) return made for key in ("r0", "r1", "length"): made[key] = parse(shape[key], names, f"{where} {key}") @@ -388,7 +394,9 @@ 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, a lathe's triangles at a pole, and n-gon caps, wound outward); smooth[i] marks the walls 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 + in the part's shapes list, of the shape the face belongs to (every copy of a repeat shares one). sharp is an + (E, 2) array of vertex index pairs: the edges shaded as a crease, which are the rings of the lathe profile points + marked "sharp", in every copy. 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 @@ -396,6 +404,7 @@ class Built(NamedTuple): counts: np.ndarray smooth: np.ndarray shape: np.ndarray + sharp: np.ndarray shell_count: int sockets: list bevel: float @@ -448,14 +457,24 @@ def _tube(shape: dict, env): faces = np.concatenate([side.ravel(), k[::-1], n + k]) counts = np.concatenate([np.full(n, 4), [n, n]]) smooth = np.concatenate([np.full(n, shape["smooth"]), [False, False]]) - return V, faces, counts, smooth + return V, faces, counts, smooth, NO_SHARP + + +NO_SHARP = np.zeros((0, 2), dtype=np.int64) +# A lathe profile encloses nothing when its closing polygon's area is at most FLAT times the square of its largest +# coordinate. Shipped least 6.1e-3 (the tank's strap, over every lathe of the kit at each corner of its part's params +# and 16 draws); the largest a flat profile reads through float rounding 4.3e-17 (the 266 constant-z profiles among +# 3000 random ones of three decimals); FLAT is their geometric mean, separation 1.2e7 each side +# (lodur:ruling:deterministic-bound-margin). +FLAT = 5.1e-10 def _lathe(shape: dict, env): """A profile of [r, z] points revolved about +z, one ring per point. Open: an end on the axis (r exactly 0) is a pole and the band to it triangles; an end off the axis gets a flat n-gon cap. Loop: the last point joins the first. The profile is listed out along the bottom and up the outside (its closing polygon, down the axis for an - open one, has positive area in (r, z)), which makes every band and cap wind as a tube's.""" + open one, has positive area in (r, z)), which makes every band and cap wind as a tube's. The fifth array returned + is the ring edges of the points marked sharp.""" where = shape["where"] P = np.array([[r.value(env), z.value(env)] for r, z in shape["profile"]]) n = _whole(shape["segments"], env, SEGMENTS) @@ -470,7 +489,7 @@ def _lathe(shape: dict, env): ring = P if loop else np.vstack([P, [[0.0, P[last, 1]], [0.0, P[0, 1]]]]) after = np.roll(ring, -1, axis=0) area = 0.5 * float((ring[:, 0] * after[:, 1] - after[:, 0] * ring[:, 1]).sum()) - if not area > 0: + if not area > FLAT * float(np.abs(P).max()) ** 2: raise KitError(f"{where} profile: list it out along the bottom and up the outside; these points run the other way or enclose nothing " f"(signed area {area:.6g} in r, z)") angle = 2.0 * math.pi * np.arange(n) / n @@ -497,7 +516,8 @@ def _lathe(shape: dict, env): faces.append(start[end] + corners) counts.append([n]) smooth.append([False]) - return V, np.concatenate(faces), np.concatenate(counts), np.concatenate(smooth).astype(bool) + sharp = [np.column_stack([start[i] + k, start[i] + j]) for i in range(len(P)) if shape["sharp"][i]] # never an end (check_kit), so never a pole + return V, np.concatenate(faces), np.concatenate(counts), np.concatenate(smooth).astype(bool), np.concatenate(sharp) if sharp else NO_SHARP BOX_FACES = np.array([[0, 3, 2, 1], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]]) @@ -508,13 +528,13 @@ def _box(shape: dict, env): size = np.array([e.value(env) for e in shape["size"]]) if not (size > 0).all(): raise KitError(f"{shape['where']}: every size must be above 0, got {size.tolist()}") - return BOX_SIGNS * size, BOX_FACES.ravel(), np.full(6, 4), np.zeros(6, dtype=bool) + return BOX_SIGNS * size, BOX_FACES.ravel(), np.full(6, 4), np.zeros(6, dtype=bool), NO_SHARP def _placed(shape: dict, env): - V, faces, counts, smooth = {"tube": _tube, "box": _box, "lathe": _lathe}[shape["shape"]](shape, env) + V, faces, counts, smooth, sharp = {"tube": _tube, "box": _box, "lathe": _lathe}[shape["shape"]](shape, env) rotation = _rotation([e.value(env) for e in shape["rot"]]) - return V @ rotation.T + np.array([e.value(env) for e in shape["at"]]), faces, counts, smooth + return V @ rotation.T + np.array([e.value(env) for e in shape["at"]]), faces, counts, smooth, sharp def build(part: dict, params: dict | None = None) -> Built: @@ -527,13 +547,13 @@ def build(part: dict, params: dict | None = None) -> Built: for index, shape in enumerate(part["shapes"]): if shape["shape"] == "repeat": count = _whole(shape["count"], env, COPIES) - V, faces, counts, smooth = _placed(shape["of"], env) + V, faces, counts, smooth, sharp = _placed(shape["of"], env) if "step" in shape: step = np.array([e.value(env) for e in shape["step"]]) - made = [(V + k * step, faces, counts, smooth) for k in range(count)] + made = [(V + k * step, faces, counts, smooth, sharp) for k in range(count)] else: # copy k turned k/count of a turn, right-handed, about the axis through center axis, center = np.array(AXES[shape["around"]]), np.array([e.value(env) for e in shape["center"]]) - made = [((V - center) @ _rotation(axis * (360.0 * k / count)).T + center, faces, counts, smooth) for k in range(count)] + made = [((V - center) @ _rotation(axis * (360.0 * k / count)).T + center, faces, counts, smooth, sharp) for k in range(count)] else: made = [_placed(shape, env)] for shell in made: @@ -560,6 +580,7 @@ def build(part: dict, params: dict | None = None) -> Built: 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), + sharp=np.concatenate([s[4] + o for s, o in zip(shells, offsets)]).astype(np.int32), shell_count=len(shells), sockets=sockets, bevel=bevel, params=env) diff --git a/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json b/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json index a09c1a1..2d170a9 100644 --- a/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json +++ b/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json @@ -285,8 +285,8 @@ "bevel": "0.15*flange_t", "shapes": [ {"shape": "lathe", "segments": "segments", "smooth": true, "profile": [ - ["1.35*big_r", 0], ["1.35*big_r", "flange_t"], ["big_r", "flange_t"], ["big_r", "flange_t+0.15*(length-2*flange_t)"], - ["small_r", "length-flange_t-0.15*(length-2*flange_t)"], ["small_r", "length-flange_t"], ["1.9*small_r", "length-flange_t"], ["1.9*small_r", "length"]]}, + ["1.35*big_r", 0], ["1.35*big_r", "flange_t"], ["big_r", "flange_t"], ["big_r", "flange_t+0.15*(length-2*flange_t)", "sharp"], + ["small_r", "length-flange_t-0.15*(length-2*flange_t)", "sharp"], ["small_r", "length-flange_t"], ["1.9*small_r", "length-flange_t"], ["1.9*small_r", "length"]]}, {"shape": "repeat", "count": 8, "around": "+z", "of": {"shape": "tube", "r0": "0.077*big_r", "r1": "0.077*big_r", "length": "1.35*flange_t", "segments": 6, "at": ["1.175*big_r", 0, "0.15*flange_t"]}}, {"shape": "repeat", "count": 4, "around": "+z", "of": diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 814e7da..8fc9341 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -72,7 +72,7 @@ then y, then z, about the shape's own origin) place it, rotation first; both def | --- | --- | --- | | `tube` | `r0`, `r1`, `length`, `segments`, `inner0`?, `inner1`?, `smooth`? | A frustum on +z from radius `r0` at z=0 to `r1` at z=`length`, with n-gon caps. Inner radii above 0 make it hollow (an inner wall and two flat end rings); they are both above 0 or both 0, and below the outer radius. `segments` is 3 to 128. `smooth` shades the walls smooth; caps stay flat. | | `box` | `size` | A box centred on its origin; every size above 0. | -| `lathe` | `profile`, `segments`, `loop`?, `smooth`? | A profile of `[r, z]` points revolved about +z into one shell, a ring of `segments` (3 to 128) vertices per point. An open profile's end on the axis (`r` exactly 0) is a pole; an end off the axis gets a flat n-gon cap. With `loop` true the last point joins the first and there are no caps (a ring: 3 points or more). `smooth` shades the walls smooth; a band between two points of one `z` (an annulus) and the caps stay flat. | +| `lathe` | `profile`, `segments`, `loop`?, `smooth`? | A profile of `[r, z]` points revolved about +z into one shell, a ring of `segments` (3 to 128) vertices per point. An open profile's end on the axis (`r` exactly 0) is a pole; an end off the axis gets a flat n-gon cap. With `loop` true the last point joins the first and there are no caps (a ring: 3 points or more). `smooth` shades the walls smooth; a band between two points of one `z` (an annulus) and the caps stay flat. A point written `[r, z, "sharp"]` is a crease. | | `repeat` | `count`, `of`, and `step` or `around` with `center`? | `count` copies (1 to 256) of one tube, box or lathe: at `k * step`, k from 0, or turned `k * 360 / count` degrees, right-handed, about the axis `around` (one of `+x -x +y -y +z -z`) through `center` (default the origin). Exactly one of `step` and `around`. A repeat cannot hold a repeat. | A lathe's profile is listed out along the bottom and up the outside, as this flanged stub is: a cap of radius 0.1 @@ -85,10 +85,24 @@ at z=0, the flange's rim, its top face, the pipe, and a cap of radius 0.05 at z= The rule behind "up the outside": the profile, closed down the axis from its last `z` to its first (a loop closes itself), has positive area in (r, z). A profile listed the other way is refused, and so are a negative `r`, an -`r` of 0 anywhere but an open profile's two ends, and a point that repeats the one before it. A profile may turn -back down inside itself (a bell's inner wall); one that crosses itself is not caught, and builds a shell that is -not a solid. A turned part with many steps is one lathe, and so one shell, where a stack of tubes is one shell -each: a Boolean on it costs less ("Assembling parts"). +`r` of 0 anywhere but an open profile's two ends, and a point that repeats the one before it. A flat profile +(every point at one `z`) encloses nothing and is refused whatever its digits: the area must be above 5.1e-10 of +the square of the profile's largest coordinate, which float rounding does not reach and no real profile comes +near. A profile may turn back down inside itself (a bell's inner wall); one that crosses itself is not caught by +`core`, and builds a shell that is not a solid. For a shipped kit `test_no_lathe_profile_crosses_itself` catches +it, at every corner of the part's params. A turned part with many steps is one lathe, and so one shell, where a +stack of tubes is one shell each: a Boolean on it costs less ("Assembling parts"). + +Smooth shading rounds every bend of a smooth lathe, and the Bevel only cuts edges sharper than 30 degrees. Where +a turned part should show a hard line at a shallower bend (a cone leaving a neck), mark the point: + +```json +["big_r", "flange_t+0.15*(length-2*flange_t)", "sharp"] +``` + +The ring of edges at that point is then shaded as a crease (`Built.sharp`, written to the mesh's `sharp_edge` +attribute by `place_part` and `set_params`). The mark is per point and authored: no angle decides it. It is +refused at an open profile's two ends, which are a cap or a pole. No modifier or auto-smooth setting takes part. Shells may overlap (a pad that runs into a tank), and a part is then not one solid: reports give the shell count. @@ -159,9 +173,12 @@ cut's edges are bevelled with the rest. The modifier's object is the cutter; the always Exact with self-intersection on: a kit part is several overlapping closed shells, and without it the shells cancel where they overlap (the 1.8 m tank with a box cut through a cradle, the pad, a strap and the barrel keeps 0.251 m3 with self-intersection and 0.006 m3 without). The cost grows with the shells that -overlap, so each turned body of the kit is one lathe: on Blender 5.3 a box cut from a part at its defaults takes -0.51 s for the tank (6 shells; 1.53 s when it was 20), 0.40 s for the nozzle (9 shells; 1.25 s at 24) and 0.24 s -for a pipe fitting (14 shells; 0.31 s at 19), each time the part is evaluated. Keep live booleans few and +overlap, so each turned body of the kit is one lathe. What carries from machine to machine is the ratio to the +same part built as a stack of tubes: 0.31 for the tank (6 shells against 20), 0.33 for the nozzle (9 against +24) and 0.81 for a pipe fitting (14 against 19). As absolute times, a box cut from a part at its defaults, +placed through the add-on with its Bevel below the Boolean, evaluated in 0.55 s for the tank, 0.49 s for the +nozzle and 0.31 s for a pipe fitting on Blender 5.3 on the workstation Starfire (medians of four processes of +five evaluations); the part pays it each time it is evaluated. Keep live booleans few and `apply` them when the shape is settled. `boolean` evaluates the part once and reports `evaluated: {faces, volume, nonManifoldEdges}`; `report` never evaluates a modifier. The cutter is any other mesh object and is not changed: hide it with `setObjectVisibility`. A cutter @@ -270,7 +287,8 @@ three faces `2*pipe_r` (0.06 to 0.14), a nozzle's mount `2*throat_r` (0.08 to 0. `2*radius` (0.16 to 0.6). So tanks, fittings and nozzles plumb together, and a ribbed cylinder takes a nozzle (throat 0.08 and up) or another ribbed cylinder face to face: its smallest flange is larger than the largest pipe. A reducer joins the two: its `big` face is `2*big_r` (0.16 to 0.6, a ribbed cylinder's whole range) and -its `small` face `2*small_r` (0.048 to 0.14, the tank ports' and the fittings'), so a chamber hangs in a tank's +its `small` face `2*small_r` (0.048 to 0.14): a tank port over that whole range, and a fitting's face only from +`small_r` 0.03, the smallest pipe. So a chamber hangs in a tank's tree as tank, tee, reducer, ribbed cylinder, nozzle. Struts and actuators pin together when `0.6*width` equals `0.9*body_r`; both ends of each lie on its own axis, so pinned parts chain in a line. Mounts (`fits`) take any part whose seat is no larger than theirs. diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index 19d7920..22ec15c 100644 --- a/surfaces/blender/tests/live/kitbash.py +++ b/surfaces/blender/tests/live/kitbash.py @@ -100,6 +100,13 @@ for index, name in enumerate(names): flat = np.zeros(max(faces, 0), dtype=bool) if obj: obj.data.attributes["sharp_face"].data.foreach_get("value", flat) + crease = obj.data.attributes.get("sharp_edge") if obj else None + creased = np.zeros(len(obj.data.edges) if crease else 0, dtype=bool) + if crease: + crease.data.foreach_get("value", creased) + marked = sorted(tuple(sorted(edge.vertices)) for edge, on in zip(obj.data.edges, creased) if on) if crease else None + check(f"place_part {name}: sharp_edge is true on exactly core's sharp edges ({len(reference.sharp)})", + marked == sorted(tuple(sorted(pair)) for pair in reference.sharp.tolist()), [marked and len(marked), len(reference.sharp)]) bevel = obj.modifiers.get("Kit Bevel") if obj else None evaluated = len(obj.evaluated_get(bpy.context.evaluated_depsgraph_get()).data.polygons) if obj else -1 placed[name] = report @@ -117,6 +124,14 @@ for index, name in enumerate(names): check("ten parts are ten mesh objects", len(bpy.data.objects) == 10 and all(o.type == "MESH" for o in bpy.data.objects), len(bpy.data.objects)) # --- set_params keeps what is not derived -------------------------------------------------------------------------------- +reducer = bpy.data.objects["P_reducer"] +send("brokkr_kitbash.set_params", object_name="P_reducer", params="segments=12") +creased = np.zeros(len(reducer.data.edges), dtype=bool) +reducer.data.attributes["sharp_edge"].data.foreach_get("value", creased) +rings = [np.array([reducer.data.vertices[v].co[:] for edge, on in zip(reducer.data.edges, creased) if on for v in edge.vertices])] +check("the reducer's creases are its two cone rings, 24 edges each at 24 segments, and set_params writes them again: 12 each at 12", + len(core.build(kit["parts"]["reducer"]).sharp) == 48 and int(creased.sum()) == 24 + and sorted(set(np.round(np.linalg.norm(rings[0][:, :2], axis=1), 5).tolist())) == [0.05, 0.12], int(creased.sum())) tank = bpy.data.objects["P_tank"] send("setObjectTransform", targetObjectName="P_tank", location=[1.0, 2.0, 3.0], rotationEuler=[0.3, -0.2, 0.5], scale=[1.0, 1.0, 1.0]) send("assignMaterial", targetObjectName="P_tank", materialName="Tank Paint", color=[0.35, 0.35, 0.35]) diff --git a/surfaces/blender/tests/live/kitbash.result.json b/surfaces/blender/tests/live/kitbash.result.json index d935e1d..9deceab 100644 --- a/surfaces/blender/tests/live/kitbash.result.json +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -21,6 +21,11 @@ "ok": true, "detail": null }, + { + "name": "place_part nozzle: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, { "name": "place_part nozzle: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -36,6 +41,11 @@ "ok": true, "detail": null }, + { + "name": "place_part tank: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, { "name": "place_part tank: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -51,6 +61,11 @@ "ok": true, "detail": null }, + { + "name": "place_part ribbed_cylinder: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, { "name": "place_part ribbed_cylinder: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -66,6 +81,11 @@ "ok": true, "detail": null }, + { + "name": "place_part strut: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, { "name": "place_part strut: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -81,6 +101,11 @@ "ok": true, "detail": null }, + { + "name": "place_part actuator: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, { "name": "place_part actuator: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -96,6 +121,11 @@ "ok": true, "detail": null }, + { + "name": "place_part pipe_fitting: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, { "name": "place_part pipe_fitting: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -111,6 +141,11 @@ "ok": true, "detail": null }, + { + "name": "place_part radiator_stack: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, { "name": "place_part radiator_stack: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -126,6 +161,11 @@ "ok": true, "detail": null }, + { + "name": "place_part vent: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, { "name": "place_part vent: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -141,6 +181,11 @@ "ok": true, "detail": null }, + { + "name": "place_part plate: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, { "name": "place_part plate: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -156,6 +201,11 @@ "ok": true, "detail": null }, + { + "name": "place_part reducer: sharp_edge is true on exactly core's sharp edges (48)", + "ok": true, + "detail": null + }, { "name": "place_part reducer: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -176,6 +226,11 @@ "ok": true, "detail": null }, + { + "name": "the reducer's creases are its two cone rings, 24 edges each at 24 segments, and set_params writes them again: 12 each at 12", + "ok": true, + "detail": null + }, { "name": "set_params doubling the tank's length doubles its z extent", "ok": true, diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index a9f342e..8b5b3f7 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -491,6 +491,7 @@ send("createObject", objectType="MESH", name="Gap", location=[0.1, -12.0, 0.0], gap = bpy.data.objects["Gap"] gap.data.materials.append(None) # the cutter's faces are in an empty first slot gap.data.materials.append(bpy.data.materials["Boss Brass"]) +gap.data.polygons[0].material_index = gap.data.polygons[1].material_index = 1 # two of its faces are brass; the rest stay in the empty slot send("brokkr_kitbash.boolean", object_name="Gapped", cutter="Gap") receipt, baked = send("brokkr_kitbash.apply", object_name="Gapped") used = np.zeros(len(gapped.data.polygons), dtype=np.int32) @@ -498,6 +499,12 @@ gapped.data.polygons.foreach_get("material_index", used) check("apply leaves no face outside the material slots when a cutter's first slot is empty", receipt["status"] == "accepted" and len(used) > 44 and used.min() >= 0 and used.max() < len(gapped.data.materials) and not gapped.data.validate_material_indices() and not gapped.data.validate(verbose=False), [receipt["message"], int(used.min()), int(used.max()), [m and m.name for m in gapped.data.materials]]) +names = [m and m.name for m in gapped.data.materials] +brass = [p.index for p in gapped.data.polygons if "Boss Brass" in names and p.material_index == names.index("Boss Brass")] +far = [p.index for p in gapped.data.polygons if (gapped.matrix_world @ p.center).x < -0.05] # the plate's half the cutter does not reach +check("and each face keeps its own slot: the cutter's brass faces are brass, the faces from its empty slot and the plate's own are the plate's paint", + names[0] == "Plate Paint" and 0 < len(brass) < len(used) and far and all(used[i] == 0 for i in far) + and all(abs((gapped.matrix_world @ gapped.data.polygons[i].center).x - 0.1) < 0.051 for i in brass), [names, len(brass), len(far), sorted(set(used.tolist()))]) R["ok"] = all(c["ok"] for c in R["checks"]) R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())} diff --git a/surfaces/blender/tests/live/kitbash_assembly.result.json b/surfaces/blender/tests/live/kitbash_assembly.result.json index e51d21b..6957612 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.result.json +++ b/surfaces/blender/tests/live/kitbash_assembly.result.json @@ -395,6 +395,11 @@ "name": "apply leaves no face outside the material slots when a cutter's first slot is empty", "ok": true, "detail": null + }, + { + "name": "and each face keeps its own slot: the cutter's brass faces are brass, the faces from its empty slot and the plate's own are the plate's paint", + "ok": true, + "detail": null } ], "hostErrors": [], diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index a84645c..980679d 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -11,6 +11,7 @@ from __future__ import annotations import copy import importlib.util +import itertools import json import math import random @@ -319,7 +320,12 @@ class ShapeTests(unittest.TestCase): (lathe([[1, 0]]), r"shape 0 \(lathe\) profile must be an array of at least 2 \[r, z\] points"), (lathe([[1, 0], [1, 1]], loop=True), r"profile must be an array of at least 3 \[r, z\] points \(it is a loop\)"), (lathe("round"), r"profile must be an array of at least 2"), - (lathe([[1, 0], [1, 1, 0]]), r"profile\[1\] must be \[r, z\]"), + (lathe([[1, 0], [1, 1, 0]]), r"profile\[1\] must be \[r, z\] or \[r, z, \"sharp\"\]"), + (lathe([[1, 0], [1, 1, "soft"], [0.5, 1]]), r"profile\[1\] must be \[r, z\] or \[r, z, \"sharp\"\]"), + (lathe([[1, 0], [1, 1, "sharp", 0], [0.5, 1]]), r"profile\[1\] must be \[r, z\] or"), + (lathe([[1, 0, "sharp"], [1, 1], [0.5, 1]]), r"profile\[0\] is marked sharp at an end of an open profile"), + (lathe([[1, 0], [1, 1], [0.5, 1, "sharp"]]), r"profile\[2\] is marked sharp at an end of an open profile"), + (lathe([[1, 0], [1, 1], [0, 1.5, "sharp"]]), r"profile\[2\] is marked sharp at an end"), # a pole is an end (lathe([[1, 0], 1]), r"profile\[1\] must be \[r, z\]"), (lathe([[1, 0], [1, "q"]]), r"profile\[1\]\[1\]: 'q' names 'q'"), (lathe([[1, 0], [1, 1]], loop=1), r"loop must be true or false"), @@ -333,10 +339,34 @@ class ShapeTests(unittest.TestCase): (lathe([[1, 1], [1, 0]]), r"shape 0 \(lathe\) profile: list it out along the bottom and up the outside"), (lathe(ring[::-1], loop=True), r"profile: list it out along the bottom and up the outside"), (lathe([[0, 0], [0, 1]]), r"enclose nothing \(signed area 0 in r, z\)"), + # flat-profile. Mutant J10 (the tolerance back to 0): the first builds, on an area of 1.6e-17 that is float rounding + (lathe([[0.129, 0.686], [1.592, 0.686]]), r"enclose nothing \(signed area \S+e-17 in r, z\)"), + (lathe([[1.592, 0.686], [0.129, 0.686]]), r"enclose nothing \(signed area 0 in r, z\)"), + (lathe([[0.1, 0.3], [0.7, 0.3]]), r"enclose nothing \(signed area 0 in r, z\)"), (lathe([[1, 0], [1, 1]], segments=2), r"segments is 2\.0: it must be a whole number from 3 to 128")): with self.assertRaisesRegex(core.KitError, message): built(shapes) + def test_a_sharp_point_marks_its_ring_in_every_copy(self): + """sharp-points. Mutant J9 (a copy's pairs not offset by the vertices before it): every copy names the first's ring.""" + n = 8 + profile = [[0, 0], [0.5, 0.2, "sharp"], [0.5, 0.6], [0.3, 0.8, "sharp"], [0.3, 1.0]] # a pole first: its ring is one vertex + b = built([{"shape": "box", "size": [1, 1, 1]}, + {"shape": "repeat", "count": 3, "step": [2, 0, 0], "of": {"shape": "lathe", "profile": profile, "segments": n, "smooth": True}}]) + each = 1 + 4 * n + expected = [[8 + c * each + 1 + i * n + k, 8 + c * each + 1 + i * n + (k + 1) % n] for c in range(3) for i in (0, 2) for k in range(n)] + self.assertEqual(b.sharp.tolist(), expected) + self.assertEqual((b.sharp.dtype, b.sharp.shape, len(b.V)), (np.int32, (48, 2), 8 + 3 * each)) + radius = np.linalg.norm(b.V[b.sharp[:, 0]][:, :2] - np.repeat([[0, 0], [2, 0], [4, 0]], 2 * n, axis=0), axis=1) + self.assertTrue(np.allclose(radius, np.tile(np.repeat([0.5, 0.3], n), 3), atol=1e-12)) # each pair lies on its own copy's marked ring + plain = built([{"shape": "lathe", "profile": [point[:2] for point in profile], "segments": n}, {"shape": "tube", "r0": 1, "r1": 1, "length": 1, "segments": n}]) + self.assertEqual((plain.sharp.shape, plain.sharp.dtype), ((0, 2), np.int32)) + self.assertEqual(plain.V.tobytes(), built([{"shape": "lathe", "profile": profile, "segments": n}, {"shape": "tube", "r0": 1, "r1": 1, "length": 1, "segments": n}]).V.tobytes()) + ring = built([{"shape": "lathe", "loop": True, "segments": n, "profile": [[0.4, 0, "sharp"], [0.6, 0], [0.6, 0.2], [0.4, 0.2, "sharp"]]}]) # a loop has no end + self.assertEqual(ring.sharp.tolist(), [[i * n + k, i * n + (k + 1) % n] for i in (0, 3) for k in range(n)]) + thin = built([{"shape": "lathe", "profile": [[0.5, 0], [0.5, 1e-6]], "segments": n}]) # thin is not flat: 2e-6 of its extent squared + self.assertGreater(signed_volume(thin), 0.0) + def test_repeat_around_turns_copies_about_the_axis(self): """repeat-around. Mutants K5 (copy k turned k*360/(count+1)) and K6 (center ignored).""" box = {"shape": "box", "size": [0.2, 0.2, 0.2]} @@ -452,6 +482,42 @@ class MechanicalKitTests(unittest.TestCase): self.assertLess(socket_seat(b, socket), 1e-6, f"{name}.{socket['name']} {given}") self.assertGreater(socket["size"], 0.0) + def test_no_lathe_profile_crosses_itself(self): + """profile-simple: closed, outward and positive volume do not see a profile that crosses itself, and core does not + check it. Mutant J11 (the nozzle's lip min(2.5*wall, 0.08*length) to 0.2*length): crosses at length 0.25, wall 0.015.""" + def side(a, b, c): + return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) + + def cross(a, b, c, d): # the two segments share a point (touching counts): their boxes overlap and each straddles the other's line + if any(max(min(a[x], b[x]), min(c[x], d[x])) > min(max(a[x], b[x]), max(c[x], d[x])) for x in (0, 1)): + return False # also what tells two stretches of one straight line apart (the bell between its hoops) + return side(a, b, c) * side(a, b, d) <= 0 and side(c, d, a) * side(c, d, b) <= 0 + + self.assertTrue(cross((0, 0), (2, 2), (0, 2), (2, 0)) and cross((0, 0), (2, 0), (1, 0), (1, 1)) and cross((0, 0), (2, 0), (1, 0), (3, 0))) + self.assertFalse(cross((0, 0), (2, 0), (0, 1), (2, 1)) or cross((0, 0), (1, 1), (2, 2), (3, 3)) or cross((0, 0), (2, 0), (3, -1), (3, 1))) + lathes = 0 + for name, part in self.kit["parts"].items(): + found = [s if s["shape"] == "lathe" else s["of"] for s in part["shapes"] if "lathe" in (s["shape"], s.get("of", {}).get("shape"))] + rng = random.Random(f"mechanical.{name}") + draws = [{p["name"]: p[key] for p in part["params"]} for key in ("default", "min", "max")] + for _ in range(16): + draws.append({p["name"]: rng.randint(p["min"], p["max"]) if p["type"] == "integer" else rng.uniform(p["min"], p["max"]) + for p in part["params"]}) + draws += [dict(zip([p["name"] for p in part["params"]], corner)) for corner in itertools.product(*[(p["min"], p["max"]) for p in part["params"]])] + for lathe in found: + lathes += 1 + for given in draws: + env = core.resolve_params(part, given) + points = [(r.value(env), z.value(env)) for r, z in lathe["profile"]] + segments = list(zip(points, points[1:] + points[:1] if lathe["loop"] else points[1:])) + count = len(segments) + for i in range(count): + for j in range(i + 2, count): + if lathe["loop"] and i == 0 and j == count - 1: + continue # neighbours round the loop + self.assertFalse(cross(*segments[i], *segments[j]), f"{name} profile segments {i} and {j} at {given}") + self.assertEqual(lathes, 6) + def test_extension_moves_the_rod_end_and_nothing_else(self): part = self.kit["parts"]["actuator"] short, long = core.build(part, {"extension": 0.0}), core.build(part, {"extension": 0.5})