diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index e4b68ba..c298351 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -250,7 +250,13 @@ def _shape(shape: Any, names, where: str, inside_repeat: bool = False) -> dict: if not isinstance(path, list) or not least <= len(path) <= PATH: raise KitError(f"{where} path must be an array of {least} to {PATH} [x, y, z] points{' (it is a loop)' if made['loop'] else ''}") made["path"] = [_vector(point, names, f"{where} path[{i}]") for i, point in enumerate(path)] - made["up"] = _vector(shape["up"], names, f"{where} up") + ups = shape["up"] + if isinstance(ups, list) and ups and all(isinstance(up, list) for up in ups): # one up for each path point + if len(ups) != len(path): + raise KitError(f"{where} up lists {len(ups)} vectors for a path of {len(path)} points: give one [x, y, z] or one for each point") + made["up"] = [_vector(up, names, f"{where} up[{i}]") for i, up in enumerate(ups)] + else: + made["up"] = [_vector(ups, names, f"{where} up")] return made for key in ("loop", "smooth"): if not isinstance(shape.get(key, False), bool): @@ -572,12 +578,13 @@ def _box(shape: dict, env): def _extrude(shape: dict, env): """A PROFILES section swept along the path: profile and sweep own the geometry (the outline's x is up cross the path's tangent, its y is up taken off the tangent, the joints are mitred), and what either refuses is refused - here under the shape's name. Every face is flat.""" + here under the shape's name. `up` is one vector for the whole path or one for each point, as sweep takes them. + Every face is flat.""" size = [shape[key].value(env) for key in ("w", "h", "t")] path = [[e.value(env) for e in point] for point in shape["path"]] - up = [e.value(env) for e in shape["up"]] + ups = [[e.value(env) for e in up] for up in shape["up"]] try: - swept = sweep(path, profile(shape["section"], *size), up, shape["loop"]) + swept = sweep(path, profile(shape["section"], *size), ups[0] if len(ups) == 1 else ups, shape["loop"]) except KitError as error: raise KitError(f"{shape['where']}: {error}") from None return swept.V, swept.faces, swept.counts, swept.smooth, NO_SHARP diff --git a/surfaces/blender/brokkr_kitbash/kits/frame.v0.json b/surfaces/blender/brokkr_kitbash/kits/frame.v0.json index a61f3c7..e25c7fe 100644 --- a/surfaces/blender/brokkr_kitbash/kits/frame.v0.json +++ b/surfaces/blender/brokkr_kitbash/kits/frame.v0.json @@ -118,16 +118,16 @@ }, { "name": "portal", - "doc": "Portal frame in the xz plane: one I section up a leg, across and down the other, mitred at both corners. Its flanges face +y and -y.", + "doc": "Portal frame in the xz plane: one I section up a leg, across and down the other, mitred at both corners. Its web stands in the frame's plane; its flanges run across y on the inside and the outside of the frame.", "params": [ {"name": "width", "type": "number", "min": 0.5, "max": 4.0, "default": 1.2, "doc": "leg axis to leg axis (x)"}, {"name": "height", "type": "number", "min": 0.4, "max": 3.0, "default": 0.9, "doc": "feet to the beam's axis (z)"}, - {"name": "w", "type": "number", "min": 0.04, "max": 0.3, "default": 0.1, "doc": "section width, in the frame's plane"}, - {"name": "h", "type": "number", "min": 0.04, "max": 0.3, "default": 0.1, "doc": "section height (y)"}, + {"name": "w", "type": "number", "min": 0.04, "max": 0.3, "default": 0.1, "doc": "flange width, across the frame's plane (y)"}, + {"name": "h", "type": "number", "min": 0.04, "max": 0.3, "default": 0.1, "doc": "section height, flange to flange in the frame's plane"}, {"name": "t", "type": "number", "min": 0.004, "max": 0.04, "default": 0.01, "doc": "wall thickness; held under 0.45 of the smaller of w and h"} ], "shapes": [ - {"shape": "extrude", "section": "I", "w": "w", "h": "h", "t": "min(t,0.45*min(w,h))", "path": [["-width/2", 0, 0], ["-width/2", 0, "height"], ["width/2", 0, "height"], ["width/2", 0, 0]], "up": [0, 1, 0]} + {"shape": "extrude", "section": "I", "w": "w", "h": "h", "t": "min(t,0.45*min(w,h))", "path": [["-width/2", 0, 0], ["-width/2", 0, "height"], ["width/2", 0, "height"], ["width/2", 0, 0]], "up": [[1, 0, 0], [1, 0, -1], [-1, 0, -1], [-1, 0, 0]]} ], "sockets": [ {"name": "foot_a", "type": "mount", "size": "min(w,h)", "at": ["-width/2", 0, 0], "z": "-z", "y": "+y"}, diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 586b9ab..8cbd115 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -76,7 +76,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. A point written `[r, z, "sharp"]` is a crease. | -| `extrude` | `section`, `w`, `h`, `t`, `path`, `up`, `loop`? | A section (`I`, `C`, `T`, `L`, `box`, `wedge` or `gusset`: a name, never an expression) of width `w`, height `h` and wall `t`, swept along `path`, 2 to 64 `[x, y, z]` points, into one shell with a flat cap at each end. `up` is one `[x, y, z]` vector the section's height stands along. With `loop` true the last point joins the first and there are no caps (3 points or more). Every face is flat. | +| `extrude` | `section`, `w`, `h`, `t`, `path`, `up`, `loop`? | A section (`I`, `C`, `T`, `L`, `box`, `wedge` or `gusset`: a name, never an expression) of width `w`, height `h` and wall `t`, swept along `path`, 2 to 64 `[x, y, z]` points, into one shell with a flat cap at each end. `up` is the direction the section's height stands along: one `[x, y, z]` vector for the whole path, or an array of one per path point. With `loop` true the last point joins the first and there are no caps (3 points or more). Every face is flat. | | `repeat` | `count`, `of`, and `step` or `around` with `center`? | `count` copies (1 to 256) of one tube, box, lathe or extrude: 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 @@ -130,9 +130,11 @@ place the whole shell as they place any shape. Every size is above 0. A build is refused, naming the kit, part and shape, when the section has no room for its wall, when `up` runs along the path at a point (or is zero), when two path points are closer than 1e-9, when the path turns more than 150 degrees at a point (past it a mitre runs 3.9 times the section's width), and when the -section folds: the path turns tighter than the section reaches on the inside of the turn. One `up` serves the -whole path, so a path that bends in two planes needs an `up` that crosses every segment and every corner's -bisector; a portal in the xz plane takes `up` +y, which stands an I section's web across the frame's plane. +section folds: the path turns tighter than the section reaches on the inside of the turn. One `up` must cross +every segment and every corner's bisector, so it can only stand a bent path's section across the plane of the +bend. To keep the section's height in that plane give one `up` per point, each in the plane and across the path +there (at a corner, across its bisector): the portal's four point toward the inside of the frame, which stands its +I section's web in the frame's plane. An array of ups that is not one per path point is refused. `smooth` is not a field of an extrude: a section's faces are flat, and its corners take the part's `bevel`. **`bevel`** is the width of a Bevel modifier `place_part` adds (2 segments, edges sharper than 30 degrees). Keep it @@ -730,7 +732,7 @@ way round (`place_part` and `describe` take `kit: "frame"`). | `beam_i`, `channel`, `tee`, `angle` | `length`, `w`, `h`, `t` | An I, C, T or L section along +z from 0 to `length`, `w` across x and `h` along y. `t` is held under 0.45 of the smaller of `w` and `h`. | `end_a` (z -z) and `end_b` (z +z), `mount`, size the smaller of `w` and `h`. On a channel and an angle they sit on the web at -x, where the end face is. | | `box_beam` | `length`, `w`, `h` | A solid rectangular bar along +z. | `end_a`, `end_b`, as a beam's | | `truss` | `length`, `height`, `pairs`, `chord`, `web` | A plane truss along +x in the xz plane: two square chords at z 0 and z `height`, `2*pairs + 1` verticals and `2*pairs` diagonals, rising then falling: `4*pairs + 3` shells. Bays come in pairs (1 to 16) because an expression has no floor: the diagonals are two repeats a double bay apart. | `end_a` (z -x) and `end_b` (z +x) on the end verticals at mid-height, `mount`, size `height` | -| `portal` | `width`, `height`, `w`, `h`, `t` | One I section up a leg, across and down the other in the xz plane, mitred at both corners; its flanges face +y and -y. | `foot_a`, `foot_b` (z -z), `mount` | +| `portal` | `width`, `height`, `w`, `h`, `t` | One I section up a leg, across and down the other in the xz plane, mitred at both corners. Its web stands in the frame's plane: `h` is the section's height in that plane, flange to flange, and `w` the flanges' width across y. | `foot_a`, `foot_b` (z -z), `mount` | | `gusset` | `w`, `h`, `t`, `thickness` | A corner plate in the xy plane with its right angle at the origin, legs along +x and +y, `thickness` along +z. | `leg_a` on the x leg's edge (z -y) and `leg_b` on the y leg's (z -x), `mount`, size `thickness` | | `wedge` | `length`, `w`, `h`, `t` | A toe cap, ramp or chock along +x: base on z 0, back `h` tall at -y, sloping to a front `t` tall at +y (`t` held under 0.9 of `h`). | `base` (z -z) and `back` (z -y), `mount` | @@ -752,9 +754,10 @@ python -m unittest discover -s surfaces/blender/tests -p "test_kitbash.py" -v seated on a face that faces its `z`, and no build passes 20000 faces. Choose param ranges so every combination builds: a `min` or `max` in an expression keeps a derived length positive where two params could cross. A new part of `mechanical` also joins the part and socket list in `test_the_kit_is_the_eleven_parts_and_three_socket_types`. -`FrameKitTests` holds `frame` to the same (its seat check reads a section's cap, which is not convex, by the -face's own normal and outline), with the truss's shells, the portal's mitres and a beam seated on a mechanical -bracket. `CuttersKitTests` holds `cutters` to the same, with each floor on its cutter's bottom, and `SurfaceFrameTests` the +`FrameKitTests` holds `frame` to the same (the seat check reads a cap that is not convex, an I section's, as it +reads a convex one), with the truss's shells and chords, the portal's mitres, its web in the frame's plane and its +feet apart, each beam's `w` across x and `h` along y, and a beam seated on a mechanical +bracket. Its bounds `SEATED`, `VOLUME` and `PLACED` carry their shipped and mutant readings in `tests/test_kitbash.py`. `CuttersKitTests` holds `cutters` to the same, with each floor on its cutter's bottom, and `SurfaceFrameTests` the frame `cut` gives a cutter. `MateTests` covers the mate arithmetic and what may mate, within a kit and across two, `PoseTests` the closed-form rolls. The operators are exercised in a real Blender by `tests/live/kitbash.py` (placing and re-parameterising, and the frame kit: its nine parts placed, the truss diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index a00e264..55c0723 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -5,8 +5,8 @@ Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; The operators are exercised in a real Blender by tests/live/kitbash.py, tests/live/kitbash_assembly.py and tests/live/kitbash_pose.py. -Bounds follow lodur:ruling:deterministic-bound-margin: a deterministic reading is exact here, so each assertion is -the built value, and each names the mutant it kills. +Bounds follow lodur:ruling:deterministic-bound-margin: SEATED, VOLUME and PLACED, below, carry their shipped and +mutant readings; a reading that is exact is asserted equal. Each check names the mutant it kills. """ from __future__ import annotations @@ -85,44 +85,52 @@ def frustum(r0, r1, h, n) -> float: return h / 3.0 * (a0 + a1 + math.sqrt(a0 * a1)) -def point_triangle(p, a, b, c) -> float: - """Distance from p to triangle abc (Ericson, Real-Time Collision Detection 5.1.5).""" - ab, ac, ap = b - a, c - a, p - a - d1, d2 = ab @ ap, ac @ ap - if d1 <= 0 and d2 <= 0: - return float(np.linalg.norm(ap)) - bp = p - b - d3, d4 = ab @ bp, ac @ bp - if d3 >= 0 and d4 <= d3: - return float(np.linalg.norm(bp)) - vc = d1 * d4 - d3 * d2 - if vc <= 0 and d1 >= 0 and d3 <= 0: - return float(np.linalg.norm(ap - ab * (d1 / (d1 - d3)))) - cp = p - c - d5, d6 = ab @ cp, ac @ cp - if d6 >= 0 and d5 <= d6: - return float(np.linalg.norm(cp)) - vb = d5 * d2 - d1 * d6 - if vb <= 0 and d2 >= 0 and d6 <= 0: - return float(np.linalg.norm(ap - ac * (d2 / (d2 - d6)))) - va = d3 * d6 - d5 * d4 - if va <= 0 and d4 - d3 >= 0 and d5 - d6 >= 0: - return float(np.linalg.norm(bp - (c - b) * ((d4 - d3) / ((d4 - d3) + (d5 - d6))))) - normal = np.cross(ab, ac) - return float(abs(ap @ normal) / np.linalg.norm(normal)) +# Bounds of the extrude shape's and the frame kit's checks (ShapeTests, FrameKitTests), by +# lodur:ruling:deterministic-bound-margin: each sits at the geometric mean of the shipped worst reading and the least +# claimed mutant's. A mutant is one edit of core.py or kits/frame.v0.json; a reading is the worst of every check under +# the bound, over every draw. +# Metres from a frame part's socket origin to the face it sits on. Shipped worst 1.1e-15; least claimed mutant 0.04 +# (a portal foot one wall above its end cap); separation 6.0e6 each side. Also claimed: a truss end on its vertical's +# axis 0.05, a channel's end off its web 0.15, a tee built as an L 0.16, a wedge not lifted onto its base 0.25. +SEATED = 6.7e-9 +# Cubic metres between a swept shell's volume and its section's area times its path's length. Shipped worst 2.7e-15; +# least claimed mutant 0.02 (E7, loop ignored: the ring an open path); separation 2.7e6 each side. A sweep with no +# mitre reads 0.023. +VOLUME = 7.3e-9 +# Metres between a built point, extent or centre and where the part's doc puts it. Shipped worst 8.9e-16; least claimed +# mutant 0.01 (a portal foot one wall above its end cap, read against its cap's middle); separation 3.4e6 each side. +# Also claimed: a truss's chords a web short 0.015, a sweep with no mitre 0.044, S14 (box_beam's w and h swapped) +# 0.075, P1 (the portal on one up +y) 0.3, U1 (only the first of an extrude's ups used) 0.6, S9 (foot_b on foot_a) 1.2, +# a truss's falling diagonals a bay late 1.6, E1 (an extrude ignores at and rot) 3.0. +PLACED = 3.0e-9 def socket_seat(b, socket) -> float: - """Distance from the socket's origin to the nearest face whose normal is the socket's z (inf when none faces it).""" + """Distance from the socket's origin to the nearest face whose normal is the socket's z (inf when none faces it). + The face's normal is Newell's sum; the origin is over the face by crossing count, and beside it the distance is + to the nearest edge: so a cap that is not convex (an I section's) reads as a convex one does.""" origin, z = socket["matrix"][:3, 3], socket["matrix"][:3, 2] best = math.inf for face in faces_of(b): p = b.V[face] - normal = np.cross(p[1] - p[0], p[2] - p[0]) + normal = np.cross(p, np.roll(p, -1, axis=0)).sum(axis=0) normal /= np.linalg.norm(normal) if np.abs(normal - z).max() > 1e-6: continue - best = min([best] + [point_triangle(origin, p[0], p[i], p[i + 1]) for i in range(1, len(face) - 1)]) + u = np.cross(normal, [1.0, 0.0, 0.0] if abs(normal[0]) < 0.9 else [0.0, 1.0, 0.0]) + u /= np.linalg.norm(u) + v = np.cross(normal, u) + a, o = np.stack([p @ u, p @ v], axis=1), np.array([origin @ u, origin @ v]) + c = np.roll(a, -1, axis=0) + straddles = (a[:, 1] > o[1]) != (c[:, 1] > o[1]) + with np.errstate(divide="ignore", invalid="ignore"): + crossing = a[:, 0] + (o[1] - a[:, 1]) * (c[:, 0] - a[:, 0]) / (c[:, 1] - a[:, 1]) + off = float(abs((origin - p[0]) @ normal)) + if not int((straddles & (crossing > o[0])).sum()) % 2: # beside the face: to its nearest edge + edge = c - a + along = np.clip(np.einsum("ij,ij->i", o - a, edge) / np.einsum("ij,ij->i", edge, edge), 0.0, 1.0) + off = math.hypot(off, float(np.linalg.norm(a + along[:, None] * edge - o, axis=1).min())) + best = min(best, off) return best @@ -435,7 +443,7 @@ class ShapeTests(unittest.TestCase): area = float(0.5 * np.sum(x * np.roll(y, -1) - np.roll(x, -1) * y)) b = built([{**self.BEAM, "section": section, "w": "a", "path": [[0, 0, 0], [0, 0, "5*a"]]}], [param("a", 0.01, 1, w)]) self.assertTrue(closed_and_oriented(b), section) - self.assertLess(abs(signed_volume(b) - area * 0.3), 1e-12, section) + self.assertLess(abs(signed_volume(b) - area * 0.3), VOLUME, section) self.assertEqual((b.shell_count, b.counts.tolist(), bool(b.smooth.any()), b.sharp.shape), (1, [4] * len(outline) + [len(outline)] * 2, False, (0, 2)), section) self.assertEqual(b.V[:len(outline)].tolist(), [[px, py, 0.0] for px, py in outline.tolist()], section) self.assertEqual(b.V[len(outline):, 2].tolist(), [0.06 * 5] * len(outline)) @@ -451,20 +459,20 @@ class ShapeTests(unittest.TestCase): swept = built([{**self.BEAM, "section": "box", "rot": rot, "at": at}]) box = built([{"shape": "box", "size": size, "rot": rot, "at": lifted}]) order = lambda V: V[np.lexsort(np.round(V, 9).T)] # noqa: E731 - self.assertLess(float(np.abs(order(swept.V) - order(box.V)).max()), 1e-12) - self.assertLess(abs(signed_volume(swept) - 0.06 * 0.1 * 0.3), 1e-12) + self.assertLess(float(np.abs(order(swept.V) - order(box.V)).max()), PLACED) + self.assertLess(abs(signed_volume(swept) - 0.06 * 0.1 * 0.3), VOLUME) area = 2 * 0.06 * 0.012 + (0.1 - 2 * 0.012) * 0.012 for change, centres in (({"step": [0.5, 0, "a"]}, [[0, 0, 0.15], [0.5, 0, 1.15], [1.0, 0, 2.15]]), ({"around": "+y", "center": [1, 0, 0]}, [[0, 0, 0.15], [1.5 + 0.15 * 0.75 ** 0.5, 0, 0.75 ** 0.5 - 0.075], [1.5 - 0.15 * 0.75 ** 0.5, 0, -0.75 ** 0.5 - 0.075]])): b = built([{"shape": "box", "size": [1, 1, 1]}, {"shape": "repeat", "count": 3, **change, "of": self.BEAM}], [param("a")]) self.assertEqual((b.shell_count, b.shape.tolist()), (4, [0] * 6 + [1] * 14 * 3)) self.assertTrue(closed_and_oriented(b)) - self.assertLess(abs(signed_volume(b) - 1.0 - 3 * area * 0.3), 1e-12) - self.assertTrue(np.allclose(b.V[8:].reshape(3, 24, 3).mean(axis=1), centres, atol=1e-12), change) + self.assertLess(abs(signed_volume(b) - 1.0 - 3 * area * 0.3), VOLUME) + self.assertLess(float(np.abs(b.V[8:].reshape(3, 24, 3).mean(axis=1) - centres).max()), PLACED, change) ring = built([{**self.BEAM, "section": "box", "w": 0.1, "h": 0.2, "loop": True, "path": [[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]], "up": [0, 0, 1]}]) self.assertEqual((ring.shell_count, ring.counts.tolist(), len(ring.V)), (1, [4] * 16, 16)) self.assertTrue(closed_and_oriented(ring)) - self.assertLess(abs(signed_volume(ring) - 0.1 * 0.2 * 4.0), 1e-12) # mitred: the area times the path's length + self.assertLess(abs(signed_volume(ring) - 0.1 * 0.2 * 4.0), VOLUME) # mitred: the area times the path's length def test_what_a_sweep_refuses_an_extrude_refuses_by_name(self): """extrude-refusals, at build. Mutant E8 (the where prefix dropped): each message starts at 'path point' or @@ -484,6 +492,33 @@ class ShapeTests(unittest.TestCase): built([{"shape": "box", "size": [1, 1, 1]}, {"shape": "repeat", "count": 2, "step": [1, 0, 0], "of": {**self.BEAM, "up": [0, 0, 1]}}]) self.assertEqual(len(built([{**self.BEAM, "t": "a"}], [param("a", 0, 1, 0.05)], {"a": 0.04}).counts), 14) + def test_an_extrude_takes_one_up_or_one_for_each_point(self): + """portal-web-across-plane, at its owner. An L of path in the xz plane: one up +y stands the I section's height + (0.1) across the plane; an up for each point, in the plane and across the path there, stands it in the plane, + at the same volume, mitred. The same up given three times is the one up, byte for byte. Mutants U1 (only the + first of the ups is used: the far leg's up runs along its path and the build is refused) and U2 (an array of + ups of another length than the path is admitted).""" + bent = {**self.BEAM, "path": [[0, 0, 0], [0, 0, 1], [1, 0, 1]]} + across, three, inplane = (built([{**bent, "up": up}]) for up in ([0, 1, 0], [[0, 1, 0]] * 3, [[1, 0, 0], [1, 0, -1], [0, 0, -1]])) + self.assertEqual((across.V.tobytes(), across.faces.tobytes()), (three.V.tobytes(), three.faces.tobytes())) + self.assertTrue(closed_and_oriented(inplane)) + self.assertLess(abs(signed_volume(inplane) - signed_volume(across)), VOLUME) + for b, extents in ((across, [1.03, 0.1, 1.03]), (inplane, [1.05, 0.06, 1.05])): # the path's 1 by 1 and half the section either end + self.assertLess(float(np.abs(np.ptp(b.V, axis=0) - extents).max()), PLACED) + ring = inplane.V.reshape(3, 12, 3) + self.assertLess(float(np.abs(ring[:, 1] - ring[:, 0] - [0.0, -0.06, 0.0]).max()), PLACED) # the flange runs across y at every point + expression = built([{**bent, "up": [["a", 0, 0], ["a", 0, "-a"], [0, 0, "-a"]]}], [param("a")]) + self.assertEqual(expression.V.tobytes(), inplane.V.tobytes()) + for up, message in (([[0, 1, 0]] * 2, r"part 'p' shape 0 \(extrude\) up lists 2 vectors for a path of 3 points: give one \[x, y, z\] or one for each point$"), + ([[0, 1, 0]], r"part 'p' shape 0 \(extrude\) up lists 1 vectors for a path of 3 points"), + ([[0, 1, 0], [0, 1, 0], [0, 1]], r"part 'p' shape 0 \(extrude\) up\[2\] must be an array of three"), + ([[0, 1, 0], [0, 1, 0], [0, "q", 0]], r"part 'p' shape 0 \(extrude\) up\[2\]\[1\]: 'q' names 'q'"), + ([], r"part 'p' shape 0 \(extrude\) up must be an array of three")): + with self.assertRaisesRegex(core.KitError, message): + core.check_kit(document([{**bent, "up": up}])) + with self.assertRaisesRegex(core.KitError, r"^kit 't' part 'p' shape 0 \(extrude\): path point 2: up \[1\.0, 0\.0, 0\.0\] runs along the path there"): + built([{**bent, "up": [[1, 0, 0], [1, 0, -1], [1, 0, 0]]}]) + 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])) @@ -763,29 +798,6 @@ class FrameKitTests(unittest.TestCase): cls.kit = core.load_kit("frame") cls.mechanical = core.load_kit("mechanical") - @staticmethod - def seat(b, socket) -> float: - """How far the socket's origin stands off the nearest face that faces its z and holds it: the face's normal by - Newell's sum and the origin inside its outline by crossing count, since a section's cap is not convex (inf - when no face holds it).""" - origin, z = socket["matrix"][:3, 3], socket["matrix"][:3, 2] - best = math.inf - for face in faces_of(b): - p = b.V[face] - normal = np.cross(p, np.roll(p, -1, axis=0)).sum(axis=0) - normal /= np.linalg.norm(normal) - if np.abs(normal - z).max() > 1e-6: - continue - u = np.cross(normal, [1.0, 0.0, 0.0] if abs(normal[0]) < 0.9 else [0.0, 1.0, 0.0]) - q, o = np.stack([p @ u, p @ np.cross(normal, u)], axis=1), np.array([origin @ u, origin @ np.cross(normal, u)]) - a, c = q, np.roll(q, -1, axis=0) - straddles = (a[:, 1] > o[1]) != (c[:, 1] > o[1]) - with np.errstate(divide="ignore", invalid="ignore"): - crossing = a[:, 0] + (o[1] - a[:, 1]) * (c[:, 0] - a[:, 0]) / (c[:, 1] - a[:, 1]) - if int((straddles & (crossing > o[0])).sum()) % 2: - best = min(best, float(abs((origin - p[0]) @ normal))) - return best - def draws(self, name): part = self.kit["parts"][name] rng = random.Random(f"frame.{name}") @@ -824,9 +836,9 @@ class FrameKitTests(unittest.TestCase): self.assertEqual(len(b.sockets), 2) for socket in b.sockets: frame = socket["matrix"][:3, :3] - self.assertLess(np.abs(frame.T @ frame - np.eye(3)).max(), 1e-9) - self.assertLess(abs(np.linalg.det(frame) - 1.0), 1e-9) - self.assertLess(self.seat(b, socket), 1e-9, f"{name}.{socket['name']} {given}") + # exact: a frame part's socket axes are named axes, so its frame is a signed permutation + self.assertEqual((float(np.abs(frame.T @ frame - np.eye(3)).max()), float(np.linalg.det(frame))), (0.0, 1.0)) + self.assertLess(socket_seat(b, socket), SEATED, f"{name}.{socket['name']} {given}") self.assertGreater(socket["size"], 0.0) def test_a_truss_is_two_chords_a_vertical_a_bay_and_a_diagonal_a_bay(self): @@ -838,25 +850,55 @@ class FrameKitTests(unittest.TestCase): self.assertEqual((b.shell_count, len(b.counts)), (2 + (2 * pairs + 1) + 2 * pairs, 6 * (4 * pairs + 3))) bay = 3.2 / (2 * pairs) shells = b.V.reshape(-1, 8, 3) - self.assertTrue(np.allclose(shells[2:2 * pairs + 3].mean(axis=1), [[k * bay, 0, 0.2] for k in range(2 * pairs + 1)], atol=1e-12)) - self.assertTrue(np.allclose(shells[2 * pairs + 3:].mean(axis=1), [[(k + 0.5) * bay, 0, 0.2] for k in list(range(0, 2 * pairs, 2)) + list(range(1, 2 * pairs, 2))], atol=1e-12)) + self.assertLess(float(np.abs(np.array([shells[:2, :, 0].min(axis=1), shells[:2, :, 0].max(axis=1)]).T - [-0.015, 3.215]).max()), PLACED) # each chord runs to the end verticals' outer faces + self.assertLess(float(np.abs(shells[2:2 * pairs + 3].mean(axis=1) - [[k * bay, 0, 0.2] for k in range(2 * pairs + 1)]).max()), PLACED) + self.assertLess(float(np.abs(shells[2 * pairs + 3:].mean(axis=1) - [[(k + 0.5) * bay, 0, 0.2] for k in list(range(0, 2 * pairs, 2)) + list(range(1, 2 * pairs, 2))]).max()), PLACED) rising, falling = shells[2 * pairs + 3], shells[3 * pairs + 3] - self.assertTrue(np.allclose([rising[:4].mean(axis=0), rising[4:].mean(axis=0)], [[0, 0, 0], [bay, 0, 0.4]], atol=1e-12)) - self.assertTrue(np.allclose([falling[:4].mean(axis=0), falling[4:].mean(axis=0)], [[bay, 0, 0.4], [2 * bay, 0, 0]], atol=1e-12)) + self.assertLess(float(np.abs(np.array([rising[:4].mean(axis=0), rising[4:].mean(axis=0)]) - [[0, 0, 0], [bay, 0, 0.4]]).max()), PLACED) + self.assertLess(float(np.abs(np.array([falling[:4].mean(axis=0), falling[4:].mean(axis=0)]) - [[bay, 0, 0.4], [2 * bay, 0, 0]]).max()), PLACED) def test_the_portals_corners_are_mitred(self): """frame-kit-holds: at each corner every point of the section stands as far from the leg's axis as from the - beam's, which is its own distance across the section (unmitred, 0.707 of it from each).""" + beam's, which is its own height in the section (unmitred, 0.707 of it from each): the section's height lies in + the frame's plane. Mutant F1 (a sweep with no mitre).""" part, draws = self.draws("portal") for given in draws[:6]: b = core.build(part, given) env = b.params - across = np.abs(core.profile("I", env["w"], env["h"], min(env["t"], 0.45 * min(env["w"], env["h"])))[:, 0]) + across = np.abs(core.profile("I", env["w"], env["h"], min(env["t"], 0.45 * min(env["w"], env["h"])))[:, 1]) for ring, corner in ((1, [-env["width"] / 2, 0.0, env["height"]]), (2, [env["width"] / 2, 0.0, env["height"]])): off = np.abs(b.V[12 * ring:12 * ring + 12] - corner) - self.assertLess(float(np.abs(off[:, [0, 2]] - across[:, None]).max()), 1e-12, given) + self.assertLess(float(np.abs(off[:, [0, 2]] - across[:, None]).max()), PLACED, given) self.assertEqual((b.shell_count, b.counts.tolist()), (1, [4] * 36 + [12, 12])) + def test_the_portal_stands_its_web_in_plane_and_its_feet_apart(self): + """portal-web-across-plane, frame-layout-unpinned. The I section's height h lies in the xz plane and its flanges + run w across y, at every point of the path: the frame is width + h wide, w deep and height + h / 2 tall, and + its web is the plate on y 0. foot_a stands under the leg at -width / 2 and foot_b under the one at +width / 2, + each on its own end cap. Mutants P1 (one up +y: the web across the plane, the frame h deep) and S9 (foot_b at + -width / 2, on foot_a).""" + part = self.kit["parts"]["portal"] + for given in ({"width": 1.2, "height": 0.9, "w": 0.06, "h": 0.2, "t": 0.01}, {"width": 0.8, "height": 1.5, "w": 0.3, "h": 0.05, "t": 0.004}): + b = core.build(part, given) + width, height, w, h, t = (given[key] for key in ("width", "height", "w", "h", "t")) + self.assertLess(float(np.abs(np.ptp(b.V, axis=0) - [width + h, w, height + h / 2]).max()), PLACED, given) + ring = b.V.reshape(4, 12, 3) + self.assertLess(float(np.abs(ring[:, 1] - ring[:, 0] - [0.0, -w, 0.0]).max()), PLACED, given) # a flange's edge runs across y + self.assertLess(float(np.abs(np.abs(ring[:, [3, 4, 9, 10], 1]) - t / 2).max()), PLACED, given) # the web's four corners, t / 2 off the plane + feet = {s["name"]: s["matrix"] for s in b.sockets} + self.assertEqual(list(feet), ["foot_a", "foot_b"]) + for name, side, cap in (("foot_a", -1.0, ring[0]), ("foot_b", 1.0, ring[3])): + self.assertLess(float(np.abs(feet[name][:3, 3] - [side * width / 2, 0.0, 0.0]).max()), PLACED, name) + self.assertLess(float(np.abs(feet[name][:3, 3] - cap.mean(axis=0)).max()), PLACED, name) # at the middle of its own cap + self.assertEqual((feet[name][:3, 2].tolist(), feet[name][:3, 1].tolist()), ([0.0, 0.0, -1.0], [0.0, 1.0, 0.0])) + + def test_a_beam_is_w_across_x_and_h_along_y(self): + """frame-layout-unpinned. Each of the five beams runs length along +z from 0, w wide across x and h tall along + y, about its axis. Mutant S14 (box_beam's w and h swapped).""" + for name in ("beam_i", "channel", "tee", "angle", "box_beam"): + b = core.build(self.kit["parts"][name], {"length": 0.7, "w": 0.05, "h": 0.2}) + self.assertLess(float(np.abs(np.array([b.V.min(axis=0), b.V.max(axis=0)]) - [[-0.025, -0.1, 0.0], [0.025, 0.1, 0.7]]).max()), PLACED, name) + def test_builds_are_deterministic(self): for part in self.kit["parts"].values(): a, b = core.build(part), core.build(part) @@ -872,8 +914,8 @@ class FrameKitTests(unittest.TestCase): self.assertEqual((mount["size"], end["size"]), (0.09, 0.08)) self.assertIsNone(core.mate_refusal(self.mechanical["socketTypes"], mount, end, self.kit["socketTypes"], names)) seated = core.mate(mount, end) @ end["matrix"] - self.assertLess(float(np.abs(seated[:3, 3]).max()), 1e-12) - self.assertLess(float(np.abs(seated[:3, 2] - [0.0, 0.0, 1.0]).max()), 1e-12) # the beam's end faces the bracket's foot and the beam runs on along -z + self.assertLess(float(np.abs(seated[:3, 3]).max()), PLACED) + self.assertEqual(seated[:3, 2].tolist(), [0.0, 0.0, 1.0]) # the beam's end faces the bracket's foot and the beam runs on along -z wide = core.build(self.kit["parts"]["box_beam"], {"w": 0.2, "h": 0.2}) self.assertIn("it is larger", core.mate_refusal(self.mechanical["socketTypes"], mount, wide.sockets[0], self.kit["socketTypes"], names)) self.assertIn("are of different types", core.mate_refusal(self.mechanical["socketTypes"], bracket.sockets[1], end, self.kit["socketTypes"], names))