brokkr_kitbash.hose: hoses routed between sockets, clamped, through a pin's axis across its roll range (cut kit-hose) #33
10 changed files with 2895 additions and 18 deletions
|
|
@ -49,6 +49,16 @@ shell is the one writer of the mesh, its crease attributes and those two modifie
|
|||
object rewrites the mesh in place, leaving the object, its cutters, ribs, Booleans and material slots. shell
|
||||
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 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:
|
||||
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
|
||||
writes them, only when the two sockets already meet, and writes nothing else; detach clears them. Nothing here
|
||||
|
|
@ -73,7 +83,7 @@ try:
|
|||
except ImportError as error: # register() says so; the classes below only need something to subclass
|
||||
RESULT, PolishOperator, Refused, mesh_object, MISSING = "brokkr_mesh_polish_result", bpy.types.Operator, RuntimeError, None, error
|
||||
|
||||
from . import core
|
||||
from . import core, route
|
||||
|
||||
KIT, PART, PARAMS = "kit_kit", "kit_part", "kit_params"
|
||||
SOCKET, PARENT_SOCKET, ROLL, BAKED = "kit_socket", "kit_parent_socket", "kit_roll", "kit_baked"
|
||||
|
|
@ -89,6 +99,15 @@ LONGERONS_LIMIT = 16 # longerons in one ribs
|
|||
SHELL = "kit_shell" # on a shell: the request its cage is derived from, as JSON; its presence admits a rebuild, and nothing reads it to decide geometry
|
||||
SUBSURF, SOLIDIFY = "Kit Subsurf", "Kit Solidify" # a shell's own modifiers, in that order, before any of its Booleans and the Kit Bevel
|
||||
SHELL_FACES_LIMIT = 262144 # faces of a shell's subdivided surface: cage quads times 4 to the levels
|
||||
HOSE = "kit_hose" # on a hose: the request it was routed from, as JSON; its presence admits a rebuild, and another hose reads its two ends to know that it crosses the same pin
|
||||
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)
|
||||
|
||||
|
||||
def kit_work(work):
|
||||
|
|
@ -1405,6 +1424,399 @@ class BROKKR_KITBASH_OT_shell(PolishOperator):
|
|||
evaluated.to_mesh_clear()
|
||||
|
||||
|
||||
class BROKKR_KITBASH_OT_hose(PolishOperator):
|
||||
"""Route a bundle of hoses between two sockets around every mesh in the scene, through clamps on mount sockets and
|
||||
through a point on a pin's axis across the pin's roll range; on an object that is already a hose, rebuild it in
|
||||
place"""
|
||||
bl_idname = "brokkr_kitbash.hose"
|
||||
bl_label = "Route A Hose"
|
||||
object_name: bpy.props.StringProperty(name="Object", description="The hose's name: a new object, or a hose to rebuild")
|
||||
start: bpy.props.StringProperty(name="Start", description="'Object:socket', a hose or flange socket of a kit part; or 'Object', an empty whose z the hose leaves along")
|
||||
end: bpy.props.StringProperty(name="End", description="As start")
|
||||
count: bpy.props.IntProperty(name="Count", default=1, min=1, max=8, description="Hoses in the bundle, side by side")
|
||||
radius: bpy.props.FloatProperty(name="Radius", default=0.01, min=0.0029, max=0.1, description="A hose's outside radius")
|
||||
spread: bpy.props.FloatProperty(name="Spread", default=0.0, min=0.0, max=0.5, description="Centre to centre between hoses; 0: 2.6 radii")
|
||||
clearance: bpy.props.FloatProperty(name="Clearance", default=0.01, min=0.0, max=0.5, description="Free space kept between the bundle and every other mesh")
|
||||
bend: bpy.props.FloatProperty(name="Bend", default=4.0, min=1.0, max=20.0, description="Least bend radius of the innermost hose, in outside diameters")
|
||||
step: bpy.props.FloatProperty(name="Step", default=0.02, min=0.0049, max=0.2, description="Voxel size of the search")
|
||||
sag: bpy.props.FloatProperty(name="Sag", default=1.0, min=0.0, max=8.0, description="How far the middle of each free span hangs, in outside diameters; 0: taut")
|
||||
clamps: bpy.props.StringProperty(name="Clamps", default="[]", description="A JSON array of up to 8 {socket: 'Object:socket'}, mount sockets, in order along the hose")
|
||||
joint: bpy.props.StringProperty(name="Joint", default="", description="Empty, or a JSON object {socket, standoff, range: [lo, hi]}: the pin the hose crosses")
|
||||
|
||||
# the action table states radius from 0.003 and step from 0.005: a float property rounds those up, so its bounds stand just under
|
||||
@kit_work
|
||||
def work(self, context):
|
||||
if not 1 <= len(self.object_name) <= 63:
|
||||
raise Refused(f"object_name {self.object_name!r} must be 1 to 63 characters; nothing changed.")
|
||||
hose = bpy.data.objects.get(self.object_name)
|
||||
if hose is not None:
|
||||
if hose.type != "MESH" or HOSE not in hose:
|
||||
raise Refused(f"An object named {hose.name!r} exists and is no hose (it carries no {HOSE}): hose rebuilds only what hose made; nothing changed.")
|
||||
own_mesh(hose, "rebuilding")
|
||||
sizes = route.bundle(self.count, self.radius, self.spread, self.clearance, self.bend)
|
||||
r, need, floor, lead, half_width = self.radius, sizes["need"], sizes["floor"], sizes["lead"], sizes["envelope"] - self.radius
|
||||
kits = {}
|
||||
start, end = (self.frame(context, text, what, ("hose", "flange"), kits, True) for text, what in ((self.start, "start"), (self.end, "end")))
|
||||
for what, port in (("start", start), ("end", end)):
|
||||
if port["size"] is not None and sizes["width"] > port["size"] * (1.0 + core.SLACK):
|
||||
raise Refused(f"{what}: a bundle of {self.count} hoses is {sizes['width']:.6g} m wide, over socket {port['name']!r} ({port['type']}, size {port['size']:.6g}): "
|
||||
"use fewer or thinner hoses, a smaller spread, or a larger port; nothing changed.")
|
||||
clamp_rows, joint = self.rows()
|
||||
clamps = [self.frame(context, row, f"clamps[{index}]", ("mount",), kits) for index, row in enumerate(clamp_rows)]
|
||||
pins, pin = self.crossed(start["object"], end["object"], kits), None
|
||||
if joint is None and pins:
|
||||
raise Refused(f"The hose crosses the pin of {pins[0][0].name!r} on {pins[0][0].parent.name!r} (socket {pins[0][1]['name']!r}): give joint, a socket on that pin's axis, "
|
||||
"a standoff and the roll range; nothing changed.")
|
||||
if joint is not None and len(pins) != 1:
|
||||
raise Refused(("joint is given and the hose crosses no pin: its ends are on parts no pivot connection stands between" if not pins else
|
||||
f"The hose crosses {len(pins)} pins ({', '.join(repr(child.name) + ' on ' + repr(child.parent.name) for child, _, _ in pins)}): a hose crosses one; "
|
||||
"end it on a part between them and route the next from there") + "; nothing changed.")
|
||||
if pins:
|
||||
child, socket, current = pins[0]
|
||||
if current is None:
|
||||
raise Refused(f"{child.name!r} on {child.parent.name!r}: its {ROLL} is not a number: detach it and attach it again; nothing changed.")
|
||||
on = self.frame(context, joint["socket"], "joint.socket", None, kits)
|
||||
axis = np.array(child.parent.matrix_world) @ socket["matrix"]
|
||||
off = float(np.linalg.norm(np.cross(on["matrix"][:3, 3] - axis[:3, 3], axis[:3, 2])))
|
||||
lean = float(np.linalg.norm(np.cross(on["matrix"][:3, 2], axis[:3, 2])))
|
||||
if off > 1e-6 or lean > 1e-6:
|
||||
raise Refused(f"joint.socket {on['name']!r} is not on the axis of the pin the hose crosses ({child.name!r} on {child.parent.name!r}, socket {socket['name']!r}): "
|
||||
f"its origin stands {off:.6g} m off the axis and its z leans {math.degrees(math.asin(min(1.0, lean))):.6g} degrees from it; nothing changed.")
|
||||
if not joint["range"][0] - 1e-9 <= current <= joint["range"][1] + 1e-9:
|
||||
raise Refused(f"{child.name!r} stands at roll {current:.6g}, outside joint.range {joint['range']}: the range holds the pose the hose is routed at; nothing changed.")
|
||||
sides = [child in self.chain(stop["object"]) for stop in (start, *clamps, end)]
|
||||
changes = [index for index in range(len(sides) - 1) if sides[index] != sides[index + 1]]
|
||||
if len(changes) != 1:
|
||||
raise Refused(f"clamps cross the pin of {child.name!r} {len(changes)} times: list them in order along the hose, those on the start's side of the pin first; nothing changed.")
|
||||
pin = {"origin": axis[:3, 3], "axis": axis[:3, 2], "current": current, "before": changes[0], "child": child, "child_first": sides[0],
|
||||
"point": on["matrix"][:3, 3] + on["matrix"][:3, 2] * joint["standoff"]}
|
||||
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
|
||||
far, far_rest, far_moved = self.reader((rest, moved, through), reach), self.reader((rest,), reach), self.reader((moved,), reach)
|
||||
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
|
||||
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:
|
||||
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:
|
||||
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.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
|
||||
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
|
||||
world = np.array(start["object"].matrix_world)
|
||||
built = built._replace(V=(built.V - world[:3, 3]) @ world[:3, :3]) # into the start's object's frame: the hose is its child
|
||||
rebuilt = hose is not None
|
||||
if rebuilt:
|
||||
mesh = hose.data
|
||||
mesh.clear_geometry()
|
||||
else:
|
||||
mesh = bpy.data.meshes.new(self.object_name)
|
||||
write_mesh(mesh, built)
|
||||
if not rebuilt:
|
||||
hose = bpy.data.objects.new(self.object_name, mesh)
|
||||
context.scene.collection.objects.link(hose)
|
||||
hose.parent = start["object"]
|
||||
hose.matrix_world = start["object"].matrix_world.copy() # read by a report; no depsgraph update here
|
||||
seat(hose, np.eye(4))
|
||||
hose[HOSE] = json.dumps({"object_name": self.object_name, "start": self.start, "end": self.end, "count": self.count, "radius": self.radius, "spread": self.spread,
|
||||
"clearance": self.clearance, "bend": self.bend, "step": self.step, "sag": self.sag, "clamps": json.loads(self.clamps),
|
||||
"joint": json.loads(self.joint) if self.joint else None})
|
||||
radii = made.radii[np.isfinite(made.radii)]
|
||||
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, "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}
|
||||
report["radii"]["corners"] = fitted(report, "corners", [round(float(v), 6) for v in radii])
|
||||
return report
|
||||
|
||||
@staticmethod
|
||||
def chain(obj) -> list:
|
||||
"""An object and its parents, nearest first."""
|
||||
found = []
|
||||
while obj is not None:
|
||||
found.append(obj)
|
||||
obj = obj.parent
|
||||
return found
|
||||
|
||||
@staticmethod
|
||||
def frame(context, text: str, what: str, kinds, kits, loose: bool = False) -> dict:
|
||||
"""What a hose reads at 'Object:socket': {object, matrix (the socket's world frame), size, type, name, depsgraph}.
|
||||
The socket is a kit part's, of one of `kinds` (any when None); with `loose`, 'Object' alone names an empty and
|
||||
its own frame. Refuses a name with no object, a part that is scaled (rigid), a socket the part does not have or
|
||||
of another type, and an object Blender does not evaluate."""
|
||||
name, socket = (text, "") if text in bpy.data.objects or ":" not in text else text.rsplit(":", 1)
|
||||
obj = bpy.data.objects.get(name)
|
||||
if obj is None:
|
||||
raise Refused(f"{what}: no object named {name!r}; nothing changed.")
|
||||
if not socket:
|
||||
if not loose or obj.type != "EMPTY":
|
||||
raise Refused(f"{what} {text!r} names no socket: give 'Object:socket'" + (", or an empty whose z the hose leaves along" if loose else "") + "; nothing changed.")
|
||||
rigid(obj)
|
||||
return {"object": obj, "matrix": np.array(obj.matrix_world), "size": None, "type": "empty", "name": text, "depsgraph": evaluable(context, obj)[0]}
|
||||
part, built = built_part(obj, kits)
|
||||
found = [s for s in built.sockets if s["name"] == socket]
|
||||
if not found:
|
||||
raise Refused(f"{what}: {obj.name!r} (a {part['name']}) has no socket {socket!r}; its sockets: {', '.join(s['name'] for s in built.sockets) or 'none'}; nothing changed.")
|
||||
if kinds is not None and found[0]["type"] not in kinds:
|
||||
raise Refused(f"{what}: socket {socket!r} of {obj.name!r} is a {found[0]['type']} socket; this takes a {' or '.join(kinds)} socket; nothing changed.")
|
||||
return {"object": obj, "matrix": np.array(obj.matrix_world) @ found[0]["matrix"], "size": found[0]["size"], "type": found[0]["type"], "name": text,
|
||||
"depsgraph": evaluable(context, obj)[0]}
|
||||
|
||||
def rows(self):
|
||||
"""(the clamps' 'Object:socket' texts, the joint as {socket, standoff, range} or None), each refused by shape."""
|
||||
try:
|
||||
clamps, joint = json.loads(self.clamps or "[]"), json.loads(self.joint) if self.joint else None
|
||||
except ValueError as error:
|
||||
raise Refused(f"clamps and joint must be JSON ({error}); nothing changed.") from None
|
||||
if not isinstance(clamps, list) or len(clamps) > HOSE_CLAMPS:
|
||||
raise Refused(f"clamps must be a JSON array of 0 to {HOSE_CLAMPS} objects; nothing changed.")
|
||||
for index, row in enumerate(clamps):
|
||||
if not isinstance(row, dict) or set(row) != {"socket"} or not isinstance(row["socket"], str):
|
||||
raise Refused(f"clamps[{index}] must be an object of socket, an 'Object:socket' text; nothing changed.")
|
||||
if joint is not None:
|
||||
span = joint.get("range") if isinstance(joint, dict) else None
|
||||
if (not isinstance(joint, dict) or set(joint) != {"socket", "standoff", "range"} or not isinstance(joint["socket"], str)
|
||||
or not (core.finite(joint["standoff"]) and 0.0 <= joint["standoff"] <= 10.0)
|
||||
or not (isinstance(span, list) and len(span) == 2 and all(core.finite(v) and -360.0 <= v <= 360.0 for v in span) and 0.0 <= span[1] - span[0] <= 360.0)):
|
||||
raise Refused("joint must be an object of socket (an 'Object:socket' text), standoff (0 to 10) and range ([lo, hi] in degrees, lo to hi at most 360, each within 360 of 0); nothing changed.")
|
||||
return [row["socket"] for row in clamps], joint
|
||||
|
||||
def crossed(self, start, end, kits) -> list:
|
||||
"""The pins between two objects, [(child, the parent's pivot socket, roll)]: a connection is a child's parent
|
||||
pointer and its kit_parent_socket (link), and it is a pin when that socket is a pivot. Read along both parent
|
||||
chains up to the first object they share; with none shared, along both whole chains."""
|
||||
up, down = self.chain(start), self.chain(end)
|
||||
shared = [obj for obj in up if obj in down]
|
||||
between = up[:up.index(shared[0])] + down[:down.index(shared[0])] if shared else up + down
|
||||
pins = []
|
||||
for child in between:
|
||||
stated = link(child)
|
||||
if stated is None or child.parent is None or PART not in child.parent:
|
||||
continue
|
||||
socket = [s for s in built_part(child.parent, kits)[1].sockets if s["name"] == stated[1] and s["type"] == "pivot"]
|
||||
if socket:
|
||||
pins.append((child, socket[0], stated[2]))
|
||||
return pins
|
||||
|
||||
def trees(self, depsgraph, hose, child, kits):
|
||||
"""(a tree of every mesh the depsgraph evaluates but this hose, the pin's child side and the hoses through
|
||||
the pin; a tree of the child side: the objects whose parent chain passes `child`; a tree of the other hoses
|
||||
that cross the pin of `child`), in world space; None for a side with no face. Membership of the depsgraph is
|
||||
what makes a mesh an obstacle: no flag or name is read for that. A hose through the same pin bends with it and
|
||||
belongs to neither side: it is an obstacle where it stands (the first two trees and it are what a route keeps
|
||||
clear of), and across the rolls each hose is measured against the parts of the two sides, not against where
|
||||
the other hose stood. Only evaluated meshes are read: no datablock is made or freed."""
|
||||
sides = ([], [], [])
|
||||
for evaluated in depsgraph.objects:
|
||||
source = evaluated.original
|
||||
if evaluated.type != "MESH" or source == hose or not len(evaluated.data.polygons):
|
||||
continue
|
||||
mesh, world = evaluated.data, np.array(evaluated.matrix_world)
|
||||
points = np.zeros(3 * len(mesh.vertices))
|
||||
mesh.vertices.foreach_get("co", points)
|
||||
mesh.calc_loop_triangles()
|
||||
corners = np.zeros(3 * len(mesh.loop_triangles), dtype=np.int32)
|
||||
mesh.loop_triangles.foreach_get("vertices", corners)
|
||||
sides[2 if child is not None and self.through(source, child, kits) else int(child is not None and child in self.chain(source))].append((points.reshape(-1, 3) @ world[:3, :3].T + world[:3, 3], corners.reshape(-1, 3)))
|
||||
made = []
|
||||
for side in sides:
|
||||
offsets = np.cumsum([0] + [len(points) for points, _ in side[:-1]])
|
||||
made.append(BVHTree.FromPolygons(np.vstack([points for points, _ in side]).tolist(), np.vstack([corners + offset for (_, corners), offset in zip(side, offsets)]).tolist())
|
||||
if side else None)
|
||||
return made
|
||||
|
||||
def through(self, source, child, kits) -> bool:
|
||||
"""Whether an object is a hose whose two stated ends stand on the two sides of the pin of `child`."""
|
||||
try:
|
||||
stated = json.loads(source.get(HOSE, "null"))
|
||||
ends = [bpy.data.objects.get(text if text in bpy.data.objects else text.rsplit(":", 1)[0]) for text in (stated["start"], stated["end"])]
|
||||
except (ValueError, TypeError, KeyError, AttributeError):
|
||||
return False
|
||||
return None not in ends and any(found[0] == child for found in self.crossed(ends[0], ends[1], kits))
|
||||
|
||||
@staticmethod
|
||||
def reader(trees, cap: float):
|
||||
"""A route distance over trees: how far each point stands from the nearest face, no further than cap (a capped
|
||||
find_nearest costs 3.4 us on 82,000 faces where an uncapped one costs 100)."""
|
||||
def distance(points):
|
||||
out = np.full(len(points), cap)
|
||||
for tree in trees:
|
||||
if tree is not None:
|
||||
for index, point in enumerate(np.asarray(points, dtype=np.float64).tolist()):
|
||||
found = tree.find_nearest(point, cap)[3]
|
||||
if found is not None and found < out[index]:
|
||||
out[index] = found
|
||||
return out
|
||||
return distance
|
||||
|
||||
@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 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:
|
||||
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(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
|
||||
each of its ends, and at each clamp a pad on the socket's face and a strap around the bundle. The ups are
|
||||
route.frames', turned so the bundle lies flat on the first clamp."""
|
||||
curve = route.thinned(curve, 0.05 * r) # an arc's chord is at least a twelfth of a radius at the least bend
|
||||
steps = np.diff(curve, axis=0)
|
||||
steps /= np.linalg.norm(steps, axis=1)[:, None]
|
||||
tangent = np.vstack([steps[:1], steps[:-1] + steps[1:], steps[-1:]])
|
||||
tangent /= np.linalg.norm(tangent, axis=1)[:, None]
|
||||
ups = route.frames(curve, start["matrix"][:3, 1])
|
||||
seats = [int(np.argmin(np.linalg.norm(curve - (clamp["matrix"][:3, 3] + clamp["matrix"][:3, 2] * stand), axis=1))) for clamp in clamps]
|
||||
if clamps: # rotation-minimising ups keep their angle to each other: turning the first turns every one as much
|
||||
k, z = seats[0], clamps[0]["matrix"][:3, 2]
|
||||
turn = math.atan2(float(tangent[k] @ np.cross(ups[k], z)), float(ups[k] @ z))
|
||||
ups = route.frames(curve, ups[0] * math.cos(turn) + np.cross(tangent[0], ups[0]) * math.sin(turn))
|
||||
side = np.cross(ups, tangent)
|
||||
shells, section = [], core.circle(r, HOSE_SEGMENTS)
|
||||
for index in range(self.count):
|
||||
path = curve + side * ((index - (self.count - 1) / 2.0) * spread)
|
||||
shells.append(core.sweep(path, section, ups))
|
||||
for at, along_, up in ((path[0], tangent[0], ups[0]), (path[-1], -tangent[-1], ups[-1])):
|
||||
shells.append(core.sweep([at, at + along_ * 4.5 * r], core.circle(1.45 * r, HOSE_SEGMENTS), up))
|
||||
shells.append(core.sweep([at + along_ * 4.5 * r, at + along_ * 6.0 * r], core.circle(1.2 * r, HOSE_SEGMENTS), up))
|
||||
band, reach = 0.5 * r, 1.25 * r + 1e-4 # a strap's thickness, and its mid-line's distance from a hose's centre
|
||||
for clamp, k in zip(clamps, seats):
|
||||
centre, across, up = curve[k], side[k], ups[k]
|
||||
turns = np.radians(np.arange(-90.0, 90.0 + 1e-9, 30.0))
|
||||
loop = ([centre + across * (half_width + reach * math.cos(a)) + up * (reach * math.sin(a)) for a in turns]
|
||||
+ [centre - across * (half_width + reach * math.cos(a)) - up * (reach * math.sin(a)) for a in turns])
|
||||
loop = np.array(loop if half_width > 1e-9 else loop[:6] + loop[7:13])
|
||||
shells.append(core.sweep(loop, core.profile("box", band, 2.0 * r, band), tangent[k], closed=True))
|
||||
face, out = clamp["matrix"][:3, 3], clamp["matrix"][:3, 2]
|
||||
shells.append(core.sweep([face, face + out * (float(((loop - face) @ out).min()) + 0.25 * band)], core.circle(1.5 * r + 0.5 * half_width, HOSE_SEGMENTS), clamp["matrix"][:3, 1]))
|
||||
return core.joined(shells)
|
||||
|
||||
|
||||
class BROKKR_KITBASH_OT_describe(PolishOperator):
|
||||
"""List a kit's parts, or one part: params with type, bounds, default and doc, and sockets in the part's frame
|
||||
at default params"""
|
||||
|
|
@ -1437,7 +1849,7 @@ class BROKKR_KITBASH_OT_report(PolishOperator):
|
|||
classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KITBASH_OT_describe, BROKKR_KITBASH_OT_report,
|
||||
BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_roll, BROKKR_KITBASH_OT_aim, BROKKR_KITBASH_OT_reach,
|
||||
BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, BROKKR_KITBASH_OT_apply, BROKKR_KITBASH_OT_ribs,
|
||||
BROKKR_KITBASH_OT_shell)
|
||||
BROKKR_KITBASH_OT_shell, BROKKR_KITBASH_OT_hose)
|
||||
|
||||
|
||||
def register():
|
||||
|
|
|
|||
|
|
@ -781,6 +781,111 @@
|
|||
"doc": "evaluate the wall (Kit Subsurf and Kit Solidify alone) and report folded, the number of its inner faces that fold over"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "brokkr_kitbash.hose",
|
||||
"doc": "Route a bundle of hoses between two sockets, around every mesh Blender evaluates in the scene. start and end are 'Object:socket' on a kit part (a hose or flange socket no narrower than the bundle) or 'Object' alone, an empty whose z the hose leaves along. A leg runs between each pair of waypoints (a fitting's lead end, each clamp, the pin point): it is searched on a voxel grid of its ends' box plus 0.25 m (at most 524288 voxels), pulled taut with room for its bends where a way has it, and the whole polyline is rounded, each corner by the largest arc its measured room allows. That polyline is a seed: one refused for want of straight between its corners is refined in continuous space (vertices dropped, moved and added, each change proven clear), and before a route is refused the legs are searched again on two more grid origins and at half the step. The refusal then names the steps and origins tried and the first seed's refusal, and says this shows no route was found, not that none exists; it says the bundle is too stiff only where that is proven at a port. The innermost hose's bend radius is at least bend outside diameters, and a fitting keeps a straight of 8 radii (a ferrule, then 1.5 outside diameters). The centre line keeps the bundle's half width plus clearance from every other mesh, other hoses included, outside those leads. sag hangs the middle of each free span by that many outside diameters, never by more than half the room measured along the span; a route the sag breaks is made taut instead (sag in the report reads 0). clamps is a JSON array of up to 8 {\"socket\": \"Object:socket\"}, mount sockets in order along the hose: the bundle runs straight over each, along the socket's y, and gets a pad and a strap. A hose may cross one pin (a pivot connection between its ends' parts): joint is then {\"socket\": \"Object:socket\", \"standoff\": metres, \"range\": [lo, hi]}, a socket on that pin's axis whose z runs along it; the hose passes through the point standoff beyond it, so each side's straights move with their own part and only the bend at that point changes. The whole range from lo to hi is measured without posing anything, each side against the other side's parts: a roll every 5 degrees answers for the rolls about it by what a point can move within them, and more are measured between where that falls short; another hose through the same pin is kept clear of where it stands, not across the rolls (follow-up aetheria-release:follow_up:hose-motion-clearance-from-skinning owes that check). Every line is measured so that nothing thinner than a spacing can stand between two readings, whatever the step. The hose is one mesh object, a child of the start's object, and a bake of the scene at the call: after a part moves or rolls, run hose again on its name to rebuild it in place. Where it crosses a pin it is meant to be skinned between the bones on either side; no weights are written. Refuses before it writes anything, naming the leg, corner, point or roll. Reports object, rebuilt, hoses, length, lengthChange (over the range, of the centre line as each roll rounds it), floor, clearance (least beyond the bundle, outside the leads; readings stop at capped), voxels per leg, seed {step, offset, refined} (the grid that gave the route, and whether its polyline was refined), sag per leg in metres, rolls (how many were measured), worstRoll, worstClearance (least over the range, each reading less what its point can move within its roll's bin), faces, volume, nonManifoldEdges and radii {least, corners}.",
|
||||
"changesScene": true,
|
||||
"editModeSafe": false,
|
||||
"result": "brokkr_mesh_polish_result",
|
||||
"fields": [
|
||||
{
|
||||
"name": "object_name",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"minLength": 1,
|
||||
"maxLength": 63,
|
||||
"doc": "the hose's name: no object's name, or a hose's, which is then rebuilt"
|
||||
},
|
||||
{
|
||||
"name": "start",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"minLength": 1,
|
||||
"maxLength": 96,
|
||||
"doc": "'Object:socket' (a hose or flange socket of a kit part), or 'Object' (an empty: the hose leaves along its z)"
|
||||
},
|
||||
{
|
||||
"name": "end",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"minLength": 1,
|
||||
"maxLength": 96,
|
||||
"doc": "as start"
|
||||
},
|
||||
{
|
||||
"name": "count",
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 8,
|
||||
"default": 1,
|
||||
"doc": "hoses in the bundle, side by side"
|
||||
},
|
||||
{
|
||||
"name": "radius",
|
||||
"type": "number",
|
||||
"minimum": 0.003,
|
||||
"maximum": 0.1,
|
||||
"default": 0.01,
|
||||
"doc": "a hose's outside radius"
|
||||
},
|
||||
{
|
||||
"name": "spread",
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 0.5,
|
||||
"default": 0,
|
||||
"doc": "centre to centre between hoses; 0: 2.6 radii"
|
||||
},
|
||||
{
|
||||
"name": "clearance",
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 0.5,
|
||||
"default": 0.01,
|
||||
"doc": "free space kept between the bundle and every other mesh"
|
||||
},
|
||||
{
|
||||
"name": "bend",
|
||||
"type": "number",
|
||||
"minimum": 1,
|
||||
"maximum": 20,
|
||||
"default": 4,
|
||||
"doc": "least bend radius of the innermost hose, in outside diameters"
|
||||
},
|
||||
{
|
||||
"name": "step",
|
||||
"type": "number",
|
||||
"minimum": 0.005,
|
||||
"maximum": 0.2,
|
||||
"default": 0.02,
|
||||
"doc": "voxel size of the search; a way narrower than the bundle plus two voxels is not found"
|
||||
},
|
||||
{
|
||||
"name": "sag",
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 8,
|
||||
"default": 1,
|
||||
"doc": "how far the middle of each free span hangs, in outside diameters; 0: taut"
|
||||
},
|
||||
{
|
||||
"name": "clamps",
|
||||
"type": "string",
|
||||
"minLength": 2,
|
||||
"maxLength": 4000,
|
||||
"doc": "a JSON array of 0 to 8 {\"socket\": \"Object:socket\"}, mount sockets in order along the hose",
|
||||
"default": "[]"
|
||||
},
|
||||
{
|
||||
"name": "joint",
|
||||
"type": "string",
|
||||
"minLength": 0,
|
||||
"maxLength": 4000,
|
||||
"doc": "empty, or a JSON object {\"socket\": \"Object:socket\", \"standoff\": 0 to 10, \"range\": [lo, hi]}: the pin the hose crosses",
|
||||
"default": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,7 +5,8 @@
|
|||
"socketTypes": {
|
||||
"flange": {"match": "equal", "doc": "bolted pipe or duct face; size is the bore diameter"},
|
||||
"mount": {"match": "fits", "doc": "flat seat; size is the free diameter around the socket"},
|
||||
"pivot": {"match": "equal", "doc": "pin joint; size is the pin diameter"}
|
||||
"pivot": {"match": "equal", "doc": "pin joint; size is the pin diameter"},
|
||||
"hose": {"match": "fits", "doc": "hose port; size is the widest bundle it takes"}
|
||||
},
|
||||
"parts": [
|
||||
{
|
||||
|
|
@ -173,7 +174,9 @@
|
|||
{"name": "base", "type": "pivot", "size": "0.9*body_r", "at": [0, "0.65*body_r", "0.8*body_r"], "z": "+y", "y": "+z"},
|
||||
{"name": "base_back", "type": "pivot", "size": "0.9*body_r", "at": [0, "-0.65*body_r", "0.8*body_r"], "z": "-y", "y": "+z"},
|
||||
{"name": "rod_end", "type": "pivot", "size": "0.9*body_r", "at": [0, "0.65*body_r", "3.8*body_r+body_len+extension"], "z": "+y", "y": "+z"},
|
||||
{"name": "rod_end_back", "type": "pivot", "size": "0.9*body_r", "at": [0, "-0.65*body_r", "3.8*body_r+body_len+extension"], "z": "-y", "y": "+z"}
|
||||
{"name": "rod_end_back", "type": "pivot", "size": "0.9*body_r", "at": [0, "-0.65*body_r", "3.8*body_r+body_len+extension"], "z": "-y", "y": "+z"},
|
||||
{"name": "port_cap", "type": "hose", "size": "0.4*body_r", "at": ["1.45*body_r", 0, "1.75*body_r"], "z": "+x", "y": "+z"},
|
||||
{"name": "port_rod", "type": "hose", "size": "0.4*body_r", "at": ["1.45*body_r", 0, "2.25*body_r+body_len"], "z": "+x", "y": "+z"}
|
||||
]
|
||||
},
|
||||
{
|
||||
|
|
|
|||
656
surfaces/blender/brokkr_kitbash/route.py
Normal file
656
surfaces/blender/brokkr_kitbash/route.py
Normal file
|
|
@ -0,0 +1,656 @@
|
|||
"""The path of a hose: from waypoints and a distance oracle to a curve with frames. numpy only, tested without
|
||||
Blender (tests/test_route.py); brokkr_kitbash.hose is the bpy around it (docs/kitbash.md, Hoses between sockets).
|
||||
|
||||
A `distance` is a callable over (N, 3) points that answers how far each stands from the nearest obstacle; the caller
|
||||
owns what an obstacle is and may cap the answer. `need` is how far a hose's centre line must stay from every
|
||||
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). 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
|
||||
unseen between them; no measurement depends on the search's step. The legs joined are one polyline; fillet rounds its
|
||||
corners, each by the largest arc its measured room allows, and verify measures the curve. sag lowers the middle of a leg
|
||||
by what its room allows. passes turns the part of a polyline beyond a point on a pin's axis through the pin's rolls,
|
||||
each roll answering for the rolls about it by what a point can move within them. frames gives the rotation-minimising ups the tubes are swept
|
||||
with (Wang, Juettler, Zheng and Liu, "Computation of rotation minimizing frames", ACM TOG 27(1), 2008: the double
|
||||
reflection method).
|
||||
|
||||
Every refusal is a RouteError that names the leg, corner, point or roll.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from typing import NamedTuple
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
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
|
||||
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:
|
||||
return "[" + ", ".join(f"{float(v):.4g}" for v in point) + "]"
|
||||
|
||||
|
||||
def bundle(count: int, radius: float, spread: float, clearance: float, bend: float) -> dict:
|
||||
"""The sizes a bundle of `count` hoses of `radius` routes by. spread is centre to centre (0: 2.6 radii). width is
|
||||
across the bundle; envelope its half; need is how far the centre line stays from obstacles; floor the least
|
||||
radius of the centre line, bend outside diameters for the innermost hose, which runs half the bundle's spread
|
||||
inside it; lead the straight a fitting keeps: a ferrule of 5 radii, then 1.5 outside diameters before any bend."""
|
||||
spread = spread if spread > 0.0 else 2.6 * radius
|
||||
half = (count - 1) / 2.0 * spread
|
||||
return {"spread": spread, "width": 2.0 * half + 2.0 * radius, "envelope": half + radius, "need": half + radius + clearance,
|
||||
"floor": bend * 2.0 * radius + half, "lead": 5.0 * radius + 1.5 * 2.0 * radius}
|
||||
|
||||
|
||||
class Grid(NamedTuple):
|
||||
"""Voxels of a box: free[i, j, k] is the voxel centred at lo + step * (i, j, k)."""
|
||||
free: np.ndarray
|
||||
lo: np.ndarray
|
||||
step: float
|
||||
|
||||
|
||||
def grid(lo, hi, step: float, distance, need: float, limit: int = 2 ** 19) -> Grid:
|
||||
"""The voxels of the box lo..hi at `step` that stand at least `need` from every obstacle. Refuses a box of more
|
||||
than `limit` voxels, naming a step that fits."""
|
||||
lo, hi = np.asarray(lo, dtype=np.float64), np.asarray(hi, dtype=np.float64)
|
||||
shape = lambda s: np.maximum(1, np.ceil((hi - lo) / s - 1e-9).astype(np.int64) + 1) # noqa: E731
|
||||
n = shape(step)
|
||||
if int(n.prod()) > limit:
|
||||
fits = step
|
||||
while int(shape(fits).prod()) > limit:
|
||||
fits *= 1.05
|
||||
raise RouteError(f"its search box of {spot(hi - lo)} m is {int(n.prod())} voxels at step {step:g}, over {limit}: a step of {math.ceil(fits * 1e4) / 1e4:g} fits")
|
||||
axes = [lo[i] + step * np.arange(n[i]) for i in range(3)]
|
||||
points = np.stack(np.meshgrid(*axes, indexing="ij"), axis=-1).reshape(-1, 3)
|
||||
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
|
||||
wave nearer that stands nearest the goal. Refuses an end that is not free, and a start no wave reaches."""
|
||||
start, goal, n = tuple(int(v) for v in start), tuple(int(v) for v in goal), free.shape
|
||||
for name, voxel in (("start", start), ("end", goal)):
|
||||
if not free[voxel]:
|
||||
raise RouteError(f"its {name} voxel is not free")
|
||||
unreached = np.iinfo(np.int32).max
|
||||
waves = np.full(n, unreached, dtype=np.int32)
|
||||
waves[goal] = 0
|
||||
front = np.zeros(n, dtype=bool)
|
||||
front[goal] = True
|
||||
wave = 0
|
||||
while waves[start] == unreached and front.any():
|
||||
wave += 1
|
||||
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")
|
||||
way, at = [start], start
|
||||
while waves[at] > 0:
|
||||
nearer = [(math.dist(m, goal), m) for m in ((at[0] + i, at[1] + j, at[2] + k) for i, j, k in NEIGHBOURS)
|
||||
if all(0 <= m[axis] < n[axis] for axis in range(3)) and waves[m] == waves[at] - 1]
|
||||
at = min(nearer)[1]
|
||||
way.append(at)
|
||||
return way
|
||||
|
||||
|
||||
class Measured(NamedTuple):
|
||||
least: float # the least reading taken; of a measure that fell short, the reading that fell short
|
||||
where: np.ndarray # the point it was taken at
|
||||
short: bool # a piece is not proven to keep need
|
||||
|
||||
|
||||
def measure(a, b, distance, need: float, rate: float = 1.0, within: float | None = None) -> Measured:
|
||||
"""The segments a[i]..b[i] measured so that what stands between two readings is bounded, not sampled. A piece's
|
||||
middle reads d, and a reading changes by at most `rate` times the distance moved (1 for a distance to obstacles),
|
||||
so every point of a piece of length L reads at least d - rate x L / 2. A piece whose bound holds need is proven;
|
||||
one whose middle reads under need falls short; any other is halved, down to FINE, where a piece still unproven
|
||||
falls short too: a measure that is not short has proven need of every point, and a line that keeps need by under
|
||||
rate x FINE / 2 is refused with the ones that do not keep it. With `within`, pieces are halved further until each
|
||||
one's bound is within that much of the least reading (or the piece is FINE long): least less `within` then bounds
|
||||
every point from below."""
|
||||
a, b = np.atleast_2d(np.asarray(a, dtype=np.float64)), np.atleast_2d(np.asarray(b, dtype=np.float64))
|
||||
least, where = math.inf, None
|
||||
while len(a):
|
||||
middle, length = (a + b) / 2.0, np.linalg.norm(b - a, axis=1)
|
||||
reads = np.asarray(distance(middle), dtype=np.float64)
|
||||
bound = reads - rate * length / 2.0
|
||||
unproven = bound < need - HELD
|
||||
short = np.flatnonzero(unproven & ((reads < need - HELD) | (length <= FINE)))
|
||||
if len(short):
|
||||
worst = int(short[np.argmin(reads[short])])
|
||||
return Measured(float(reads[worst]), middle[worst], True)
|
||||
if reads.min() < least:
|
||||
least, where = float(reads.min()), middle[int(np.argmin(reads))]
|
||||
again = unproven if within is None else unproven | ((bound < least - within) & (length > FINE))
|
||||
a, b = np.concatenate([a[again], middle[again]]), np.concatenate([middle[again], b[again]])
|
||||
return Measured(least, where, False)
|
||||
|
||||
|
||||
def falls(reading: float, need: float) -> str:
|
||||
"""How a reading that fell short of need reads in a refusal."""
|
||||
return (f"under the {need:.4g} m the bundle needs" if reading < need - HELD else
|
||||
f"too near the {need:.4g} m the bundle needs to prove it of what stands between two readings")
|
||||
|
||||
|
||||
def clear(a, b, distance, need: float, rate: float = 1.0) -> bool:
|
||||
return not measure(a, b, distance, need, rate).short
|
||||
|
||||
|
||||
def room(a, b, distance, need: float) -> float:
|
||||
"""What every point of the segment a..b stands beyond need, less what verify needs to prove an arc that uses it
|
||||
all: the least reading of a measure within FINE, less FINE for its bound and half of FINE more."""
|
||||
return measure(a, b, distance, -math.inf, within=FINE).least - need - 1.5 * FINE
|
||||
|
||||
|
||||
def span(curve, low: float, high: float) -> np.ndarray:
|
||||
"""The part of a polyline between two lengths along it; no point when low is not under high."""
|
||||
curve = np.asarray(curve, dtype=np.float64)
|
||||
s = np.r_[0.0, np.cumsum(np.linalg.norm(np.diff(curve, axis=0), axis=1))]
|
||||
low, high = max(low, 0.0), min(high, float(s[-1]))
|
||||
if not low < high:
|
||||
return curve[:0]
|
||||
ends = np.stack([np.interp((low, high), s, curve[:, axis]) for axis in range(3)], axis=1)
|
||||
return np.vstack([ends[:1], curve[(s > low) & (s < high)], ends[1:]])
|
||||
|
||||
|
||||
def pull(points, distance, need: float, rate: float = 1.0) -> np.ndarray:
|
||||
"""A polyline pulled taut: from each kept point, the farthest later point in clear sight (the line between them
|
||||
swept at need); the next point when none is."""
|
||||
points = np.asarray(points, dtype=np.float64)
|
||||
kept, i = [points[0]], 0
|
||||
while i < len(points) - 1:
|
||||
j = len(points) - 1
|
||||
while j > i + 1 and not clear(points[i], points[j], distance, need, rate):
|
||||
j -= 1
|
||||
kept.append(points[j])
|
||||
i = j
|
||||
return np.array(kept)
|
||||
|
||||
|
||||
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. `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 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 - 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 = []
|
||||
for label, point in (("start", a), ("end", b)):
|
||||
middle = np.clip(np.round((point - cells.lo) / step).astype(int), 0, np.array(cells.free.shape) - 1)
|
||||
beside = [tuple(int(v) for v in middle + np.array(d)) for d in [(0, 0, 0)] + NEIGHBOURS]
|
||||
beside = [m for m in beside if all(0 <= m[axis] < cells.free.shape[axis] for axis in range(3)) and cells.free[m]]
|
||||
beside.sort(key=lambda m: float(np.linalg.norm(cells.lo + step * np.array(m) - point)))
|
||||
seen = [m for m in beside if clear(point, cells.lo + step * np.array(m), distance, need)]
|
||||
if not seen:
|
||||
raise RouteError(f"{name}: no free voxel stands in sight of its {label} {spot(point)}: an obstacle is nearer it than {need + pad + REACH * step:.4g} m on every side")
|
||||
ends.append(seen[0])
|
||||
try:
|
||||
way = wavefront(cells.free, ends[0], ends[1])
|
||||
except RouteError as error:
|
||||
raise RouteError(f"{name}: {error}") from None
|
||||
padded = distance if pad <= 0.0 else lambda p: np.asarray(distance(p)) - np.minimum(pad, 0.5 * np.minimum(np.linalg.norm(p - a, axis=1), np.linalg.norm(p - b, axis=1)))
|
||||
return pull(np.vstack([a[None], cells.lo + step * np.array(way, dtype=np.float64), b[None]]), padded, need, 1.0 if pad <= 0.0 else 1.5), int(cells.free.size)
|
||||
|
||||
|
||||
def sag(points, depth: float, room, down=(0.0, 0.0, -1.0)):
|
||||
"""(the polyline, the metres it was lowered): the middle of a leg's longest segment lowered by `depth`, less where
|
||||
the segment runs along `down` (a hanging span sags, a vertical one does not) and never by more than half the room
|
||||
`room(a, b)` measures along that segment: both halves then stand within that much of the taut segment, so they keep
|
||||
need with as much room again for the arc at the middle. A segment shorter than 8 times the drop is left taut."""
|
||||
points = np.asarray(points, dtype=np.float64)
|
||||
lengths = np.linalg.norm(np.diff(points, axis=0), axis=1)
|
||||
i = int(np.argmax(lengths))
|
||||
a, b = points[i], points[i + 1]
|
||||
across = np.asarray(down, dtype=np.float64) - (b - a) / lengths[i] * float(np.asarray(down) @ (b - a) / lengths[i])
|
||||
hang = float(np.linalg.norm(across))
|
||||
if depth <= 0.0 or hang < 1e-6:
|
||||
return points, 0.0
|
||||
drop = min(depth, 0.5 * (math.inf if room is None else float(room(a, b)))) * hang
|
||||
if drop <= 1e-6 or lengths[i] < 8.0 * drop:
|
||||
return points, 0.0
|
||||
return np.vstack([points[:i + 1], ((a + b) / 2.0 + across / hang * drop)[None], points[i + 1:]]), drop
|
||||
|
||||
|
||||
def _turns(points):
|
||||
steps = np.diff(points, axis=0)
|
||||
lengths = np.linalg.norm(steps, axis=1)
|
||||
if (lengths < 1e-9).any():
|
||||
raise RouteError(f"point {int(np.argmax(lengths < 1e-9))} {spot(points[int(np.argmax(lengths < 1e-9))])}: the segment from it is shorter than 1e-9")
|
||||
unit = steps / lengths[:, None]
|
||||
return lengths, unit, np.arccos(np.clip(np.einsum("ij,ij->i", unit[:-1], unit[1:]), -1.0, 1.0))
|
||||
|
||||
|
||||
def _kept(count: int, lead: float, keep) -> np.ndarray:
|
||||
keep = np.zeros(count) if keep is None else np.array(keep, dtype=np.float64)
|
||||
keep[0] += lead
|
||||
keep[-1] += lead
|
||||
return keep
|
||||
|
||||
|
||||
def _radius(point, before, after, turn: float, cap: float, room) -> float:
|
||||
"""The largest radius of the arc at a corner whose tangent lengths stay within cap and whose room allows it: the
|
||||
arc stands within radius x (1 - cos(turn / 2)) of its two tangent segments, so with that much room beyond need
|
||||
measured along them it keeps need (the triangle inequality). The tangent segments grow with the radius, so the
|
||||
room can only shrink: the largest radius is found by bisection."""
|
||||
most = max(cap, 0.0) / math.tan(turn / 2.0)
|
||||
if room is None:
|
||||
return most
|
||||
depth = 1.0 - math.cos(turn / 2.0)
|
||||
|
||||
def fits(radius: float) -> bool:
|
||||
t = radius * math.tan(turn / 2.0)
|
||||
return radius * depth <= min(room(point - before * t, point), room(point, point + after * t))
|
||||
|
||||
if fits(most):
|
||||
return most
|
||||
low, high = 0.0, most
|
||||
for _ in range(24):
|
||||
middle = (low + high) / 2.0
|
||||
low, high = (middle, high) if fits(middle) else (low, middle)
|
||||
return low
|
||||
|
||||
|
||||
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
|
||||
(_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, 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)
|
||||
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):
|
||||
"""(curve, owner): the polyline with the arc of tangent length t[c] at each interior point c + 1, as points
|
||||
ARC to the radian, and for each curve point the corner whose arc it is on (-1 on the straights' ends). Every arc
|
||||
is tangent to both its segments."""
|
||||
points = np.asarray(points, dtype=np.float64)
|
||||
_, unit, turn = _turns(points)
|
||||
curve, owner = [points[0]], [-1]
|
||||
for c in range(len(turn)):
|
||||
corner, before, after = points[c + 1], unit[c], unit[c + 1]
|
||||
if turn[c] < STRAIGHT or t[c] < 1e-9:
|
||||
curve.append(corner)
|
||||
owner.append(c)
|
||||
continue
|
||||
radius = t[c] / math.tan(turn[c] / 2.0)
|
||||
inward = after - before * float(before @ after)
|
||||
inward /= np.linalg.norm(inward)
|
||||
centre = corner - before * t[c] + inward * radius
|
||||
for angle in np.linspace(0.0, turn[c], max(2, int(math.ceil(turn[c] * ARC))) + 1):
|
||||
curve.append(centre + radius * (before * math.sin(angle) - inward * math.cos(angle)))
|
||||
owner.append(c)
|
||||
curve.append(points[-1])
|
||||
owner.append(-1)
|
||||
curve, owner = np.array(curve), np.array(owner)
|
||||
keep = np.r_[True, np.linalg.norm(np.diff(curve, axis=0), axis=1) > 1e-9]
|
||||
return curve[keep], owner[keep]
|
||||
|
||||
|
||||
class Filleted(NamedTuple):
|
||||
curve: np.ndarray # (N, 3)
|
||||
owner: np.ndarray # (N,) the corner a curve point's arc belongs to, -1 off the arcs
|
||||
t: np.ndarray # tangent length at each interior point of the polyline
|
||||
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, 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. `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, 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)
|
||||
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 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))
|
||||
why = (f"the route passes too near an obstacle to bend here: its segments stand {max(stands, 0.0):.4g} m clear beyond what the bundle needs and the arc at the floor takes {depth:.4g} "
|
||||
"(a lower bend, more room about the obstacle, or a clamp that leads the hose wide of it)")
|
||||
else:
|
||||
why = "it shares a segment with the corner beside it and their tangents do not both fit on it (a lower bend, or the two further apart)"
|
||||
raise RouteError(f"corner {c + 1} at {spot(polyline[c + 1])} turns {math.degrees(turn[c]):.1f} degrees and gets a bend of radius {radii[c]:.4g} m, under the floor {floor:.4g}: {why}")
|
||||
return Filleted(*arcs(polyline, t), t, radii)
|
||||
|
||||
|
||||
def verify(curve, distance, need: float, lead: float, name: str = "the hose") -> float:
|
||||
"""The least distance the curve stands from an obstacle outside its two leads (the first and last `lead` of its
|
||||
length, where it leaves its own ports), within half of FINE (measure). Refuses a curve not proven to keep need at
|
||||
every point, naming the point."""
|
||||
curve = np.asarray(curve, dtype=np.float64)
|
||||
inside = span(curve, lead, float(np.linalg.norm(np.diff(curve, axis=0), axis=1).sum()) - lead)
|
||||
if len(inside) < 2:
|
||||
return math.inf
|
||||
swept = measure(inside[:-1], inside[1:], distance, need, within=FINE / 2.0)
|
||||
if swept.short:
|
||||
raise RouteError(f"{name} stands {swept.least:.4g} m from an obstacle at {spot(swept.where)}, {falls(swept.least, need)}")
|
||||
return swept.least
|
||||
|
||||
|
||||
def thinned(curve, gap: float) -> np.ndarray:
|
||||
"""A curve without the points that stand within `gap` of the point kept before them; its two ends stay. Where two
|
||||
arcs meet tangent to tangent they can leave a straight far shorter than a tube is wide between them, and a
|
||||
section swept over it would fold; with the short straight gone the two arcs meet at one point."""
|
||||
curve = np.asarray(curve, dtype=np.float64)
|
||||
kept = [0]
|
||||
for index in range(1, len(curve)):
|
||||
if np.linalg.norm(curve[index] - curve[kept[-1]]) > gap:
|
||||
kept.append(index)
|
||||
if kept[-1] != len(curve) - 1:
|
||||
kept[-1 if len(kept) > 1 else len(kept):] = [len(curve) - 1]
|
||||
return curve[kept]
|
||||
|
||||
|
||||
def frames(curve, up0) -> np.ndarray:
|
||||
"""An up for each point of a curve, rotation minimising: the first is up0 projected off the tangent, each next the
|
||||
last reflected twice (Wang et al. 2008), so the ups do not twist about the curve. Tangents are the unit bisectors
|
||||
core.sweep stands its sections on. Refuses an up0 along the first tangent."""
|
||||
curve, up = np.asarray(curve, dtype=np.float64), np.asarray(up0, dtype=np.float64)
|
||||
steps = np.diff(curve, axis=0)
|
||||
steps = steps / np.linalg.norm(steps, axis=1)[:, None]
|
||||
tangent = np.vstack([steps[:1], steps[:-1] + steps[1:], steps[-1:]])
|
||||
tangent /= np.linalg.norm(tangent, axis=1)[:, None]
|
||||
r = up - tangent[0] * float(up @ tangent[0])
|
||||
if not np.linalg.norm(r) > 1e-6 * np.linalg.norm(up):
|
||||
raise RouteError(f"up {spot(up)} runs along the curve's first tangent (or is zero)")
|
||||
r = r / np.linalg.norm(r)
|
||||
ups = [r]
|
||||
for i in range(len(curve) - 1):
|
||||
v1 = curve[i + 1] - curve[i]
|
||||
c1 = float(v1 @ v1)
|
||||
r_left = r - (2.0 / c1) * float(v1 @ r) * v1
|
||||
t_left = tangent[i] - (2.0 / c1) * float(v1 @ tangent[i]) * v1
|
||||
v2 = tangent[i + 1] - t_left
|
||||
c2 = float(v2 @ v2)
|
||||
r = r_left - (2.0 / c2) * float(v2 @ r_left) * v2 if c2 > 1e-18 else r_left
|
||||
ups.append(r)
|
||||
return np.array(ups)
|
||||
|
||||
|
||||
def turned(points, origin, axis, degrees: float) -> np.ndarray:
|
||||
"""Points turned `degrees` about the line through origin along axis, right-handed."""
|
||||
axis = np.asarray(axis, dtype=np.float64) / np.linalg.norm(axis)
|
||||
p = np.asarray(points, dtype=np.float64) - origin
|
||||
c, s = math.cos(math.radians(degrees)), math.sin(math.radians(degrees))
|
||||
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)]
|
||||
|
||||
|
||||
def passes(polyline, t, j: int, origin, axis, rolls, finest: float, current: float, parent, child, need: float, floor: float, lead: float, keep=None) -> dict:
|
||||
"""A hose through a pin's rolls, every roll between the first and last of `rolls` and not those alone. `polyline`
|
||||
runs from the parent's side through point j, which stands on the pin's axis (origin, axis), to the child's side;
|
||||
`t` are its tangent lengths at the roll `current`. The points beyond j turn about the axis with the child's parts
|
||||
and the straights and bends on each side move with their own part; only the corner at j is rounded again.
|
||||
|
||||
Each roll of `rolls` answers for a bin: the rolls nearer it than any other. Within a bin of half width w a point
|
||||
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 (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.
|
||||
{rolls: how many were measured, worstRoll, least: the least reading, each less what its point moves within its
|
||||
bin, lengthChange, radius}."""
|
||||
polyline, origin = np.asarray(polyline, dtype=np.float64), np.asarray(origin, dtype=np.float64)
|
||||
axis = np.asarray(axis, dtype=np.float64) / np.linalg.norm(axis)
|
||||
c, least, lengths, radius = j - 1, (math.inf, None), [], math.inf
|
||||
off = float(np.linalg.norm(np.cross(polyline[j] - origin, axis)))
|
||||
if off > 1e-6: # a point counted wrong (a sag's point before it, say) would turn the hose about a point it does not pass
|
||||
raise RouteError(f"point {j} {spot(polyline[j])} of the hose stands {off:.4g} m off the pin's axis: the hose passes the pin at a point on it")
|
||||
kept, sharp = _kept(len(polyline) - 1, lead, keep), np.array(t, dtype=np.float64)
|
||||
sharp[c] = 0.0
|
||||
rolls = [float(v) for v in rolls]
|
||||
edges = [rolls[0]] + [(u + v) / 2.0 for u, v in zip(rolls, rolls[1:])] + [rolls[-1]]
|
||||
bins = [(edges[k + 1], edges[k], roll) for k, roll in reversed(list(enumerate(rolls)))] # a stack: the lowest roll is measured first
|
||||
while bins:
|
||||
high, low, roll = bins.pop()
|
||||
half = max(high - roll, roll - low)
|
||||
width = math.radians(half)
|
||||
posed = np.vstack([polyline[:j + 1], turned(polyline[j + 1:], origin, axis, roll - current)])
|
||||
back = lambda points, roll=roll: turned(points, origin, axis, current - roll) # noqa: E731
|
||||
moves = lambda points: np.linalg.norm(np.cross(points - origin, axis), axis=1) * width # noqa: E731
|
||||
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(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):
|
||||
"""None, or (side, the measure that fell short, the dip) of the bend's two tangent segments at the bin's sharpest turn."""
|
||||
reach, depth = bend * math.tan(sharpest / 2.0), bend * (1.0 - math.cos(sharpest / 2.0))
|
||||
for side, a, b in (("parent's side", corner - unit[c] * reach, corner), ("child's side", corner, corner + unit[c + 1] * reach)):
|
||||
swept = measure(a, b, sides[side], need + depth, 1.0 + width)
|
||||
if swept.short:
|
||||
return side, swept, depth
|
||||
return None
|
||||
|
||||
failed, bend, reach = None, math.inf, 0.0
|
||||
if sharpest >= STRAIGHT:
|
||||
most = max(cap, 0.0) / math.tan(sharpest / 2.0)
|
||||
if most < floor * (1.0 - 1e-9):
|
||||
failed = (f"the bend at the pin turns up to {math.degrees(sharpest):.1f} degrees and its segments leave room for a radius of {most:.4g} m, under the floor {floor:.4g}", None)
|
||||
else:
|
||||
short = fits(floor)
|
||||
if short is not None:
|
||||
failed = (f"the bend at the pin turns up to {math.degrees(sharpest):.1f} degrees and at the floor radius {floor:.4g} its arc can dip {short[2]:.4g} m; "
|
||||
f"the hose's {short[0]} beside it", short[1], need + short[2])
|
||||
else:
|
||||
bend, high_ = floor, most
|
||||
for _ in range(12 if fits(most) is not None else 0):
|
||||
middle = (bend + high_) / 2.0
|
||||
bend, high_ = (middle, high_) if fits(middle) is None else (bend, middle)
|
||||
bend = bend if high_ < most else most
|
||||
reach = bend * math.tan(sharpest / 2.0)
|
||||
curve, owner = arcs(posed, sharp)
|
||||
s = np.r_[0.0, np.cumsum(np.linalg.norm(np.diff(curve, axis=0), axis=1))]
|
||||
at = float(s[np.flatnonzero(owner == c)[0]])
|
||||
for side, part in (("parent's side", span(curve, lead, at - reach)), ("child's side", span(curve, at + reach, float(s[-1]) - lead))):
|
||||
if failed is None and len(part) >= 2:
|
||||
swept = measure(part[:-1], part[1:], sides[side], need, 1.0 + width)
|
||||
if swept.short:
|
||||
failed = (f"the hose's {side}", swept, need)
|
||||
else:
|
||||
least = min(least, (swept.least, float(roll)))
|
||||
if failed is None:
|
||||
radius = min(radius, bend)
|
||||
lengths.append(float(s[-1]) + (0.0 if not math.isfinite(bend) else bend * (float(turn[c]) - 2.0 * math.tan(float(turn[c]) / 2.0))))
|
||||
continue
|
||||
if half > finest and high > low:
|
||||
bins += [(high, (low + high) / 2.0, (low + 3.0 * high) / 4.0), ((low + high) / 2.0, low, (3.0 * low + high) / 4.0)]
|
||||
continue
|
||||
through = f" through the {half:.3g} degrees either side of it" if half > 0.0 else ""
|
||||
if failed[1] is None:
|
||||
raise RouteError(f"roll {roll:.4g}: {failed[0]}{through}")
|
||||
swept, bar = failed[1], failed[2]
|
||||
raise RouteError(f"roll {roll:.4g}: {failed[0]} reads {swept.least:.4g} m from the parts about the pin at {spot(swept.where)}, counting the {float(moves(swept.where[None])[0]):.4g} m it can move against the other side's{through}: "
|
||||
f"{falls(swept.least, bar)}")
|
||||
return {"rolls": len(lengths), "worstRoll": least[1], "least": least[0], "lengthChange": max(lengths) - min(lengths), "radius": radius}
|
||||
|
|
@ -604,6 +604,165 @@ evaluate, but deleting the copy costs the same whole evaluation (1.44 to 1.54 s
|
|||
included, and the hole cut's temporary objects must be deleted too. So a hull with twenty cutters pays their
|
||||
evaluation once for every `ribs` call; iterate planes on the cage before it is cut, or with its Booleans off.
|
||||
|
||||
## Hoses between sockets
|
||||
|
||||
`brokkr_kitbash.hose` routes a bundle of hoses from one socket to another around everything in the scene:
|
||||
|
||||
```json
|
||||
{"action": "brokkr_kitbash.hose", "object_name": "Feed", "start": "ThighRam:port_cap", "end": "ShinRam:port_cap",
|
||||
"count": 3, "radius": 0.006, "clearance": 0.005,
|
||||
"joint": "{\"socket\": \"Shin:end_a_back\", \"standoff\": 0.08, \"range\": [-120, 20]}"}
|
||||
```
|
||||
|
||||
**Ends.** `start` and `end` are `Object:socket` on a kit part, a `hose` socket (an actuator's `port_cap` and
|
||||
`port_rod`) or a `flange`, no narrower than the bundle; or `Object` alone, an empty whose z the hose leaves along.
|
||||
A fitting keeps a straight lead of 8 radii (a ferrule of 5, then 1.5 outside diameters before any bend), and the
|
||||
bundle's clearance is not asked of that lead: it stands on its own port.
|
||||
|
||||
**The path.** `route.py` (numpy, no Blender) owns it. Waypoints are each fitting's lead end, each clamp and the
|
||||
pin point. A leg between two waypoints is searched on a voxel grid of their box plus 0.25 m: a voxel is free when it
|
||||
stands the bundle's half width, the clearance and half a voxel's diagonal from every other mesh, so every step
|
||||
between neighbouring free voxels keeps the clearance; a 26-connected wavefront finds a shortest way and it is
|
||||
pulled taut. The legs joined are one polyline, and each corner is rounded by the largest arc its measured room
|
||||
allows: the arc stands within `radius * (1 - cos(turn / 2))` of its two tangent segments, so with that much room
|
||||
beyond the clearance measured along them it keeps the clearance. Where two arcs would overlap on a segment each
|
||||
keeps the tangent its bend takes at the floor and they share what the segment has left, in proportion to what each
|
||||
asked beyond that; the corner at a pin holds the tangent its sharpest roll takes. The floor is `bend` outside diameters for the innermost hose (the centre line's is half the
|
||||
bundle's spread more). The finished curve is measured once more against every mesh before anything is written.
|
||||
|
||||
**Measured, not sampled.** Every line the route trusts (a sight line of the pull, a tangent segment's room, the
|
||||
finished curve, each side at each roll) is measured by `route.measure`: a reading answers for the piece of line
|
||||
around it, less half the piece's length, because a distance to obstacles changes by no more than the distance
|
||||
moved. A piece that this proves clear is done, one that reads under the need is refused, and any other is halved,
|
||||
down to 1 mm. So a plate thinner than any spacing cannot stand unseen between two readings, and no measurement
|
||||
depends on `step`: `step` sets only how fine the search for a way is. The price is half a millimetre: a line that
|
||||
keeps the clearance by less than that cannot be proven and is refused as too near.
|
||||
|
||||
**Room for the bends.** A line pulled taut at the clearance alone grazes whatever it wraps, and the corner there
|
||||
has no room for an arc; how much it happened to keep changed with `step`, so a bundle could route at 0.02 and at
|
||||
0.03 and be refused at 0.0125. Each leg is therefore searched and pulled with room for its bends first: 0.29 of the
|
||||
floor beyond the clearance, what the arc of a quarter turn at the floor takes (within twice that of a leg's end
|
||||
the pull asks half the distance from the end instead, since an end stands where it is given). A leg with no way
|
||||
that roomy (a clamp stands nearer its seat than that, and so does a gap the bundle only just passes) is searched
|
||||
again without, and the hose is longer where the roomy way goes round.
|
||||
|
||||
**A seed, refined.** The polyline a search gives is a seed. Its vertices stand where the grid's lattice put them,
|
||||
so whether two corners have the straight between them for both bends follows the lattice too: searched and pulled
|
||||
with room alone, the first bundle on the knee routed at steps 0.125 and 0.13 and was refused at 0.1275, and the
|
||||
second was refused at 26 of the 76 steps from 0.0125 to 0.2. Three things take the lattice out of the answer.
|
||||
|
||||
- A corner keeps its floor's tangent before a neighbour gets more (above), and the pin's corner holds what its
|
||||
sharpest roll takes, exactly (`route.sharpest_turn`: the turn's cosine over a range of rolls is a + b cos + c sin).
|
||||
- A seed that is refused is refined in continuous space (`route.relax`). About each segment too short for its
|
||||
corners' tangents at the floor (`route.strain`), a vertex the search placed is dropped, moved along each axis and
|
||||
along its own two segments, or joined by a new one beside a segment's middle; the try that lowers the shortfall
|
||||
most is kept if `route.measure` proves its changed segments clear with the room a leg is pulled with. The moves
|
||||
start a floor long and halve when nothing helps, down to 1 mm. Ports, lead ends, clamp straights and the pin
|
||||
point do not move. The refinement prices straight only: room for an arc is still measured by the fillet after it.
|
||||
- A route still refused is searched again on two more grid origins (half a step along each axis; then 0.31, 0.67
|
||||
and 0.13 of a step), and then at half the step on all three, each seed refined the same way. `seed` in the
|
||||
report is the step and origin that gave the route and whether it was refined.
|
||||
|
||||
The cost is in the refusals and in sameness: a route that cannot be made runs up to six seeds, three of them on 8
|
||||
times the voxels, before it is refused, and the same request at another `step` may take another way round, though
|
||||
never one that clears less than the clearance or bends under the floor.
|
||||
|
||||
A refusal after all that says what was tried, and that this shows no route was found, not that none exists: `the
|
||||
search found no route: it tried steps 0.02 and 0.01, each on grid origins (0, 0, 0), (0.5, 0.5, 0.5), (0.31, 0.67,
|
||||
0.13) of a step, and refined each seed in continuous space; this does not show that no route exists. The first
|
||||
refusal: corner 2 at ...`. The first refusal is the requested step's own seed's, by corner, point or roll, with
|
||||
what that polyline lacked: straight for a tangent, room for an arc (both distances named), or a segment two corners
|
||||
cannot share. An end that stands nearer an obstacle than the bundle needs is refused at once: no grid lifts that.
|
||||
|
||||
`too stiff` is said only where it is proven (`route.leaves`). For its first pi floors of length a curve that bends
|
||||
no tighter than the floor stays out of every ball of radius floor that touches its line where it starts, and ahead
|
||||
of that point, and by then it stands 2 floors away (Schwarz's bound on a chord; Dubins 1957). So where a fitting's
|
||||
lead ends, the hose must reach the sphere of 2 floors through points that keep the clearance and lie outside those
|
||||
balls. They are read on voxels of a sixth of the floor with the bound every other measurement uses, and when they
|
||||
do not join the lead's end to the sphere no route exists at that `bend`: `the bundle is too stiff to leave its
|
||||
start: from the end of its lead at ... no curve that bends at the floor radius ... or wider keeps ... from what
|
||||
stands within ... of it`. The proof is tried at both ports when no route was found. It does not look at clamps or
|
||||
the pin, so a bundle too stiff for the room there gets the search's refusal. The remedies are a lower `bend`,
|
||||
thinner or fewer hoses, waypoints further apart (a larger `standoff`), or a clamp that leads the hose wide.
|
||||
|
||||
**Slack.** `sag` (outside diameters, default 1) lowers the middle of each free span's longest segment along world
|
||||
-z, by less where the span runs steeply, and never by more than half the room measured along it: both halves then
|
||||
keep the clearance with as much room again for the arc at the middle. A route that the sag would break is made
|
||||
taut instead; the report's `sag` lists the metres each leg hangs. 0 routes taut.
|
||||
|
||||
**Clamps.** `clamps` is a JSON array of up to 8 `{"socket": "Object:socket"}`, `mount` sockets in order along the
|
||||
hose. The bundle runs straight along the socket's y through the point its half width, the clearance and one hose
|
||||
radius above the face, for 2 outside diameters each side, and gets a pad on the face and a strap around it. The
|
||||
bundle lies flat on the first clamp; its ups are rotation minimising (Wang et al. 2008), so it does not twist
|
||||
between clamps, and a later clamp's strap follows the bundle as it arrives.
|
||||
|
||||
**A pin.** A hose may cross one pin: a pivot connection between its ends' parts, found from their parent chains.
|
||||
`joint` names a socket on that pin's axis whose z runs along it (the free end face of the pin: a strut's
|
||||
`end_a_back`), a `standoff` and the pin's roll `range`. The hose passes through the point `standoff` beyond that
|
||||
socket, on the axis, as a robot's dress pack does: the straights on each side then move with their own part and
|
||||
only the bend at that point changes with the roll. The whole range is measured without posing anything, not a
|
||||
list of rolls in it. Each roll from `lo` to `hi` in steps of 5 degrees answers for the rolls nearer it than any
|
||||
other: within such a bin of half width w a point that stands rho from the pin's axis moves at most `rho * w`
|
||||
against the other side's parts, so its reading against them counts for that much less. The bend at the pin has one
|
||||
radius through a bin, the largest that fits at the bin's sharpest turn, and its two tangent segments are measured
|
||||
for the clearance and the arc's dip more. A bin that falls short is halved and measured again at each half's
|
||||
middle, down to 0.3 degrees of half width, so a range that is clear costs 9 rolls for 40 degrees and one that
|
||||
passes near a part costs more only there (`rolls` reports how many were measured). A range that fails is refused
|
||||
by roll, side and point (`roll 50.78: the hose's child's side reads 0.0264 m from the parts about the pin at
|
||||
[-0.2122, -0.2044, 0.7269], counting the 0.0005875 m it can move against the other side's through the 0.156 degrees
|
||||
either side of it: under the 0.0266 m the bundle needs`); when the sagged route and the taut one both fail the
|
||||
refusal names both. `worstClearance` is the least reading over the range, each less what its point can move within
|
||||
its bin. `lengthChange` is the centre line's longest less its shortest over the rolls measured, as each rounds the
|
||||
bend. Two pins between the ends are refused: end the hose on a part between them.
|
||||
|
||||
Another hose through the same pin bends with it and belongs to neither side. A route keeps clear of it where it
|
||||
stands, and across the rolls each hose is measured against the parts of the two sides, not against where the other
|
||||
hose stood: give two hoses through one pin different standoffs, and their clearance from each other holds at the
|
||||
pose they were routed at. That is a ruled limit (`aetheria-release:ruling:hose-same-pin-pose-only-now`), and the
|
||||
check it leaves out has an owner: follow-up `aetheria-release:follow_up:hose-motion-clearance-from-skinning` will pose
|
||||
each other hose across the range with the skin blend the output mesh uses. Until it lands nothing measures two hoses
|
||||
through one pin against each other in motion.
|
||||
|
||||
**What it writes.** One mesh object, a child of the start's object under identity matrices, with no modifier and
|
||||
no material: each hose, two ferrule collars at each of its ends, and the clamps, all swept by `core.sweep`.
|
||||
`kit_hose` on it is the request as JSON; the one thing read back from it is which two parts a hose joins, by a
|
||||
later hose that crosses the same pin. Other hoses are obstacles like any mesh, so route the stiffest first. The hose is a bake of the scene at the call: after a part moves or rolls, run `hose`
|
||||
again with the same `object_name` and it is rebuilt in place.
|
||||
|
||||
A hose that crosses a pin stays one object. In the exported mesh it is skinned geometry, meant to be weighted
|
||||
between the bones on either side of the pin, blending near the pin point; the posed shape then comes from the
|
||||
skin, and the rebuild is for stills and for checking the range. This package writes no weights or vertex groups:
|
||||
skin weights are `brokkr_rig`'s.
|
||||
|
||||
**Refusals**, each before anything is written: a name taken by an object that is no hose; an end or clamp that
|
||||
names no object, no such socket, or a socket of the wrong type; a bundle wider than a port, naming both sizes; a
|
||||
part that is scaled or that Blender does not evaluate; a pin crossed with no `joint`, a `joint` with no pin, two
|
||||
pins, a `joint` socket off the pin's axis, the current roll outside `range`; a search box over 524288 voxels,
|
||||
naming a step that fits; an end nearer an obstacle than the bundle needs; a bundle proven too stiff to leave a
|
||||
port; and, once every seed has been tried, no route found, with the first seed's refusal: no way through, a corner
|
||||
under the floor by what its polyline lacked, a curve not proven to keep the clearance at a named point, or a roll
|
||||
that fails.
|
||||
|
||||
**Cost.** Probes in Blender 5.3 on Starfire, medians of 3 interleaved repetitions: a nearest-face query on a tree of
|
||||
81,920 faces takes 100 to 123 us uncapped and 3.4 us capped at 0.06 m, so every query is capped; on a grid of
|
||||
97,061 voxels with a wall and a hole a heap A* took 8.47 s (56,824 pops) and the wavefront 0.26 s (100 waves); on
|
||||
a knee of five boxes (96,565 voxels at 0.02 m) the occupancy took 0.46 s uncapped, the search 0.19 s, the pull, the
|
||||
fillet and the verification under 2 ms together, 27 rolls 0.056 s and the sweep of three hoses 4 ms. The live
|
||||
knee of `tests/live/kitbash_hose.py` (two struts, two actuators and a plate; two legs of 79,488 and 53,406
|
||||
voxels at roll 0, timed at roll 10; three hoses, 9 rolls) took 0.80 s a call, median of 3 each after one report
|
||||
action, where it took 0.50 s when lines were sampled at half a voxel and each leg was searched once: the occupancy
|
||||
is read to a larger cap and the room, the curve and the rolls are measured to 1 mm near what they pass. With
|
||||
seeds refined and retried the same call took 0.64 s. Over the 76 steps from 0.0125 to 0.2 on that knee, one call
|
||||
each with three other Blenders running, the first bundle took 0.53 s at the median and 2.34 s at most, and the
|
||||
second 0.32 s and 2.56 s; of the second's 76 routes 8 came from a refined seed, 3 from another grid origin and 12
|
||||
from half the step.
|
||||
|
||||
`tests/test_route.py` proves the path without Blender (the half-diagonal rule, a plate between two readings, a leg's
|
||||
room where it wraps, the fillet's tangency, sharing, room and floor, a corner's floor before its neighbour's share, a
|
||||
seed refined where the oracle allows, the proof of too stiff, the sharpest turn of a range of rolls, the sag's bound, the frames against the double
|
||||
reflection method, the rolls and a plate between two of them, the bend at the pin's room), and
|
||||
`tests/live/kitbash_hose.py` the action in Blender.
|
||||
|
||||
## Expressions
|
||||
|
||||
Every numeric field of a shape or socket, and `bevel`, is a number or a string over the part's params:
|
||||
|
|
@ -638,6 +797,7 @@ vertices overflow.
|
|||
| `brokkr_kitbash.apply` | `object_name` | Bakes the evaluated mesh into the kit part and clears its modifiers and the collections its Booleans held. Refuses a part with no modifiers, a mesh another object shares and a part Blender does not evaluate. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. |
|
||||
| `brokkr_kitbash.ribs` | `object_name` (the cage), `ribs_name`, `planes` (a JSON array of 1 to 64 `{origin, normal}`, up to 16000 characters), `standoff`, `depth`, `thickness`, `step`, `holes`, `posts`, `post_r`, `bridge`, `clearance`, `longerons` (a JSON array of 0 to 16 `{origin, axis, toward}`, up to 8000 characters), `longeron`, `longeron_w`, `longeron_h`, `longeron_t` | Derives ribs, lightening holes, posts and longerons from the cage as it is cut, as one mesh object under it. Refuses before it writes anything, naming the plane or longeron. Reports `object`, `ribs`, `thickness`, `sections: [{plane, chains, pieces, length, open}]`, `posts`, `holes`, `longerons: [{index, stations}]` (trimmed to a receipt, with `longeronsOmitted`), `faces`, `volume` and `nonManifoldEdges`. |
|
||||
| `brokkr_kitbash.shell` | `object_name`, `sheet` (a JSON object `{rings, closed, mirror, creases, rim, flip}`, up to 32000 characters), `thickness`, `offset`, `levels`, `bevel`, `count_folds` | Makes a faceted, hollow armor shell from a loft of rings with crease runs, or rebuilds a shell's cage in place under its cutters and ribs. Refuses before it writes anything, naming the field and index. Reports `object`, `rebuilt`, `rings`, `points`, `cageFaces`, `creases`, `folded` (with `count_folds`, the number of the evaluated wall's inner faces that fold; else null), `corners`, `subdividedFaces`, `facing`, `thickness`, `offset`, `levels` and `children`. |
|
||||
| `brokkr_kitbash.hose` | `object_name`, `start`, `end`, `count`, `radius`, `spread`, `clearance`, `bend`, `step`, `sag`, `clamps` (a JSON array of up to 8 `{socket}`), `joint` (empty, or a JSON object `{socket, standoff, range}`) | Routes a bundle of hoses between two sockets around every other mesh, over clamps and through a pin's axis across its roll range; on a hose's name, rebuilds it in place. Reports `length`, `lengthChange`, `clearance`, `radii`, `sag`, `voxels`, `seed`, `rolls`, `worstRoll`, `faces`, `nonManifoldEdges`. |
|
||||
|
||||
`params` is `name=value; name=value`; a param left out takes the part's default (`place_part`) or keeps its stored
|
||||
value (`set_params`). A value outside its bounds is refused with the bounds in the message.
|
||||
|
|
@ -683,8 +843,8 @@ file holds each report in `hostResult`. `tools/turntable_recipe.py` renders the
|
|||
|
||||
## The mechanical kit
|
||||
|
||||
`kits/mechanical.v0.json`: eleven parts, each along +z, with socket types `flange` (equal), `mount` (fits) and
|
||||
`pivot` (equal).
|
||||
`kits/mechanical.v0.json`: eleven parts, each along +z, with socket types `flange` (equal), `mount` (fits),
|
||||
`pivot` (equal) and `hose` (fits: a port takes a bundle no wider than its size).
|
||||
|
||||
| part | params | sockets |
|
||||
| --- | --- | --- |
|
||||
|
|
@ -692,7 +852,7 @@ file holds each report in `hostResult`. `tools/turntable_recipe.py` renders the
|
|||
| `tank` | `radius`, `length`, `segments` | `port_a`, `port_b` (flange), `saddle` (mount), `lug_a`, `lug_b`, `lug_a_back`, `lug_b_back` (mount): a lug on each side (+x, and -x for `_back`) of each strap |
|
||||
| `ribbed_cylinder` | `radius`, `length`, `ribs`, `rib_depth`, `rib_width`, `segments` | `end_a`, `end_b` (flange) |
|
||||
| `strut` | `length`, `width`, `thickness`, `segments` | `end_a`, `end_a_back`, `end_b`, `end_b_back` (pivot): the two end faces of the pin at each end |
|
||||
| `actuator` | `body_r`, `body_len`, `rod_r`, `extension`, `segments` | `base`, `base_back`, `rod_end`, `rod_end_back` (pivot); the rod end's two move with `extension` |
|
||||
| `actuator` | `body_r`, `body_len`, `rod_r`, `extension`, `segments` | `base`, `base_back`, `rod_end`, `rod_end_back` (pivot); the rod end's two move with `extension`; `port_cap`, `port_rod` (hose, `0.4*body_r` wide) on the end faces of its two port bosses |
|
||||
| `pipe_fitting` | `pipe_r`, `run`, `branch`, `flange_r`, `flange_t`, `segments` | `a`, `b`, `c` (flange) |
|
||||
| `radiator_stack` | `fins`, `fin_w`, `fin_h`, `fin_t`, `pitch`, `segments` | `base` (mount) |
|
||||
| `vent` | `width`, `height`, `depth`, `slats`, `slat_t`, `tilt` | `back` (mount) |
|
||||
|
|
|
|||
|
|
@ -481,7 +481,8 @@
|
|||
"brokkr_kitbash.cut_many",
|
||||
"brokkr_kitbash.apply",
|
||||
"brokkr_kitbash.ribs",
|
||||
"brokkr_kitbash.shell"
|
||||
"brokkr_kitbash.shell",
|
||||
"brokkr_kitbash.hose"
|
||||
],
|
||||
"frame": {
|
||||
"beam_i": {
|
||||
|
|
@ -608,7 +609,9 @@
|
|||
"base",
|
||||
"base_back",
|
||||
"rod_end",
|
||||
"rod_end_back"
|
||||
"rod_end_back",
|
||||
"port_cap",
|
||||
"port_rod"
|
||||
]
|
||||
},
|
||||
"pipe_fitting": {
|
||||
|
|
|
|||
471
surfaces/blender/tests/live/kitbash_hose.py
Normal file
471
surfaces/blender/tests/live/kitbash_hose.py
Normal file
|
|
@ -0,0 +1,471 @@
|
|||
"""Live proof, in a background Blender, of brokkr_kitbash.hose through run_intent: a bundle of three hoses from an actuator
|
||||
on one strut to an actuator on the next, around an armour plate and through a point on the knee pin's axis; the pin's
|
||||
roll range measured without posing anything, and a range that swings the hose into the plate refused by roll; a second
|
||||
hose that keeps clear of the first; a rebuild in place; a hose from a tank's flange over two clamps to an actuator's
|
||||
port; and the refusals. Not part of the unittest run: it needs Blender.
|
||||
|
||||
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_hose.py -- <out> [<blend>]
|
||||
|
||||
Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses
|
||||
without them). <out> is an absolute path; writes <out>.result.json and exits 1 when a check failed. With <blend>, an
|
||||
absolute path, the scene is saved there at the end.
|
||||
|
||||
Bounds follow lodur:ruling:deterministic-bound-margin; each is written beside its constant with the shipped reading
|
||||
and the least claimed mutant's (cut kit-hose's H list). The checks run inside one try: an uncaught error is a failed
|
||||
check that names its section, and the result file is always written.
|
||||
"""
|
||||
import importlib.util
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import traceback
|
||||
import types
|
||||
from pathlib import Path
|
||||
|
||||
import bpy
|
||||
import numpy as np
|
||||
from mathutils import Vector
|
||||
from mathutils.bvhtree import BVHTree
|
||||
|
||||
SURFACE = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(SURFACE / "tools"))
|
||||
import private_dirs # noqa: E402
|
||||
|
||||
_refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind))
|
||||
if _refused:
|
||||
raise SystemExit(_refused)
|
||||
OUT = sys.argv[sys.argv.index("--") + 1]
|
||||
if not Path(OUT).is_absolute():
|
||||
raise SystemExit(f"{OUT!r} is not an absolute path")
|
||||
package = types.ModuleType("brokkr_bridge")
|
||||
package.__path__ = [str(SURFACE / "brokkr_bridge")]
|
||||
sys.modules["brokkr_bridge"] = package
|
||||
from brokkr_bridge import blender_target as bt # noqa: E402
|
||||
|
||||
import addon_utils # noqa: E402
|
||||
|
||||
spec = importlib.util.spec_from_file_location("brokkr_kitbash_core_reference", SURFACE / "brokkr_kitbash" / "core.py")
|
||||
core = importlib.util.module_from_spec(spec) # core as the unit tests load it
|
||||
spec.loader.exec_module(core)
|
||||
|
||||
sys.path.append(str(SURFACE))
|
||||
bpy.ops.wm.read_factory_settings(use_empty=True)
|
||||
for module in ("brokkr_mesh_polish", "brokkr_kitbash"):
|
||||
addon_utils.enable(module, default_set=True)
|
||||
target = bt.BrokkrBlenderTarget(bpy)
|
||||
WORK = Path(tempfile.mkdtemp(prefix="brokkr-kitbash-hose-"))
|
||||
target.configure_action_dirs("", str(WORK))
|
||||
target.reload_host_actions()
|
||||
R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], "readings": {}, "reports": {}, "seconds": {}}
|
||||
COUNT, SECTION = [0], ["setup"]
|
||||
kit = core.load_kit("mechanical")
|
||||
RADIUS, CLEARANCE, COUNT_HOSES = 0.006, 0.005, 3
|
||||
SPREAD = 2.6 * RADIUS
|
||||
ENVELOPE = SPREAD + RADIUS # half the bundle's width
|
||||
LEAD = 8.0 * RADIUS
|
||||
FLOOR = 4.0 * 2.0 * RADIUS + SPREAD # of the centre line: the innermost hose keeps 4 outside diameters
|
||||
BUNDLE = {"count": COUNT_HOSES, "radius": RADIUS, "clearance": CLEARANCE}
|
||||
# Metres between a hose's surface and the nearest other mesh, read on the hose's own vertices further than the lead
|
||||
# from both its ports (the least is the worst), over every hose this suite makes. Shipped worst 0.031. Least claimed
|
||||
# mutant 0.0089: H4b (route.verify measures and refuses nothing) accepts the hose past the plate beside a port's
|
||||
# straight, section "verify", and the ring of it nearest the plate reads that; shipped refuses it and makes no hose.
|
||||
# The geometric mean, separation 1.8 and 1.9.
|
||||
CLEAR = 0.017
|
||||
# Metres a clamped hose's ring vertices stand off the radius about its own line over a clamp (the line through the
|
||||
# clamp point along the socket's y, offset across the bundle), over the 24 nearest; 1 when a hose has no 24 vertices
|
||||
# there. Shipped worst 4.6e-08 (float32 meshes); least claimed mutant 1 (C2, the straight laid along the socket's x:
|
||||
# the route is refused, or no ring stands on the line); the geometric mean, separation 4700 each side.
|
||||
CLAMPED = 2.1e-4
|
||||
# Metres along a clamped hose's line from a clamp point to the nearest ring of a bend. Shipped 0.028; least claimed
|
||||
# mutant 0.013 (C1, no straight kept at a clamp); the geometric mean, separation 1.47 each side.
|
||||
KEPT = 0.019
|
||||
|
||||
def check(name, ok, detail=None):
|
||||
R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail})
|
||||
|
||||
|
||||
def reading(name, value, least=False):
|
||||
"""The worst of a metric: the largest, or with `least` the smallest."""
|
||||
R["readings"][name] = (min if least else max)(R["readings"].get(name, float(value)), float(value))
|
||||
return float(value)
|
||||
|
||||
|
||||
def section(name):
|
||||
SECTION[0] = name
|
||||
|
||||
|
||||
def send(action, **fields):
|
||||
COUNT[0] += 1
|
||||
receipt = target.run_intent(bpy.context, {"commandId": f"live-{COUNT[0]}", "requestedBy": "test/driver", "action": action, **fields})
|
||||
result = None
|
||||
if receipt.get("hostResult"):
|
||||
try:
|
||||
result = json.loads(receipt["hostResult"])
|
||||
except ValueError:
|
||||
result = None
|
||||
print("SEND", action, receipt["status"], str(receipt["message"])[:400], flush=True)
|
||||
return receipt, result
|
||||
|
||||
|
||||
def scene_state():
|
||||
return {o.name: (o.parent and o.parent.name, np.round(np.array(o.matrix_basis), 6).tolist(), {k: repr(o[k]) for k in sorted(o.keys()) if k.startswith("kit_")},
|
||||
[(m.name, m.type, m.show_viewport) for m in o.modifiers], o.data.name if o.type == "MESH" else None, len(o.data.polygons) if o.type == "MESH" else None,
|
||||
np.round(np.array([v.co for v in o.data.vertices[:8]]), 6).tolist() if o.type == "MESH" else None)
|
||||
for o in bpy.data.objects}, sorted(m.name for m in bpy.data.meshes), sorted(c.name for c in bpy.data.collections)
|
||||
|
||||
|
||||
def refused(label, fields, expected):
|
||||
state = scene_state()
|
||||
receipt, _ = send("brokkr_kitbash.hose", **fields)
|
||||
check(f"refused, scene unchanged: {label}", receipt["status"] != "accepted" and expected in str(receipt["message"]) and scene_state() == state,
|
||||
[receipt["status"], receipt["message"]])
|
||||
|
||||
|
||||
def place(name, part, params="", location=None, rotation=None, parent=None):
|
||||
send("brokkr_kitbash.place_part", part=part, object_name=name, params=params)
|
||||
if location is not None:
|
||||
send("setObjectTransform", targetObjectName=name, location=location, rotationEuler=rotation or [0.0, 0.0, 0.0])
|
||||
made = bpy.data.objects[name]
|
||||
if parent is not None: # carried rigidly: a plain parent, which states no connection
|
||||
bpy.context.view_layer.update()
|
||||
made.parent = parent
|
||||
made.matrix_parent_inverse = parent.matrix_world.inverted()
|
||||
return made
|
||||
|
||||
|
||||
def box(name, low, high, parent=None):
|
||||
(x0, y0, z0), (x1, y1, z1) = low, high
|
||||
made = bpy.data.objects.new(name, bpy.data.meshes.new(name))
|
||||
made.data.from_pydata([(x0, y0, z0), (x1, y0, z0), (x1, y1, z0), (x0, y1, z0), (x0, y0, z1), (x1, y0, z1), (x1, y1, z1), (x0, y1, z1)], [],
|
||||
[(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)])
|
||||
bpy.context.scene.collection.objects.link(made)
|
||||
if parent is not None:
|
||||
bpy.context.view_layer.update()
|
||||
made.parent = parent
|
||||
made.matrix_parent_inverse = parent.matrix_world.inverted()
|
||||
return made
|
||||
|
||||
|
||||
def frame(obj, name):
|
||||
"""A socket's world frame, from the object's matrix_world and core's build of its stored params."""
|
||||
built = core.build(core.part(kit, obj["kit_part"]), json.loads(obj["kit_params"]))
|
||||
return np.array(obj.matrix_world, dtype=np.float64) @ next(s for s in built.sockets if s["name"] == name)["matrix"]
|
||||
|
||||
|
||||
def world_points(obj):
|
||||
points = np.zeros(3 * len(obj.data.vertices))
|
||||
obj.data.vertices.foreach_get("co", points)
|
||||
world = np.array(obj.matrix_world)
|
||||
return points.reshape(-1, 3) @ world[:3, :3].T + world[:3, 3]
|
||||
|
||||
|
||||
def others(hose):
|
||||
"""A tree of every other mesh object's evaluated mesh in the world: this test's own reading of the obstacles."""
|
||||
depsgraph, points, faces = bpy.context.evaluated_depsgraph_get(), [], []
|
||||
for obj in bpy.context.scene.objects:
|
||||
if obj.type != "MESH" or obj == hose:
|
||||
continue
|
||||
evaluated = obj.evaluated_get(depsgraph)
|
||||
mesh, start = evaluated.to_mesh(), sum(len(p) for p in points)
|
||||
points.append(np.array([evaluated.matrix_world @ v.co for v in mesh.vertices]).reshape(-1, 3))
|
||||
faces += [[start + i for i in polygon.vertices] for polygon in mesh.polygons]
|
||||
evaluated.to_mesh_clear()
|
||||
return BVHTree.FromPolygons(np.vstack(points).tolist(), faces)
|
||||
|
||||
|
||||
def surface_clearance(hose, ports):
|
||||
"""The least distance from the hose's vertices to any other mesh, over the vertices further than the lead and the
|
||||
bundle's half width from both ports."""
|
||||
bpy.context.view_layer.update()
|
||||
tree, points = others(hose), world_points(hose)
|
||||
far = np.all([np.linalg.norm(points - port, axis=1) > LEAD + ENVELOPE + CLEARANCE for port in ports], axis=0)
|
||||
return min(tree.find_nearest(Vector(p))[3] for p in points[far])
|
||||
|
||||
|
||||
def shells(obj):
|
||||
"""(closed shells, edges that do not join two faces) of a mesh object."""
|
||||
edges = {}
|
||||
for polygon in obj.data.polygons:
|
||||
for a, b in polygon.edge_keys:
|
||||
edges[(a, b)] = edges.get((a, b), 0) + 1
|
||||
root = list(range(len(obj.data.vertices)))
|
||||
|
||||
def find(i):
|
||||
while root[i] != i:
|
||||
root[i] = root[root[i]]
|
||||
i = root[i]
|
||||
return i
|
||||
for a, b in edges:
|
||||
root[find(a)] = find(b)
|
||||
return len({find(i) for i in range(len(root))}), sum(1 for n in edges.values() if n != 2)
|
||||
|
||||
|
||||
def timed(fields):
|
||||
"""Median wall seconds of three rebuilds of a hose, each after one report action."""
|
||||
import time
|
||||
taken = []
|
||||
for _ in range(3):
|
||||
send("brokkr_kitbash.report", object_name="Thigh")
|
||||
started = time.perf_counter()
|
||||
send("brokkr_kitbash.hose", **fields)
|
||||
taken.append(time.perf_counter() - started)
|
||||
return sorted(taken)[1]
|
||||
|
||||
|
||||
try:
|
||||
section("knee")
|
||||
STRUT = "length=0.8;width=0.08;thickness=0.05"
|
||||
RAM = "body_r=0.12;body_len=0.2;extension=0"
|
||||
thigh = place("Thigh", "strut", STRUT)
|
||||
place("Shin", "strut", STRUT)
|
||||
send("brokkr_kitbash.attach", object_name="Shin", socket="end_a", parent_name="Thigh", parent_socket="end_b_back", roll=0.0)
|
||||
shin = bpy.data.objects["Shin"]
|
||||
upper = place("ActT", "actuator", RAM, [-0.674, -0.2, -0.2], parent=thigh)
|
||||
lower = place("ActS", "actuator", RAM, [-0.674, -0.2, 0.89], parent=shin)
|
||||
plate = box("Armour", (-0.21, -0.45, 0.15), (-0.19, 0.05, 0.7), parent=thigh)
|
||||
bpy.context.view_layer.update()
|
||||
ports = [frame(upper, "port_cap")[:3, 3], frame(lower, "port_cap")[:3, 3]]
|
||||
check("the actuator's ports sit on its boss faces, facing out", np.allclose(ports[0], [-0.5, -0.2, 0.01], atol=1e-6) and np.allclose(frame(upper, "port_cap")[:3, 2], [1, 0, 0], atol=1e-6)
|
||||
and others(None).find_nearest(Vector(ports[0]))[3] < 1e-6 and np.allclose(frame(upper, "port_rod")[:3, 3], [-0.5, -0.2, 0.27], atol=1e-6), ports[0].tolist())
|
||||
JOINT = {"socket": "Shin:end_a_back", "standoff": 0.08, "range": [-20, 20]}
|
||||
FEED = {"object_name": "Feed", "start": "ActT:port_cap", "end": "ActS:port_cap", **BUNDLE, "joint": json.dumps(JOINT)}
|
||||
state = scene_state()
|
||||
receipt, report = send("brokkr_kitbash.hose", **FEED)
|
||||
R["reports"]["feed"] = report
|
||||
check("hose-behind-armour: three hoses route from the thigh's ram to the shin's, round the plate and through the pin point",
|
||||
receipt["status"] == "accepted" and report["hoses"] == 3 and not report["rebuilt"] and report["nonManifoldEdges"] == 0 and report["rolls"] >= 9
|
||||
and report["clearance"] >= CLEARANCE and report["worstClearance"] >= CLEARANCE and report["radii"]["least"] >= FLOOR * (1 - 1e-6) and len(report["voxels"]) == 2,
|
||||
[receipt["status"], receipt["message"], report])
|
||||
feed = bpy.data.objects["Feed"]
|
||||
check("the hose is one object, the start's child under an identity parent inverse, and carries its request",
|
||||
feed.parent == upper and np.allclose(np.array(feed.matrix_parent_inverse), np.eye(4)) and np.allclose(np.array(feed.matrix_basis), np.eye(4))
|
||||
and json.loads(feed["kit_hose"])["joint"] == JOINT and len(feed.data.materials) == 0 and len(feed.vertex_groups) == 0, feed.get("kit_hose"))
|
||||
check("every hose and collar is a closed shell", shells(feed) == (3 + 3 * 4, 0), shells(feed))
|
||||
points = world_points(feed)
|
||||
check("each hose starts on the port's face, side by side across it",
|
||||
min(np.linalg.norm(points - ports[0], axis=1)) < RADIUS * 1.5 and abs(float(((points - ports[0]) @ [1.0, 0, 0]).min())) < 1e-5, None)
|
||||
line_blocked = others(feed).ray_cast(Vector(ports[0] + [0.12, 0, 0]), Vector((np.array([0, -0.2075, 0.764]) - ports[0] - [0.12, 0, 0])))[0] is not None
|
||||
check("the straight way from the port to the pin point is through the plate", line_blocked, None)
|
||||
check("hose-behind-armour: the hose's surface keeps the clearance from every other mesh outside its leads",
|
||||
reading("clear", surface_clearance(feed, ports), least=True) >= CLEAR, R["readings"])
|
||||
check("the hose passes the pin's axis: its vertices come within the bundle of the point 0.08 beyond the shin's pin face",
|
||||
float(np.linalg.norm(points - [0.0, -0.2075, 0.764], axis=1).min()) < 0.08, float(np.linalg.norm(points - [0.0, -0.2075, 0.764], axis=1).min()))
|
||||
check("the report states sag for both legs, no more than the sag asked for", len(report["sag"]) == 2 and all(0.0 <= s <= 2 * RADIUS + 1e-9 for s in report["sag"]) and any(s > 0 for s in report["sag"]), report["sag"])
|
||||
_, taut = send("brokkr_kitbash.hose", **{**FEED, "sag": 0.0})
|
||||
check("sag 0 routes taut and no longer than the sagged hose", taut["sag"] == [0.0, 0.0] and taut["rebuilt"] and taut["length"] < report["length"], [taut["length"], report["length"]])
|
||||
reading("slack", report["length"] - taut["length"])
|
||||
section("range")
|
||||
_, again = send("brokkr_kitbash.hose", **FEED)
|
||||
check("a rebuild at the same pose reports what the first call did", {**again, "rebuilt": False} == report and len(bpy.data.meshes) == len(state[1]) + 1, again)
|
||||
check("hose-through-range: the range passes and reports the length's change", report["lengthChange"] is not None and report["lengthChange"] >= 0 and report["worstRoll"] is not None, report)
|
||||
refused("a range that swings the shin's hose into the thigh's parts, naming the sagged attempt and the taut one", {**FEED, "joint": json.dumps({**JOINT, "range": [-20, 90]})},
|
||||
"sagged: roll 48.59: the hose's child's side reads 0.0269 m from the parts about the pin at [-0.2144, -0.2042, 0.7271], counting the 0.0005933 m it can move against the other side's "
|
||||
"through the 0.156 degrees either side of it: too near the 0.0266 m the bundle needs to prove it of what stands between two readings; taut: roll 50.78: the hose's child's side reads 0.0264 m")
|
||||
receipt, _ = send("brokkr_kitbash.hose", **{**FEED, "joint": json.dumps({**JOINT, "range": [-20, 90]})})
|
||||
check("the refusal names both attempts, each by its roll and its side", "sagged: roll " in str(receipt["message"]) and "; taut: roll " in str(receipt["message"])
|
||||
and str(receipt["message"]).count("the hose's child's side reads") == 2, receipt["message"])
|
||||
section("thin plate")
|
||||
# A plate 1 mm thick, 4 cm square, on the thigh, where a point of the shin's side of a single hose stands at roll
|
||||
# -17.5: between two of the rolls 5 degrees apart. At -20 and at -15 the hose keeps its need from it.
|
||||
SINGLE = {**FEED, "object_name": "Single", "start": "ActT:port_rod", "end": "ActS:port_rod", "count": 1, "joint": json.dumps({**JOINT, "standoff": 0.24})}
|
||||
_, single = send("brokkr_kitbash.hose", **SINGLE)
|
||||
line = world_points(bpy.data.objects["Single"])
|
||||
pivot = frame(shin, "end_a_back")
|
||||
origin, axis = pivot[:3, 3], pivot[:3, 2]
|
||||
beyond = line[(line[:, 2] > origin[2] + 0.1) & (np.linalg.norm(line - frame(lower, "port_rod")[:3, 3], axis=1) > 0.15)]
|
||||
far_point = beyond[np.argmax(np.linalg.norm(np.cross(beyond - origin, axis), axis=1))]
|
||||
turn = math.radians(-17.5)
|
||||
rel = far_point - origin
|
||||
at = origin + rel * math.cos(turn) + np.cross(axis, rel) * math.sin(turn) + axis * float(rel @ axis) * (1.0 - math.cos(turn))
|
||||
way = np.cross(axis, at - origin)
|
||||
way /= np.linalg.norm(way)
|
||||
out = np.cross(way, axis)
|
||||
corners = [at + axis * a * 0.02 + out * b * 0.02 + way * c * 0.0005 for c in (-1, 1) for a in (-1, 1) for b in (-1, 1)]
|
||||
thin = bpy.data.objects.new("Thin", bpy.data.meshes.new("Thin"))
|
||||
thin.data.from_pydata([tuple(v) for v in corners], [], [(0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (1, 5, 7, 3), (3, 7, 6, 2), (2, 6, 4, 0)])
|
||||
bpy.context.scene.collection.objects.link(thin)
|
||||
bpy.context.view_layer.update()
|
||||
thin.parent = thigh
|
||||
thin.matrix_parent_inverse = thigh.matrix_world.inverted()
|
||||
bpy.context.view_layer.update()
|
||||
check("the plate stands in the single hose's swing, over 0.03 from where it stands now", single is not None and float(np.linalg.norm(line - at, axis=1).min()) > 0.03, float(np.linalg.norm(line - at, axis=1).min()))
|
||||
refused("range-sampled-not-swept: a 1 mm plate the hose crosses between two rolls 5 degrees apart", SINGLE, "roll -1")
|
||||
receipt, _ = send("brokkr_kitbash.hose", **SINGLE)
|
||||
named = [float(part.split(":")[0]) for part in str(receipt["message"]).split("roll ")[1:]]
|
||||
check("the refusal names a roll between -20 and -15 for each attempt", len(named) >= 1 and all(-20.0 < roll < -15.0 for roll in named), receipt["message"])
|
||||
receipt, narrow = send("brokkr_kitbash.hose", **{**SINGLE, "joint": json.dumps({**JOINT, "standoff": 0.24, "range": [-10, 20]})})
|
||||
check("short of the plate the same hose passes its range", receipt["status"] == "accepted" and narrow["rolls"] >= 7, receipt["message"])
|
||||
for name in ("Thin", "Single"):
|
||||
gone = bpy.data.objects[name]
|
||||
mesh = gone.data
|
||||
bpy.data.objects.remove(gone)
|
||||
bpy.data.meshes.remove(mesh)
|
||||
bpy.context.view_layer.update()
|
||||
section("coarse step")
|
||||
# coarse-step-cuts-thin-plate: no measurement of a hose depends on the search's step. At the coarsest step the
|
||||
# single taut hose of the finding and the bundle both keep the clearance from the 2 cm armour plate.
|
||||
for label, extra in (("one taut hose", {"count": 1, "sag": 0.0}), ("the bundle", {})):
|
||||
receipt, coarse = send("brokkr_kitbash.hose", **{**FEED, "step": 0.2, **extra})
|
||||
check(f"at step 0.2 {label} routes and keeps the clearance from every other mesh", receipt["status"] == "accepted" and coarse["rebuilt"] and coarse["clearance"] >= CLEARANCE
|
||||
and reading("clear", surface_clearance(feed, ports), least=True) >= CLEAR, [receipt["message"], R["readings"]])
|
||||
section("range")
|
||||
send("brokkr_kitbash.roll", object_name="Shin", roll=10.0)
|
||||
bpy.context.view_layer.update()
|
||||
receipt, rolled = send("brokkr_kitbash.hose", **FEED)
|
||||
check("after a roll the hose rebuilds in place on its name", receipt["status"] == "accepted" and rolled["rebuilt"] and bpy.data.objects["Feed"] == feed and rolled["rolls"] >= 9, receipt["message"])
|
||||
check("the rebuilt hose keeps the clearance at the new pose", reading("clear", surface_clearance(feed, [frame(upper, "port_cap")[:3, 3], frame(lower, "port_cap")[:3, 3]]), least=True) >= CLEAR, R["readings"])
|
||||
mesh = feed.data
|
||||
bpy.data.objects.remove(feed)
|
||||
bpy.data.meshes.remove(mesh)
|
||||
bpy.context.view_layer.update()
|
||||
receipt, fresh = send("brokkr_kitbash.hose", **FEED)
|
||||
feed = bpy.data.objects["Feed"]
|
||||
check("hose-through-range: roll then rebuild gives the same report as a fresh hose", receipt["status"] == "accepted" and {**rolled, "rebuilt": False} == fresh, [rolled, fresh])
|
||||
R["seconds"]["hose on the knee, median of 3"] = round(timed(FEED), 3)
|
||||
section("second hose")
|
||||
RETURN = {"object_name": "Return", "start": "ActT:port_rod", "end": "ActS:port_rod", **BUNDLE, "joint": json.dumps({**JOINT, "standoff": 0.24})} # the pin point further out than the first hose's, at the default step
|
||||
receipt, back = send("brokkr_kitbash.hose", **RETURN)
|
||||
R["reports"]["return"] = back
|
||||
check("second-bundle: a second hose routes through the same knee at the default step, its range measured against the parts and not against where the first hose stood",
|
||||
receipt["status"] == "accepted" and back["nonManifoldEdges"] == 0 and back["rolls"] >= 9 and abs(json.loads(bpy.data.objects["Return"]["kit_hose"])["step"] - 0.02) < 1e-6, [receipt["status"], receipt["message"]])
|
||||
for step in (0.0125, 0.03, 0.04): # feasibility does not turn on the step: a leg is searched with room for its bends
|
||||
receipt, _ = send("brokkr_kitbash.hose", **{**FEED, "step": step})
|
||||
check(f"the first hose's route also stands at step {step}, beside the second", receipt["status"] == "accepted", receipt["message"])
|
||||
# bend-room-not-monotone-in-step: a search's polyline is a seed. These are steps whose seeds were refused before
|
||||
# seeds were refined and searched on other grid origins (0.1275 of the first bundle, the rest of the second).
|
||||
seeds = []
|
||||
for base, step in [(FEED, 0.1275)] + [(RETURN, step) for step in (0.0225, 0.04, 0.115, 0.1425, 0.155, 0.2)]:
|
||||
receipt, swept = send("brokkr_kitbash.hose", **{**base, "step": step})
|
||||
ok = receipt["status"] == "accepted"
|
||||
check(f"{base['object_name']} routes at step {step}: no bend under the floor, the clearance kept", ok and swept["radii"]["least"] >= FLOOR * (1 - 1e-6) and swept["clearance"] >= CLEARANCE
|
||||
and swept["worstClearance"] >= CLEARANCE and reading("clear", surface_clearance(bpy.data.objects[base["object_name"]], [frame(ram, "port_cap" if base is FEED else "port_rod")[:3, 3] for ram in (upper, lower)]), least=True) >= CLEAR,
|
||||
[receipt["message"], swept, R["readings"]])
|
||||
seeds.append(swept["seed"] if ok else None)
|
||||
R["reports"]["seeds"] = seeds
|
||||
check("some of those routes come from a refined seed and some from another grid origin, and the report says which",
|
||||
any(seed and seed["refined"] for seed in seeds) and any(seed and seed["offset"] != [0.0, 0.0, 0.0] for seed in seeds), seeds)
|
||||
send("brokkr_kitbash.hose", **FEED)
|
||||
send("brokkr_kitbash.hose", **RETURN)
|
||||
refused("a bend the search finds no route for on the knee, by what its first seed lacked", {**FEED, "bend": 16.0}, "under the floor 0.2076: ")
|
||||
rod_ports = [frame(upper, "port_rod")[:3, 3], frame(lower, "port_rod")[:3, 3]]
|
||||
check("hose-behind-armour: the second hose keeps the clearance from the first", reading("clear", surface_clearance(bpy.data.objects["Return"], rod_ports), least=True) >= CLEAR, R["readings"])
|
||||
refused("a pin point another hose already passes", {**RETURN, "object_name": "Third"}, "from an obstacle")
|
||||
section("too stiff")
|
||||
# too stiff is said where it is proven: a wall 0.08 above a port leaves the centre line 0.021 beyond its lead to
|
||||
# turn aside in, and a curve of the floor radius 0.048 cannot; one of 0.012 can, and routes.
|
||||
for name, x in (("Nozzle", 10.0), ("Drain", 10.6)):
|
||||
empty = bpy.data.objects.new(name, None)
|
||||
empty.location = (x, 0.0, 0.0)
|
||||
bpy.context.scene.collection.objects.link(empty)
|
||||
box("Lid", (9.0, -1.0, 0.08), (11.6, 1.0, 0.1))
|
||||
bpy.context.view_layer.update()
|
||||
LOOP = {"object_name": "Loop", "start": "Nozzle", "end": "Drain", "count": 1, "radius": RADIUS, "clearance": CLEARANCE}
|
||||
refused("a bundle proven too stiff to leave its port under a wall", LOOP, "the bundle is too stiff to leave its start: from the end of its lead at [10, 0, 0.048] no curve that bends at the floor radius 0.048 m or wider")
|
||||
receipt, loop = send("brokkr_kitbash.hose", **{**LOOP, "bend": 1.0})
|
||||
check("the same hose at bend 1 routes under the wall", receipt["status"] == "accepted" and loop["radii"]["least"] >= 0.012 * (1 - 1e-6) and loop["clearance"] >= CLEARANCE, [receipt["message"], loop])
|
||||
section("clamps")
|
||||
tank = place("Tank", "tank", "radius=0.22;length=0.9", [3.0, 0.0, 0.0])
|
||||
seats = [place(name, "plate", "width=0.1;height=0.1", [x, 0.0, 1.25], [0.0, 0.0, math.pi / 2]) for name, x in (("SeatA", 3.45), ("SeatB", 4.05))]
|
||||
ram = place("Ram", "actuator", RAM, [5.074, 0.0, 1.07], [0.0, 0.0, math.pi])
|
||||
bpy.context.view_layer.update()
|
||||
LINE = {"object_name": "Line", "start": "Tank:port_b", "end": "Ram:port_cap", **BUNDLE, "clamps": json.dumps([{"socket": "SeatA:front"}, {"socket": "SeatB:front"}])}
|
||||
receipt, line = send("brokkr_kitbash.hose", **LINE)
|
||||
R["reports"]["line"] = line
|
||||
check("hose-clamps-ports: a hose runs from the tank's flange over two clamps to the ram's port", receipt["status"] == "accepted" and line["nonManifoldEdges"] == 0 and len(line["voxels"]) == 3
|
||||
and line["rolls"] is None and line["lengthChange"] is None, [receipt["status"], receipt["message"]])
|
||||
hose = bpy.data.objects["Line"]
|
||||
check("three hoses with four collars each, two straps and two pads", shells(hose) == (3 + 12 + 4, 0), shells(hose))
|
||||
points = world_points(hose)
|
||||
stand, held = ENVELOPE + CLEARANCE + RADIUS, 4.0 * RADIUS + FLOOR
|
||||
for seat in seats:
|
||||
at = frame(seat, "front")
|
||||
centre, y, x = at[:3, 3] + at[:3, 2] * stand, at[:3, 1], at[:3, 0]
|
||||
for k in range(COUNT_HOSES):
|
||||
origin = centre + x * (k - 1) * SPREAD
|
||||
rel = points - origin
|
||||
along = rel @ y
|
||||
off = np.abs(np.linalg.norm(rel - np.outer(along, y), axis=1) - RADIUS)
|
||||
near = np.sort(off[np.abs(along) <= held + 1e-6])[:24] # the two rings where the kept straight ends, twelve vertices each
|
||||
reading("clamped", near.max() if len(near) == 24 else 1.0)
|
||||
reading("kept", np.abs(along[off < 1e-5]).min() if (off < 1e-5).any() else 0.0, least=True)
|
||||
check("hose-clamps-ports: each hose passes each clamp point straight along the socket's y", R["readings"]["clamped"] <= CLAMPED, R["readings"])
|
||||
check("the bundle runs straight for two outside diameters each side of a clamp point: no ring of a bend stands nearer", R["readings"]["kept"] >= KEPT, R["readings"])
|
||||
check("the clamped hose reports the clearance it keeps (its pads stand on their seats)", line["clearance"] >= CLEARANCE and surface_clearance(hose, [frame(tank, "port_b")[:3, 3], frame(ram, "port_cap")[:3, 3]]) < 1e-6,
|
||||
line["clearance"])
|
||||
refused("a bundle wider than the port", {**LINE, "object_name": "Wide", "count": 5}, "a bundle of 5 hoses is 0.0744 m wide, over socket 'Ram:port_cap' (hose, size 0.048)")
|
||||
tip = bpy.data.objects.new("Tip", None)
|
||||
bpy.context.scene.collection.objects.link(tip)
|
||||
tip.location, tip.rotation_euler = (3.5, 0.0, -1.3), (0.0, -math.pi / 6, 0.0) # under the tank's lower port, its z up toward it
|
||||
bpy.context.view_layer.update()
|
||||
receipt, loose = send("brokkr_kitbash.hose", object_name="Loose", start="Tank:port_a", end="Tip", radius=0.02)
|
||||
check("a hose runs from a flange to an empty", receipt["status"] == "accepted" and loose["hoses"] == 1 and shells(bpy.data.objects["Loose"]) == (5, 0), [receipt["status"], receipt["message"]])
|
||||
section("verify")
|
||||
# h4-claimable-live: a straight hose from a ram's port to an empty in line with it has no corner and no pin, and
|
||||
# its leg starts beyond the plate that stands 0.008 under its first straight: route.verify is the only thing that
|
||||
# measures that straight, and refuses it. With verify refusing nothing (H4b) the hose is made and reads under CLEAR.
|
||||
solo = place("Solo", "actuator", RAM, [10.0, 0.0, 0.0])
|
||||
bpy.context.view_layer.update()
|
||||
mouth = frame(solo, "port_cap")[:3, 3]
|
||||
stub = bpy.data.objects.new("Stub", None)
|
||||
bpy.context.scene.collection.objects.link(stub)
|
||||
stub.location, stub.rotation_euler = (float(mouth[0]) + 0.5, float(mouth[1]), float(mouth[2])), (0.0, -math.pi / 2, 0.0) # its z back along the line toward the port
|
||||
box("Beside", (mouth[0] + 0.06, mouth[1] - 0.05, mouth[2] - 0.06), (mouth[0] + 0.08, mouth[1] + 0.05, mouth[2] - 0.008))
|
||||
bpy.context.view_layer.update()
|
||||
PAST = {"object_name": "Past", "start": "Solo:port_cap", "end": "Stub", "radius": RADIUS, "clearance": CLEARANCE, "sag": 0.0}
|
||||
state = scene_state()
|
||||
receipt, _ = send("brokkr_kitbash.hose", **PAST)
|
||||
past = bpy.data.objects.get("Past")
|
||||
if past is not None:
|
||||
reading("clear", surface_clearance(past, [mouth, np.array(stub.location)]), least=True)
|
||||
check("h4: the straight past the plate is refused by route.verify, naming the point; nothing changed",
|
||||
receipt["status"] != "accepted" and "the hose stands 0.008 m from an obstacle at [" in str(receipt["message"]) and "under the 0.011 m the bundle needs" in str(receipt["message"])
|
||||
and scene_state() == state, [receipt["status"], receipt["message"]])
|
||||
check("h4: no hose this suite made stands nearer another mesh than CLEAR", R["readings"]["clear"] >= CLEAR, R["readings"])
|
||||
bpy.data.objects["Beside"].location = (0.0, 0.0, -0.01) # 0.018 under the straight: the same call routes
|
||||
bpy.context.view_layer.update()
|
||||
receipt, past = send("brokkr_kitbash.hose", **PAST)
|
||||
check("with the plate 0.018 under it the same straight is made", receipt["status"] == "accepted" and (past["radii"]["least"] is None or past["radii"]["least"] > 1e3) and abs(past["clearance"] - 0.012) < 1e-4, [receipt["message"], past])
|
||||
section("refusals")
|
||||
refused("a name taken by a mesh that is no hose", {**FEED, "object_name": "Thigh"}, "An object named 'Thigh' exists and is no hose")
|
||||
refused("a socket the part does not have", {**FEED, "start": "ActT:nope"}, "start: 'ActT' (a actuator) has no socket 'nope'; its sockets: base, base_back, rod_end, rod_end_back, port_cap, port_rod")
|
||||
refused("an object that does not exist", {**FEED, "end": "Nobody:port_cap"}, "end: no object named 'Nobody'")
|
||||
refused("a pivot as an end", {**FEED, "start": "Thigh:end_a"}, "start: socket 'end_a' of 'Thigh' is a pivot socket; this takes a hose or flange socket")
|
||||
refused("a mesh that is no empty as an end", {**FEED, "end": "Armour"}, "end 'Armour' names no socket")
|
||||
refused("a clamp on a pivot", {**FEED, "clamps": json.dumps([{"socket": "Thigh:end_a"}])}, "clamps[0]: socket 'end_a' of 'Thigh' is a pivot socket; this takes a mount socket")
|
||||
refused("clamps that are not rows of socket", {**FEED, "clamps": json.dumps([{"at": [0, 0, 0]}])}, "clamps[0] must be an object of socket")
|
||||
refused("nine clamps", {**FEED, "clamps": json.dumps([{"socket": "SeatA:front"}] * 9)}, "clamps must be a JSON array of 0 to 8 objects")
|
||||
refused("a pin crossed with no joint", {k: v for k, v in FEED.items() if k != "joint"}, "The hose crosses the pin of 'Shin' on 'Thigh' (socket 'end_b_back'): give joint")
|
||||
refused("a joint where no pin is crossed", {**LINE, "object_name": "New", "joint": json.dumps(JOINT)}, "joint is given and the hose crosses no pin")
|
||||
place("Jack", "actuator", "body_r=0.0534;body_len=0.2;extension=0")
|
||||
send("brokkr_kitbash.attach", object_name="Jack", socket="base", parent_name="Shin", parent_socket="end_b", roll=90.0)
|
||||
bpy.context.view_layer.update()
|
||||
refused("two pins crossed", {**FEED, "object_name": "New", "end": "Jack:port_cap", "count": 1, "radius": 0.004}, "The hose crosses 2 pins ('Jack' on 'Shin', 'Shin' on 'Thigh'): a hose crosses one")
|
||||
refused("a joint socket off the crossed pin's axis", {**FEED, "joint": json.dumps({**JOINT, "socket": "Shin:end_b_back"})}, "joint.socket 'Shin:end_b_back' is not on the axis of the pin the hose crosses ('Shin' on 'Thigh', socket 'end_b_back')")
|
||||
refused("the current roll outside the range", {**FEED, "joint": json.dumps({**JOINT, "range": [30, 60]})}, "'Shin' stands at roll 10, outside joint.range [30, 60]")
|
||||
refused("a range over a full turn", {**FEED, "joint": json.dumps({**JOINT, "range": [-200, 200]})}, "joint must be an object of socket")
|
||||
refused("a grid past the voxel limit", {**FEED, "step": 0.005}, "voxels at step 0.005, over 524288: a step of ")
|
||||
lower.scale = (1.0, 1.0, 1.01)
|
||||
bpy.context.view_layer.update()
|
||||
refused("a scaled part", FEED, "'ActS' is scaled, mirrored or sheared in the world")
|
||||
lower.scale = (1.0, 1.0, 1.0)
|
||||
tip.hide_viewport = True
|
||||
bpy.context.view_layer.update()
|
||||
refused("a hidden end", {"object_name": "Loose", "start": "Tank:port_a", "end": "Tip", "radius": 0.02}, "Blender does not evaluate 'Tip' in this view layer")
|
||||
tip.hide_viewport = False
|
||||
bpy.context.view_layer.update()
|
||||
if len(sys.argv) > sys.argv.index("--") + 2:
|
||||
bpy.ops.wm.save_as_mainfile(filepath=sys.argv[sys.argv.index("--") + 2])
|
||||
except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, not a missing result file
|
||||
check(f"no uncaught error in section: {SECTION[0]}", False, traceback.format_exc().splitlines()[-6:])
|
||||
finally:
|
||||
R["ok"] = all(c["ok"] for c in R["checks"])
|
||||
R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())}
|
||||
seconds = R.pop("seconds") # wall time is this machine's: printed, and kept out of the result file
|
||||
Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8")
|
||||
for c in R["checks"]:
|
||||
print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True)
|
||||
print("READINGS", R["readings"], flush=True)
|
||||
print("SECONDS", seconds, flush=True)
|
||||
sys.exit(0 if R["ok"] else 1)
|
||||
553
surfaces/blender/tests/live/kitbash_hose.result.json
Normal file
553
surfaces/blender/tests/live/kitbash_hose.result.json
Normal file
|
|
@ -0,0 +1,553 @@
|
|||
{
|
||||
"blender": "5.3.0",
|
||||
"checks": [
|
||||
{
|
||||
"name": "the actuator's ports sit on its boss faces, facing out",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "hose-behind-armour: three hoses route from the thigh's ram to the shin's, round the plate and through the pin point",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "the hose is one object, the start's child under an identity parent inverse, and carries its request",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "every hose and collar is a closed shell",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "each hose starts on the port's face, side by side across it",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "the straight way from the port to the pin point is through the plate",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "hose-behind-armour: the hose's surface keeps the clearance from every other mesh outside its leads",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "the hose passes the pin's axis: its vertices come within the bundle of the point 0.08 beyond the shin's pin face",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "the report states sag for both legs, no more than the sag asked for",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "sag 0 routes taut and no longer than the sagged hose",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "a rebuild at the same pose reports what the first call did",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "hose-through-range: the range passes and reports the length's change",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a range that swings the shin's hose into the thigh's parts, naming the sagged attempt and the taut one",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "the refusal names both attempts, each by its roll and its side",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "the plate stands in the single hose's swing, over 0.03 from where it stands now",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: range-sampled-not-swept: a 1 mm plate the hose crosses between two rolls 5 degrees apart",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "the refusal names a roll between -20 and -15 for each attempt",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "short of the plate the same hose passes its range",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "at step 0.2 one taut hose routes and keeps the clearance from every other mesh",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "at step 0.2 the bundle routes and keeps the clearance from every other mesh",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "after a roll the hose rebuilds in place on its name",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "the rebuilt hose keeps the clearance at the new pose",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "hose-through-range: roll then rebuild gives the same report as a fresh hose",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "second-bundle: a second hose routes through the same knee at the default step, its range measured against the parts and not against where the first hose stood",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "the first hose's route also stands at step 0.0125, beside the second",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "the first hose's route also stands at step 0.03, beside the second",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "the first hose's route also stands at step 0.04, beside the second",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "Feed routes at step 0.1275: no bend under the floor, the clearance kept",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "Return routes at step 0.0225: no bend under the floor, the clearance kept",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "Return routes at step 0.04: no bend under the floor, the clearance kept",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "Return routes at step 0.115: no bend under the floor, the clearance kept",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "Return routes at step 0.1425: no bend under the floor, the clearance kept",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "Return routes at step 0.155: no bend under the floor, the clearance kept",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "Return routes at step 0.2: no bend under the floor, the clearance kept",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "some of those routes come from a refined seed and some from another grid origin, and the report says which",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a bend the search finds no route for on the knee, by what its first seed lacked",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "hose-behind-armour: the second hose keeps the clearance from the first",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a pin point another hose already passes",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a bundle proven too stiff to leave its port under a wall",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "the same hose at bend 1 routes under the wall",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "hose-clamps-ports: a hose runs from the tank's flange over two clamps to the ram's port",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "three hoses with four collars each, two straps and two pads",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "hose-clamps-ports: each hose passes each clamp point straight along the socket's y",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "the bundle runs straight for two outside diameters each side of a clamp point: no ring of a bend stands nearer",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "the clamped hose reports the clearance it keeps (its pads stand on their seats)",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a bundle wider than the port",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "a hose runs from a flange to an empty",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "h4: the straight past the plate is refused by route.verify, naming the point; nothing changed",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "h4: no hose this suite made stands nearer another mesh than CLEAR",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "with the plate 0.018 under it the same straight is made",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a name taken by a mesh that is no hose",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a socket the part does not have",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: an object that does not exist",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a pivot as an end",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a mesh that is no empty as an end",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a clamp on a pivot",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: clamps that are not rows of socket",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: nine clamps",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a pin crossed with no joint",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a joint where no pin is crossed",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: two pins crossed",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a joint socket off the crossed pin's axis",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: the current roll outside the range",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a range over a full turn",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a grid past the voxel limit",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a scaled part",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a hidden end",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
}
|
||||
],
|
||||
"hostErrors": [],
|
||||
"readings": {
|
||||
"clamped": 4.6e-08,
|
||||
"clear": 0.031,
|
||||
"kept": 0.028,
|
||||
"slack": 0.017
|
||||
},
|
||||
"reports": {
|
||||
"feed": {
|
||||
"object": "Feed",
|
||||
"rebuilt": false,
|
||||
"hoses": 3,
|
||||
"length": 1.642855,
|
||||
"lengthChange": 0.034539,
|
||||
"floor": 0.0636,
|
||||
"clearance": 0.024995,
|
||||
"capped": 0.1522,
|
||||
"voxels": [
|
||||
79488,
|
||||
53406
|
||||
],
|
||||
"seed": {
|
||||
"step": 0.02,
|
||||
"offset": [
|
||||
0.0,
|
||||
0.0,
|
||||
0.0
|
||||
],
|
||||
"refined": false
|
||||
},
|
||||
"sag": [
|
||||
0.001879,
|
||||
0.009076
|
||||
],
|
||||
"rolls": 9,
|
||||
"worstRoll": -20.0,
|
||||
"worstClearance": 0.025166,
|
||||
"faces": 3378,
|
||||
"volume": 0.000577468,
|
||||
"nonManifoldEdges": 0,
|
||||
"radii": {
|
||||
"least": 0.134032,
|
||||
"corners": [
|
||||
0.297307,
|
||||
0.134032,
|
||||
28.760693,
|
||||
0.232497,
|
||||
3.487729,
|
||||
0.140588
|
||||
]
|
||||
}
|
||||
},
|
||||
"return": {
|
||||
"object": "Return",
|
||||
"rebuilt": false,
|
||||
"hoses": 3,
|
||||
"length": 1.679265,
|
||||
"lengthChange": 0.032203,
|
||||
"floor": 0.0636,
|
||||
"clearance": 0.026679,
|
||||
"capped": 0.1522,
|
||||
"voxels": [
|
||||
82110,
|
||||
92820
|
||||
],
|
||||
"seed": {
|
||||
"step": 0.02,
|
||||
"offset": [
|
||||
0.0,
|
||||
0.0,
|
||||
0.0
|
||||
],
|
||||
"refined": false
|
||||
},
|
||||
"sag": [
|
||||
0.008745,
|
||||
0.00844
|
||||
],
|
||||
"rolls": 9,
|
||||
"worstRoll": -20.0,
|
||||
"worstClearance": 0.027159,
|
||||
"faces": 5466,
|
||||
"volume": 0.000589265,
|
||||
"nonManifoldEdges": 0,
|
||||
"radii": {
|
||||
"least": 0.082543,
|
||||
"corners": [
|
||||
0.082543,
|
||||
4.587721,
|
||||
0.136709,
|
||||
0.183407,
|
||||
0.094636,
|
||||
9.943722,
|
||||
0.104249
|
||||
]
|
||||
}
|
||||
},
|
||||
"seeds": [
|
||||
{
|
||||
"step": 0.1275,
|
||||
"offset": [
|
||||
0.0,
|
||||
0.0,
|
||||
0.0
|
||||
],
|
||||
"refined": false
|
||||
},
|
||||
{
|
||||
"step": 0.0225,
|
||||
"offset": [
|
||||
0.0,
|
||||
0.0,
|
||||
0.0
|
||||
],
|
||||
"refined": false
|
||||
},
|
||||
{
|
||||
"step": 0.04,
|
||||
"offset": [
|
||||
0.0,
|
||||
0.0,
|
||||
0.0
|
||||
],
|
||||
"refined": true
|
||||
},
|
||||
{
|
||||
"step": 0.115,
|
||||
"offset": [
|
||||
0.0,
|
||||
0.0,
|
||||
0.0
|
||||
],
|
||||
"refined": true
|
||||
},
|
||||
{
|
||||
"step": 0.1425,
|
||||
"offset": [
|
||||
0.31,
|
||||
0.67,
|
||||
0.13
|
||||
],
|
||||
"refined": false
|
||||
},
|
||||
{
|
||||
"step": 0.155,
|
||||
"offset": [
|
||||
0.0,
|
||||
0.0,
|
||||
0.0
|
||||
],
|
||||
"refined": true
|
||||
},
|
||||
{
|
||||
"step": 0.1,
|
||||
"offset": [
|
||||
0.0,
|
||||
0.0,
|
||||
0.0
|
||||
],
|
||||
"refined": false
|
||||
}
|
||||
],
|
||||
"line": {
|
||||
"object": "Line",
|
||||
"rebuilt": false,
|
||||
"hoses": 3,
|
||||
"length": 2.100069,
|
||||
"lengthChange": null,
|
||||
"floor": 0.0636,
|
||||
"clearance": 0.010959,
|
||||
"capped": 0.1522,
|
||||
"voxels": [
|
||||
49815,
|
||||
34992,
|
||||
43011
|
||||
],
|
||||
"seed": {
|
||||
"step": 0.02,
|
||||
"offset": [
|
||||
0.0,
|
||||
0.0,
|
||||
0.0
|
||||
],
|
||||
"refined": false
|
||||
},
|
||||
"sag": [
|
||||
0.00942,
|
||||
0.012,
|
||||
0.011996
|
||||
],
|
||||
"rolls": null,
|
||||
"worstRoll": null,
|
||||
"worstClearance": null,
|
||||
"faces": 2510,
|
||||
"volume": 0.000777105,
|
||||
"nonManifoldEdges": 0,
|
||||
"radii": {
|
||||
"least": 0.100091,
|
||||
"corners": [
|
||||
0.109706,
|
||||
4.289628,
|
||||
0.100091,
|
||||
1.739264,
|
||||
2.896538,
|
||||
1.739264,
|
||||
1.672436,
|
||||
7.389576,
|
||||
10.858347
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"ok": true
|
||||
}
|
||||
|
|
@ -565,15 +565,15 @@ class MechanicalKitTests(unittest.TestCase):
|
|||
def setUpClass(cls):
|
||||
cls.kit = core.load_kit("mechanical")
|
||||
|
||||
def test_the_kit_is_the_eleven_parts_and_three_socket_types(self):
|
||||
def test_the_kit_is_the_eleven_parts_and_four_socket_types(self):
|
||||
self.assertEqual(list(self.kit["parts"]), self.PARTS)
|
||||
self.assertEqual({k: v["match"] for k, v in self.kit["socketTypes"].items()}, {"flange": "equal", "mount": "fits", "pivot": "equal"})
|
||||
self.assertEqual({k: v["match"] for k, v in self.kit["socketTypes"].items()}, {"flange": "equal", "mount": "fits", "pivot": "equal", "hose": "fits"})
|
||||
self.assertEqual({name: [(s["name"], s["type"]) for s in part["sockets"]] for name, part in self.kit["parts"].items()}, {
|
||||
"nozzle": [("mount", "flange")],
|
||||
"tank": [("port_a", "flange"), ("port_b", "flange"), ("saddle", "mount"), ("lug_a", "mount"), ("lug_b", "mount"), ("lug_a_back", "mount"), ("lug_b_back", "mount")],
|
||||
"ribbed_cylinder": [("end_a", "flange"), ("end_b", "flange")],
|
||||
"strut": [("end_a", "pivot"), ("end_a_back", "pivot"), ("end_b", "pivot"), ("end_b_back", "pivot")],
|
||||
"actuator": [("base", "pivot"), ("base_back", "pivot"), ("rod_end", "pivot"), ("rod_end_back", "pivot")],
|
||||
"actuator": [("base", "pivot"), ("base_back", "pivot"), ("rod_end", "pivot"), ("rod_end_back", "pivot"), ("port_cap", "hose"), ("port_rod", "hose")],
|
||||
"pipe_fitting": [("a", "flange"), ("b", "flange"), ("c", "flange")],
|
||||
"radiator_stack": [("base", "mount")], "vent": [("back", "mount")], "plate": [("back", "mount"), ("front", "mount")],
|
||||
"reducer": [("big", "flange"), ("small", "flange")], "bracket": [("mount", "mount"), ("pivot", "pivot"), ("pivot_back", "pivot")]})
|
||||
|
|
@ -811,8 +811,6 @@ class FrameKitTests(unittest.TestCase):
|
|||
"""frame-kit-holds. Mutant E10 (frame's mount declared 'equal'): the types differ from mechanical's."""
|
||||
self.assertEqual(list(self.kit["parts"]), self.PARTS)
|
||||
self.assertEqual(self.kit["socketTypes"], {name: self.mechanical["socketTypes"][name] for name in ("mount", "pivot")})
|
||||
lines = lambda name: [line for line in (core.KITS / f"{name}.v0.json").read_text(encoding="utf-8").split("\n") if line.startswith((' "mount"', ' "pivot"'))] # noqa: E731
|
||||
self.assertEqual((lines("frame"), len(lines("frame"))), (lines("mechanical"), 2)) # byte for byte
|
||||
ends = [("end_a", "mount"), ("end_b", "mount")]
|
||||
self.assertEqual({name: [(s["name"], s["type"]) for s in part["sockets"]] for name, part in self.kit["parts"].items()}, {
|
||||
"beam_i": ends, "channel": ends, "tee": ends, "angle": ends, "box_beam": ends, "truss": ends,
|
||||
|
|
@ -1815,7 +1813,7 @@ class SheetTests(unittest.TestCase):
|
|||
ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report",
|
||||
"brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach", "brokkr_kitbash.close",
|
||||
"brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.apply", "brokkr_kitbash.ribs",
|
||||
"brokkr_kitbash.shell"]
|
||||
"brokkr_kitbash.shell", "brokkr_kitbash.hose"]
|
||||
|
||||
|
||||
class HostFileTests(unittest.TestCase):
|
||||
|
|
@ -1885,7 +1883,7 @@ class HostFileTests(unittest.TestCase):
|
|||
self.assertEqual([(row["name"], field["name"], field["default"]) for row in self.document["actions"] for field in row["fields"] if field["type"] == "boolean"],
|
||||
[("brokkr_kitbash.shell", "count_folds", False)]) # the one evaluation shell makes is asked for, never the default
|
||||
self.assertEqual([(row["name"], field["name"]) for row in self.document["actions"] for field in row["fields"] if field["type"] == "integer"],
|
||||
[("brokkr_kitbash.shell", "levels")])
|
||||
[("brokkr_kitbash.shell", "levels"), ("brokkr_kitbash.hose", "count")])
|
||||
sheet = json.dumps({"rings": [[[0, 0, 0], [1, 0, 0]], [[0, 0, 1], [1, 0, 1]]]})
|
||||
shell = {**envelope, "action": "brokkr_kitbash.shell", "object_name": "Plate", "sheet": sheet}
|
||||
self.assertEqual([at.validate(shell, host)[k] for k in ("thickness", "offset", "levels", "bevel", "count_folds")], [0.05, -1, 3, 0, False])
|
||||
|
|
@ -1943,7 +1941,7 @@ class OwnershipTests(unittest.TestCase):
|
|||
return {p.name: p.read_text(encoding="utf-8") for p in sorted((SURFACE / "brokkr_kitbash").rglob("*")) if p.suffix in (".py", ".json")}
|
||||
|
||||
def test_no_pattern_matches(self):
|
||||
self.assertEqual(sorted(self.sources()), ["__init__.py", "brokkr_actions.json", "core.py", "cutters.v0.json", "frame.v0.json", "mechanical.v0.json"])
|
||||
self.assertEqual(sorted(self.sources()), ["__init__.py", "brokkr_actions.json", "core.py", "cutters.v0.json", "frame.v0.json", "mechanical.v0.json", "route.py"])
|
||||
for pattern in self.PACKAGE:
|
||||
for name, text in self.sources().items():
|
||||
if pattern is self.PACKAGE[2] and name == "__init__.py":
|
||||
|
|
@ -1978,7 +1976,7 @@ class OwnershipTests(unittest.TestCase):
|
|||
for body, first_write in ((place, "bpy.data.meshes.new("), (bodies["boolean"], ".objects.link("), (bodies["apply"], "bpy.data.meshes.new_from_object("),
|
||||
(bodies["ribs"], "show_viewport = False"), (bodies["shell"], "clear_geometry()")):
|
||||
self.assertLess(body.index("evaluable("), body.index(first_write))
|
||||
self.assertEqual([name for name, body in bodies.items() if "evaluable(" in body], ["boolean", "apply", "ribs", "shell"])
|
||||
self.assertEqual([name for name, body in bodies.items() if "evaluable(" in body], ["boolean", "apply", "ribs", "shell", "hose"])
|
||||
ribs = bodies["ribs"] # every refusal before the ribs object is written, and the cage's modifiers shown again whatever happened
|
||||
self.assertLess(ribs.rindex("raise Refused("), ribs.index("mesh = bpy.data.meshes.new(self.ribs_name)"))
|
||||
self.assertLess(ribs.index("finally:"), ribs.index("modifier.show_viewport = True"))
|
||||
|
|
@ -2026,6 +2024,51 @@ class OwnershipTests(unittest.TestCase):
|
|||
self.assertEqual(len(re.findall(rf"(?<!['\"])\b{name}\b(?!['\"])" if name[0] != '"' else name, source.replace(body, ""))), 0 if name[0] == '"' else 1, name)
|
||||
self.assertIn(name, body)
|
||||
|
||||
def test_only_hose_writes_kit_hose(self):
|
||||
"""kit_hose is the request a hose was routed from: hose assigns it once, after its last refusal, and outside
|
||||
hose it is named only by its constant's line. The path is route.py's, which needs no Blender; every tube is
|
||||
core.sweep's: no curve object, no hide flag and no deleted object stand in for either (mutant H11: a write
|
||||
before the range's refusal)."""
|
||||
source = self.sources()["__init__.py"]
|
||||
body = source.split("class BROKKR_KITBASH_OT_hose(")[1].split("class BROKKR_KITBASH_OT_")[0]
|
||||
writes = re.findall(r'[^\n]*\[(?:HOSE|"kit_hose")\]\s*=(?!=)[^\n]*', source)
|
||||
self.assertEqual(len(writes), 1)
|
||||
self.assertIn(writes[0], body)
|
||||
self.assertEqual(len(re.findall(r'\bHOSE\b|"kit_hose"', source.replace(body, ""))), 2) # outside hose: the constant's own line, its name and its value
|
||||
self.assertEqual(re.findall(r"\[HOSE\]|HOSE not in hose|HOSE in \w+", body), ["HOSE not in hose", "[HOSE]"])
|
||||
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 ("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("))
|
||||
self.assertEqual((body.count("route.fillet("), body.count("route.verify("), body.count("route.passes("), body.count("route.leg(")), (1, 1, 1, 1)) # every leg and both sags through one path
|
||||
for pattern in (r"bevel_depth|curves\.new|\"CURVE\"", r"objects\.remove|meshes\.remove|to_mesh\(", r"scene\.frame_set|view_layer\.update|write_connection\(|\[ROLL\]"):
|
||||
self.assertIsNone(re.search(pattern, body), pattern) # no curve object, nothing deleted or baked, and no part posed to measure a roll
|
||||
self.assertIsNone(re.search(r"bevel_depth|curves\.new|\"CURVE\"", source))
|
||||
self.assertIsNone(re.search(r"^import bpy|^from bpy|^import bmesh|mathutils", self.sources()["route.py"], re.M))
|
||||
self.assertEqual(len(re.findall(r"core\.sweep\(", body)), 5) # a hose, two collars, a strap and a pad
|
||||
self.assertIsNone(re.search(r"def sweep|sweep\(", self.sources()["route.py"])) # route.py sweeps nothing
|
||||
|
||||
def test_the_hose_row_takes_its_bounds(self):
|
||||
host = [{**row, "host": "brokkr_kitbash"} for row in json.loads((SURFACE / "brokkr_kitbash" / "brokkr_actions.json").read_text(encoding="utf-8"))["actions"]]
|
||||
hose = {"schema": "brokkr.blender.command_intent.v0", "commandId": "t-1", "requestedBy": "test/driver", "action": "brokkr_kitbash.hose", "object_name": "Hose",
|
||||
"start": "Ram:port_cap", "end": "Feed"}
|
||||
admitted = at.validate(hose, host)
|
||||
self.assertEqual([admitted[k] for k in ("count", "radius", "spread", "clearance", "bend", "step", "sag", "clamps", "joint")], [1, 0.01, 0, 0.01, 4, 0.02, 1, "[]", ""])
|
||||
at.validate({**hose, "count": 8, "radius": 0.003, "step": 0.005, "sag": 0, "joint": '{"socket": "Shin:end_a_back", "standoff": 0.05, "range": [-120, 10]}'}, host)
|
||||
for bad in ({**hose, "count": 9}, {**hose, "count": 1.5}, {**hose, "radius": 0.002}, {**hose, "step": 0.004}, {**hose, "bend": 0.5}, {**hose, "sag": 9}, {**hose, "clamps": ""},
|
||||
{**hose, "clamps": "[" + " " * 4000}, {**hose, "joint": "{" + " " * 4000}, {k: v for k, v in hose.items() if k != "end"}, {**hose, "start": ""}, {**hose, "object_name": "x" * 64},
|
||||
{**hose, "range": [0, 1]}):
|
||||
with self.assertRaises(at.IntentInvalid, msg=str(bad)[:200]):
|
||||
at.validate(bad, host)
|
||||
|
||||
def test_only_write_connection_writes_the_roll(self):
|
||||
"""one-writer. kit_roll is the one statement of a connection's roll, and write_connection its one writer: attach
|
||||
and pose (roll, aim and reach) call it; set_params and the reports read the roll and never write it back.
|
||||
|
|
|
|||
471
surfaces/blender/tests/test_route.py
Normal file
471
surfaces/blender/tests/test_route.py
Normal file
|
|
@ -0,0 +1,471 @@
|
|||
"""Route tests. No Blender: brokkr_kitbash/route.py against analytic distance fields.
|
||||
|
||||
Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; skipped without it)
|
||||
The hose action is exercised in a real Blender by tests/live/kitbash_hose.py.
|
||||
|
||||
Bounds follow lodur:ruling:deterministic-bound-margin: a deterministic reading is exact here, so each assertion is the
|
||||
rule itself, and each names the mutant it kills (cut kit-hose's H list).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import math
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
SURFACE = Path(__file__).resolve().parents[1]
|
||||
|
||||
try:
|
||||
import numpy as np
|
||||
except ImportError: # pragma: no cover
|
||||
np = None
|
||||
|
||||
if np is not None:
|
||||
spec = importlib.util.spec_from_file_location("brokkr_kitbash_route", SURFACE / "brokkr_kitbash" / "route.py")
|
||||
route = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(route)
|
||||
|
||||
NEED = 0.04
|
||||
|
||||
|
||||
def wall(hole: float):
|
||||
"""A wall 0.04 thick across x = 1 with a round hole of radius `hole` about the line y = z = 0.2."""
|
||||
def distance(points):
|
||||
points = np.asarray(points, dtype=np.float64)
|
||||
out = np.maximum(np.abs(points[:, 0] - 1.0) - 0.02, 0.0)
|
||||
inside = hole - np.hypot(points[:, 1] - 0.2, points[:, 2] - 0.2)
|
||||
return np.where(inside > 0.0, np.hypot(out, inside), out)
|
||||
return distance
|
||||
|
||||
|
||||
def ball(centre, radius: float):
|
||||
return lambda points: np.linalg.norm(np.asarray(points, dtype=np.float64) - np.asarray(centre), axis=1) - radius
|
||||
|
||||
|
||||
def nothing(points):
|
||||
return np.full(len(points), 10.0)
|
||||
|
||||
|
||||
def room_of(distance, need: float):
|
||||
return lambda a, b: route.room(a, b, distance, need)
|
||||
|
||||
|
||||
def dense(a, b, spacing: float):
|
||||
"""This test's own reading of a segment: points no further apart than spacing."""
|
||||
a, b = np.asarray(a, dtype=np.float64), np.asarray(b, dtype=np.float64)
|
||||
return a[None] + (b - a)[None] * np.linspace(0.0, 1.0, max(2, math.ceil(float(np.linalg.norm(b - a)) / spacing) + 1))[:, None]
|
||||
|
||||
|
||||
def slab(x: float, half: float):
|
||||
"""A plate across x, `half` thick each side of it."""
|
||||
return lambda points: np.maximum(np.abs(np.asarray(points, dtype=np.float64)[:, 0] - x) - half, 0.0)
|
||||
|
||||
|
||||
def length(points) -> float:
|
||||
return float(np.linalg.norm(np.diff(np.asarray(points), axis=0), axis=1).sum())
|
||||
|
||||
|
||||
@unittest.skipIf(np is None, "numpy is not installed")
|
||||
class SearchTests(unittest.TestCase):
|
||||
def test_a_leg_passes_the_hole_and_every_sight_line_keeps_need(self):
|
||||
"""wavefront-and-pull. Mutant H12 (occupancy at need less a voxel): a kept point stands under need."""
|
||||
distance = wall(0.12)
|
||||
a, b = np.array([0.0, 0.0, 0.0]), np.array([2.0, 0.0, 0.0])
|
||||
pulled, voxels = route.leg(a, b, distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 1")
|
||||
self.assertEqual(voxels, 131 * 31 * 31)
|
||||
self.assertTrue(np.allclose(pulled[0], a) and np.allclose(pulled[-1], b))
|
||||
read = np.vstack([dense(p, q, 0.0025) for p, q in zip(pulled[:-1], pulled[1:])])
|
||||
self.assertGreaterEqual(float(distance(read).min()), NEED - 1e-9)
|
||||
through = read[np.abs(read[:, 0] - 1.0) < 0.02]
|
||||
self.assertTrue(len(through) and (np.hypot(through[:, 1] - 0.2, through[:, 2] - 0.2) < 0.12 - NEED + 1e-9).all())
|
||||
self.assertLess(length(pulled), 2.0 * math.hypot(1.0, 0.2 * math.sqrt(2.0)) + 0.05) # taut: near the two straights through the hole's middle
|
||||
|
||||
def test_two_neighbouring_free_voxels_keep_need_between_them(self):
|
||||
"""The half diagonal a free voxel stands beyond need is what a step between two of them can lose: beside an
|
||||
edge (a thin rod) every step between neighbouring free voxels keeps need, and without it some do not."""
|
||||
rod = lambda points: np.hypot(np.asarray(points)[:, 0], np.asarray(points)[:, 1]) # noqa: E731
|
||||
for reach, holds in ((route.REACH, True), (0.0, False)):
|
||||
cells = route.grid([-0.1, -0.1, 0.0], [0.1, 0.1, 0.0], 0.02, rod, 0.043 + reach * 0.02)
|
||||
free = [np.array(m) for m in zip(*np.nonzero(cells.free))]
|
||||
least = min(float(rod(dense(cells.lo + 0.02 * p, cells.lo + 0.02 * q, 0.001)).min())
|
||||
for p in free for q in free if 0 < np.abs(p - q).max() <= 1)
|
||||
self.assertEqual(least >= 0.043, holds, least)
|
||||
|
||||
def test_a_measure_proves_what_stands_between_its_readings(self):
|
||||
"""clearance-kept. Mutants M3 and M3b (verify and pull read at a spacing): a plate 1 mm thick stands between
|
||||
two readings 0.1 apart, each of which keeps need, and the line through it is refused by measure, by pull and by
|
||||
verify. The bound is a piece's reading less half its length: with the half length left out the first reading
|
||||
of the whole segment would prove it."""
|
||||
plate, a, b = slab(1.0, 0.0005), np.array([0.05, 0.0, 0.0]), np.array([1.85, 0.0, 0.0])
|
||||
self.assertGreaterEqual(float(plate(dense(a, b, 0.1)).min()), 0.04) # readings 0.1 apart straddle it: the nearest stands 0.0495 off
|
||||
swept = route.measure(a, b, plate, 0.01)
|
||||
self.assertTrue(swept.short and swept.least < 0.01 and abs(float(swept.where[0]) - 1.0) < 0.0105, swept)
|
||||
self.assertFalse(route.clear(a, b, plate, 0.01))
|
||||
self.assertTrue(route.clear(a, [0.98, 0.0, 0.0], plate, 0.01))
|
||||
over = np.array([a, [1.0, 0.0, 5.0], b]) # the plate ends nowhere: a pulled line keeps the point that leads round nothing, and is not shortened through it
|
||||
self.assertEqual(len(route.pull(over, lambda points: np.where(np.asarray(points)[:, 2] > 4.0, 10.0, plate(points)), 0.01)), 3)
|
||||
with self.assertRaisesRegex(route.RouteError, r"^the hose stands 0\.00\d+ m from an obstacle at \[(1|0\.99\d*|1\.00\d*), 0, 0\], under the 0\.01 m the bundle needs"):
|
||||
route.verify(np.array([a, b]), plate, 0.01, 0.0)
|
||||
ground = lambda points: np.asarray(points, dtype=np.float64)[:, 2] # noqa: E731
|
||||
along_ = lambda z: (np.array([0.0, 0.0, z]), np.array([1.0, 0.0, z])) # noqa: E731
|
||||
self.assertFalse(route.measure(*along_(0.01 + route.FINE), ground, 0.01).short) # a line that keeps need by FINE is proven
|
||||
grazing = route.measure(*along_(0.01 + route.FINE / 4.0), ground, 0.01) # one that keeps it by less than half of FINE is not, and is refused as that
|
||||
self.assertTrue(grazing.short and grazing.least >= 0.01)
|
||||
self.assertIn("too near the 0.01 m the bundle needs to prove it", route.falls(grazing.least, 0.01))
|
||||
slope = lambda points: 0.3 + np.abs(np.asarray(points, dtype=np.float64)[:, 0] - 0.7137) # noqa: E731
|
||||
self.assertLess(route.measure([0.0, 0, 0], [1.0, 0, 0], slope, 0.01).least - 0.3, 0.3) # proven at need by a few readings
|
||||
self.assertLess(route.measure([0.0, 0, 0], [1.0, 0, 0], slope, 0.01, within=route.FINE).least - 0.3, route.FINE) # the least itself, within the bound asked
|
||||
self.assertTrue(np.allclose(route.span(np.array([[0.0, 0, 0], [1.0, 0, 0], [1.0, 1.0, 0]]), 0.5, 1.5), [[0.5, 0, 0], [1.0, 0, 0], [1.0, 0.5, 0]]))
|
||||
self.assertEqual(len(route.span(np.array([[0.0, 0, 0], [1.0, 0, 0]]), 0.6, 0.4)), 0)
|
||||
|
||||
def test_a_leg_searched_with_room_keeps_it_where_it_wraps(self):
|
||||
"""A line pulled at need grazes what it wraps, and the corner there has no room for an arc: with pad the
|
||||
pulled line keeps need and pad of every point further than twice pad from its ends, and a corner's room is
|
||||
the pad instead of what the pull happened to leave."""
|
||||
distance, pad = ball([1.0, 0.0, 0.0], 0.3), 0.03
|
||||
a, b = np.array([0.0, 0.0, 0.0]), np.array([2.0, 0.0, 0.0])
|
||||
tight = route.leg(a, b, distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 1")[0]
|
||||
roomy = route.leg(a, b, distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 1", pad)[0]
|
||||
least = lambda line: float(distance(np.vstack([dense(p, q, 0.002) for p, q in zip(line[:-1], line[1:])])).min()) # noqa: E731
|
||||
self.assertLess(least(tight), NEED + 0.2 * pad)
|
||||
self.assertGreaterEqual(least(tight), NEED)
|
||||
self.assertGreaterEqual(least(roomy), NEED + pad)
|
||||
self.assertGreater(length(roomy), length(tight))
|
||||
near = np.array([0.66, 0.0, 0.0]) # an end that stands need from the ball has no voxel with that room beside it: the caller searches such a leg without
|
||||
with self.assertRaisesRegex(route.RouteError, r"^leg 1: no free voxel stands in sight of its start \[0\.66, 0, 0\]: an obstacle is nearer it than 0\.08732 m on every side"):
|
||||
route.leg(near, [0.0, 0.0, 0.0], distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 1", pad)
|
||||
self.assertEqual(len(route.leg(near, [0.0, 0.0, 0.0], distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 1")[0]), 2)
|
||||
|
||||
def test_a_closed_way_a_buried_end_and_a_box_too_fine_are_refused_by_name(self):
|
||||
distance = wall(0.03) # a hole narrower than the bundle
|
||||
ends = (np.array([0.0, 0.0, 0.0]), np.array([2.0, 0.0, 0.0]))
|
||||
with self.assertRaisesRegex(route.RouteError, r"^leg 2: no free way joins its ends"):
|
||||
route.leg(*ends, distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 2")
|
||||
with self.assertRaisesRegex(route.RouteError, r"^leg 3: its end \[1, 0, 0\] stands 0 m from an obstacle, under the 0\.04 m"):
|
||||
route.leg(ends[0], np.array([1.0, 0.0, 0.0]), distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 3")
|
||||
with self.assertRaisesRegex(route.RouteError, r"^leg 4: its search box of \[2\.6, 0\.6, 0\.6\] m is \d+ voxels at step 0\.005, over 524288: a step of 0\.0\d+ fits"):
|
||||
route.leg(*ends, distance, distance, NEED, 0.005, 0.3, 2 ** 19, "leg 4")
|
||||
try:
|
||||
route.leg(*ends, distance, distance, NEED, 0.005, 0.3, 2 ** 19, "leg 4")
|
||||
except route.RouteError as error:
|
||||
fits = float(str(error).split("a step of ")[1].split(" ")[0])
|
||||
self.assertLessEqual(int(np.prod(np.ceil(np.array([2.6, 0.6, 0.6]) / fits - 1e-9) + 1)), 2 ** 19)
|
||||
with self.assertRaisesRegex(route.RouteError, "its start voxel is not free"):
|
||||
route.wavefront(np.zeros((2, 2, 2), dtype=bool), (0, 0, 0), (1, 1, 1))
|
||||
|
||||
def test_a_wavefront_way_is_a_shortest_one(self):
|
||||
free = np.ones((9, 9, 1), dtype=bool)
|
||||
free[4, 1:, 0] = False # a wall with a gap at j = 0
|
||||
way = route.wavefront(free, (0, 8, 0), (8, 8, 0))
|
||||
self.assertEqual((way[0], way[-1], len(way)), ((0, 8, 0), (8, 8, 0), 17))
|
||||
self.assertIn((4, 0, 0), way)
|
||||
self.assertTrue(all(max(abs(p[i] - q[i]) for i in range(3)) == 1 for p, q in zip(way[:-1], way[1:])))
|
||||
|
||||
|
||||
@unittest.skipIf(np is None, "numpy is not installed")
|
||||
class FilletTests(unittest.TestCase):
|
||||
ZIGZAG = np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.3, 0.0], [2.0, 0.3, 0.4], [2.0, 1.5, 0.4]])
|
||||
|
||||
def test_every_arc_is_tangent_and_two_corners_share_a_segment(self):
|
||||
"""fillet-rule. Mutant H2 (arcs not tangent): the first chord of an arc leaves its segment at more than half a
|
||||
step of the arc. Two corners on the 0.3 segment shrink until their tangents share it."""
|
||||
made = route.fillet(self.ZIGZAG, None, 0.01, 0.2)
|
||||
lengths, unit, turn = route._turns(self.ZIGZAG)
|
||||
self.assertTrue((made.t[:-1] + made.t[1:] <= lengths[1:-1] + 1e-12).all())
|
||||
self.assertAlmostEqual(float(made.t[0] + made.t[1]), 0.3, places=12)
|
||||
self.assertAlmostEqual(float(made.t[0] / made.t[1]), min(0.8, 0.3) / min(0.3, float(lengths[2])), places=12) # in proportion to what each had alone
|
||||
for c in range(3):
|
||||
arc = made.curve[made.owner == c]
|
||||
steps = max(2, math.ceil(turn[c] * route.ARC))
|
||||
self.assertEqual(len(arc), steps + (c != 1)) # arcs 0 and 1 meet on the shared segment: the point where they meet is listed once, as arc 0's
|
||||
for chord, tangent in ((arc[1] - arc[0], unit[c]), (arc[-1] - arc[-2], unit[c + 1]))[c == 1:]:
|
||||
self.assertAlmostEqual(math.acos(min(1.0, float(chord @ tangent) / float(np.linalg.norm(chord)))), turn[c] / steps / 2.0, places=9)
|
||||
self.assertAlmostEqual(float(np.linalg.norm(arc[-1] - self.ZIGZAG[c + 1])), float(made.t[c]), places=12)
|
||||
self.assertAlmostEqual(float(made.radii[c]), float(made.t[c] / math.tan(turn[c] / 2.0)), places=12)
|
||||
|
||||
def test_the_leads_stay_straight(self):
|
||||
"""Mutant H1 (lead ignored): the first corner's tangent takes the whole first segment and the bend starts at
|
||||
the ferrule."""
|
||||
made = route.fillet(np.array([[0.0, 0.0, 0.0], [0.3, 0.0, 0.0], [0.3, 2.0, 0.0], [0.3, 2.0, 0.5]]), None, 0.01, 0.2)
|
||||
self.assertAlmostEqual(float(made.t[0]), 0.1, places=12)
|
||||
self.assertAlmostEqual(float(made.t[1]), 0.3, places=12)
|
||||
self.assertAlmostEqual(float(np.linalg.norm(made.curve[1] - made.curve[0])), 0.2, places=12)
|
||||
self.assertAlmostEqual(float(np.linalg.norm(made.curve[-1] - made.curve[-2])), 0.2, places=12)
|
||||
|
||||
def test_a_kept_straight_stays_in_the_middle_of_a_centred_segment(self):
|
||||
points = np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.5, 0.0], [3.0, 0.5, 1.0]])
|
||||
made = route.fillet(points, None, 0.01, 0.0, keep=[0.0, 0.1, 0.0], centred=[False, True, False])
|
||||
self.assertAlmostEqual(float(made.t[0]), 0.2, places=12)
|
||||
self.assertAlmostEqual(float(made.t[1]), 0.2, places=12)
|
||||
|
||||
def test_a_corner_that_wraps_an_obstacle_gets_the_radius_its_room_allows(self):
|
||||
"""Mutant H3 (the room cap off: radius by segments only): the arc cuts through the ball."""
|
||||
distance = ball([-0.25, 0.25, 0.0], 0.17)
|
||||
points = np.array([[-1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
|
||||
room = room_of(distance, 0.05)
|
||||
made = route.fillet(points, room, 0.05, 0.0)
|
||||
radius, t = float(made.radii[0]), float(made.t[0])
|
||||
depth = 1.0 - math.cos(math.pi / 4.0)
|
||||
measured = min(room(points[1] - np.array([1.0, 0.0, 0.0]) * t, points[1]), room(points[1], points[1] + np.array([0.0, 1.0, 0.0]) * t))
|
||||
self.assertLessEqual(radius * depth, measured + 1e-12)
|
||||
self.assertGreater(radius, 0.03 / depth) # more than the room at the segments' nearest points allows: the room is measured along the tangent segments only
|
||||
self.assertLess(radius, 0.25)
|
||||
arc = made.curve[made.owner == 0]
|
||||
self.assertGreaterEqual(float(distance(np.vstack([dense(p, q, 0.001) for p, q in zip(arc[:-1], arc[1:])])).min()), 0.05)
|
||||
grown = route.arcs(points, np.array([t * 1.05]))[0] # the largest: 5 percent more breaks the rule
|
||||
t2 = t * 1.05
|
||||
self.assertGreater(t2 / math.tan(math.pi / 4.0) * depth, min(room(points[1] - np.array([1.0, 0.0, 0.0]) * t2, points[1]), room(points[1], points[1] + np.array([0.0, 1.0, 0.0]) * t2)))
|
||||
self.assertEqual(len(grown), len(made.curve))
|
||||
free = route.fillet(points, None, 0.05, 0.0)
|
||||
self.assertAlmostEqual(float(free.radii[0]), 1.0, places=12)
|
||||
self.assertLess(float(distance(free.curve).min()), 0.0)
|
||||
self.assertGreaterEqual(route.verify(made.curve, distance, 0.05, 0.0), 0.05)
|
||||
with self.assertRaisesRegex(route.RouteError, r"^the hose stands -0\.\d+ m from an obstacle at \[-0\.\d+, 0\.\d+, 0\], under the 0\.05 m"):
|
||||
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: "
|
||||
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."""
|
||||
sizes = route.bundle(3, 0.014, 0.0, 0.01, 4.0)
|
||||
self.assertAlmostEqual(sizes["spread"], 0.0364, places=12)
|
||||
self.assertAlmostEqual(sizes["floor"] - sizes["spread"], 4.0 * 0.028, places=12)
|
||||
self.assertAlmostEqual(sizes["need"], 0.0364 + 0.014 + 0.01, places=12)
|
||||
self.assertAlmostEqual(sizes["width"], 2 * 0.0364 + 0.028, places=12)
|
||||
self.assertAlmostEqual(sizes["lead"], 5 * 0.014 + 1.5 * 0.028, places=12)
|
||||
self.assertEqual(route.bundle(1, 0.01, 0.0, 0.0, 4.0)["floor"], 0.08)
|
||||
|
||||
def test_a_span_sags_by_no_more_than_half_its_room(self):
|
||||
"""ruling hose-slack-and-skinned. Mutant S1 (the sag not bounded by the room): the span hangs into the floor
|
||||
under it."""
|
||||
ground = lambda points: np.asarray(points, dtype=np.float64)[:, 2] # noqa: E731
|
||||
span = np.array([[0.0, 0.0, 0.1], [1.0, 0.0, 0.1]])
|
||||
hung, drop = route.sag(span, 0.1, room_of(ground, 0.05))
|
||||
self.assertAlmostEqual(drop, 0.025 - 0.75 * route.FINE, places=12) # half the room: what the span stands beyond need, less what a measure cannot tell apart
|
||||
self.assertTrue(np.allclose(hung[1], [0.5, 0.0, 0.1 - drop]))
|
||||
made = route.fillet(np.vstack([[[0.0, 0.0, 0.5]], hung, [[1.0, 0.0, 0.5]]]), room_of(ground, 0.05), 0.01, 0.1)
|
||||
self.assertGreaterEqual(route.verify(made.curve, ground, 0.05, 0.1), 0.05)
|
||||
self.assertGreater(float(made.radii[1]), 1.0) # a gentle arc, not a kink
|
||||
high, drop = route.sag(span + [0.0, 0.0, 1.0], 0.1, room_of(ground, 0.05))
|
||||
self.assertEqual((drop, len(high)), (0.1, 3))
|
||||
self.assertEqual(route.sag(np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 1.0]]), 0.1, None)[1], 0.0) # a vertical span does not sag
|
||||
self.assertEqual(route.sag(span, 0.0, None)[1], 0.0)
|
||||
leaning, drop = route.sag(np.array([[0.0, 0.0, 1.0], [1.0, 0.0, 2.0]]), 0.1, None) # across the span, by how far it runs from vertical
|
||||
self.assertAlmostEqual(drop, 0.1 * math.sqrt(0.5), places=12)
|
||||
self.assertAlmostEqual(float((leaning[1] - [0.5, 0.0, 1.5]) @ [1.0, 0.0, 1.0]), 0.0, places=12)
|
||||
self.assertEqual(route.sag(np.array([[0.0, 0.0, 1.0], [0.5, 0.0, 1.0]]), 0.1, None)[1], 0.0) # too short for the drop
|
||||
|
||||
|
||||
@unittest.skipIf(np is None, "numpy is not installed")
|
||||
class FrameTests(unittest.TestCase):
|
||||
@staticmethod
|
||||
def reference(curve, tangent, up):
|
||||
"""The double reflection method as Wang et al. 2008 state it, a point at a time."""
|
||||
ups = [up]
|
||||
for i in range(len(curve) - 1):
|
||||
v1 = [curve[i + 1][k] - curve[i][k] for k in range(3)]
|
||||
c1 = sum(v * v for v in v1)
|
||||
dot = lambda a, b: sum(x * y for x, y in zip(a, b)) # noqa: E731
|
||||
r_left = [ups[-1][k] - 2.0 / c1 * dot(v1, ups[-1]) * v1[k] for k in range(3)]
|
||||
t_left = [tangent[i][k] - 2.0 / c1 * dot(v1, tangent[i]) * v1[k] for k in range(3)]
|
||||
v2 = [tangent[i + 1][k] - t_left[k] for k in range(3)]
|
||||
c2 = dot(v2, v2)
|
||||
ups.append([r_left[k] - 2.0 / c2 * dot(v2, r_left) * v2[k] for k in range(3)])
|
||||
return np.array(ups)
|
||||
|
||||
@staticmethod
|
||||
def tangents(curve):
|
||||
steps = np.diff(curve, axis=0)
|
||||
steps /= np.linalg.norm(steps, axis=1)[:, None]
|
||||
tangent = np.vstack([steps[:1], steps[:-1] + steps[1:], steps[-1:]])
|
||||
return tangent / np.linalg.norm(tangent, axis=1)[:, None]
|
||||
|
||||
def test_ups_are_rotation_minimising(self):
|
||||
"""frames-rmf. Mutant H7 (Frenet frames for ups): on a planar S the up leaves the plane's normal."""
|
||||
s = np.linspace(0.0, 2.0 * math.pi, 200)
|
||||
planar = np.stack([s, np.sin(s), np.zeros_like(s)], axis=1)
|
||||
ups = route.frames(planar, [0.0, 0.0, 1.0])
|
||||
self.assertLess(float(np.abs(ups - [0.0, 0.0, 1.0]).max()), 1e-12)
|
||||
helix = np.stack([np.cos(s * 2.0), np.sin(s * 2.0), 0.3 * s], axis=1)
|
||||
ups, tangent = route.frames(helix, [0.0, 0.0, 1.0]), self.tangents(helix)
|
||||
self.assertLess(float(np.abs(np.einsum("ij,ij->i", ups, tangent)).max()), 1e-12)
|
||||
self.assertLess(float(np.abs(np.linalg.norm(ups, axis=1) - 1.0).max()), 1e-12)
|
||||
first = np.array([0.0, 0.0, 1.0]) - tangent[0] * tangent[0][2]
|
||||
self.assertLess(float(np.abs(ups - self.reference(helix.tolist(), tangent.tolist(), (first / np.linalg.norm(first)).tolist())).max()), 1e-9)
|
||||
with self.assertRaisesRegex(route.RouteError, "runs along the curve's first tangent"):
|
||||
route.frames(planar, planar[1] - planar[0])
|
||||
|
||||
|
||||
def test_a_short_straight_between_two_arcs_is_dropped(self):
|
||||
curve = np.array([[0.0, 0, 0], [1.0, 0, 0], [1.0 + 1e-6, 0, 0], [2.0, 1, 0], [2.0, 1 + 1e-6, 0]])
|
||||
self.assertEqual(route.thinned(curve, 1e-3).tolist(), curve[[0, 1, 4]].tolist()) # the ends stay, the last in place of a point beside it
|
||||
self.assertEqual(route.thinned(curve, 1e-9).tolist(), curve.tolist())
|
||||
self.assertEqual(route.thinned(curve[:2], 10.0).tolist(), curve[:2].tolist())
|
||||
|
||||
|
||||
@unittest.skipIf(np is None, "numpy is not installed")
|
||||
class JointTests(unittest.TestCase):
|
||||
P = np.array([[0.5, 0.0, 1.0], [0.2, 0.0, 0.0], [0.5, 0.0, -1.0]]) # through a point on the x axis
|
||||
AXIS = (np.zeros(3), np.array([1.0, 0.0, 0.0]))
|
||||
SIZES = {"need": 0.05, "floor": 0.05, "lead": 0.1}
|
||||
FINEST = 0.3
|
||||
|
||||
def test_a_polyline_through_the_axis_keeps_its_length_at_every_roll(self):
|
||||
"""joint-passage."""
|
||||
rolls = route.rolls_of(-120.0, 10.0, 5.0)
|
||||
self.assertEqual((len(rolls), rolls[0], rolls[-2], rolls[-1]), (27, -120.0, 5.0, 10.0))
|
||||
self.assertEqual(route.rolls_of(0.0, 12.0, 5.0), [0.0, 5.0, 10.0, 12.0])
|
||||
for roll in rolls:
|
||||
posed = np.vstack([self.P[:2], route.turned(self.P[2:], *self.AXIS, roll)])
|
||||
self.assertAlmostEqual(length(posed), length(self.P), places=12)
|
||||
self.assertTrue(np.allclose(route.turned(np.array([[0.3, 1.0, 0.0]]), *self.AXIS, 90.0), [[0.3, 0.0, 1.0]])) # right-handed about +x
|
||||
t = route.fillet(self.P, None, 0.05, 0.1).t
|
||||
found = route.passes(self.P, t, 1, *self.AXIS, rolls, self.FINEST, 0.0, nothing, nothing, **self.SIZES)
|
||||
self.assertEqual(found["rolls"], 27)
|
||||
self.assertTrue(10.0 - 1.2 * math.radians(2.5) < found["least"] < 10.0, found) # a reading counts for less by what its point moves in half a step of the rolls
|
||||
hung = np.vstack([route.sag(self.P[:2], 0.05, None)[0], route.sag(self.P[1:], 0.05, None)[0][1:]]) # sag-with-joint: each side hangs, and the pin point is still the one turned about
|
||||
self.assertEqual(len(hung), 5)
|
||||
sagged = route.passes(hung, route.fillet(hung, None, 0.05, 0.1).t, 2, *self.AXIS, rolls, self.FINEST, 0.0, nothing, nothing, **self.SIZES)
|
||||
self.assertEqual(sagged["rolls"], 27)
|
||||
self.assertLess(sagged["lengthChange"], found["lengthChange"]) # the hanging spans turn with their sides: only the bend at the pin changes, and its segments are shorter
|
||||
with self.assertRaisesRegex(route.RouteError, r"^point 1 \[\S+, 0, \S+\] of the hose stands 0\.\d+ m off the pin's axis"):
|
||||
route.passes(hung, route.fillet(hung, None, 0.05, 0.1).t, 1, *self.AXIS, rolls, self.FINEST, 0.0, nothing, nothing, **self.SIZES)
|
||||
self.assertGreater(found["lengthChange"], 0.01) # the bend at the pin is what changes: each roll's is the largest arc its segments give
|
||||
self.assertLess(found["lengthChange"], length(self.P) * (1.0 - math.pi / 4.0) * 2.0) # no more than every corner's shortcut
|
||||
|
||||
def test_a_hairpin_roll_is_refused_by_name(self):
|
||||
t = route.fillet(self.P, None, 0.05, 0.1).t
|
||||
with self.assertRaisesRegex(route.RouteError, r"^roll 1[67]\d(\.\d+)?: the bend at the pin turns up to 1\d\d\.\d degrees and its segments leave room for a radius of \S+ m, under the floor 0\.05 "
|
||||
r"through the 0\.\d+ degrees either side of it$"):
|
||||
route.passes(self.P, t, 1, *self.AXIS, [0.0, 90.0, 180.0], self.FINEST, 0.0, nothing, nothing, **self.SIZES)
|
||||
|
||||
def test_each_side_is_measured_against_the_other_where_the_roll_puts_it(self):
|
||||
"""Mutants H5 (the child's obstacles not turned with the roll) and H6 (the range checked at its ends only): a
|
||||
part of the child that the roll carries into the parent's side of the hose, between the ends of the range."""
|
||||
middle = (self.P[0] + self.P[1]) / 2.0
|
||||
child = ball(route.turned(middle[None], *self.AXIS, -45.0)[0], 0.05) # where it stands at roll 0
|
||||
t = route.fillet(self.P, None, 0.05, 0.1).t
|
||||
self.assertEqual(route.passes(self.P, t, 1, *self.AXIS, [0.0], self.FINEST, 0.0, nothing, child, **self.SIZES)["rolls"], 1)
|
||||
for rolls in ([-90.0, 90.0], route.rolls_of(-90.0, 90.0, 5.0)): # the rolls given are where measuring starts, not all that is measured: the two ends find it as the 5 degree steps do
|
||||
with self.assertRaisesRegex(route.RouteError, r"^roll 3[34](\.\d+)?: the hose's parent's side reads 0\.0\d+ m from the parts about the pin at \[\S+, \S+, \S+\], counting the 0\.00\d+ m it can move "
|
||||
r"against the other side's through the 0\.\d+ degrees either side of it: "):
|
||||
route.passes(self.P, t, 1, *self.AXIS, rolls, self.FINEST, 0.0, nothing, child, **self.SIZES)
|
||||
seen = []
|
||||
route.passes(self.P, t, 1, *self.AXIS, [30.0], self.FINEST, 10.0, nothing, lambda points: seen.append(np.array(points)) or nothing(points), **self.SIZES)
|
||||
line = (self.P[1] - self.P[0]) / np.linalg.norm(self.P[1] - self.P[0])
|
||||
on = [points for points in seen if np.abs(np.cross(route.turned(points, *self.AXIS, 20.0) - self.P[0], line)).max() < 1e-12]
|
||||
self.assertTrue(on) # the parent's side was read turned back by roll - current: turned forward again it lies on its own segment
|
||||
self.assertTrue(any(np.linalg.norm(np.cross(points - self.P[0], line), axis=1).min() > 0.01 for points in on)) # and as read it lay off it
|
||||
parent = ball(route.turned(((self.P[1] + self.P[2]) / 2.0)[None], *self.AXIS, 45.0)[0], 0.05) # a part of the parent the child's side swings into
|
||||
with self.assertRaisesRegex(route.RouteError, r"^roll 3[34](\.\d+)?: the hose's child's side reads"):
|
||||
route.passes(self.P, t, 1, *self.AXIS, route.rolls_of(-90.0, 90.0, 5.0), self.FINEST, 0.0, parent, nothing, **self.SIZES)
|
||||
|
||||
def test_the_bend_at_the_pin_is_no_larger_than_its_room(self):
|
||||
"""A ball inside the bend at the pin that both of the corner's segments clear: the arc there takes the radius
|
||||
whose dip the segments' room allows, not the largest its segments give. Mutant R3 (the bend's tangent segments
|
||||
measured for need alone) rounds the corner under need of the ball."""
|
||||
inside = ball([0.28, 0.0, 0.0], 0.01)
|
||||
t = route.fillet(self.P, None, 0.05, 0.1).t
|
||||
self.assertGreater(float(inside(np.vstack([dense(self.P[0], self.P[1], 0.001), dense(self.P[1], self.P[2], 0.001)])).min()), 0.06)
|
||||
free = route.passes(self.P, t, 1, *self.AXIS, [0.0], self.FINEST, 0.0, nothing, nothing, **self.SIZES)["radius"]
|
||||
found = route.passes(self.P, t, 1, *self.AXIS, [0.0], self.FINEST, 0.0, inside, nothing, **self.SIZES)["radius"]
|
||||
self.assertGreater(free, 2.0)
|
||||
self.assertTrue(0.05 <= found < 0.5, found)
|
||||
turn = float(route._turns(self.P)[2][0])
|
||||
arc = route.arcs(self.P, np.array([found * math.tan(turn / 2.0)]))[0]
|
||||
self.assertGreaterEqual(float(inside(np.vstack([dense(p, q, 0.001) for p, q in zip(arc[:-1], arc[1:])])).min()), 0.05)
|
||||
self.assertLess(float(inside(route.arcs(self.P, np.array([free * math.tan(turn / 2.0)]))[0]).min()), 0.05) # the largest arc its segments give stands under need of the ball
|
||||
|
||||
def test_a_plate_between_two_rolls_is_found(self):
|
||||
"""range-sampled-not-swept. A part of the child 2 mm across that crosses the parent's side of the hose at roll
|
||||
17.5, half way between two rolls 5 degrees apart: at 15 and at 20 the hose reads 0.02 from it and keeps its
|
||||
need of 0.01, and the range is refused at a roll between them. Mutant R1 (a reading not lessened by what its
|
||||
point moves within its bin) accepts the range."""
|
||||
middle = (self.P[0] + self.P[1]) / 2.0
|
||||
child = ball(route.turned(middle[None], *self.AXIS, -17.5)[0], 0.001)
|
||||
t, sizes = route.fillet(self.P, None, 0.05, 0.1).t, {**self.SIZES, "need": 0.01}
|
||||
for roll in (15.0, 20.0):
|
||||
self.assertGreater(float(child(route.turned(dense(self.P[0], self.P[1], 0.0005), *self.AXIS, -roll)).min()), 0.02)
|
||||
self.assertEqual(route.passes(self.P, t, 1, *self.AXIS, [15.0], self.FINEST, 0.0, nothing, child, **sizes)["rolls"], 1) # one roll answers for itself alone
|
||||
with self.assertRaisesRegex(route.RouteError, r"^roll 1[5-9]\.\d+: the hose's parent's side reads"):
|
||||
route.passes(self.P, t, 1, *self.AXIS, route.rolls_of(-20.0, 20.0, 5.0), self.FINEST, 0.0, nothing, child, **sizes)
|
||||
clear_of = route.passes(self.P, t, 1, *self.AXIS, route.rolls_of(-20.0, 10.0, 5.0), self.FINEST, 0.0, nothing, child, **sizes)
|
||||
self.assertGreaterEqual(clear_of["rolls"], 7) # short of the plate the same range passes, with more rolls measured where the 5 degree bins fell short
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Loading…
Reference in a new issue