diff --git a/surfaces/blender/brokkr_kitbash/plate.py b/surfaces/blender/brokkr_kitbash/plate.py index 8789fad..be0150c 100644 --- a/surfaces/blender/brokkr_kitbash/plate.py +++ b/surfaces/blender/brokkr_kitbash/plate.py @@ -48,7 +48,8 @@ TIE = 1e-9 # areas (m2) and lengths (m) closer than this are equal: th OUTER = 0.97 # clad facets "outer": the facet's normal on the face's normal is over this SHARE = (0.36, 0.64) # where a split panel's cut falls along the facet's longest edge MITER = 0.3 # an inset corner moves at most c / MITER -REFLEX = 1e-6 # an outline corner turning right by more than this (the sine) makes the outline not convex +REFLEX = 1e-6 # a corner turning right by more than this (radians) can reach an edge that is not its own +PARALLEL = 1e-9 # two edges whose normals cross by less than this (the sine) are parallel PANEL_MIN = (0.25, 0.02) # a panel under this share of its facet, or under this many m2, is not made SINK, CHAMFER = 0.02, 0.02 # a panel starts this far under its facet; its far rim is chamfered this much BOLT = 0.028 @@ -60,8 +61,8 @@ class PlateError(ValueError): """The plate table breaks a rule of the format, or a row bounds no solid; the message names the path.""" -class NotConvex(PlateError): - """inset2d met an edge running backwards on an outline that is not convex: half-planes do not bound that one.""" +class NotSimple(PlateError): + """inset2d cannot keep the ring simple: moved in, a corner that turns right reaches an edge that is not its own.""" # --- reading the table ---------------------------------------------------------------------------------------------- @@ -345,18 +346,22 @@ def plane_basis(normal, up=(0.0, 0.0, 1.0), right=None, path: str = "plane"): def inset2d(ring, c: float) -> np.ndarray: """A counter-clockwise outline moved in by c on every edge, and it stands inside the outline. Each corner moves - along its miter to where its two edges' lines, moved in by c, cross. Where every edge still runs forwards - (longer than TIE) those corners are the answer, a sharp one held to c / MITER from where it was unless that - turns the ring the other way at some corner. Otherwise a convex outline gives what its edges' half-planes, each - moved in by c, leave of it, sharp corners and all: empty, shape (0, 2), when that is nothing. An outline that is - not convex is refused there: NotConvex, naming the first point whose edge ran backwards; a slab's row adds its - path.""" + along its miter, where its two edges' lines, moved in, cross. Where no edge runs out of length on the way (TIE) + those corners are the answer, a sharp one held to c / MITER from where it was unless that turns the ring the + other way at some corner. Otherwise the ring is followed in: the edge that runs out first is dropped where it + does and its neighbours meet there, then the next, the sharp corners standing where the lines cross; two edges + left facing each other on one line take the shorter away, two left on one line are one. Empty, shape (0, 2), + when nothing is left. A corner that turns right can reach an edge that is not its own before c: the ring would + meet itself there, and NotSimple names them; a slab's row adds its path. An outline with no right turn over + REFLEX never does.""" ring = np.asarray(ring, dtype=np.float64) count = len(ring) ways = [(ring[(k + 1) % count] - ring[k]) / np.linalg.norm(ring[(k + 1) % count] - ring[k]) for k in range(count)] lefts = [np.array([-e[1], e[0]]) for e in ways] turn = lambda into, away: float(into[0] * away[1] - into[1] * away[0]) # noqa: E731 + move = lambda n0, n1: (n0 + n1) * (2.0 / max(float((n0 + n1) @ (n0 + n1)), 1e-24)) # noqa: E731 the miter over its cosine, with no 1 + cos lost to rounding at a sharp corner met, out = np.empty_like(ring), np.empty_like(ring) + corners = [] # where a corner stood, at what inset, its move per metre, its turn for i in range(count): n0 = lefts[i - 1] miter = n0 + lefts[i] @@ -364,15 +369,68 @@ def inset2d(ring, c: float) -> np.ndarray: miter = miter / length if length > 0 else n0 met[i] = ring[i] + miter * (c / max(float(miter @ n0), 1e-12)) out[i] = ring[i] + miter * (c / max(float(miter @ n0), MITER)) - back = [k for k in range(count) if float((met[(k + 1) % count] - met[k]) @ ways[k]) <= TIE] - if not back and (np.array_equal(met, out) or all( - turn(out[k] - out[k - 1], out[(k + 1) % count] - out[k]) * turn(ways[k - 1], ways[k]) >= 0 for k in range(count))): - return out - if any(turn(ways[k - 1], ways[k]) < -REFLEX for k in range(count)): - raise NotConvex(f"the outline is not convex and, moved in {c}, " + (f"its edge from point {back[0]} runs backwards" if back else "a sharp corner turns it the other way")) - left = list(ring) - for k in range(count): - left = clip(left, ring[k] + lefts[k] * c, -lefts[k]) + corners.append((ring[i], 0.0, move(n0, lefts[i]), math.atan2(turn(ways[i - 1], ways[i]), float(ways[i - 1] @ ways[i])))) + live = list(range(count)) # the edges left, in ring order: corner j stands where live[j - 1] meets live[j] + + def at(j: int, t: float) -> np.ndarray: + q, since, move, _ = corners[j % len(corners)] + return q + move * (t - since) + now = 0.0 + while len(live) > 2: + n = len(live) + first, when = None, math.inf + for j in range(n): # the edge that runs out first, of those with no length left at c + if float((at(j + 1, c) - at(j, c)) @ ways[live[j]]) > TIE: + continue + length, rate = float((at(j + 1, now) - at(j, now)) @ ways[live[j]]), float((corners[(j + 1) % n][2] - corners[j][2]) @ ways[live[j]]) + t = min(now + max(length, 0.0) / -rate, c) if rate < 0 else now + if t < when: + first, when = j, t + for j in range(n): # a corner turning right that reaches another edge before that + if corners[j][3] >= -REFLEX: + continue + for m in range(n): + if m in (j, (j - 1) % n): + continue + edge = live[m] + closing = 1.0 - float(lefts[edge] @ corners[j][2]) + ahead = float(lefts[edge] @ (at(j, now) - ring[edge])) - now + if closing <= 1e-12 or ahead < -TIE: + continue + t = now + max(ahead, 0.0) / closing + if t <= min(when - TIE, c + TIE) and float((at(j, t) - at(m, t)) @ ways[edge]) >= -TIE and float((at(m + 1, t) - at(j, t)) @ ways[edge]) >= -TIE: + raise NotSimple(f"moved in {c}, the outline meets itself: the corner of the edges from points {live[j - 1]} and {live[j]} reaches the edge from point {edge}") + if first is None: + break + now = when + q, angle = at(first, now), corners[first][3] + corners[(first + 1) % n][3] + del live[first], corners[first] + i = first % len(live) # the corner the dropped edge's two ends are now + while len(live) > 2: + n = len(live) + a, b = live[i - 1], live[i] + level = abs(turn(lefts[a], lefts[b])) <= PARALLEL + if not level and angle < math.pi: # a corner: it turns left by less than half a turn + corners[i] = (q, now, move(lefts[a], lefts[b]), angle) + break + if level and float(lefts[a] @ lefts[b]) > 0: # one line: the two edges are one edge, and no corner is between them + del live[i], corners[i] + break + span = float((q - at(i - 1, now)) @ ways[a]), float((at(i + 1, now) - q) @ ways[b]) # facing each other: the shorter is gone + if span[1] < span[0] - TIE: + q, angle = at(i + 1, now), angle + corners[(i + 1) % n][3] + else: + q, angle = at(i - 1, now), angle + corners[i - 1][3] + (corners[(i + 1) % n][3] if span[1] <= span[0] + TIE else 0.0) + i = (i - 1) % n + del live[i], corners[i] + i %= len(live) + if span[1] <= span[0] + TIE: + del live[i], corners[i] + i %= max(len(live), 1) + if len(live) == count: + held = np.array_equal(met, out) or all(turn(out[k] - out[k - 1], out[(k + 1) % count] - out[k]) * turn(ways[k - 1], ways[k]) >= 0 for k in range(count)) + return out if held else met + left = [at(j, c) for j in range(len(live))] if len(live) > 2 else [] left = [p for k, p in enumerate(left) if np.linalg.norm(p - left[k - 1]) > TIE] return np.array(left) if len(left) > 2 else np.zeros((0, 2)) @@ -477,7 +535,7 @@ def _row_points(row: dict, path: str): if slab["taper"] and 2 * slab["taper"] >= _width(drawn): raise PlateError(f"{at}.taper: {slab['taper']} is half the outline's least width ({_width(drawn):.4f}) or more") points = slab_points(origin, a, b, n, ring, slab["thick"], slab["taper"], slab["back"], slab["gap"]) - except NotConvex as error: + except NotSimple as error: raise PlateError(f"{key}: {error}") from None face = (origin, a, b, n) elif "sections" in row: @@ -695,12 +753,22 @@ def clip(poly: list[np.ndarray], point: np.ndarray, normal: np.ndarray) -> list[ return out +def _moved(outline: np.ndarray, c: float) -> np.ndarray: + """inset2d for a ring build makes of a facet: empty where the outline, moved in, would meet itself. No table row + draws such a ring, so there is none to refuse; a slab's outline is refused in _row_points, which check and build + both run.""" + try: + return inset2d(outline, c) + except NotSimple: + return np.zeros((0, 2)) + + def prism(mesh: _Mesh, origin, x, y, z, outline: np.ndarray, depth: float, chamfer: float) -> None: """A block on a counter-clockwise outline, drawn depth along z, its far rim chamfered; the rim is the outline itself where the chamfer leaves it fewer corners.""" c = min(chamfer, 0.45 * depth) n = len(outline) - rim = inset2d(outline, c) if c > 1e-6 else outline + rim = _moved(outline, c) if c > 1e-6 else outline rings = [(outline, 0.0), (outline, depth - c), (rim if len(rim) == n else outline, depth)] verts = [origin + x * q[0] + y * q[1] + z * h for ring, h in rings for q in ring] faces = [list(reversed(range(n))), [2 * n + k for k in range(n)]] @@ -719,10 +787,10 @@ def hex_bolt(mesh: _Mesh, origin, x, y, z, r: float, depth: float) -> None: def panel(panels: _Mesh, bolts: _Mesh, polygon: list[np.ndarray], out: np.ndarray, lift: float, inset: float, bolt_r: float) -> bool: - """A raised panel on a flat convex polygon: the polygon moved in inset on every edge, standing lift over it from - SINK below, its far rim chamfered; a bolt inside each of its corners, 3.2 bolt_r in, none where that leaves no - ring, and bolts whose centres stand under 2 bolt_r apart made one at their middle. False for a polygon too small - for a panel, or one the inset leaves nothing of.""" + """A raised panel on a flat polygon, a facet or a part of one: the polygon moved in inset on every edge, + standing lift over it from SINK below, its far rim chamfered; a bolt inside each of its corners, 3.2 bolt_r in, + none where that leaves no ring, and any two bolts whose centres stand under 2 bolt_r apart made one at their + middle. False for a polygon too small for a panel, or one the inset leaves nothing of or cannot keep simple.""" pts = np.array(polygon) centre = pts.mean(axis=0) normal = np.cross(pts - centre, np.roll(pts, -1, axis=0) - centre).sum(axis=0) @@ -733,20 +801,22 @@ def panel(panels: _Mesh, bolts: _Mesh, polygon: list[np.ndarray], out: np.ndarra pts, normal = pts[::-1], -normal x, y = _stand(normal) flat = np.column_stack(((pts - centre) @ x, (pts - centre) @ y)) - inner = inset2d(flat, inset) + inner = _moved(flat, inset) if _area2(inner) < PANEL_MIN[0] * _area2(flat) or _area2(inner) < PANEL_MIN[1]: return False prism(panels, centre - normal * SINK, x, y, normal, inner, lift + SINK, CHAMFER) - heads = list(inset2d(inner, 3.2 * bolt_r)) - k = 0 - while k < len(heads) > 1: # neighbours in ring order, the first pair first - after = (k + 1) % len(heads) - if np.linalg.norm(heads[after] - heads[k]) < 2 * bolt_r: - heads[k] = (heads[k] + heads[after]) / 2 - del heads[after] - k = 0 - else: + heads = list(_moved(inner, 3.2 * bolt_r)) + reach, k = 1, 0 + while reach <= len(heads) // 2: # the pair fewest corners apart round the ring first, of those the first + other = (k + reach) % len(heads) + if np.linalg.norm(heads[other] - heads[k]) < 2 * bolt_r: + heads[k] = (heads[k] + heads[other]) / 2 + del heads[other] + reach, k = 1, 0 + elif k + 1 < len(heads): k += 1 + else: + reach, k = reach + 1, 0 for q in heads: hex_bolt(bolts, centre + x * q[0] + y * q[1] + normal * (lift + 0.3 * bolt_r), x, y, normal, bolt_r, 0.6 * bolt_r) return True diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index eda6812..e83da17 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -1051,20 +1051,38 @@ go to the edge whose middle is greater by x, y, z. Then every chosen facet draws quarter of the part's area or under 0.02 m2; it is a prism from 0.02 below the facet to its lift above, its far rim chamfered 0.02 (not chamfered where the chamfer would cost the rim a corner). A hexagonal bolt of radius `bolt_r` stands inside each panel corner, on the panel's outline moved in 3.2 `bolt_r`: a panel with no room for -that ring has no bolts, and bolts whose centres would stand under 2 `bolt_r` apart are one bolt at their middle -(neighbours in ring order, the first such pair first, until none is left). +that ring has no bolts, and any two bolts whose centres would stand under 2 `bolt_r` apart are one bolt at their +middle, in the first one's place in the ring. Neighbours in ring order are read first, from the first corner, then +pairs one corner further apart round the ring, and after each joining the reading starts again; so no two bolt +heads of a panel overlap, neighbours or not. One inset, `inset2d`, makes every such ring: a slab's `gap` and `taper`, a panel's outline, its rim and its bolt -ring. What it returns stands inside the outline. It moves each corner along its miter to where its two edges' -lines, moved in, cross. Where every edge then still runs forwards, those corners are the ring, a sharp one held to -the distance / 0.3 from where it was (unless that would turn the ring the other way at some corner): the corner -move alone, to the byte. Where an edge runs backwards, its two ends passed over each other, a convex outline -gives what its edges' half-planes, each moved in, leave of it: the edges with no room are gone, the sharp corners -stand where the lines cross, and where nothing is left the ring is empty. So a sharp corner jumps inward, from -the 0.3 limit to the crossing, at the distance where the ring first loses an edge. A slab's outline need not be -convex: with every edge running forwards it is moved corner by corner; with one running backwards `check` refuses -the row at `slab.outline` (or `slab.corners`), naming the first point whose edge did, because half-planes do not -bound such an outline. +ring. What it returns stands inside the outline. It moves each corner along its miter, where its two edges' +lines, moved in, cross. Where no edge runs out of length on the way, those corners are the ring, a sharp one held +to the distance / 0.3 from where it was (unless that would turn the ring the other way at some corner): the +corner move alone, to the byte. Otherwise the ring is followed in, as a straight skeleton's front is: the edge +that runs out first is dropped where it does and its two neighbours meet there, then the next, and the sharp +corners stand where the lines cross. Two edges left facing each other on one line (a tab's sides when its end has +run out) take the shorter away, both when they are equal, and two left on one line are one edge. Where nothing is +left the ring is empty. For a convex outline that is what its edges' half-planes, each moved in, leave of it. + +A held corner steps. While no edge has run out, a corner sharper than 35 degrees (the sine of its half angle +under 0.3) stands distance / 0.3 along its miter; from the distance where the ring first loses an edge it stands +where its lines cross, distance / that sine along the same miter. The step is their difference and no more: on a +10.5 degree tip that loses its first edge at 0.109, from 0.36 to 1.19 m from the outline's corner. It is the +skeleton's own corner the step lands on, and it is inside the outline before and after; a facet near that +distance changes its panel by the step for a small change of `inset`. + +An outline need not be convex: a slab's may be drawn so, and facets within 0.5 degrees of each other are one +facet whose outline can turn right. Its corners that turn right move in too, faster the sharper they are (the +distance / the sine of half the corner), and such a corner can reach an edge that is not its own: a neck between +two parallel edges closes at half its width. From there the ring would meet itself and be two rings or none, and +`inset2d` refuses it (`NotSimple`, a `PlateError`), naming the corner's two edges and the edge it reaches. For a +slab's `gap` or `taper` that is the row's refusal at `slab.outline` (or `slab.corners`), from `check` and from +`build` in the same words, since both make the slab's points the same way. A facet is no row's drawing: where +the inset of a facet or of a facet's part would meet itself, that part takes no panel; where the bolt ring of a +panel would, the panel takes no bolts; where the rim would, the rim is the outline. So `build` refuses nothing +that `check` passed. ### Anchors @@ -1096,7 +1114,8 @@ Every refusal is a `PlateError` (a `ValueError`) that names the path, as `plates `plates[0].clad.seed`: a schema that is not `brokkr.plates.v0`; an unknown key anywhere; a row with no solid form or two; a name built twice; a number that is not finite; an outline under 3 points or over 64, one that crosses itself, repeats a point or has zero area; `thick`, `taper`, `back` or `gap` outside 0.001 to 2, 0 to 0.5, 0.1 to -1.5 and 0 to 0.5; a `taper` of half the outline's least width or more; corners that are not a plate; faces that +1.5 and 0 to 0.5; a `taper` of half the outline's least width or more; a `gap` or `taper` at which an outline +that is not convex would meet itself; corners that are not a plate; faces that bound nothing; points in one plane; a pair of seeds on a one-sided row, an equal pair, or no seed; an `up` along the normal; a fit on a row with no face; an unknown fit kind; two anchors of one name in a row. @@ -1123,10 +1142,18 @@ and paladin's `Thigh.Outer`, have a panel whose outline dropped a corner, and th no truth. What holds every ring instead: every `inset2d` call the three fixtures make at both sides (812) stands inside its outline. The 6 on a slab outline that is not convex are the corner move, every corner the distance clear of every edge; 24 hold a sharp corner at the 0.3 limit with every edge running forwards; the other 782 -equal, within 1e-12 m, the outline's half-planes moved in and clipped (37 of them an edge or more short, 22 -empty). 3,000 drawn convex rings are held the same way, and every bolt of 104 blade plates (tips of 14 to 32 -degrees) stands whole on its plate. No panel ring or bolt ring of any plate at either side turns right or -crosses, and no two bolt heads of a panel overlap. +equal, within 1e-12 m, the outline's half-planes moved in and clipped by the test's own clipper (37 of them an +edge or more short, 22 empty). 3,000 drawn convex rings are held the same way, and every bolt of 104 blade plates +(tips of 14 to 32 degrees) stands whole on its plate. No panel ring or bolt ring of any plate at either side turns +right or crosses, and no two bolt heads of a panel overlap; nor do any two on 3,591 blade plates (tips of 8 to 44 +degrees), 50 of which kept such a pair while only neighbours were joined. + +No fixture facet turns right, so 1,500 drawn sheets hold that case: 5 to 9 points up to 12 mm off one plane, whose +top facets the hull makes one. Each passes `check` and builds. Of their 519 rings that turn right, 84 lose an +edge, and each of those stands inside its outline without crossing, the distance clear of every edge, each of its +edges along one of the outline's in the outline's order; 2, both bolt rings, would meet themselves, and their +panels stand bare. A two-lobed facet with a neck holds the rest: no panel at an inset over half the neck, a bare +panel under it, and a prism whose rim would meet itself keeps its outline for a rim. The same test builds the three fixtures to one sha256 of every coordinate rounded to 1e-9 m and every face, pinned from Starfire (Windows 11, numpy 2.5.4) and Yggdrasil (Debian 13, numpy 2.2.4 on the system LAPACK). The diff --git a/surfaces/blender/tests/test_plate.py b/surfaces/blender/tests/test_plate.py index 99b1a94..e331030 100644 --- a/surfaces/blender/tests/test_plate.py +++ b/surfaces/blender/tests/test_plate.py @@ -153,12 +153,41 @@ def within(point, ring): return bool(np.sum(a[over, 0] + (point[1] - a[over, 1]) * (b[over, 0] - a[over, 0]) / (b[over, 1] - a[over, 1]) > point[0]) % 2) -def blade(tip, length, rear, bolt_r=0.03): - """A blade plate 0.4 thick, its tip at the origin `tip` degrees wide, `rear` across its far end, clad on top.""" +def blade_top(tip, length, rear): + """A blade's outline: its tip at the origin `tip` degrees wide, widest at 0.7 of its length, `rear` across its far end.""" half = math.tan(math.radians(tip / 2)) * 0.7 * length - top = [(0, 0), (0.7 * length, -half), (length, -rear / 2), (length, rear / 2), (0.7 * length, half)] - clad = {"mat": "c", "facets": [{"n": [0, 0, 1], "cos": 0.6}], "min_area": 0.01, "lifts": [0.045, 0.075], "inset": 0.11, "gap": 0.05, "split": 99, "seed": 1, "bolt_r": bolt_r} - return doc(row("Fin", clad=clad, points=[[x, y, z] for z in (0, 0.4) for x, y in top])) + return [(0, 0), (0.7 * length, -half), (length, -rear / 2), (length, rear / 2), (0.7 * length, half)] + + +def blade(tip, length, rear, inset=0.11, bolt_r=0.03): + """A blade plate 0.4 thick on blade_top, clad on top.""" + clad = {"mat": "c", "facets": [{"n": [0, 0, 1], "cos": 0.6}], "min_area": 0.01, "lifts": [0.045, 0.075], "inset": inset, "gap": 0.05, "split": 99, "seed": 1, "bolt_r": bolt_r} + return doc(row("Fin", clad=clad, points=[[x, y, z] for z in (0, 0.4) for x, y in blade_top(tip, length, rear)])) + + +def followed(made, ring, c): + """Whether a ring is its outline moved in by c, edges dropped or not: it stands inside the outline and does not + cross, c clear of every edge of it, and each of its edges runs along one of the outline's, c inside that edge's + line, in the outline's order.""" + made, ring = np.asarray(made, dtype=np.float64), np.asarray(ring, dtype=np.float64) + if not all(within(p, ring) for p in made) or plate._crosses(made) or float(clear(made, ring).min()) < c - 1e-9: + return False + ways = [(np.roll(r, -1, axis=0) - r) / np.linalg.norm(np.roll(r, -1, axis=0) - r, axis=1)[:, None] for r in (made, ring)] + along = [[j for j in range(len(ring)) if ways[0][i] @ ways[1][j] > 1 - 1e-9 and abs(float((made[i] - ring[j]) @ (-ways[1][j][1], ways[1][j][0])) - c) < 1e-9] + for i in range(len(made))] + took = [] + for found in along: # of two outline edges on one line, the next one round + if not found: + return False + took.append(next((j for j in found if took and j > took[-1]), found[0])) + return sum(took[i] < took[i - 1] for i in range(len(took))) == 1 + + +def sheet(top, inset=0.11, bolt_r=0.03): + """A sheet 0.3 thick under `top`, its top facets clad: points that stand a little off one plane make top facets + within MERGE of each other, which the hull makes one facet that need not be convex.""" + clad = {"mat": "c", "facets": [{"n": [0, 0, 1], "cos": 0.6}], "min_area": 0.01, "lifts": [0.045, 0.075], "inset": inset, "gap": 0.05, "split": 99, "seed": 1, "bolt_r": bolt_r} + return doc(row("Fin", clad=clad, points=[list(p) for p in top] + [[x, y, z - 0.3] for x, y, z in top])) def turns(ring): @@ -248,20 +277,55 @@ class InsetTests(unittest.TestCase): self.assertLess(apart2(made, half_planes(ring, c)), 1e-12) self.assertEqual((held, dropped, empty), HELD) - def test_an_outline_that_is_not_convex_is_moved_or_refused(self): + def test_an_outline_that_is_not_convex_is_followed_in(self): tab = [[0, 0], [4, 0], [4, 2], [2.2, 2], [2.2, 2.8], [1.8, 2.8], [1.8, 2], [0, 2]] # a tab 0.4 wide on a 4 by 2 body - for c in (0.05, 0.15): + for c in (0.05, 0.15, 0.1999): made = plate.inset2d(tab, c) self.assertEqual(made.tobytes(), corner_move(tab, c)[0].tobytes()) - self.assertGreater(float(clear(made, tab).min()), c - 1e-12) - self.assertTrue(all(within(p, tab) for p in made) and not plate._crosses(made)) - with self.assertRaises(plate.NotConvex) as caught: - plate.inset2d(tab, 0.25) - self.assertIn("its edge from point 4 runs backwards", str(caught.exception)) + self.assertTrue(followed(made, tab, c)) + arm = [[0, 0], [4, 0], [4, 2], [0.4, 2], [0.4, 5], [0, 5]] # an arm 0.4 wide up the body's left side + self.assertEqual(len(plate.inset2d(arm, 0.1999)), 6) + for outline in (tab, arm): # the tab's end runs out at 0.2: its sides face each other and go, the body's top is one edge again + for c in (0.2001, 0.25, 0.9): + made = plate.inset2d(outline, c) + self.assertLess(apart2(made, [[c, c], [4 - c, c], [4 - c, 2 - c], [c, 2 - c]]), 1e-12) + self.assertTrue(len(made) == 4 and followed(made, outline, c)) + self.assertEqual(plate.inset2d(outline, 1.0001).shape, (0, 2)) + barb = [[0, 0], [6, 0], [2, 0.5], [0, 2]] # a sharp tip whose upper edge ends at a corner turning right + self.assertEqual(plate.inset2d(barb, 0.2).tobytes(), corner_move(barb, 0.2)[0].tobytes()) + made = plate.inset2d(barb, 0.3) # that edge has run out: its two neighbours bound a triangle + self.assertLess(apart2(made, half_planes([[0, 0], [8 / 3, 0], [0, 2]], 0.3)), 1e-12) + self.assertTrue(len(made) == 3 and followed(made, barb, 0.3)) straight = [[0, 0], [3 * 0.3, 3 * 0.3 * 0.3], [3, 3 * 0.3], [3, 3 * 0.3 + 0.2], [0, 1]] # its second point is on a straight run - self.assertTrue(-1e-12 < float(turns(straight)[1]) < 0) # and turns right by a rounding: that is no outline to refuse - self.assertEqual(len(plate.inset2d(straight, 0.15)), 3) - self.assertLess(apart2(plate.inset2d(straight, 0.15), half_planes(straight, 0.15)), 1e-12) + self.assertTrue(-1e-12 < float(turns(straight)[1]) < 0) # and turns right by a rounding: no corner that can reach an edge + made = plate.inset2d(straight, 0.15) # its short edge runs out; the point on the run stays a point on the run + self.assertTrue(len(made) == 4 and followed(made, straight, 0.15)) + self.assertLess(apart2(made[[0, 2, 3]], half_planes(straight, 0.15)), 1e-12) + + def test_an_outline_that_would_meet_itself_is_refused_at_half_its_neck(self): + neck = [[0, 0], [2, 0], [2, 0.9], [4, 0.9], [4, 0], [6, 0], [6, 2], [4, 2], [4, 1.1], [2, 1.1], [2, 2], [0, 2]] # two lobes, a neck 0.2 wide + for c in (0.05, 0.0999): + made = plate.inset2d(neck, c) + self.assertEqual(made.tobytes(), corner_move(neck, c)[0].tobytes()) + self.assertTrue(followed(made, neck, c)) + for c in (0.1001, 0.15, 0.3): + with self.assertRaises(plate.NotSimple) as caught: + plate.inset2d(neck, c) + self.assertEqual(str(caught.exception), f"moved in {c}, the outline meets itself: the corner of the edges from points 1 and 2 reaches the edge from point 8") + hook = [[0, -2], [3, -2], [3, 5], [0, 5], [0, 2.2], [2, 1.5], [0, 0.8]] # a corner turning right, 1 from the far side + reach = 1 / (1 + math.hypot(2, 0.7) / 0.7) # it moves in 3.03 for the far side's 1: they meet at 0.2483 + self.assertTrue(followed(plate.inset2d(hook, reach - 1e-4), hook, reach - 1e-4)) + self.assertRaises(plate.NotSimple, plate.inset2d, hook, reach + 1e-4) + + def test_a_held_corner_steps_to_the_crossing_where_the_ring_first_loses_an_edge(self): + """The step kitbash.md states: c / MITER from the outline's corner while every edge has length, c over the sine + of half the corner from there on, and never out of the outline.""" + top, sine = blade_top(10.5, 2.43, 0.2), math.sin(math.radians(10.5 / 2)) + for c, corners, tip in ((0.05, 5, 0.05 / plate.MITER), (0.108, 5, 0.108 / plate.MITER), (0.109, 4, 0.109 / sine), (0.15, 4, 0.15 / sine)): + made = plate.inset2d(top, c) + self.assertEqual(len(made), corners) + self.assertLess(abs(float(np.linalg.norm(made, axis=1).min()) - tip), 1e-12) + self.assertGreater(float(depths(made, top).min()), 0) def test_every_inset_of_the_fixtures_is_what_the_half_planes_leave(self): inset, calls = plate.inset2d, [] @@ -366,11 +430,20 @@ class CheckTests(unittest.TestCase): def test_outline_of_zero_area(self): self.refused(doc(row(slab=dict(SLAB, outline=[[0, 0], [1, 0], [2, 0]]))), "plates[0].slab.outline: the outline has zero area") - def test_an_outline_not_convex_that_the_gap_or_the_taper_collapses(self): + def test_an_outline_not_convex_is_refused_where_the_gap_or_the_taper_makes_it_meet_itself(self): tab = [[0, 0], [4, 0], [4, 2], [2.2, 2], [2.2, 2.8], [1.8, 2.8], [1.8, 2], [0, 2]] - self.refused(doc(row(slab=dict(SLAB, outline=tab, gap=0.25))), "plates[0].slab.outline: the outline is not convex and, moved in 0.25, its edge from point 4 runs backwards") - self.refused(doc(row(slab=dict(SLAB, outline=tab, gap=0.15, taper=0.06))), "plates[0].slab.outline: the outline is not convex and, moved in 0.06,") - plate.check(doc(row(slab=dict(SLAB, outline=tab, gap=0.15)))) + neck = [[0, 0], [2, 0], [2, 0.9], [4, 0.9], [4, 0], [6, 0], [6, 2], [4, 2], [4, 1.1], [2, 1.1], [2, 2], [0, 2]] + meets = "the outline meets itself: the corner of the edges from points 1 and 2 reaches the edge from point 8" + for document, message in ((doc(row(slab=dict(SLAB, outline=neck, gap=0.15))), f"plates[0].slab.outline: moved in 0.15, {meets}"), + (doc(row(slab=dict(SLAB, outline=neck, gap=0.05, taper=0.06))), f"plates[0].slab.outline: moved in 0.06, {meets}")): + self.refused(document, message) + with self.assertRaises(plate.PlateError) as caught: # build refuses what check does, in the same words + plate.build(document) + self.assertEqual(str(caught.exception), message) + plate.check(doc(row(slab=dict(SLAB, outline=neck, gap=0.0999, taper=0.0)))) + for gap in (0.15, 0.25): # the tab is gone at 0.2: the slab is the body's + (entry,) = plate.build(plate.check(doc(row(slab=dict(SLAB, outline=tab, gap=gap, taper=0.0))))) + self.assertEqual(entry["report"]["corners"], 12 if gap < 0.2 else 8) def test_slab_ranges(self): for key, low, high in (("thick", 0.0005, 2.5), ("taper", -0.01, 0.6), ("back", 0.05, 1.6), ("gap", -0.01, 0.6)): @@ -637,6 +710,18 @@ class CladTests(unittest.TestCase): made = bolts.done()[0].reshape(-1, 12, 3).mean(axis=1)[:, :2] self.assertLess(apart2(made, np.array([[1.5, 40], [-18, 40], [-18, 9], [0.95, 0]]) * r), 1e-12) + def test_two_near_heads_that_are_not_neighbours_are_one(self): + """Kills: the merge reading neighbours in ring order only (it leaves the second and the fourth 1.8 r apart).""" + r = 0.06 + heads = np.array([[2.2, 0], [0, 0.9], [-2.2, 0], [0, -0.9]]) * r # neighbours 2.38 r apart, the second and the fourth 1.8 r + outline = corner_move(heads, -(0.05 + 3.2 * r))[0] + self.assertLess(apart2(plate.inset2d(plate.inset2d(outline, 0.05), 3.2 * r), heads), 1e-12) + bolts = plate._Mesh() + self.assertTrue(plate.panel(plate._Mesh(), bolts, [np.array([x, y, 0.0]) for x, y in outline], np.array([0.0, 0.0, 1.0]), 0.04, 0.05, r)) + made = bolts.done()[0].reshape(-1, 12, 3).mean(axis=1)[:, :2] + self.assertLess(apart2(made, np.array([[2.2, 0], [0, 0], [-2.2, 0]]) * r), 1e-12) + self.assertLess(float(np.abs(made[1]).max()), 1e-12) # the one made of two stands where the first of them stood in the ring + def test_every_bolt_of_a_blade_plate_stands_on_it(self): """Kills: the half-planes left out (10 of these blades then put a bolt off the plate, the worst 3.3 m).""" entry = plate.build(blade(20, 1.5, 0.3), 1)[0] # its bolt ring is narrower than the bolts stand in: no ring, no bolts @@ -654,6 +739,72 @@ class CladTests(unittest.TestCase): self.assertEqual(bolted, 104) self.assertGreater(least, 0.03) # a head's corners reach bolt_r: every head whole on its facet + def test_no_two_bolt_heads_of_a_blade_plate_overlap(self): + """3,591 blades, tips of 8 to 44 degrees. Kills: the merge reading neighbours in ring order only (50 of them + then keep two heads under 2 bolt_r apart, the nearest 0.27).""" + bolted, heads, nearest = 0, 0, math.inf + for tip in range(8, 46, 2): + for length in (0.5, 0.8, 1.0, 1.5, 2.0, 3.0, 4.0): + for rear in (0.03, 0.06, 0.1, 0.15, 0.2, 0.3, 0.4, 0.6, 0.8): + for inset in (0.05, 0.11, 0.2): + at = plate.build(blade(tip, length, rear, inset), 1)[0]["bolts"][0].reshape(-1, 12, 3).mean(axis=1) + bolted, heads = bolted + (len(at) > 0), heads + len(at) + if len(at) > 1: + nearest = min(nearest, float((np.linalg.norm(at[:, None] - at[None], axis=2) + 9 * np.eye(len(at))).min())) + self.assertEqual((bolted, heads), (1857, 7446)) + self.assertGreaterEqual(nearest, 2 * 0.03) + + def test_a_facet_that_is_not_convex_is_built_as_check_says(self): + """Top facets within MERGE of each other are one facet, and that one need not be convex. Soul's table, then + 1,500 drawn like it. Kills: an inset that refuses such a facet (build then raises on 77 sheets check passed); + panel taking that refusal for the table's (the 3 rings that would meet themselves raise).""" + soul = [[0.46231115288947655, -0.7464122608740515, 0.005076090953713479], [0.48625943944459826, -0.5771679834143375, 0.006610213759068515], + [0.7933326463565815, 0.3201403232773634, 0.009341146944706617], [-0.06168868858561849, 0.6415607593647952, 0.006680572413020032], + [-0.5231073349097417, 0.9203597671588255, 0.00622360127002797], [0.8223018952005992, -0.9577282429612575, 0.0028711637754610976], + [0.7686109712617415, -0.6216304824437804, 0.007801596935861264]] + (entry,) = plate.build(plate.check(sheet(soul)), 1) + self.assertEqual(entry["report"], {"corners": 9, "facets": 8, "panels": 1, "bolts": 3}) + inset, calls = plate.inset2d, [] + + def spy(ring, c): + calls.append([np.array(ring, dtype=np.float64), c, None]) + calls[-1][2] = inset(ring, c) + return calls[-1][2] + draw, tally = random.Random(5), {"reflex": 0, "short": 0, "met": 0, "panels": 0, "bolts": 0} + with mock.patch.object(plate, "inset2d", spy): + for _ in range(1500): + top = [[draw.uniform(-1, 1), draw.uniform(-1, 1), draw.uniform(0, 0.012)] for _ in range(draw.randint(5, 9))] + del calls[:] + (entry,) = plate.build(plate.check(sheet(top, draw.choice((0.05, 0.11, 0.2)))), 1) + tally["panels"], tally["bolts"] = tally["panels"] + entry["report"]["panels"], tally["bolts"] + entry["report"]["bolts"] + at = entry["bolts"][0].reshape(-1, 12, 3).mean(axis=1) + self.assertTrue(len(at) < 2 or float((np.linalg.norm(at[:, None] - at[None], axis=2) + 9 * np.eye(len(at))).min()) >= 2 * 0.03) + for ring, c, made in calls: + if float(turns(ring).min()) < -plate.REFLEX: + tally["reflex"], tally["met"] = tally["reflex"] + 1, tally["met"] + (made is None) + if made is not None and len(made) != len(ring): + tally["short"] += 1 + self.assertTrue(not len(made) or followed(made, ring, c)) + self.assertEqual(tally, {"reflex": 519, "short": 84, "met": 2, "panels": 1991, "bolts": 5946}) + + def test_a_ring_that_would_meet_itself_is_left_out_and_not_refused(self): + """Kills: panel or prism letting NotSimple through (build would refuse what check passed).""" + neck = [[0, 0], [2, 0], [2, 0.9], [4, 0.9], [4, 0], [6, 0], [6, 2], [4, 2], [4, 1.1], [2, 1.1], [2, 2], [0, 2]] # two lobes, a neck 0.2 wide + facet, up = [np.array([x, y, 0.0]) for x, y in neck], np.array([0.0, 0.0, 1.0]) + self.assertRaises(plate.NotSimple, plate.inset2d, neck, 0.15) + panels, bolts = plate._Mesh(), plate._Mesh() + self.assertFalse(plate.panel(panels, bolts, facet, up, 0.04, 0.15, 0.03)) # the panel's outline would: no panel + self.assertEqual((len(panels.verts), len(bolts.verts)), (0, 0)) + self.assertTrue(plate.panel(panels, bolts, facet, up, 0.04, 0.05, 0.03)) # its neck is 0.1 wide and the bolts stand 0.096 in: a bare panel + self.assertEqual((len(panels.verts), len(bolts.verts)), (36, 0)) + self.assertTrue(plate.panel(plate._Mesh(), bolts, facet, up, 0.04, 0.001, 0.03)) # a neck 0.198 wide: the bolts' ring keeps 0.006 of it, + self.assertEqual(len(bolts.verts), 12 * 10) # and its heads across each end of the neck are one: 10 of 12 + thin = np.array([[x, y if y in (0, 2) else 1 + (y - 1) * 0.15] for x, y in neck]) # a neck 0.03 wide: the rim, 0.02 in, would + mesh = plate._Mesh() + plate.prism(mesh, np.zeros(3), *np.eye(3), thin, 0.1, 0.02) + V = mesh.done()[0] + self.assertTrue(np.array_equal(V[24:, :2], thin) and np.array_equal(V[12:24, :2], thin)) + def test_a_rim_the_chamfer_leaves_fewer_corners_is_the_outline(self): mesh, axes = plate._Mesh(), np.eye(3) plate.prism(mesh, np.zeros(3), *axes, np.array([[0, 0], [1, 0], [1, 1], [0.502, 1.2], [0.498, 1.2], [0, 1]], dtype=float), 0.1, 0.02)