brokkr_kitbash.hose: a search's polyline is a seed, refined in continuous space; other grid origins and half the step before a refusal; too stiff only where proven (cut kit-hose, h3)

route.tangents gives each corner its floor's tangent before a neighbour gets more, and the pin's corner the
tangent of its sharpest roll (sharpest_turn, exact over a range; passes sizes a bin's bend by it). route.relax
drops, moves and adds a seed's free vertices until every segment has the straight its corners take (strain),
each change proven clear by the oracle. hose searches each leg on three grid origins and then at half the step,
names what it tried when it refuses, and says too stiff only where route.leaves proves no curve of the floor
radius leaves a port.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-02 19:21:33 +01:00
commit edbd04f1ef
4 changed files with 373 additions and 91 deletions

View file

@ -50,12 +50,14 @@ object rewrites the mesh in place, leaving the object, its cutters, ribs, Boolea
evaluates nothing: Blender's own update after the action evaluates the plate once.
hose routes a bundle of hoses between two sockets. route.py owns the path (legs searched on a voxel grid of the
scene's clearance, pulled taut, sagged a little, filleted, verified, and turned through the rolls of the one pin it may
cross) and core.sweep owns every tube, ferrule and clamp. A hose is a bake of the scene at the call: posing or moving a
scene's clearance and pulled taut, which is a seed; refined in continuous space where its corners lack straight, sagged a
little, filleted, verified, and turned through the rolls of the one pin it may cross; other grid origins and half the
step are searched before a route is refused) and core.sweep owns every tube, ferrule and clamp. A hose is a bake of the scene at the call: posing or moving a
part leaves it stale until hose runs again on its name. It is one object: where it crosses a pin it is meant to be
skinned between the bones on either side, and this package writes no weights. kit_hose on it is the request, kept as
a record: hose is its one writer, and the one thing read back from it is which two parts a hose joins, by a later hose
that crosses the same pin (it bends with the pin, so it is measured as an obstacle where it stands and not across the rolls).
that crosses the same pin (it bends with the pin, so it is measured as an obstacle where it stands and not across the rolls:
follow-up aetheria-release:follow_up:hose-motion-clearance-from-skinning owes that check).
Connections are a tree. A loop (a brace from one branch to another) is closed by a closure: three ID properties
on the closing part, kit_close_socket, kit_close_to (a pointer to the other part) and kit_close_to_socket. close
@ -101,6 +103,8 @@ HOSE = "kit_hose" # on a hose: the request it was routed from, as JSON; its pre
HOSE_CLAMPS = 8 # clamps in one hose: each is one more leg to search
HOSE_VOXELS = 2 ** 19 # voxels of one leg's search box: 1.8 s of capped nearest-face queries at 3.4 us each
HOSE_MARGIN = 0.25 # metres a leg's search box reaches beyond its two ends: the room a way around an obstacle between them has
HOSE_OFFSETS = ((0.0, 0.0, 0.0), (0.5, 0.5, 0.5), (0.31, 0.67, 0.13)) # of a step: the grid origins a leg's seed is searched on before a route is refused
HOSE_FINEST = 0.005 # metres: the least step, and the least a refused step is halved to for one more round of seeds
HOSE_SEGMENTS = 12 # sides of a hose, a ferrule and a clamp's pad
ROLL_STEP = 5.0 # degrees between the rolls of a joint's range that hose measures first: the step an assembly's clearance is read at
ROLL_FINEST = 0.3 # degrees: the half width under which a bin of rolls that falls short is refused instead of halved (5 degrees halved 4 times)
@ -1489,42 +1493,45 @@ class BROKKR_KITBASH_OT_hose(PolishOperator):
rest, moved, through = self.trees(start["depsgraph"], hose, pin and pin["child"], kits)
reach = need + 2.0 * floor + self.step
roomy = route.BEND * floor # room beyond need a leg is searched with: what the arc of a quarter turn at the floor takes
occupied = self.reader((rest, moved, through), need + roomy + route.REACH * self.step)
far, far_rest, far_moved = self.reader((rest, moved, through), reach), self.reader((rest,), reach), self.reader((moved,), reach)
room = lambda a, b: route.room(a, b, far, need) # noqa: E731
exempt = max(lead, need) # a bundle wider than its lead stands on its own port's face that far
stand = sizes["envelope"] + self.clearance + r # a clamped bundle's centre line above the socket's face: its pad is one radius thick
held = 2.0 * 2.0 * r + floor
ends = [port["matrix"][:3, 3] + port["matrix"][:3, 2] * (lead + floor) for port in (start, end)] # a leg starts where the first bend has its floor's length of straight behind it
stops = [("clamp", f"clamps[{index}]", clamp["matrix"][:3, 3] + clamp["matrix"][:3, 2] * stand, clamp["matrix"][:3, 1]) for index, clamp in enumerate(clamps)]
if pin is not None:
stops.insert(pin["before"], ("pin", "the pin", pin["point"], None))
sized = {"need": need, "floor": floor, "lead": lead, "exempt": exempt, "roomy": roomy, "held": 2.0 * 2.0 * r + floor, "kept": 4.0 * 2.0 * r, # a clamp keeps 2 outside diameters of straight each side of its point
"far": far, "far_rest": far_rest, "far_moved": far_moved, "room": lambda a, b: route.room(a, b, far, need), "pin": pin, "joint": joint}
steps = [self.step] + [self.step / 2.0] * (self.step / 2.0 >= HOSE_FINEST)
shaped, tried, blocked = None, [], None
try:
ends = [port["matrix"][:3, 3] + port["matrix"][:3, 2] * (lead + floor) for port in (start, end)] # a leg starts where the first bend has its floor's length of straight behind it
stops = [("clamp", f"clamps[{index}]", clamp["matrix"][:3, 3] + clamp["matrix"][:3, 2] * stand, clamp["matrix"][:3, 1]) for index, clamp in enumerate(clamps)]
if pin is not None:
stops.insert(pin["before"], ("pin", "the pin", pin["point"], None))
legs, at, came = [], ends[0], "start"
for kind, label, point, y in stops + [("end", "end", ends[1], None)]:
into, out = point, point
if kind == "clamp":
into, out = sorted((point - y * held, point + y * held), key=lambda p: float(np.linalg.norm(p - at)))
name = f"leg {len(legs) + 1} ({came} to {label})"
for pad in (roomy, 0.0): # with room for its bends where a way with that room exists; a clamp stands nearer its seat than that
for step in steps: # a seed's vertices follow its lattice: a route is refused only after other lattices gave their seeds
occupied = self.reader((rest, moved, through), need + roomy + route.REACH * step)
for offset in HOSE_OFFSETS:
try:
pulled, voxels = route.leg(at, into, occupied, far, need, self.step, HOSE_MARGIN, HOSE_VOXELS, name, pad)
points, kinds, voxels = self.seed(start, end, ends, stops, occupied, step, offset, sized)
shaped = (*self.routed(points, kinds, sized), voxels, {"step": round(step, 6), "offset": list(offset)})
break
except route.RouteError:
if pad <= 0.0:
raise
legs.append((pulled, voxels, kind, out))
at, came = out, label
shaped, refusals = None, []
for depth in dict.fromkeys((self.sag * 2.0 * r, 0.0)): # slack yields to clearance: a route the sag breaks is made taut
try:
shaped = self.shaped(legs, start, end, depth, room, far, far_rest, far_moved, pin, joint, need, floor, lead, exempt, 4.0 * 2.0 * r) # a clamp keeps 2 outside diameters of straight each side of its point
except route.Blocked as error: # where a waypoint stands: no other seed lifts it
blocked = str(error)
break
except route.RouteError as error:
tried.append(str(error))
if shaped is not None or blocked is not None:
break
except route.RouteError as error:
refusals.append(("sagged" if depth > 0.0 else "taut", str(error)))
if shaped is None: # both attempts are named: the taut one is the one sag 0 would make
raise route.RouteError(refusals[0][1] if len({text for _, text in refusals}) == 1 else "; ".join(f"{how}: {text}" for how, text in refusals))
curve, made, sagged, least, swing = shaped
if shaped is None:
for what, port, towards in (("start", start, stops[0][2] if stops else ends[1]), ("end", end, stops[-1][2] if stops else ends[0])):
tip, out = port["matrix"][:3, 3] + port["matrix"][:3, 2] * lead, port["matrix"][:3, 2]
if (lead >= need and np.linalg.norm(towards - tip) > 2.0 * floor and float(far(tip[None])[0]) >= need - route.HELD
and not route.leaves(tip, out, floor, far, need)):
raise route.RouteError(f"the bundle is too stiff to leave its {what}: from the end of its lead at {route.spot(tip)} no curve that bends at the floor radius {floor:.4g} m or wider "
f"keeps {need:.4g} m from what stands within {2.0 * floor:.4g} m of it (a lower bend, thinner hoses, or more room before the port)")
if blocked is not None:
raise route.RouteError(blocked)
origins = ", ".join("(" + ", ".join(f"{v:g}" for v in offset) + ")" for offset in HOSE_OFFSETS)
raise route.RouteError(f"the search found no route: it tried step{'s' if len(steps) > 1 else ''} {' and '.join(f'{step:g}' for step in steps)}, each on grid origins {origins} of a step, "
f"and refined each seed in continuous space; this does not show that no route exists. The first refusal: {tried[0]}")
curve, made, sagged, least, swing, refined, voxels, seeded = shaped
built = self.built(curve, start, clamps, stand, r, sizes["spread"], half_width)
except route.RouteError as error:
raise Refused(f"{error}; nothing changed.") from None
@ -1550,7 +1557,7 @@ class BROKKR_KITBASH_OT_hose(PolishOperator):
report = {"object": hose.name, "rebuilt": rebuilt, "hoses": self.count, "length": round(float(np.linalg.norm(np.diff(curve, axis=0), axis=1).sum()), 6),
"lengthChange": None if swing is None else round(swing["lengthChange"], 6), "floor": round(floor, 6),
"clearance": None if not math.isfinite(least) else round(least - sizes["envelope"], 6), "capped": round(reach - sizes["envelope"], 6),
"voxels": [voxels for _, voxels, _, _ in legs], "sag": [round(drop, 6) for drop in sagged],
"voxels": voxels, "seed": {**seeded, "refined": refined}, "sag": [round(drop, 6) for drop in sagged],
"rolls": None if swing is None else swing["rolls"], "worstRoll": None if swing is None else swing["worstRoll"],
"worstClearance": None if swing is None or not math.isfinite(swing["least"]) else round(swing["least"] - sizes["envelope"], 6), **measured(mesh)}
report["radii"] = {"least": round(float(radii.min()), 6) if len(radii) else None}
@ -1677,35 +1684,102 @@ class BROKKR_KITBASH_OT_hose(PolishOperator):
return out
return distance
def shaped(self, legs, start, end, depth, room, far, far_rest, far_moved, pin, joint, need, floor, lead, exempt, kept):
@staticmethod
def seed(start, end, ends, stops, occupied, step, offset, sized):
"""(points, kinds, the voxels each leg searched) of one seed: every leg searched on the grid of `step` at
`offset` and pulled (route.leg), joined port to port. A point's kind says what holds it: "P" a port, "E" the
end of a fitting's straight, "I" and "O" where the hose comes onto and leaves a clamp's straight, "J" the
pin point; None is a vertex the search put there, which a refinement may move."""
points, kinds, voxels, at, came = [start["matrix"][:3, 3]], ["P"], [], ends[0], "start"
for kind, label, point, y in stops + [("end", "end", ends[1], None)]:
into, out = point, point
if kind == "clamp":
into, out = sorted((point - y * sized["held"], point + y * sized["held"]), key=lambda p: float(np.linalg.norm(p - at)))
name = f"leg {len(voxels) + 1} ({came} to {label})"
for pad in (sized["roomy"], 0.0): # with room for its bends where a way with that room exists; a clamp stands nearer its seat than that
try:
pulled, searched = route.leg(at, into, occupied, sized["far"], sized["need"], step, HOSE_MARGIN, HOSE_VOXELS, name, pad, offset)
break
except route.Blocked:
raise
except route.RouteError:
if pad <= 0.0:
raise
if kinds[-1] != "J": # a leg from the pin point starts on the point the last one ended on
points.append(pulled[0])
kinds.append("E" if came == "start" else "O")
points += list(pulled[1:])
kinds += [None] * (len(pulled) - 2) + [{"pin": "J", "clamp": "I", "end": "E"}[kind]]
voxels.append(searched)
at, came = out, label
return np.array(points + [end["matrix"][:3, 3]]), kinds + ["P"], voxels
@staticmethod
def straights(points, kinds, sized):
"""(keep, centred, least) for route's fillet and strain: a clamp's straight keeps its length in its middle,
and the corner at the pin holds the tangent its sharpest turn of the joint's range takes at the floor."""
clamped = np.array([a == "I" and b == "O" for a, b in zip(kinds, kinds[1:])])
least, pin = np.zeros(len(points) - 2), sized["pin"]
if pin is not None:
j = kinds.index("J")
before, after = points[j] - points[j - 1], points[j + 1] - points[j]
if min(np.linalg.norm(before), np.linalg.norm(after)) > 1e-9:
before, after = before / np.linalg.norm(before), after / np.linalg.norm(after)
if pin["child_first"]: # read from the parent's side, as route.passes turns it
before, after = -after, -before
low, high = (v - pin["current"] for v in sized["joint"]["range"])
least[j - 1] = sized["floor"] * math.tan(min(route.sharpest_turn(before, after, pin["axis"], low, high), route.STIFF) / 2.0)
return np.where(clamped, sized["kept"], 0.0), clamped, least
def routed(self, points, kinds, sized):
"""(curve, its fillet, sags, least distance, passes, whether the seed was refined) of one seed: shaped as it
is, sagged and then taut (slack yields to clearance); and where that is refused, refined in continuous space
(route.relax: until every segment has the straight its corners' tangents take at the floor, each moved
segment proven clear with the room a leg is pulled with) and shaped again. Refuses with what each shaping
was refused for, by name."""
fixed = np.array([point for point, kind in zip(points, kinds) if kind is not None])
padded = lambda p: np.asarray(sized["far"](p)) - np.minimum(sized["roomy"], 0.5 * np.linalg.norm(np.asarray(p)[:, None] - fixed[None], axis=2).min(axis=1)) # noqa: E731
refusals = []
for refined in (False, True):
if refined:
moved, tags = route.relax(points, kinds, lambda p, g: route.strain(p, sized["floor"], sized["lead"], *self.straights(p, g, sized)),
lambda a, b: route.clear(a, b, padded, sized["need"], 1.5), sized["floor"])
if len(moved) == len(points) and np.allclose(moved, points, atol=1e-12):
break
points, kinds = moved, tags
for depth in dict.fromkeys((self.sag * 2.0 * self.radius, 0.0)):
try:
return (*self.shaped(points, kinds, depth, sized), refined)
except route.RouteError as error:
refusals.append((("sagged" if depth > 0.0 else "taut") + (", refined" if refined else ""), str(error)))
raise route.RouteError(refusals[0][1] if len({text for _, text in refusals}) == 1 else "; ".join(f"{how}: {text}" for how, text in refusals))
def shaped(self, points, kinds, depth, sized):
"""(curve, its fillet, the metres each leg sagged, the least distance outside the leads, the joint's passes or
None) of the legs joined at one sag depth: one polyline from port to port, one fillet, one verification, and
with a pin its whole range: the rolls from the range's low to its high every ROLL_STEP degrees, each answering
for the rolls about it, and more between them where one falls short (route.passes)."""
points, keep, centred, sagged, j, last = [start["matrix"][:3, 3]], [], [], [], None, None
for pulled, _, kind, _ in legs:
hung, drop = route.sag(pulled, depth, room)
sagged.append(drop)
hung = hung[1:] if last == "pin" else hung # a leg from the pin point starts on the point the last one ended on
points += list(hung)
keep += [kept if last == "clamp" else 0.0] + [0.0] * (len(hung) - 1) # a leg from a clamp starts at the far end of the clamp's straight
centred += [last == "clamp"] + [False] * (len(hung) - 1)
if kind == "pin":
j = len(points) - 1
last = kind
points.append(end["matrix"][:3, 3])
keep.append(0.0)
centred.append(False)
points = np.array(points)
made = route.fillet(points, room, floor, lead, keep, centred)
least = route.verify(made.curve, far, need, exempt)
None) of a polyline at one sag depth: each leg sagged (the runs between held points, but a fitting's straight
and a clamp's), one fillet, one verification, and with a pin its whole range: the rolls from the range's low
to its high every ROLL_STEP degrees, each answering for the rolls about it, and more between them where one
falls short (route.passes)."""
hung, tags, sagged = [points[0]], [kinds[0]], []
held = [index for index, kind in enumerate(kinds) if kind is not None]
for a, b in zip(held, held[1:]):
run = points[a:b + 1]
if (kinds[a], kinds[b]) not in (("P", "E"), ("E", "P"), ("I", "O")):
run, drop = route.sag(run, depth, sized["room"])
sagged.append(drop)
hung += list(run[1:])
tags += [None] * (len(run) - 2) + [kinds[b]]
points, pin = np.array(hung), sized["pin"]
keep, centred, least = self.straights(points, tags, sized)
made = route.fillet(points, sized["room"], sized["floor"], sized["lead"], keep, centred, least)
clearance = route.verify(made.curve, sized["far"], sized["need"], sized["exempt"])
swing = None
if pin is not None:
order = slice(None, None, -1) if pin["child_first"] else slice(None) # passes reads a polyline from the parent's side
j, order = tags.index("J"), slice(None, None, -1) if pin["child_first"] else slice(None) # passes reads a polyline from the parent's side
swing = route.passes(points[order], made.t[order], (len(points) - 1 - j) if pin["child_first"] else j, pin["origin"], pin["axis"],
route.rolls_of(joint["range"][0], joint["range"][1], ROLL_STEP), ROLL_FINEST, pin["current"], far_rest, far_moved, need, floor, exempt,
keep=np.array(keep)[order])
return made.curve, made, sagged, least, swing
route.rolls_of(sized["joint"]["range"][0], sized["joint"]["range"][1], ROLL_STEP), ROLL_FINEST, pin["current"], sized["far_rest"], sized["far_moved"],
sized["need"], sized["floor"], sized["exempt"], keep=keep[order])
return made.curve, made, sagged, clearance, swing
def built(self, curve, start, clamps, stand, r, spread, half_width):
"""The mesh, in world space: each hose swept along the curve offset across the bundle, two ferrule collars at

View file

@ -6,7 +6,12 @@ owns what an obstacle is and may cap the answer. `need` is how far a hose's cent
obstacle: the bundle's half width plus its clearance.
A leg between two waypoints is searched on a voxel grid of the box around them (grid, wavefront), then pulled taut
(pull). A voxel is free when it stands need plus half a voxel's diagonal from every obstacle: distance changes by at
(pull). That polyline is a seed and no more: where its vertices stand follows the grid's lattice, so whether its
corners have straight enough for their bends does too. relax then moves, drops and adds vertices in continuous
space until every segment has the straight its corners' tangents take at the floor radius (strain), each move kept
only if the oracle proves its segments clear; tangents gives every corner its floor's tangent before any corner gets
more. leaves is the one proof of a bundle too stiff: a curve that bends no tighter than the floor cannot get out of
what stands about the end of a fitting's lead. A voxel is free when it stands need plus half a voxel's diagonal from every obstacle: distance changes by at
most the distance moved, so every point of a step between two neighbouring free voxels keeps need. The same bound is
what every measurement of a line rests on (measure): a reading answers for the piece around it, less half the piece's
length, and pieces are halved until that proves need, so nothing thinner than the spacing of some samples can stand
@ -31,6 +36,10 @@ class RouteError(ValueError):
"""A route that cannot be made, in words that name where."""
class Blocked(RouteError):
"""A refusal that rests on where a waypoint stands, not on a search: no other grid lifts it."""
NEIGHBOURS = [(i, j, k) for i in (-1, 0, 1) for j in (-1, 0, 1) for k in (-1, 0, 1) if (i, j, k) != (0, 0, 0)]
REACH = math.sqrt(3.0) / 2.0 # of a voxel: how far a point of a step between two neighbouring voxels can stand from the nearer one
STRAIGHT = 1e-9 # radians: a corner that turns less is no corner
@ -38,6 +47,8 @@ HELD = 1e-9 # metres under need that a reading may stand and hold it
FINE = 1e-3 # metres: the shortest piece measure halves to; a line must keep need by half of this to be proven
BEND = 1.0 - math.cos(math.pi / 4.0) # of a radius: how far the arc of a quarter turn stands from its tangent segments
ARC = 24 # arc segments a radian of turn
STIFF = math.radians(170.0) # a turn past this is priced as this one: its tangent at the floor is already 11 floors long
AXES = [np.array(v, dtype=np.float64) for v in ((1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1))]
def spot(point) -> str:
@ -78,6 +89,14 @@ def grid(lo, hi, step: float, distance, need: float, limit: int = 2 ** 19) -> Gr
return Grid(free=(np.asarray(distance(points)) >= need).reshape(n), lo=lo, step=float(step))
def _grow(front: np.ndarray) -> np.ndarray:
"""The 26 neighbours of a front's voxels, by array shifts."""
n, padded, grown = front.shape, np.pad(front, 1), np.zeros(front.shape, dtype=bool)
for i, j, k in NEIGHBOURS:
grown |= padded[1 + i:1 + i + n[0], 1 + j:1 + j + n[1], 1 + k:1 + k + n[2]]
return grown
def wavefront(free: np.ndarray, start, goal) -> list:
"""The voxels of a shortest 26-connected way from start to goal through free voxels, both ends included: a
wavefront grown from the goal by array shifts, then walked down from the start, at each step to the neighbour one
@ -94,10 +113,7 @@ def wavefront(free: np.ndarray, start, goal) -> list:
wave = 0
while waves[start] == unreached and front.any():
wave += 1
padded, grown = np.pad(front, 1), np.zeros(n, dtype=bool)
for i, j, k in NEIGHBOURS:
grown |= padded[1 + i:1 + i + n[0], 1 + j:1 + j + n[1], 1 + k:1 + k + n[2]]
front = grown & free & (waves == unreached)
front = _grow(front) & free & (waves == unreached)
waves[front] = wave
if waves[start] == unreached:
raise RouteError("no free way joins its ends: obstacles close every way through its search box")
@ -184,21 +200,22 @@ def pull(points, distance, need: float, rate: float = 1.0) -> np.ndarray:
return np.array(kept)
def leg(a, b, occupancy, distance, need: float, step: float, margin: float, limit: int, name: str, pad: float = 0.0):
def leg(a, b, occupancy, distance, need: float, step: float, margin: float, limit: int, name: str, pad: float = 0.0, offset=(0.0, 0.0, 0.0)):
"""(the pulled polyline from a to b, the voxels searched): a grid over the two ends' box plus margin, free where
`occupancy` reads need plus pad plus REACH of a voxel, a wavefront between the free voxels beside the ends, pulled
against `distance`. `pad` is room kept beyond need for the bends the leg's corners will get: a line pulled at
need alone grazes what it wraps, and the corner there has no room for an arc. Within twice pad of an end the pull
asks for half the distance from that end instead, since an end stands where it is given. Refuses, naming the
leg: an end nearer an obstacle than need, an end with no free voxel in sight beside it, a box over the limit, and
no way through."""
asks for half the distance from that end instead, since an end stands where it is given. `offset`, in steps along
each axis, moves the lattice's origin: the polyline is a seed whose vertices follow the lattice, and another origin
gives another seed. Refuses, naming the leg: an end nearer an obstacle than need (Blocked: no grid lifts that), an
end with no free voxel in sight beside it, a box over the limit, and no way through."""
a, b = np.asarray(a, dtype=np.float64), np.asarray(b, dtype=np.float64)
for label, point in (("start", a), ("end", b)):
reads = float(np.asarray(distance(point[None]))[0])
if reads < need - HELD:
raise RouteError(f"{name}: its {label} {spot(point)} stands {reads:.4g} m from an obstacle, under the {need:.4g} m the bundle needs")
raise Blocked(f"{name}: its {label} {spot(point)} stands {reads:.4g} m from an obstacle, under the {need:.4g} m the bundle needs")
try:
cells = grid(np.minimum(a, b) - margin, np.maximum(a, b) + margin, step, occupancy, need + pad + REACH * step, limit)
cells = grid(np.minimum(a, b) - margin - step * np.asarray(offset, dtype=np.float64), np.maximum(a, b) + margin, step, occupancy, need + pad + REACH * step, limit)
except RouteError as error:
raise RouteError(f"{name}: {error}") from None
ends = []
@ -277,23 +294,131 @@ def _radius(point, before, after, turn: float, cap: float, room) -> float:
return low
def tangents(points, room, lead: float, keep=None, centred=None) -> np.ndarray:
def _straights(lengths, lead: float, keep, centred):
"""(free, each, centred) of a polyline's segments: the straight a segment has to give its corners' tangents (its
length less what it keeps: `keep`, and `lead` more on the first and last), and what one end of it may take: all of
it, or half on a centred segment, whose kept straight stays in its middle."""
free = np.maximum(lengths - _kept(len(lengths), lead, keep), 0.0)
centred = np.zeros(len(lengths), dtype=bool) if centred is None else np.asarray(centred, dtype=bool)
return free, np.where(centred, free / 2.0, free), centred
def _floors(turn, floor: float, least) -> np.ndarray:
"""The tangent length each corner needs: its turn's at the floor radius, and `least` where that is more (a corner
that will turn further than it does here: the one at a pin)."""
need = floor * np.tan(np.minimum(turn, STIFF) / 2.0)
return need if least is None else np.maximum(need, np.asarray(least, dtype=np.float64))
def tangents(points, room, lead: float, keep=None, centred=None, floor: float = 0.0, least=None) -> np.ndarray:
"""The tangent length of the arc at each interior point of a polyline (0 where it runs straight on). Each corner
first gets the largest radius its room allows (_radius) within the straight its two segments have to give: a
segment's length less what it keeps straight (`keep` for each segment, and `lead` more on the first and last), or
half of that at each end of a `centred` segment, whose kept straight stays in its middle. Where two corners'
tangents overlap on a segment both shrink in proportion until they share it."""
first gets the largest radius its room allows (_radius) within the straight its two segments have to give
(_straights). Where two corners' tangents overlap on a segment, each keeps what it needs (_floors: its tangent at
`floor`, or `least`) and what the segment has beyond that is shared in proportion to what each asked beyond its
need; a corner holds its `least` of a segment even where its arc here is shorter. Where the two needs do not fit
the segment both shrink in proportion, and fillet refuses the corner."""
points = np.asarray(points, dtype=np.float64)
lengths, unit, turn = _turns(points)
free = np.maximum(lengths - _kept(len(lengths), lead, keep), 0.0)
each = np.where(np.zeros(len(lengths), dtype=bool) if centred is None else np.asarray(centred, dtype=bool), free / 2.0, free)
free, each, _ = _straights(lengths, lead, keep, centred)
t = np.zeros(len(turn))
for c in np.flatnonzero(turn >= STRAIGHT):
t[c] = _radius(points[c + 1], unit[c], unit[c + 1], float(turn[c]), float(min(each[c], each[c + 1])), room) * math.tan(turn[c] / 2.0)
share = np.ones(len(lengths))
both = t[:-1] + t[1:] # on segment s, between corners s - 1 and s
share[1:-1] = np.where(both > free[1:-1], free[1:-1] / np.maximum(both, 1e-300), 1.0)
return t * np.minimum(share[:-1], share[1:])
need = _floors(turn, floor, least)
claim = np.maximum(t, need)
held = claim.copy()
for s in range(1, len(lengths) - 1): # segment s, between corners s - 1 and s
both, needs = claim[s - 1] + claim[s], need[s - 1] + need[s]
if both > free[s]:
for c in (s - 1, s):
held[c] = min(held[c], need[c] + (claim[c] - need[c]) * (free[s] - needs) / (both - needs) if needs <= free[s] else claim[c] * free[s] / both)
return np.minimum(t, held)
def strain(points, floor: float, lead: float, keep=None, centred=None, least=None) -> np.ndarray:
"""For each segment of a polyline, the straight its corners' tangents take at the floor radius beyond what the
segment has to give (_straights, _floors); all 0 where every corner has the straight for its bend. What fillet
refuses for want of straight, as lengths relax can lower."""
lengths, _, turn = _turns(np.asarray(points, dtype=np.float64))
free, each, centred = _straights(lengths, lead, keep, centred)
need = _floors(turn, floor, least)
first, last = np.r_[0.0, need], np.r_[need, 0.0] # of the corner a segment starts at, and the one it ends at
return np.where(centred, np.maximum(first - each, 0.0) + np.maximum(last - each, 0.0), np.maximum(first + last - free, 0.0))
def relax(points, tags, cost, clear, reach: float, rounds: int = 64):
"""(points, tags) of a polyline refined in continuous space until `cost(points, tags)`, an amount for each
segment, is all 0 or nothing tried lowers its sum. A vertex whose tag is None is free; the others stay. Each round
tries, about the segments that cost: a free vertex dropped; a free vertex moved by a length (first `reach`) along
each axis and along its two segments; and a vertex added at a segment's middle, moved that length along an axis.
The try that lowers the sum most among those whose changed segments `clear(a, b)` proves is kept; with none, the
length is halved, down to FINE. The oracle alone says what is clear: no lattice is read."""
points, tags = np.asarray(points, dtype=np.float64), list(tags)
def price(p, g):
try:
return float(np.sum(cost(p, g)))
except RouteError: # two vertices on one point
return math.inf
now, delta, most = price(points, tags), float(reach), len(points) + 4
for _ in range(rounds):
if not 0.0 < now < math.inf or delta < FINE:
break
strained = np.flatnonzero(np.asarray(cost(points, tags)) > 0.0)
tries = []
for v in sorted({v for s in strained for v in range(s - 1, s + 3) if 0 < v < len(points) - 1 and tags[v] is None}):
tries.append((np.delete(points, v, axis=0), tags[:v] + tags[v + 1:], (v - 1,)))
along = [(points[v + side] - points[v]) / max(float(np.linalg.norm(points[v + side] - points[v])), 1e-12) for side in (-1, 1)]
for way in AXES + along + [-d for d in along]:
moved = points.copy()
moved[v] += delta * way
tries.append((moved, tags, (v - 1, v)))
if len(points) < most:
for s in sorted({q for s in strained for q in (s - 1, s, s + 1) if 0 <= q < len(points) - 1}):
for way in AXES:
tries.append((np.insert(points, s + 1, (points[s] + points[s + 1]) / 2.0 + delta * way, axis=0), tags[:s + 1] + [None] + tags[s + 1:], (s, s + 1)))
priced = sorted(((price(p, g), index) for index, (p, g, _) in enumerate(tries)), key=lambda row: row[0])
for value, index in priced:
if not value < now - 1e-12:
delta /= 2.0
break
p, g, changed = tries[index]
if all(clear(p[q], p[q + 1]) for q in changed):
now, points, tags = value, p, g
break
else:
delta /= 2.0
return points, tags
def leaves(point, heading, floor: float, distance, need: float, cells: int = 6) -> bool:
"""Whether a curve that bends no tighter than `floor` and keeps need can get 2 floors away from `point`, which it
leaves along `heading`. False is a proof that none can: the bundle is too stiff for the room there.
Until such a curve is pi floors long it stays out of every ball of radius floor that touches its line at the
point and never falls behind the point (it has gone floor x sin(length / floor) along its heading), and by then
it stands at least 2 floors from the point (Schwarz's bound on a curve's chord; Dubins, "On curves of minimal
length with a constraint on average curvature", Amer. J. Math. 79, 1957). So it reaches the sphere of 2 floors
through points that keep need, stand outside those balls and are not behind the point. On voxels of floor / cells
a voxel is open unless its centre reads under need less REACH of a voxel, or stands more than that inside the
balls or behind the point: every point of such a curve then lies in an open voxel, and neighbouring points in neighbouring voxels.
When no open voxel on the sphere is joined to the point's, no curve exists; the grid sets how often the proof is
found, never whether it is true."""
point, heading = np.asarray(point, dtype=np.float64), np.asarray(heading, dtype=np.float64) / np.linalg.norm(heading)
step, n = floor / cells, 4 * cells + 3 # 2 floors and a voxel each way
axis = step * (np.arange(n) - (n - 1) / 2.0)
offsets = np.stack(np.meshgrid(axis, axis, axis, indexing="ij"), axis=-1).reshape(-1, 3)
along = offsets @ heading
inside = floor - np.sqrt((np.linalg.norm(offsets - along[:, None] * heading, axis=1) - floor) ** 2 + along ** 2)
opened = ((np.asarray(distance(point + offsets)) >= need - REACH * step) & (inside <= REACH * step) & (along >= -REACH * step)).reshape(n, n, n)
reached = np.zeros((n, n, n), dtype=bool)
reached[(n - 1) // 2, (n - 1) // 2, (n - 1) // 2] = True
while True:
front = _grow(reached) & opened & ~reached
if not front.any():
break
reached |= front
return bool((reached.reshape(-1) & (np.linalg.norm(offsets, axis=1) >= 2.0 * floor - REACH * step)).any())
def arcs(points, t):
@ -330,25 +455,25 @@ class Filleted(NamedTuple):
radii: np.ndarray # radius at each interior point, inf where the polyline runs straight on
def fillet(polyline, room, floor: float, lead: float, keep=None, centred=None) -> Filleted:
def fillet(polyline, room, floor: float, lead: float, keep=None, centred=None, least=None) -> Filleted:
"""A polyline with its corners rounded (tangents, arcs). `room(a, b)` is the least obstacle distance along the
segment a..b less need, or None where nothing stands near. Refuses a corner whose radius is under `floor`, naming
the corner, its point, the radius it got and the floor."""
segment a..b less need, or None where nothing stands near. `least` is the tangent length a corner holds of its
segments whatever it turns here. Refuses a corner whose radius is under `floor`, naming the corner, its point, the
radius it got, the floor and what this polyline lacks there: it speaks of this polyline, not of every route."""
polyline = np.asarray(polyline, dtype=np.float64)
if len(polyline) < 3:
return Filleted(polyline, np.full(len(polyline), -1), np.zeros(0), np.zeros(0))
t = tangents(polyline, room, lead, keep, centred)
t = tangents(polyline, room, lead, keep, centred, floor, least)
turn = _turns(polyline)[2]
radii = np.where(turn >= STRAIGHT, t / np.tan(np.maximum(turn, STRAIGHT) / 2.0), np.inf)
under = np.flatnonzero(radii < floor * (1.0 - 1e-9))
if len(under):
c = int(under[np.argmin(radii[under])])
lengths, unit, _ = _turns(polyline)
free = np.maximum(lengths - _kept(len(lengths), lead, keep), 0.0)
each = np.where(np.zeros(len(lengths), dtype=bool) if centred is None else np.asarray(centred, dtype=bool), free / 2.0, free)
each = _straights(lengths, lead, keep, centred)[1]
straight, tangent, depth = float(min(each[c], each[c + 1])), floor * math.tan(turn[c] / 2.0), floor * (1.0 - math.cos(turn[c] / 2.0))
if straight < tangent:
why = (f"the bundle is too stiff for this route: the corner's segments leave {straight:.4g} m of straight for the {tangent:.4g} m its tangent takes at the floor "
why = (f"the corner's segments leave {straight:.4g} m of straight for the {tangent:.4g} m its tangent takes at the floor "
"(a lower bend, thinner hoses, or ends, clamps and the pin point further apart)")
elif room is not None and _radius(polyline[c + 1], unit[c], unit[c + 1], float(turn[c]), straight, room) < floor * (1.0 - 1e-9):
stands = min(room(polyline[c + 1] - unit[c] * tangent, polyline[c + 1]), room(polyline[c + 1], polyline[c + 1] + unit[c + 1] * tangent))
@ -422,6 +547,18 @@ def turned(points, origin, axis, degrees: float) -> np.ndarray:
return origin + p * c + np.cross(axis, p) * s + axis[None] * (p @ axis)[:, None] * (1.0 - c)
def sharpest_turn(before, after, axis, low: float, high: float) -> float:
"""The largest turn, in radians, from the unit `before` to the unit `after` turned about `axis` by any angle of
low..high degrees. The turn's cosine is a + b cos + c sin of the angle, least at one angle of a full turn: the
largest turn is there where the range holds that angle, and at an end of the range where it does not."""
axis = np.asarray(axis, dtype=np.float64) / np.linalg.norm(axis)
along = axis * float(after @ axis)
a, b, c = float(before @ along), float(before @ (after - along)), float(before @ np.cross(axis, after))
worst = math.degrees(math.atan2(-c, -b))
angles = [low, high] + [worst + 360.0 * k for k in range(-2, 3) if low < worst + 360.0 * k < high]
return max(math.acos(max(-1.0, min(1.0, a + b * math.cos(math.radians(v)) + c * math.sin(math.radians(v))))) for v in angles)
def rolls_of(low: float, high: float, step: float) -> list:
"""low, then every step up to high, and high."""
return [float(v) for v in np.arange(low, high - 1e-9, step)] + [float(high)]
@ -437,7 +574,7 @@ def passes(polyline, t, j: int, origin, axis, rolls, finest: float, current: flo
that stands rho from the axis moves at most rho x w against the other side's parts, so its reading against them
counts for that much less (`parent` and `child` read each side's parts where they stand at `current`; samples are
turned back for the child's). The bend at the pin has one radius through a bin, the largest that fits at the bin's
sharpest turn: its arc then stands within radius x (1 - cos(turn / 2)) of its two tangent segments, which are swept
sharpest turn (sharpest_turn, over the bin's rolls): its arc then stands within radius x (1 - cos(turn / 2)) of its two tangent segments, which are swept
for need and that much more. Everything else outside the leads is swept for need (measure). A bin that falls short
is halved and measured at each half's middle, down to `finest` degrees of half width, where it is refused, naming
the roll, the side, the point and the reading; so is a bin whose bend at the pin has no room for the floor.
@ -464,7 +601,7 @@ def passes(polyline, t, j: int, origin, axis, rolls, finest: float, current: flo
sides = {"parent's side": lambda p: np.minimum(np.asarray(parent(p)), np.asarray(child(back(p))) - moves(p)),
"child's side": lambda p: np.minimum(np.asarray(child(back(p))), np.asarray(parent(p)) - moves(p))}
lengths_, unit, turn = _turns(posed)
corner, sharpest = posed[j], min(float(turn[c]) + width, math.pi - 1e-6)
corner, sharpest = posed[j], min(sharpest_turn(unit[c], unit[c + 1], axis, low - roll, high - roll), math.pi - 1e-6)
cap = min(lengths_[c] - kept[c] - (sharp[c - 1] if c > 0 else 0.0), lengths_[c + 1] - kept[c + 1] - (sharp[c + 1] if c + 1 < len(sharp) else 0.0))
def fits(bend: float):

View file

@ -2039,8 +2039,12 @@ class OwnershipTests(unittest.TestCase):
work = body.split(" @staticmethod")[0]
first = min(work.index(write) for write in ("clear_geometry()", "bpy.data.meshes.new(", "write_mesh(", ".parent =", "[HOSE] ="))
self.assertLess(work.rindex("raise Refused("), first) # every refusal before any write
for call in ("route.leg(", "self.shaped(", "self.built(", "self.trees(", "self.crossed(", "self.rows()", "self.frame("):
for call in ("self.seed(", "self.routed(", "route.leaves(", "self.built(", "self.trees(", "self.crossed(", "self.rows()", "self.frame("):
self.assertLess(work.rindex(call), first, call)
for write in ("clear_geometry()", "bpy.data.meshes.new(", "write_mesh(", ".parent =", "[HOSE] ="): # what work calls to seed, refine and shape a route writes nothing
self.assertEqual(body.count(write), work.count(write), write)
for owner, call in (("seed", "route.leg("), ("routed", "route.relax("), ("routed", "self.shaped(")):
self.assertIn(call, body.split(f" def {owner}(")[1].split("\n def ")[0], call)
shaped = body.split(" def shaped(")[1].split(" def built(")[0]
self.assertLess(shaped.index("route.fillet("), shaped.index("route.verify("))
self.assertLess(shaped.index("route.verify("), shaped.index("route.passes("))

View file

@ -224,13 +224,80 @@ class FilletTests(unittest.TestCase):
route.verify(free.curve, distance, 0.05, 0.0)
def test_a_corner_under_the_floor_is_refused_by_name(self):
with self.assertRaisesRegex(route.RouteError, r"^corner 1 at \[1, 0, 0\] turns 90\.0 degrees and gets a bend of radius 0\.15 m, under the floor 0\.5: the bundle is too stiff for this route: "
with self.assertRaisesRegex(route.RouteError, r"^corner 1 at \[1, 0, 0\] turns 90\.0 degrees and gets a bend of radius 0\.15 m, under the floor 0\.5: "
r"the corner's segments leave 0\.3 m of straight for the 0\.5 m its tangent takes at the floor"):
route.fillet(self.ZIGZAG, None, 0.5, 0.2)
with self.assertRaisesRegex(route.RouteError, r"^corner 1 at \[0, 0, 0\] turns 90\.0 degrees and gets a bend of radius 0(\.00\d+)? m, under the floor 0\.05: the route passes too near an obstacle to bend here: "
r"its segments stand 0(\.00\d+)? m clear beyond what the bundle needs and the arc at the floor takes 0\.01464 "):
route.fillet(np.array([[-1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]]), room_of(ball([-0.05, 0.05, 0.0], 0.02), 0.05), 0.05, 0.0) # a ball in the corner
def test_a_corner_keeps_its_floor_s_tangent_before_its_neighbour_gets_more(self):
"""bend-room-searched. Two corners on a 0.5 segment ask 0.5 and 0.25 of it and need 0.22 each at the floor:
each keeps its need and the 0.06 left is shared by what each asked beyond it. Mutant T1 (shared in proportion
to what each asked, floor = 0 in tangents): the second corner gets 0.167 and the polyline is refused."""
points = np.array([[0.0, 0.0, 0.0], [3.0, 0.0, 0.0], [3.0, 0.5, 0.0], [3.25, 0.5, 0.0]])
made = route.fillet(points, None, 0.22, 0.0)
self.assertAlmostEqual(float(made.t.sum()), 0.5, places=12)
self.assertAlmostEqual(float((made.t[0] - 0.22) / (made.t[1] - 0.22)), 0.28 / 0.03, places=9)
self.assertAlmostEqual(float(route.tangents(points, None, 0.0)[1]), 0.5 / 3.0, places=12) # the share a corner got before its need counted
self.assertEqual(float(route.strain(points, 0.22, 0.0).sum()), 0.0)
self.assertAlmostEqual(float(route.strain(points, 0.3, 0.0)[1]), 0.1, places=12)
self.assertAlmostEqual(float(route.strain(points, 0.3, 0.0, keep=[0.0, 0.1, 0.0], centred=[False, True, False])[1]), 0.2, places=12)
held = route.fillet(points, None, 0.1, 0.0, least=[0.4, 0.0]) # a corner that will turn further holds the tangent that takes
self.assertAlmostEqual(float(held.t[0]), 0.4, places=12)
self.assertAlmostEqual(float(held.t[1]), 0.1, places=12)
def test_a_seed_without_the_straight_for_its_bends_is_refined_where_the_oracle_allows(self):
"""bend-room-searched. A seed's vertex stands 0.18 from a held corner and their two tangents at the floor take
0.25; a ball closes the straight way past it. relax moves the vertex until every segment has its straight,
each moved segment proven clear. Mutant X1 (relax returns its seed): strain stays and fillet refuses."""
distance, need, floor = ball([1.0, 0.7, 0.0], 0.05), 0.05, 0.3
seed, tags = np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.15, 0.1, 0.0], [1.15, 1.5, 0.0]]), ["P", "E", None, "P"]
self.assertFalse(route.clear(seed[1], seed[3], distance, need))
self.assertGreater(float(route.strain(seed, floor, 0.0).sum()), 0.05)
with self.assertRaisesRegex(route.RouteError, "under the floor 0.3: it shares a segment with the corner beside it"):
route.fillet(seed, room_of(distance, need), floor, 0.0)
tried = []
def sure(a, b):
tried.append((a, b))
return route.clear(a, b, distance, need)
points, kept = route.relax(seed, tags, lambda p, g: route.strain(p, floor, 0.0), sure, floor)
self.assertTrue(tried)
self.assertEqual(float(route.strain(points, floor, 0.0).sum()), 0.0)
self.assertEqual([tag for tag in kept if tag is not None], ["P", "E", "P"])
for index in (0, 1, -1):
self.assertTrue((points[index] == seed[index]).all())
self.assertGreaterEqual(float(distance(np.vstack([dense(p, q, 0.001) for p, q in zip(points[:-1], points[1:])])).min()), need)
made = route.fillet(points, room_of(distance, need), floor, 0.0)
self.assertGreaterEqual(float(made.radii.min()), floor * (1 - 1e-9))
open_points, open_tags = route.relax(seed, tags, lambda p, g: route.strain(p, floor, 0.0), lambda a, b: True, floor)
self.assertEqual(open_tags, ["P", "E", "P"]) # with nothing in the way the vertex is dropped
same, _ = route.relax(seed, tags, lambda p, g: route.strain(p, floor, 0.0), lambda a, b: False, floor)
self.assertTrue((same == seed).all()) # nothing the oracle does not prove is kept
def test_too_stiff_is_proven_of_a_pocket_and_of_nothing_else(self):
"""bend-room-searched. A wall 0.08 ahead of a point a hose leaves along x: no curve of radius 0.2 turns
aside in the 0.06 its centre line has, and one of radius 0.04 does. Mutant S1 (the balls a curve cannot
enter left out of leaves): the stiff bundle is said to leave."""
wall = lambda at: (lambda p: at - np.asarray(p)[:, 0]) # noqa: E731
origin, ahead = np.zeros(3), np.array([1.0, 0.0, 0.0])
self.assertFalse(route.leaves(origin, ahead, 0.2, wall(0.08), 0.02))
self.assertTrue(route.leaves(origin, ahead, 0.04, wall(0.08), 0.02))
self.assertTrue(route.leaves(origin, ahead, 0.2, wall(0.5), 0.02))
slit = lambda p: np.where(np.abs(np.asarray(p)[:, 1]) < 0.03, 1.0, wall(0.08)(p)) # noqa: E731 the wall, open along a slit 0.06 wide straight ahead
self.assertTrue(route.leaves(origin, ahead, 0.2, slit, 0.02))
def test_the_sharpest_turn_of_a_range_is_exact(self):
"""range-measured-unposed. The turn at a pin over a range of rolls, against the turn at 4001 rolls of it."""
rng = np.random.default_rng(7)
for low, high in ((-20.0, 20.0), (-170.0, 5.0), (30.0, 31.0), (-360.0, 360.0), (4.0, 4.0)):
before, after, axis = (v / np.linalg.norm(v) for v in rng.normal(size=(3, 3)))
turns = [math.acos(max(-1.0, min(1.0, float(before @ route.turned(after[None], np.zeros(3), axis, float(roll))[0])))) for roll in np.linspace(low, high, 4001)]
found = route.sharpest_turn(before, after, axis, low, high)
self.assertGreaterEqual(found, max(turns) - 1e-12)
self.assertLess(found - max(turns), 1e-5)
def test_the_floor_is_the_innermost_hose_s(self):
"""Mutant H8 (the floor taken at the centre line): the innermost of three hoses bends tighter than bend
outside diameters."""