diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index 49b3c36..0df5aef 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -1,9 +1,10 @@ """The kit format: what a kit document may say, and the geometry and socket frames a part and its params produce. 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, repeat) 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 whitelist; nothing in a kit is ever run as Python. +(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 +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 @@ -34,7 +35,8 @@ AXES = {"+x": (1.0, 0.0, 0.0), "-x": (-1.0, 0.0, 0.0), "+y": (0.0, 1.0, 0.0), "- PLACED = ("at", "rot") SHAPES = {"tube": (("r0", "r1", "length", "segments"), ("inner0", "inner1", "smooth") + PLACED), "box": (("size",), PLACED), - "repeat": (("count", "step", "of"), ())} + "lathe": (("profile", "segments"), ("loop", "smooth") + PLACED), + "repeat": (("count", "of"), ("step", "around", "center"))} SEGMENTS = (3, 128) COPIES = (1, 256) @@ -190,22 +192,47 @@ def _shape(shape: Any, names, where: str, inside_repeat: bool = False) -> dict: if kind == "repeat": if inside_repeat: raise KitError(f"{where}: a repeat cannot hold a repeat") - return {"shape": kind, "count": parse(shape["count"], names, f"{where} count"), - "step": _vector(shape["step"], names, f"{where} step"), + if ("step" in shape) == ("around" in shape): + raise KitError(f"{where} takes exactly one of step (copies a step apart) and around (copies turned about an axis)") + made = {"shape": kind, "count": parse(shape["count"], names, f"{where} count"), "of": _shape(shape["of"], names, f"{where} of", inside_repeat=True)} + if "step" in shape: + if "center" in shape: + raise KitError(f"{where}: center goes with around, not with step") + made["step"] = _vector(shape["step"], names, f"{where} step") + else: + if not isinstance(shape["around"], str) or shape["around"] not in AXES: + raise KitError(f"{where}: around must be one of {', '.join(AXES)}") + made["around"] = shape["around"] + made["center"] = _vector(shape["center"], names, f"{where} center") if "center" in shape else ZERO + return made made = {"shape": kind, "where": where, "at": _vector(shape["at"], names, f"{where} at") if "at" in shape else ZERO, "rot": _vector(shape["rot"], names, f"{where} rot") if "rot" in shape else ZERO} if kind == "box": made["size"] = _vector(shape["size"], names, f"{where} size") return made - for key in ("r0", "r1", "length", "segments"): + for key in ("loop", "smooth"): + if not isinstance(shape.get(key, False), bool): + raise KitError(f"{where} {key} must be true or false") + made["smooth"] = shape.get("smooth", False) + made["segments"] = parse(shape["segments"], names, f"{where} segments") + if kind == "lathe": + made["loop"] = shape.get("loop", False) + least = 3 if made["loop"] else 2 + 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"] = [] + 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)]) + return made + for key in ("r0", "r1", "length"): made[key] = parse(shape[key], names, f"{where} {key}") for key in ("inner0", "inner1"): made[key] = parse(shape.get(key, 0), names, f"{where} {key}") - if not isinstance(shape.get("smooth", False), bool): - raise KitError(f"{where} smooth must be true or false") - made["smooth"] = shape.get("smooth", False) return made @@ -360,7 +387,7 @@ 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; shape[i] is the index, + 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 {'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.""" @@ -424,6 +451,55 @@ def _tube(shape: dict, env): return V, faces, counts, smooth +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.""" + where = shape["where"] + P = np.array([[r.value(env), z.value(env)] for r, z in shape["profile"]]) + n = _whole(shape["segments"], env, SEGMENTS) + loop, last = shape["loop"], len(P) - 1 + for i, (r, z) in enumerate(P): + if r < 0: + raise KitError(f"{where} profile[{i}]: r is {r}, below 0") + if r == 0 and (loop or 0 < i < last): + raise KitError(f"{where} profile[{i}]: r is 0; only the first and last point of an open profile may lie on the axis") + if (i > 0 or loop) and (P[i] == P[i - 1]).all(): + raise KitError(f"{where} profile[{i}]: [{r}, {z}] repeats the point before it{' (a loop closes itself)' if i == 0 else ''}") + 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: + 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 + cos, sin = np.cos(angle), np.sin(angle) + pole = P[:, 0] == 0 + start = np.concatenate([[0], np.cumsum(np.where(pole, 1, n))[:-1]]) + V = np.vstack([[[0.0, 0.0, z]] if on_axis else np.column_stack([r * cos, r * sin, np.full(n, z)]) for (r, z), on_axis in zip(P, pole)]) + k = np.arange(n) + j = (k + 1) % n + faces, counts, smooth = [], [], [] + for a, b in [(i, i + 1) for i in range(last)] + ([(last, 0)] if loop else []): + if pole[a]: + band = np.column_stack([np.full(n, start[a]), start[b] + j, start[b] + k]) + elif pole[b]: + band = np.column_stack([start[a] + k, start[a] + j, np.full(n, start[b])]) + else: + band = np.column_stack([start[a] + k, start[a] + j, start[b] + j, start[b] + k]) + faces.append(band.ravel()) + counts.append(np.full(n, band.shape[1])) + smooth.append(np.full(n, shape["smooth"] and P[a, 1] != P[b, 1])) # an annulus is flat + if not loop: + for end, corners in ((0, k[::-1]), (last, k)): + if not pole[end]: + faces.append(start[end] + corners) + counts.append([n]) + smooth.append([False]) + return V, np.concatenate(faces), np.concatenate(counts), np.concatenate(smooth).astype(bool) + + 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]]) BOX_SIGNS = np.array([[-1, -1, -1], [1, -1, -1], [1, 1, -1], [-1, 1, -1], [-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1]]) * 0.5 @@ -436,7 +512,7 @@ def _box(shape: dict, env): def _placed(shape: dict, env): - V, faces, counts, smooth = (_tube if shape["shape"] == "tube" else _box)(shape, env) + V, faces, counts, smooth = {"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 @@ -451,9 +527,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) - 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)] + 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)] + 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)] else: made = [_placed(shape, env)] for shell in made: diff --git a/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json b/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json index a47db06..a09c1a1 100644 --- a/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json +++ b/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json @@ -20,42 +20,26 @@ ], "bevel": "0.3*wall", "shapes": [ - {"shape": "tube", "r0": "2.1*throat_r", "r1": "2.1*throat_r", "length": "0.3*throat_r", "segments": "segments", "smooth": true}, - {"shape": "repeat", "count": 2, "step": ["2.62*throat_r", 0, 0], "of": - {"shape": "tube", "r0": "0.14*throat_r", "r1": "0.14*throat_r", "length": "0.35*throat_r", "segments": 6, "at": ["-1.31*throat_r", "-1.31*throat_r", "0.1*throat_r"]}}, - {"shape": "repeat", "count": 2, "step": ["2.62*throat_r", 0, 0], "of": - {"shape": "tube", "r0": "0.14*throat_r", "r1": "0.14*throat_r", "length": "0.35*throat_r", "segments": 6, "at": ["-1.31*throat_r", "1.31*throat_r", "0.1*throat_r"]}}, - {"shape": "tube", "r0": "1.6*throat_r", "r1": "1.6*throat_r", "length": "1.75*throat_r", "segments": "segments", "smooth": true, "at": [0, 0, "0.15*throat_r"]}, - {"shape": "tube", "r0": "1.6*throat_r", "r1": "throat_r+wall", "length": "throat_r", "segments": "segments", "smooth": true, "at": [0, 0, "1.9*throat_r"]}, - {"shape": "tube", "r0": "1.78*throat_r", "r1": "1.78*throat_r", "length": "0.5*throat_r", "segments": "segments", "smooth": true, "at": [0, 0, "1.6*throat_r"]}, - {"shape": "tube", "r0": "throat_r+wall", "r1": "throat_r+wall+0.1164*(exit_r-throat_r-wall)", "inner0": "throat_r", "inner1": "throat_r+0.1164*(exit_r-throat_r-wall)", - "length": "0.06*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r"]}, - {"shape": "tube", "r0": "throat_r+wall+0.1164*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.2604*(exit_r-throat_r-wall)", "inner0": "throat_r+0.1164*(exit_r-throat_r-wall)", "inner1": "throat_r+0.2604*(exit_r-throat_r-wall)", - "length": "0.08*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.06*length"]}, - {"shape": "tube", "r0": "throat_r+wall+0.2604*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.4224*(exit_r-throat_r-wall)", "inner0": "throat_r+0.2604*(exit_r-throat_r-wall)", "inner1": "throat_r+0.4224*(exit_r-throat_r-wall)", - "length": "0.1*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.14*length"]}, - {"shape": "tube", "r0": "throat_r+wall+0.4224*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.5904*(exit_r-throat_r-wall)", "inner0": "throat_r+0.4224*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5904*(exit_r-throat_r-wall)", - "length": "0.12*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.24*length"]}, - {"shape": "tube", "r0": "throat_r+wall+0.5904*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.75*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5904*(exit_r-throat_r-wall)", "inner1": "throat_r+0.75*(exit_r-throat_r-wall)", - "length": "0.14*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.36*length"]}, - {"shape": "tube", "r0": "throat_r+wall+0.75*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.8844*(exit_r-throat_r-wall)", "inner0": "throat_r+0.75*(exit_r-throat_r-wall)", "inner1": "throat_r+0.8844*(exit_r-throat_r-wall)", - "length": "0.16*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.5*length"]}, - {"shape": "tube", "r0": "throat_r+wall+0.8844*(exit_r-throat_r-wall)", "r1": "throat_r+wall+0.9676*(exit_r-throat_r-wall)", "inner0": "throat_r+0.8844*(exit_r-throat_r-wall)", "inner1": "throat_r+0.9676*(exit_r-throat_r-wall)", - "length": "0.16*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.66*length"]}, - {"shape": "tube", "r0": "throat_r+wall+0.9676*(exit_r-throat_r-wall)", "r1": "exit_r", "inner0": "throat_r+0.9676*(exit_r-throat_r-wall)", "inner1": "exit_r-wall", - "length": "0.18*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.82*length"]}, - {"shape": "tube", "r0": "throat_r+2.4*wall+0.6132*(exit_r-throat_r-wall)", "r1": "throat_r+2.4*wall+0.6474*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5*wall+0.6132*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5*wall+0.6474*(exit_r-throat_r-wall)", - "length": "0.03*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.38*length"]}, - {"shape": "tube", "r0": "throat_r+2.4*wall+0.834*(exit_r-throat_r-wall)", "r1": "throat_r+2.4*wall+0.8592*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5*wall+0.834*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5*wall+0.8592*(exit_r-throat_r-wall)", - "length": "0.03*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.6*length"]}, - {"shape": "tube", "r0": "throat_r+2.4*wall+0.9748*(exit_r-throat_r-wall)", "r1": "throat_r+2.4*wall+0.9802*(exit_r-throat_r-wall)", "inner0": "throat_r+0.5*wall+0.9748*(exit_r-throat_r-wall)", "inner1": "throat_r+0.5*wall+0.9802*(exit_r-throat_r-wall)", - "length": "0.03*length", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+0.86*length"]}, - {"shape": "repeat", "count": 2, "step": ["3.4*throat_r", 0, 0], "of": - {"shape": "box", "size": ["0.5*throat_r", "0.35*throat_r", "0.6*throat_r"], "at": ["-1.7*throat_r", 0, "throat_r"]}}, - {"shape": "repeat", "count": 2, "step": [0, "3.4*throat_r", 0], "of": - {"shape": "box", "size": ["0.35*throat_r", "0.5*throat_r", "0.6*throat_r"], "at": [0, "-1.7*throat_r", "throat_r"]}}, - {"shape": "tube", "r0": "exit_r+1.6*wall", "r1": "exit_r+1.6*wall", "inner0": "exit_r-0.5*wall", "inner1": "exit_r-0.5*wall", - "length": "3*wall", "segments": "segments", "smooth": true, "at": [0, 0, "2.9*throat_r+length-2.5*wall"]} + {"shape": "lathe", "segments": "segments", "smooth": true, "profile": [ + ["2.1*throat_r", 0], ["2.1*throat_r", "0.3*throat_r"], ["1.6*throat_r", "0.3*throat_r"], ["1.6*throat_r", "1.6*throat_r"], ["1.78*throat_r", "1.6*throat_r"], ["1.78*throat_r", "2.1*throat_r"], ["1.48*throat_r+0.2*wall", "2.1*throat_r"], ["throat_r+wall", "2.9*throat_r"], + ["throat_r+wall+0.1164*(exit_r-throat_r-wall)", "2.9*throat_r+0.06*length"], + ["throat_r+wall+0.2604*(exit_r-throat_r-wall)", "2.9*throat_r+0.14*length"], + ["throat_r+wall+0.4224*(exit_r-throat_r-wall)", "2.9*throat_r+0.24*length"], + ["throat_r+wall+0.5904*(exit_r-throat_r-wall)", "2.9*throat_r+0.36*length"], + ["throat_r+wall+0.6132*(exit_r-throat_r-wall)", "2.9*throat_r+0.38*length"], ["throat_r+2.4*wall+0.6132*(exit_r-throat_r-wall)", "2.9*throat_r+0.38*length"], ["throat_r+2.4*wall+0.6474*(exit_r-throat_r-wall)", "2.9*throat_r+0.41*length"], ["throat_r+wall+0.6474*(exit_r-throat_r-wall)", "2.9*throat_r+0.41*length"], + ["throat_r+wall+0.75*(exit_r-throat_r-wall)", "2.9*throat_r+0.5*length"], + ["throat_r+wall+0.834*(exit_r-throat_r-wall)", "2.9*throat_r+0.6*length"], ["throat_r+2.4*wall+0.834*(exit_r-throat_r-wall)", "2.9*throat_r+0.6*length"], ["throat_r+2.4*wall+0.8592*(exit_r-throat_r-wall)", "2.9*throat_r+0.63*length"], ["throat_r+wall+0.8592*(exit_r-throat_r-wall)", "2.9*throat_r+0.63*length"], + ["throat_r+wall+0.8844*(exit_r-throat_r-wall)", "2.9*throat_r+0.66*length"], + ["throat_r+wall+0.9676*(exit_r-throat_r-wall)", "2.9*throat_r+0.82*length"], + ["throat_r+wall+0.9748*(exit_r-throat_r-wall)", "2.9*throat_r+0.86*length"], ["throat_r+2.4*wall+0.9748*(exit_r-throat_r-wall)", "2.9*throat_r+0.86*length"], ["throat_r+2.4*wall+0.9802*(exit_r-throat_r-wall)", "2.9*throat_r+0.89*length"], ["throat_r+wall+0.9802*(exit_r-throat_r-wall)", "2.9*throat_r+0.89*length"], + ["throat_r+wall+(1-0.18*min(2.5*wall,0.08*length)/length)*(exit_r-throat_r-wall)", "2.9*throat_r+length-min(2.5*wall,0.08*length)"], ["exit_r+1.6*wall", "2.9*throat_r+length-min(2.5*wall,0.08*length)"], ["exit_r+1.6*wall", "2.9*throat_r+length+0.5*wall"], ["exit_r-0.5*wall", "2.9*throat_r+length+0.5*wall"], ["exit_r-wall", "2.9*throat_r+length"], + ["throat_r+0.9676*(exit_r-throat_r-wall)", "2.9*throat_r+0.82*length"], ["throat_r+0.8844*(exit_r-throat_r-wall)", "2.9*throat_r+0.66*length"], ["throat_r+0.75*(exit_r-throat_r-wall)", "2.9*throat_r+0.5*length"], ["throat_r+0.5904*(exit_r-throat_r-wall)", "2.9*throat_r+0.36*length"], + ["throat_r+0.4224*(exit_r-throat_r-wall)", "2.9*throat_r+0.24*length"], ["throat_r+0.2604*(exit_r-throat_r-wall)", "2.9*throat_r+0.14*length"], ["throat_r+0.1164*(exit_r-throat_r-wall)", "2.9*throat_r+0.06*length"], + ["throat_r", "2.9*throat_r"]]}, + {"shape": "repeat", "count": 4, "around": "+z", "of": + {"shape": "tube", "r0": "0.14*throat_r", "r1": "0.14*throat_r", "length": "0.35*throat_r", "segments": 6, "at": ["1.31*throat_r", "1.31*throat_r", "0.1*throat_r"]}}, + {"shape": "repeat", "count": 4, "around": "+z", "of": + {"shape": "box", "size": ["0.5*throat_r", "0.35*throat_r", "0.6*throat_r"], "at": ["1.7*throat_r", 0, "throat_r"]}} ], "sockets": [ {"name": "mount", "type": "flange", "size": "2*throat_r", "at": [0, 0, 0], "z": "-z", "y": "+y"} @@ -71,23 +55,16 @@ ], "bevel": "0.008*radius", "shapes": [ - {"shape": "tube", "r0": "0.3*radius", "r1": "0.3*radius", "length": "0.05*radius", "segments": "segments", "smooth": true}, - {"shape": "tube", "r0": "0.2*radius", "r1": "0.2*radius", "length": "0.18*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.02*radius"]}, - {"shape": "tube", "r0": "0.47*radius", "r1": "0.6984*radius", "length": "0.07*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.12*radius"]}, - {"shape": "tube", "r0": "0.6984*radius", "r1": "0.8512*radius", "length": "0.08*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.19*radius"]}, - {"shape": "tube", "r0": "0.8512*radius", "r1": "0.9581*radius", "length": "0.1*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.27*radius"]}, - {"shape": "tube", "r0": "0.9581*radius", "r1": "radius", "length": "0.12*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.37*radius"]}, - {"shape": "tube", "r0": "radius", "r1": "radius", "length": "length-0.98*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.49*radius"]}, - {"shape": "tube", "r0": "radius", "r1": "0.9581*radius", "length": "0.12*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.49*radius"]}, - {"shape": "tube", "r0": "0.9581*radius", "r1": "0.8512*radius", "length": "0.1*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.37*radius"]}, - {"shape": "tube", "r0": "0.8512*radius", "r1": "0.6984*radius", "length": "0.08*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.27*radius"]}, - {"shape": "tube", "r0": "0.6984*radius", "r1": "0.47*radius", "length": "0.07*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.19*radius"]}, - {"shape": "tube", "r0": "0.2*radius", "r1": "0.2*radius", "length": "0.18*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.2*radius"]}, - {"shape": "tube", "r0": "0.3*radius", "r1": "0.3*radius", "length": "0.05*radius", "segments": "segments", "smooth": true, "at": [0, 0, "length-0.05*radius"]}, - {"shape": "repeat", "count": 2, "step": [0, 0, "length-0.98*radius"], "of": - {"shape": "tube", "r0": "1.012*radius", "r1": "1.012*radius", "inner0": "0.97*radius", "inner1": "0.97*radius", "length": "0.04*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.47*radius"]}}, + {"shape": "lathe", "segments": "segments", "smooth": true, "profile": [ + ["0.3*radius", 0], ["0.3*radius", "0.05*radius"], ["0.2*radius", "0.05*radius"], ["0.2*radius", "0.12*radius"], + ["0.47*radius", "0.12*radius"], ["0.6984*radius", "0.19*radius"], ["0.8512*radius", "0.27*radius"], ["0.9581*radius", "0.37*radius"], + ["0.9965*radius", "0.47*radius"], ["1.012*radius", "0.47*radius"], ["1.012*radius", "0.51*radius"], ["radius", "0.51*radius"], + ["radius", "length-0.51*radius"], ["1.012*radius", "length-0.51*radius"], ["1.012*radius", "length-0.47*radius"], ["0.9965*radius", "length-0.47*radius"], + ["0.9581*radius", "length-0.37*radius"], ["0.8512*radius", "length-0.27*radius"], ["0.6984*radius", "length-0.19*radius"], ["0.47*radius", "length-0.12*radius"], + ["0.2*radius", "length-0.12*radius"], ["0.2*radius", "length-0.05*radius"], ["0.3*radius", "length-0.05*radius"], ["0.3*radius", "length"]]}, {"shape": "repeat", "count": 2, "step": [0, 0, "0.56*(length-0.98*radius)"], "of": - {"shape": "tube", "r0": "1.035*radius", "r1": "1.035*radius", "inner0": "0.97*radius", "inner1": "0.97*radius", "length": "0.1*radius", "segments": "segments", "smooth": true, "at": [0, 0, "0.44*radius+0.22*(length-0.98*radius)"]}}, + {"shape": "lathe", "loop": true, "segments": "segments", "smooth": true, "at": [0, 0, "0.44*radius+0.22*(length-0.98*radius)"], + "profile": [["0.97*radius", 0], ["1.035*radius", 0], ["1.035*radius", "0.1*radius"], ["0.97*radius", "0.1*radius"]]}}, {"shape": "repeat", "count": 2, "step": [0, 0, "0.56*(length-0.98*radius)"], "of": {"shape": "box", "size": ["1.3*radius", "0.55*radius", "0.1*radius"], "at": [0, "-0.85*radius", "0.49*radius+0.22*(length-0.98*radius)"]}}, {"shape": "box", "size": ["1.5*radius", "0.08*radius", "0.56*(length-0.98*radius)+0.3*radius"], "at": [0, "-1.14*radius", "length/2"]} @@ -200,25 +177,19 @@ ], "bevel": "min(0.15*flange_t,0.06*(flange_r-pipe_r))", "shapes": [ - {"shape": "tube", "r0": "pipe_r", "r1": "pipe_r", "length": "run-flange_t", "segments": "segments", "smooth": true, "at": [0, 0, "0.5*flange_t"]}, - {"shape": "tube", "r0": "flange_r", "r1": "flange_r", "length": "flange_t", "segments": "segments", "smooth": true}, - {"shape": "tube", "r0": "flange_r", "r1": "flange_r", "length": "flange_t", "segments": "segments", "smooth": true, "at": [0, 0, "run-flange_t"]}, - {"shape": "tube", "r0": "1.3*pipe_r", "r1": "1.3*pipe_r", "length": "min(3*pipe_r,run-4*flange_t)", "segments": "segments", "smooth": true, "at": [0, 0, "run/2-min(3*pipe_r,run-4*flange_t)/2"]}, - {"shape": "tube", "r0": "pipe_r", "r1": "pipe_r", "length": "branch-0.5*flange_t", "segments": "segments", "smooth": true, "rot": [0, 90, 0], "at": [0, 0, "run/2"]}, - {"shape": "tube", "r0": "1.3*pipe_r", "r1": "1.3*pipe_r", "length": "min(2.2*pipe_r,branch-2*flange_t)", "segments": "segments", "smooth": true, "rot": [0, 90, 0], "at": [0, 0, "run/2"]}, - {"shape": "tube", "r0": "flange_r", "r1": "flange_r", "length": "flange_t", "segments": "segments", "smooth": true, "rot": [0, 90, 0], "at": ["branch-flange_t", 0, "run/2"]}, - {"shape": "repeat", "count": 2, "step": ["0.7072*(flange_r+pipe_r)", 0, 0], "of": - {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "at": ["-0.3536*(flange_r+pipe_r)", "-0.3536*(flange_r+pipe_r)", "0.15*flange_t"]}}, - {"shape": "repeat", "count": 2, "step": ["0.7072*(flange_r+pipe_r)", 0, 0], "of": - {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "at": ["-0.3536*(flange_r+pipe_r)", "0.3536*(flange_r+pipe_r)", "0.15*flange_t"]}}, - {"shape": "repeat", "count": 2, "step": ["0.7072*(flange_r+pipe_r)", 0, 0], "of": - {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "at": ["-0.3536*(flange_r+pipe_r)", "-0.3536*(flange_r+pipe_r)", "run-1.5*flange_t"]}}, - {"shape": "repeat", "count": 2, "step": ["0.7072*(flange_r+pipe_r)", 0, 0], "of": - {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "at": ["-0.3536*(flange_r+pipe_r)", "0.3536*(flange_r+pipe_r)", "run-1.5*flange_t"]}}, - {"shape": "repeat", "count": 2, "step": [0, 0, "0.7072*(flange_r+pipe_r)"], "of": - {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "rot": [0, 90, 0], "at": ["branch-1.5*flange_t", "-0.3536*(flange_r+pipe_r)", "run/2-0.3536*(flange_r+pipe_r)"]}}, - {"shape": "repeat", "count": 2, "step": [0, 0, "0.7072*(flange_r+pipe_r)"], "of": - {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "rot": [0, 90, 0], "at": ["branch-1.5*flange_t", "0.3536*(flange_r+pipe_r)", "run/2-0.3536*(flange_r+pipe_r)"]}} + {"shape": "lathe", "segments": "segments", "smooth": true, "profile": [ + ["flange_r", 0], ["flange_r", "flange_t"], ["pipe_r", "flange_t"], + ["pipe_r", "run/2-min(3*pipe_r,run-4*flange_t)/2"], ["1.3*pipe_r", "run/2-min(3*pipe_r,run-4*flange_t)/2"], ["1.3*pipe_r", "run/2+min(3*pipe_r,run-4*flange_t)/2"], ["pipe_r", "run/2+min(3*pipe_r,run-4*flange_t)/2"], + ["pipe_r", "run-flange_t"], ["flange_r", "run-flange_t"], ["flange_r", "run"]]}, + {"shape": "lathe", "segments": "segments", "smooth": true, "profile": [ + ["1.2*pipe_r", 0], ["1.2*pipe_r", "min(2.2*pipe_r,branch-2*flange_t)"], ["pipe_r", "min(2.2*pipe_r,branch-2*flange_t)"], + ["pipe_r", "branch-flange_t"], ["flange_r", "branch-flange_t"], ["flange_r", "branch"]], "rot": [0, 90, 0], "at": [0, 0, "run/2"]}, + {"shape": "repeat", "count": 4, "around": "+z", "of": + {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "at": ["0.3536*(flange_r+pipe_r)", "0.3536*(flange_r+pipe_r)", "0.15*flange_t"]}}, + {"shape": "repeat", "count": 4, "around": "+z", "of": + {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "at": ["0.3536*(flange_r+pipe_r)", "0.3536*(flange_r+pipe_r)", "run-1.5*flange_t"]}}, + {"shape": "repeat", "count": 4, "around": "+x", "center": [0, 0, "run/2"], "of": + {"shape": "tube", "r0": "0.22*(flange_r-pipe_r)", "r1": "0.22*(flange_r-pipe_r)", "length": "1.35*flange_t", "segments": 6, "rot": [0, 90, 0], "at": ["branch-1.5*flange_t", "0.3536*(flange_r+pipe_r)", "run/2+0.3536*(flange_r+pipe_r)"]}} ], "sockets": [ {"name": "a", "type": "flange", "size": "2*pipe_r", "at": [0, 0, 0], "z": "-z", "y": "+y"}, @@ -300,6 +271,31 @@ {"name": "back", "type": "mount", "size": "min(width,height)", "at": [0, 0, 0], "z": "-z", "y": "+y"}, {"name": "front", "type": "mount", "size": "0.76*min(width,height)", "at": [0, 0, "thickness"], "z": "+z", "y": "+y"} ] + }, + { + "name": "reducer", + "doc": "Concentric reducer: a cone between a large and a small bolted flange, joining a chamber or housing to the plumbing.", + "params": [ + {"name": "big_r", "type": "number", "min": 0.08, "max": 0.3, "default": 0.12, "doc": "large bore radius"}, + {"name": "small_r", "type": "number", "min": 0.024, "max": 0.07, "default": 0.05, "doc": "small bore radius"}, + {"name": "length", "type": "number", "min": 0.12, "max": 0.6, "default": 0.25, "doc": "big face to small face"}, + {"name": "flange_t", "type": "number", "min": 0.01, "max": 0.04, "default": 0.02, "doc": "flange thickness"}, + {"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of every round"} + ], + "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"]]}, + {"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": + {"shape": "tube", "r0": "0.198*small_r", "r1": "0.198*small_r", "length": "1.35*flange_t", "segments": 6, "at": ["1.45*small_r", 0, "length-1.5*flange_t"]}} + ], + "sockets": [ + {"name": "big", "type": "flange", "size": "2*big_r", "at": [0, 0, 0], "z": "-z", "y": "+y"}, + {"name": "small", "type": "flange", "size": "2*small_r", "at": [0, 0, "length"], "z": "+z", "y": "+y"} + ] } ] } diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index a05ee4e..19d7920 100644 --- a/surfaces/blender/tests/live/kitbash.py +++ b/surfaces/blender/tests/live/kitbash.py @@ -1,5 +1,5 @@ """Live proof, in a background Blender, that the brokkr_kitbash rows are admitted by Brokkr as host actions and that -the mechanical kit goes through run_intent: describe, place_part for all nine parts, setObjectTransform, +the mechanical kit goes through run_intent: describe, place_part for all ten parts, setObjectTransform, assignMaterial, set_params, report, the refusals, and exportGltf. Not part of the unittest run: it needs Blender. blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash.py -- @@ -81,7 +81,7 @@ check("the eight kitbash rows load as host actions with no errors", not R["hostE kit = core.load_kit("mechanical") receipt, described = send("brokkr_kitbash.describe") names = [p["name"] for p in described["parts"]] if described else [] -check("describe lists nine parts, whole, inside a receipt", receipt["status"] == "accepted" and names == list(kit["parts"]) and len(names) == 9 +check("describe lists ten parts, whole, inside a receipt", receipt["status"] == "accepted" and names == list(kit["parts"]) and len(names) == 10 and "[truncated]" not in receipt["hostResult"], [names, len(receipt.get("hostResult") or "")]) receipt, one = send("brokkr_kitbash.describe", part="actuator") check("describe of one part gives its params and its sockets at default params", one and [p["name"] for p in one["parts"]] == ["actuator"] @@ -114,7 +114,7 @@ for index, name in enumerate(names): check(f"place_part {name}: kit, part and every resolved param stored on the object, sockets reported in the part frame", obj is not None and obj["kit_kit"] == "mechanical" and obj["kit_part"] == name and json.loads(obj["kit_params"]) == reference.params == report["params"] and report["sockets"] == core.socket_rows(reference.sockets), report) -check("nine parts are nine mesh objects", len(bpy.data.objects) == 9 and all(o.type == "MESH" for o in bpy.data.objects), len(bpy.data.objects)) +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 -------------------------------------------------------------------------------- tank = bpy.data.objects["P_tank"] @@ -225,7 +225,7 @@ receipt, alone = send("brokkr_kitbash.set_params", object_name="P_vent", params= 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"]) +check("with scale back at 1 every part reports again", receipt["status"] == "accepted" and whole and len(whole["parts"]) == 10, receipt["message"]) # --- export --------------------------------------------------------------------------------------------------------------- receipt, _ = send("exportGltf", filepath="kit.glb", extras=False, yUp=True, applyModifiers=True, selection=[f"P_{n}" for n in names]) @@ -234,7 +234,7 @@ meshes = -1 if glb.is_file(): blob = glb.read_bytes() meshes = len(json.loads(blob[20:20 + int.from_bytes(blob[12:16], "little")]).get("meshes", [])) -check("exportGltf of all nine parts succeeds", receipt["status"] == "accepted" and meshes == 9, [receipt["message"], meshes]) +check("exportGltf of all ten parts succeeds", receipt["status"] == "accepted" and meshes == 10, [receipt["message"], meshes]) R["placed"] = {name: {"faces": report["faces"], "shells": report["shells"], "bevel": report["bevel"], "sockets": [s["name"] for s in report["sockets"]]} for name, report in placed.items() if report} diff --git a/surfaces/blender/tests/live/kitbash.result.json b/surfaces/blender/tests/live/kitbash.result.json index 14da142..d935e1d 100644 --- a/surfaces/blender/tests/live/kitbash.result.json +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -7,7 +7,7 @@ "detail": null }, { - "name": "describe lists nine parts, whole, inside a receipt", + "name": "describe lists ten parts, whole, inside a receipt", "ok": true, "detail": null }, @@ -157,7 +157,22 @@ "detail": null }, { - "name": "nine parts are nine mesh objects", + "name": "place_part reducer: core's faces, a valid mesh, core's flat faces, at the origin", + "ok": true, + "detail": null + }, + { + "name": "place_part reducer: a Bevel of the part's width, 2 segments, angle 30, that evaluates", + "ok": true, + "detail": null + }, + { + "name": "place_part reducer: kit, part and every resolved param stored on the object, sockets reported in the part frame", + "ok": true, + "detail": null + }, + { + "name": "ten parts are ten mesh objects", "ok": true, "detail": null }, @@ -302,7 +317,7 @@ "detail": null }, { - "name": "exportGltf of all nine parts succeeds", + "name": "exportGltf of all ten parts succeeds", "ok": true, "detail": null } @@ -327,16 +342,16 @@ ], "placed": { "nozzle": { - "faces": 1312, - "shells": 24, + "faces": 994, + "shells": 9, "bevel": 0.0024, "sockets": [ "mount" ] }, "tank": { - "faces": 740, - "shells": 20, + "faces": 764, + "shells": 6, "bevel": 0.00176, "sockets": [ "port_a", @@ -372,8 +387,8 @@ ] }, "pipe_fitting": { - "faces": 278, - "shells": 19, + "faces": 436, + "shells": 14, "bevel": 0.0027, "sockets": [ "a", @@ -405,6 +420,15 @@ "back", "front" ] + }, + "reducer": { + "faces": 266, + "shells": 13, + "bevel": 0.003, + "sockets": [ + "big", + "small" + ] } }, "ok": true diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index fe6aa5f..a84645c 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -282,6 +282,91 @@ 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_lathes_are_closed_oriented_and_hold_their_volume(self): + """lathe-shape. Mutants K1 (first cap not reversed), K2 (pole triangles reversed) and K7 (a loop's closing + band dropped) break the edge census; K3 (horizontal bands smooth) the smooth flags.""" + capped = [[0.5, 0], [0.5, 0.4], [0.3, 0.4], [0.3, 1.0], [0.6, 1.0], [0.6, 1.2]] # a cap at each end, two annuli + spindle = [[0, 0], [0.5, 0.3], [0.5, 1.0], [0, 1.4]] # a pole at each end + cup = [[0, 0], [0.5, 0], [0.7, 1.0], [0.6, 1.0], [0.4, 0.1]] # a pole, then back down inside to a cap + ring = [[0.4, 0], [0.6, 0], [0.6, 0.2], [0.4, 0.2]] + for n in (3, 32): + for profile, loop, faces, flat in ((capped, False, 5 * n + 2, [1, 3]), (spindle, False, 3 * n, []), (cup, False, 4 * n + 1, [0, 2]), + (ring, True, 4 * n, [0, 2])): + b = built([{"shape": "lathe", "profile": profile, "segments": n, "smooth": True, "loop": loop}]) + joined = profile + profile[:1] if loop else profile + expected = sum(frustum(r0, r1, z1 - z0, n) for (r0, z0), (r1, z1) in zip(joined, joined[1:])) + self.assertTrue(closed_and_oriented(b), (profile, n)) + self.assertGreater(expected, 0.01) + self.assertLess(abs(signed_volume(b) - expected), 1e-9 * expected) + self.assertEqual((len(b.counts), b.shell_count), (faces, 1)) + bands = len(joined) - 1 + self.assertEqual(b.smooth.tolist(), [i not in flat for i in range(bands) for _ in range(n)] + [False] * (faces - bands * n)) + self.assertFalse(built([{"shape": "lathe", "profile": profile, "segments": n, "loop": loop}]).smooth.any()) + b = built([{"shape": "lathe", "profile": spindle, "segments": 8}]) + self.assertEqual(b.counts.tolist(), [3] * 8 + [4] * 8 + [3] * 8) + self.assertEqual((len(b.V), b.V[0].tolist(), b.V[-1].tolist()), (18, [0.0, 0.0, 0.0], [0.0, 0.0, 1.4])) + b = built([{"shape": "lathe", "profile": capped, "segments": 8, "rot": [0, 90, 0], "at": [1, 0, 0]}]) # placed as a tube is: +z turns to +x + self.assertTrue(np.allclose([b.V[:, 0].min(), b.V[:, 0].max()], [1.0, 2.2], atol=1e-12)) + self.assertEqual(b.counts.tolist(), [4] * 40 + [8, 8]) + grown = built([{"shape": "lathe", "profile": [["a", 0], ["a", "2*a"]], "segments": 8}], [param("a")], {"a": 0.5}) # expressions, and the least profile + self.assertLess(abs(signed_volume(grown) - frustum(0.5, 0.5, 1.0, 8)), 1e-12) + + def test_what_a_lathe_refuses_names_the_point(self): + """Mutants K4 (the orientation refusal dropped) and K8 (r = 0 allowed inside a profile).""" + ring = [[0.4, 0], [0.6, 0], [0.6, 0.2], [0.4, 0.2]] + lathe = lambda profile, **more: [{"shape": "lathe", "profile": profile, "segments": 8, **more}] # noqa: E731 + for shapes, message in ( + (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]), 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"), + (lathe([[1, 0], [1, 1]], smooth="yes"), r"smooth must be true or false"), + (lathe([[1, 0], [1, 1]], inner0=0.5), r"shape 0 \(lathe\) has no key 'inner0'"), + (lathe([[1, 0], [-0.1, 0.5], [1, 1]]), r"profile\[1\]: r is -0\.1, below 0"), + (lathe([[1, 0], [0, 0.5], [1, 1]]), r"profile\[1\]: r is 0; only the first and last point of an open profile"), + (lathe([[0, 0], [0.6, 0], [0.6, 0.2]], loop=True), r"profile\[0\]: r is 0; only the first and last"), + (lathe([[1, 0], [1, 1], [1, 1], [0.5, 1]]), r"profile\[2\]: \[1\.0, 1\.0\] repeats the point before it"), + (lathe(ring + ring[:1], loop=True), r"profile\[0\]: \[0\.4, 0\.0\] repeats the point before it \(a loop closes itself\)"), + (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\)"), + (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_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]} + for shape, expected in ( + ({"count": 4, "around": "+z", "of": {**box, "at": [1, 0, 0.5]}}, [[1, 0, 0.5], [0, 1, 0.5], [-1, 0, 0.5], [0, -1, 0.5]]), + ({"count": 4, "around": "-z", "of": {**box, "at": [1, 0, 0.5]}}, [[1, 0, 0.5], [0, -1, 0.5], [-1, 0, 0.5], [0, 1, 0.5]]), + ({"count": 4, "around": "+x", "center": [0, 1, "2*a"], "of": {**box, "at": [3, 1, 3]}}, [[3, 1, 3], [3, 0, 2], [3, 1, 1], [3, 2, 2]]), + ({"count": "n", "around": "+y", "center": [1, 0, 0], "of": {**box, "at": [1, 5, 1]}}, [[1, 5, 1], [1 + 0.75 ** 0.5, 5, -0.5], [1 - 0.75 ** 0.5, 5, -0.5]])): + b = built([{"shape": "box", "size": [1, 1, 1]}, {"shape": "repeat", **shape}], [param("a"), param("n", 1, 300, 3)]) + copies = len(expected) + self.assertEqual((b.shell_count, b.shape.tolist()), (1 + copies, [0] * 6 + [1] * 6 * copies)) + self.assertTrue(np.allclose(b.V[8:].reshape(copies, 8, 3).mean(axis=1), expected, atol=1e-12), shape) + self.assertTrue(closed_and_oriented(b)) + self.assertLess(abs(signed_volume(b) - 1.0 - 0.008 * copies), 1e-12) + turned = built([{"shape": "repeat", "count": 3, "around": "+z", "of": {"shape": "lathe", "profile": [[0.1, 0], [0.1, 1]], "segments": 8, "at": [1, 0, 0]}}]) + self.assertTrue(closed_and_oriented(turned)) + self.assertEqual((turned.shell_count, len(turned.counts)), (3, 30)) + of = {"shape": "repeat", "count": 2, "of": box} + for change, message in (({"step": [1, 0, 0], "around": "+z"}, r"shape 0 \(repeat\) takes exactly one of step .* and around"), + ({}, r"takes exactly one of step .* and around"), + ({"center": [0, 0, 0]}, r"takes exactly one of step"), + ({"step": [1, 0, 0], "center": [0, 0, 0]}, r"shape 0 \(repeat\): center goes with around, not with step"), + ({"around": "up"}, r"around must be one of \+x, -x, \+y, -y, \+z, -z"), + ({"around": ["+z"]}, r"around must be one of"), + ({"around": "+z", "center": [0, 0]}, r"center must be an array of three"), + ({"around": "+z", "of": {"shape": "repeat", "count": 2, "around": "+x", "of": box}}, r"a repeat cannot hold a repeat"), + ({"around": "+z", "count": 257}, r"count is .*whole number from 1 to 256")): + with self.assertRaisesRegex(core.KitError, message): + built([{**of, **change}]) + 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]}, @@ -330,20 +415,21 @@ class ParamTests(unittest.TestCase): @unittest.skipIf(np is None, "numpy is not installed") class MechanicalKitTests(unittest.TestCase): - PARTS = ["nozzle", "tank", "ribbed_cylinder", "strut", "actuator", "pipe_fitting", "radiator_stack", "vent", "plate"] + PARTS = ["nozzle", "tank", "ribbed_cylinder", "strut", "actuator", "pipe_fitting", "radiator_stack", "vent", "plate", "reducer"] @classmethod def setUpClass(cls): cls.kit = core.load_kit("mechanical") - def test_the_kit_is_the_nine_parts_and_three_socket_types(self): + def test_the_kit_is_the_ten_parts_and_three_socket_types(self): self.assertEqual(list(self.kit["parts"]), self.PARTS) self.assertEqual({k: v["match"] for k, v in self.kit["socketTypes"].items()}, {"flange": "equal", "mount": "fits", "pivot": "equal"}) self.assertEqual({name: [(s["name"], s["type"]) for s in part["sockets"]] for name, part in self.kit["parts"].items()}, { "nozzle": [("mount", "flange")], "tank": [("port_a", "flange"), ("port_b", "flange"), ("saddle", "mount")], "ribbed_cylinder": [("end_a", "flange"), ("end_b", "flange")], "strut": [("end_a", "pivot"), ("end_b", "pivot")], "actuator": [("base", "pivot"), ("rod_end", "pivot")], "pipe_fitting": [("a", "flange"), ("b", "flange"), ("c", "flange")], - "radiator_stack": [("base", "mount")], "vent": [("back", "mount")], "plate": [("back", "mount"), ("front", "mount")]}) + "radiator_stack": [("base", "mount")], "vent": [("back", "mount")], "plate": [("back", "mount"), ("front", "mount")], + "reducer": [("big", "flange"), ("small", "flange")]}) def test_every_part_holds_everywhere(self): """kit-parts-hold-everywhere. Mutant M8 (flip one socket's z in the kit): no face at that origin faces it.""" @@ -451,7 +537,7 @@ class MateTests(unittest.TestCase): self.assertEqual(core.FLIP.tolist(), [[-1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, -1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]) def test_what_may_mate(self): - """mate-refusal. Mutants A3 (fits reversed) and A4 (equal at 10 percent).""" + """mate-refusal. Mutants A3 (fits reversed), A4 (equal at 10 percent) and K10 (the equal rule's slack 5e-3).""" types = self.kit["socketTypes"] socket = lambda name, kind, size: {"name": name, "type": kind, "size": size, "matrix": np.eye(4)} # noqa: E731 self.assertRegex(core.mate_refusal(types, socket("p", "flange", 0.1), socket("c", "mount", 0.1)), @@ -462,19 +548,47 @@ class MateTests(unittest.TestCase): self.assertIsNone(core.mate_refusal(types, socket("p", kind, 0.2), socket("c", kind, 0.198))) self.assertIn("mate at equal sizes", core.mate_refusal(types, socket("p", kind, 100.0), socket("c", kind, 98.99))) self.assertIn("mate at equal sizes", core.mate_refusal(types, socket("p", kind, 98.99), socket("c", kind, 100.0))) + # equal-slack: past the 1 percent by 2.2e-6 of it. Shipped slack 1e-9; least mutant 5e-3 (K10); separation 2200 each side + self.assertIn("mate at equal sizes", core.mate_refusal(types, socket("p", kind, 100.0), socket("c", kind, 100.0 - 1.0000022))) + self.assertIn("mate at equal sizes", core.mate_refusal(types, socket("p", kind, 100.0 - 1.0000022), socket("c", kind, 100.0))) self.assertIsNone(core.mate_refusal(types, socket("p", "mount", 0.3), socket("c", "mount", 0.3))) # fits: the child at most the parent self.assertIsNone(core.mate_refusal(types, socket("p", "mount", 0.3), socket("c", "mount", 0.1))) self.assertIn("it is larger", core.mate_refusal(types, socket("p", "mount", 0.3), socket("c", "mount", 0.3 + 1e-6))) self.assertIn("it is larger", core.mate_refusal(types, socket("p", "mount", 0.1), socket("c", "mount", 0.3))) + self.assertIn("it is larger", core.mate_refusal(types, socket("p", "mount", 0.3), socket("c", "mount", 0.3 * (1 + 2.2e-6)))) def test_the_kit_s_own_flanges_do_not_meet_everywhere(self): - """A chamber flange (ribbed_cylinder, 0.16 and up) and the plumbing (pipe_fitting, 0.14 and down) never mate.""" + """A chamber flange (ribbed_cylinder, 0.16 and up) and the plumbing (pipe_fitting, 0.14 and down) never mate + face to face.""" parts = self.kit["parts"] drum = core.build(parts["ribbed_cylinder"], {"radius": 0.08}).sockets[1] pipe = core.build(parts["pipe_fitting"], {"pipe_r": 0.07}).sockets[0] self.assertEqual((drum["size"], pipe["size"]), (0.16, 0.14)) self.assertIn("mate at equal sizes", core.mate_refusal(self.kit["socketTypes"], drum, pipe)) + def test_a_reducer_bridges_chamber_and_plumbing(self): + """reducer-bridges, at the ends of each range. Mutant K16 (the reducer's sockets swapped end for end): each + socket then lies on the other flange's face.""" + parts, types = self.kit["parts"], self.kit["socketTypes"] + for big_r, small_r in ((0.08, 0.024), (0.3, 0.07), (0.08, 0.07), (0.3, 0.024)): + reducer = core.build(parts["reducer"], {"big_r": big_r, "small_r": small_r}) + big, small = reducer.sockets + self.assertEqual((big["name"], small["name"], big["size"], small["size"]), ("big", "small", 2 * big_r, 2 * small_r)) + drum = core.build(parts["ribbed_cylinder"], {"radius": big_r}).sockets[1] + tee = core.build(parts["pipe_fitting"], {"pipe_r": max(small_r, 0.03)}).sockets[0] + port = core.build(parts["tank"], {"radius": {0.024: 0.12, 0.07: 0.35}[small_r]}).sockets[1] + self.assertIsNone(core.mate_refusal(types, drum, big)) + self.assertIsNone(core.mate_refusal(types, big, drum)) + self.assertIsNone(core.mate_refusal(types, port, small)) + if small_r >= 0.03: + self.assertIsNone(core.mate_refusal(types, small, tee)) + for a, b in ((big, small), (small, big), (drum, small), (tee, big), (port, big)): + self.assertIn("mate at equal sizes", core.mate_refusal(types, a, b)) + for socket, flange in ((big, 1.35 * big_r), (small, 1.9 * small_r)): # the face a socket lies on is its own flange's + face = reducer.V[np.abs(reducer.V[:, 2] - socket["matrix"][2, 3]) < 1e-12] + self.assertAlmostEqual(float(np.linalg.norm(face[:, :2], axis=1).max()), flange, places=12) + self.assertEqual([s["matrix"][:3, 2].tolist() for s in reducer.sockets], [[0.0, 0.0, -1.0], [0.0, 0.0, 1.0]]) + def test_a_joint_is_two_named_sockets_of_one_kit(self): """The cross-kit refusal (one kit ships, so no scene can show it) and the unknown-socket refusals.""" parts = self.kit["parts"] @@ -548,7 +662,8 @@ class OwnershipTests(unittest.TestCase): PACKAGE = (r"\beval\(|\bexec\(|\bcompile\(", r"brokkr_bridge", r"\bsolver\s*=\s*[\"']MANIFOLD|\buse_self\s*=\s*False", # a boolean is Exact with self-intersection, nothing else r"hide_render|hide_viewport|display_type", # a cutter's visibility is setObjectVisibility's - r"kit_parent_name|kit_parent\b|matrix_world_stored") # obj.parent has no second owner + r"kit_parent_name|kit_parent\b|matrix_world_stored", # obj.parent has no second owner + r"SCREW|\"ARRAY\"|spin\(") # core makes every vertex: no modifier or bmesh op makes kit geometry CORE = r"^import bpy|^from bpy|^import bmesh" SCHEMAS = r"brokkr\.kit\.v0" @@ -576,8 +691,18 @@ class OwnershipTests(unittest.TestCase): self.assertEqual(source.count("evaluated_of("), 3) self.assertEqual(source.count("to_mesh("), 1) + def test_only_attach_writes_the_roll(self): + """kit_roll is the one statement of a connection's roll: set_params and the reports read it and never write it back.""" + source = self.sources()["__init__.py"] + writes = re.findall(r'[^\n]*(?:\[ROLL\]|\["kit_roll"\])\s*=(?!=)[^\n]*', source) + self.assertEqual(writes, [" child[SOCKET], child[PARENT_SOCKET], child[ROLL] = stated"]) + self.assertIn(writes[0], source.split("class BROKKR_KITBASH_OT_attach")[1].split("class BROKKR_KITBASH_OT_")[0]) + def test_the_patterns_bite(self): - planted = ("value = eval(text)", "from brokkr_bridge import x", 'modifier.solver = "MANIFOLD"', "cutter.hide_render = True", 'obj["kit_parent"] = parent.name') + planted = ("value = eval(text)", "from brokkr_bridge import x", 'modifier.solver = "MANIFOLD"', "cutter.hide_render = True", 'obj["kit_parent"] = parent.name', + 'obj.modifiers.new("Turn", "SCREW")') + for text in ('obj.modifiers.new("Bolts", "ARRAY")', "bmesh.ops.spin(bm, geom=geom)"): + self.assertIsNotNone(re.search(self.PACKAGE[5], text)) self.assertEqual(len(planted), len(self.PACKAGE)) for pattern, text in zip(self.PACKAGE, planted): self.assertIsNotNone(re.search(pattern, text))