inire/inire/geometry/components.py

704 lines
29 KiB
Python

from __future__ import annotations
from dataclasses import dataclass, field, replace
from itertools import pairwise
from math import asin, ceil, pi, radians, sqrt
from typing import TYPE_CHECKING, Literal
import numpy
from shapely import get_num_coordinates, snap
from shapely.affinity import rotate as shapely_rotate
from shapely.affinity import scale as shapely_scale
from shapely.affinity import translate as shapely_translate
from shapely.geometry import Polygon, box
from inire.constants import TOLERANCE_ANGULAR, TOLERANCE_LINEAR
from inire.geometry.sbend import sbend_grid_span, sbend_span
from inire.seeds import Bend90Seed, PathSegmentSeed, SBendSeed, StraightSeed
from .primitives import Port, rotation_matrix2
if TYPE_CHECKING:
from collections.abc import Iterable, Sequence
from numpy.typing import NDArray
MoveKind = Literal["straight", "bend90", "sbend"]
BendCollisionModelName = Literal["arc", "bbox", "clipped_bbox"]
BendCollisionModel = BendCollisionModelName | Polygon
BendPhysicalGeometry = Literal["arc"] | Polygon
def path_within_board(path: Iterable[ComponentResult], board: Polygon) -> bool:
"""Check containment of the physical geometry, including boundary contact."""
return all(board.covers(shape) for component in path for shape in component.physical_geometry)
PortFace = tuple[float, float, float, float]
def _port_face(polygon: Polygon, port: Port, *, arrival: bool) -> PortFace | None:
"""Find a centered port face with material on the required side."""
axis = 0 if port.r % 180 == 0 else 1
position = (port.x, port.y)
exterior = polygon.exterior
coordinates = numpy.asarray(exterior.coords)
normal = coordinates[:, axis] - position[axis]
on_plane = numpy.abs(normal) <= TOLERANCE_LINEAR
lateral = coordinates[:, 1 - axis] - position[1 - axis]
lower = numpy.minimum(lateral[:-1], lateral[1:])
upper = numpy.maximum(lateral[:-1], lateral[1:])
# The interior is left of a counterclockwise exterior edge.
forward = 1 if port.r < 180 else -1
inward = forward if not arrival else -forward
left = (lateral[1:] - lateral[:-1]) * (1 if axis == 1 else -1)
interior = left if exterior.is_ccw else -left
edges = numpy.flatnonzero(on_plane[:-1] & on_plane[1:] & (interior * inward > 0))
intervals = sorted((lower[i], upper[i], min(normal[i:i + 2]), max(normal[i:i + 2])) for i in edges)
spans: list[PortFace] = []
for lo, hi, near, far in intervals:
if spans and lo <= spans[-1][1]:
prev_lo, prev_hi, prev_near, prev_far = spans[-1]
spans[-1] = prev_lo, max(prev_hi, hi), min(prev_near, near), max(prev_far, far)
else:
spans.append((lo, hi, near, far))
return next((span for span in spans if span[0] < 0 < span[1]), None)
def _face_matches_width(face: PortFace | None, width: float | None) -> bool:
return face is not None and (
width is None or max(abs(face[0] + width / 2), abs(face[1] - width / 2)) <= TOLERANCE_LINEAR
)
def _has_port_face(polygon: Polygon, port: Port, *, arrival: bool, width: float) -> bool:
return _face_matches_width(_port_face(polygon, port, arrival=arrival), width)
def _shares_face(left: Polygon, right: Polygon) -> bool:
if left.intersection(right).length > TOLERANCE_LINEAR:
return True
# Separately transformed outlines can differ by rounding at the shared edge.
snapped = snap(right, left, TOLERANCE_LINEAR)
return snapped.is_valid and left.intersection(snapped).length > TOLERANCE_LINEAR
def check_path_geometry(path: Sequence[ComponentResult]) -> tuple[bool, bool]:
"""Return polygon validity and physical continuity for a path."""
continuous = True
for component in path:
valid, connected = component.physical_checks
if not valid:
return False, False
continuous = continuous and connected
return True, continuous and all(components_join(a, b) for a, b in pairwise(path))
def components_join(left: ComponentResult, right: ComponentResult) -> bool:
if left.end_port != right.start_port:
return False
if left.standard_faces and right.standard_faces:
return True
a, b = left.port_faces[1], right.port_faces[0]
return (
_face_matches_width(a, left.width)
and _face_matches_width(b, right.width)
and a is not None and b is not None
and min(a[1], b[1]) > max(a[0], b[0])
and max(abs(a[2] - b[3]), abs(a[3] - b[2])) <= TOLERANCE_LINEAR
)
def bend_fits_width(radius: float, width: float) -> bool:
return radius >= width / 2
def bend90_grid_span(radius: float) -> int:
"""Distance from either port face to the corner on the routing grid."""
return ceil(radius)
def _normalize_length(value: float) -> float:
return float(value)
def _advance_port(start: Port, rotation: NDArray[numpy.int32], forward: float, lateral: float = 0.0, turn: int = 0) -> Port:
dx, dy = rotation @ numpy.array((forward, lateral))
return Port(start.x + dx, start.y + dy, start.r + turn)
def _bend90_length(radius: float) -> float:
return radius * pi / 2 + 2 * (bend90_grid_span(radius) - radius)
@dataclass(frozen=True, slots=True)
class ComponentResult:
start_port: Port
collision_geometry: Sequence[Polygon]
end_port: Port
length: float
move_type: MoveKind
move_spec: PathSegmentSeed
physical_geometry: Sequence[Polygon]
dilated_collision_geometry: Sequence[Polygon]
dilated_physical_geometry: Sequence[Polygon]
width: float | None = None
standard_faces: bool = False
_bounds: tuple[tuple[float, float, float, float], ...] = field(init=False, repr=False)
_total_bounds: tuple[float, float, float, float] = field(init=False, repr=False)
_dilated_bounds: tuple[tuple[float, float, float, float], ...] = field(init=False, repr=False)
_total_dilated_bounds: tuple[float, float, float, float] = field(init=False, repr=False)
_total_physical_bounds: tuple[float, float, float, float] | None = field(init=False, repr=False, compare=False, default=None)
_physical_checks: tuple[bool, bool] | None = field(init=False, repr=False, compare=False, default=None)
_port_faces: tuple[PortFace | None, PortFace | None] | None = field(init=False, repr=False, compare=False, default=None)
_coordinate_count: int | None = field(init=False, repr=False, compare=False, default=None)
def __post_init__(self) -> None:
collision_geometry = tuple(self.collision_geometry)
physical_geometry = tuple(self.physical_geometry)
dilated_collision_geometry = tuple(self.dilated_collision_geometry)
dilated_physical_geometry = tuple(self.dilated_physical_geometry)
object.__setattr__(self, "collision_geometry", collision_geometry)
object.__setattr__(self, "physical_geometry", physical_geometry)
object.__setattr__(self, "dilated_collision_geometry", dilated_collision_geometry)
object.__setattr__(self, "dilated_physical_geometry", dilated_physical_geometry)
object.__setattr__(self, "length", float(self.length))
bounds = tuple(poly.bounds for poly in collision_geometry)
object.__setattr__(self, "_bounds", bounds)
object.__setattr__(self, "_total_bounds", _combine_bounds(list(bounds)))
dilated_bounds = tuple(poly.bounds for poly in dilated_collision_geometry)
object.__setattr__(self, "_dilated_bounds", dilated_bounds)
object.__setattr__(self, "_total_dilated_bounds", _combine_bounds(list(dilated_bounds)))
@property
def bounds(self) -> tuple[tuple[float, float, float, float], ...]:
return self._bounds
@property
def total_bounds(self) -> tuple[float, float, float, float]:
return self._total_bounds
@property
def dilated_bounds(self) -> tuple[tuple[float, float, float, float], ...]:
return self._dilated_bounds
@property
def total_dilated_bounds(self) -> tuple[float, float, float, float]:
return self._total_dilated_bounds
@property
def total_physical_bounds(self) -> tuple[float, float, float, float]:
bounds = self._total_physical_bounds
if bounds is None:
shapes = self.physical_geometry
bounds = shapes[0].bounds if len(shapes) == 1 else _combine_bounds([shape.bounds for shape in shapes])
object.__setattr__(self, "_total_physical_bounds", bounds)
return bounds
@property
def bend_radius(self) -> float | None:
return self.move_spec.radius if isinstance(self.move_spec, Bend90Seed) else None
@property
def coordinate_count(self) -> int:
count = self._coordinate_count
if count is None:
polygons = {
id(polygon): polygon
for group in (self.physical_geometry, self.collision_geometry, self.dilated_physical_geometry, self.dilated_collision_geometry)
for polygon in group
}
count = sum(int(get_num_coordinates(polygon)) for polygon in polygons.values())
object.__setattr__(self, "_coordinate_count", count)
return count
@property
def port_faces(self) -> tuple[PortFace | None, PortFace | None]:
if self._port_faces is None:
shapes = self.physical_geometry
faces = (
_port_face(shapes[0], self.start_port, arrival=False),
_port_face(shapes[-1], self.end_port, arrival=True),
) if shapes else (None, None)
object.__setattr__(self, "_port_faces", faces)
return faces
return self._port_faces
@property
def physical_checks(self) -> tuple[bool, bool]:
if self._physical_checks is None:
shapes = self.physical_geometry
valid = bool(shapes) and all(not shape.is_empty and shape.is_valid for shape in shapes)
connected = (
valid
and (self.standard_faces or all(_face_matches_width(face, self.width) for face in self.port_faces))
and all(_shares_face(a, b) for a, b in pairwise(shapes))
)
object.__setattr__(self, "_physical_checks", (valid, connected))
return valid, connected
return self._physical_checks
def translate(self, dx: int | float, dy: int | float) -> ComponentResult:
# The collision and physical views often reference the same polygons.
translated: dict[int, Polygon] = {}
def translate_geometry(polygons: Sequence[Polygon]) -> tuple[Polygon, ...]:
geometry = []
for polygon in polygons:
key = id(polygon)
shifted = translated.get(key)
if shifted is None:
shifted = shapely_translate(polygon, dx, dy)
translated[key] = shifted
geometry.append(shifted)
return tuple(geometry)
result = ComponentResult(
start_port=self.start_port.translate(dx, dy),
collision_geometry=translate_geometry(self.collision_geometry),
end_port=self.end_port.translate(dx, dy),
length=self.length,
move_type=self.move_type,
move_spec=self.move_spec,
physical_geometry=translate_geometry(self.physical_geometry),
dilated_collision_geometry=translate_geometry(self.dilated_collision_geometry),
dilated_physical_geometry=translate_geometry(self.dilated_physical_geometry),
width=self.width,
standard_faces=self.standard_faces,
)
object.__setattr__(result, "_coordinate_count", self._coordinate_count)
return result
def _combine_bounds(bounds_list: list[tuple[float, float, float, float]]) -> tuple[float, float, float, float]:
arr = numpy.asarray(bounds_list, dtype=numpy.float64)
return (
float(arr[:, 0].min()),
float(arr[:, 1].min()),
float(arr[:, 2].max()),
float(arr[:, 3].max()),
)
def _get_num_segments(radius: float, angle_deg: float, sagitta: float = 0.01) -> int:
if radius <= 0:
return 1
if not numpy.isfinite(sagitta) or sagitta <= 0:
raise ValueError("Arc sagitta must be finite and positive")
theta_max = 4 * asin(min(1.0, sqrt(sagitta) / sqrt(radius) / sqrt(2.0)))
return max(8, ceil(radians(abs(angle_deg)) / theta_max))
def _get_arc_polygons(
cxy: tuple[float, float],
radius: float,
width: float,
ts: tuple[float, float],
sagitta: float = 0.01,
dilation: float = 0.0,
*,
port_faces: tuple[Port, Port] | None = None,
) -> list[Polygon]:
t_start, t_end = numpy.radians(ts[0]), numpy.radians(ts[1])
cx, cy = cxy
inner_radius = radius - width / 2.0 - dilation
outer_radius = radius + width / 2.0 + dilation
num_segments = _get_num_segments(outer_radius, abs(ts[1] - ts[0]), sagitta)
angles = numpy.linspace(t_start, t_end, num_segments + 1)
cos_a = numpy.cos(angles)
sin_a = numpy.sin(angles)
if port_faces is not None:
cos_a[[0, -1]] = numpy.rint(cos_a[[0, -1]])
sin_a[[0, -1]] = numpy.rint(sin_a[[0, -1]])
inner_points = numpy.column_stack((cx + inner_radius * cos_a, cy + inner_radius * sin_a))
outer_points = numpy.column_stack((cx + outer_radius * cos_a[::-1], cy + outer_radius * sin_a[::-1]))
if port_faces is not None:
# Extend fractional radii along both tangents to reach exact grid faces.
centers = numpy.array([(port.x, port.y) for port in port_faces])
edge = (width / 2 + dilation) * numpy.column_stack((cos_a[[0, -1]], sin_a[[0, -1]]))
start_inner, end_inner = centers - edge
start_outer, end_outer = centers + edge
arc = slice(None) if radius < bend90_grid_span(radius) else slice(1, -1)
inner_points = numpy.vstack((start_inner, inner_points[arc], end_inner))
outer_points = numpy.vstack((end_outer, outer_points[arc], start_outer))
return [Polygon(numpy.concatenate((inner_points, outer_points), axis=0))]
def _clip_bbox_polygonal(
cxy: tuple[float, float],
radius: float,
width: float,
ts: tuple[float, float],
tangent_extensions: tuple[float, float],
) -> Polygon:
"""Return a conservative polygonal proxy for the arc and its tangents.
The polygon uses 4 points along the outer edge and 4 along the inner edge.
The outer edge is a circumscribed polyline and the inner edge is an
inscribed polyline, so the result conservatively contains the true arc.
"""
cx, cy = cxy
sample_count = 4
angle_span = abs(float(ts[1]) - float(ts[0]))
if angle_span < TOLERANCE_ANGULAR:
return box(*_get_arc_polygons(cxy, radius, width, ts)[0].bounds)
segment_half_angle = numpy.radians(angle_span / (2.0 * (sample_count - 1)))
cos_half = max(float(numpy.cos(segment_half_angle)), 1e-9)
inner_radius = max(0.0, radius - width / 2.0)
outer_radius = radius + width / 2.0
tolerance = max(1e-3, radius * 1e-4)
conservative_inner_radius = max(0.0, inner_radius * cos_half - tolerance)
conservative_outer_radius = outer_radius / cos_half + tolerance
angles = numpy.radians(numpy.linspace(ts[0], ts[1], sample_count))
cos_a = numpy.cos(angles)
sin_a = numpy.sin(angles)
cos_a[numpy.abs(cos_a) < 1e-15] = 0
sin_a[numpy.abs(sin_a) < 1e-15] = 0
outer_points = numpy.column_stack((cx + conservative_outer_radius * cos_a, cy + conservative_outer_radius * sin_a))
inner_points = numpy.column_stack((cx + conservative_inner_radius * cos_a[::-1], cy + conservative_inner_radius * sin_a[::-1]))
start_extension, end_extension = tangent_extensions
sweep_sign = 1 if ts[1] > ts[0] else -1
# Keep the same conservative radial width along each attached tangent.
if start_extension > 0:
shift = numpy.array((sin_a[0], -cos_a[0])) * (sweep_sign * (start_extension + TOLERANCE_LINEAR))
outer_points = numpy.vstack((outer_points[0] + shift, outer_points))
inner_points = numpy.vstack((inner_points, inner_points[-1] + shift))
if end_extension > 0:
shift = numpy.array((-sin_a[-1], cos_a[-1])) * (sweep_sign * (end_extension + TOLERANCE_LINEAR))
outer_points = numpy.vstack((outer_points, outer_points[-1] + shift))
inner_points = numpy.vstack((inner_points[0] + shift, inner_points))
return Polygon(numpy.concatenate((outer_points, inner_points), axis=0))
def _transform_custom_collision_polygon(
collision_poly: Polygon,
cxy: tuple[float, float],
rotation_deg: float,
mirror_y: bool,
) -> Polygon:
poly = collision_poly
if mirror_y:
poly = shapely_scale(poly, xfact=1.0, yfact=-1.0, origin=(0.0, 0.0))
if rotation_deg % 360:
poly = shapely_rotate(poly, rotation_deg, origin=(0.0, 0.0), use_radians=False)
return shapely_translate(poly, cxy[0], cxy[1])
def _apply_collision_model(
arc_poly: Polygon,
collision_type: BendCollisionModel,
radius: float,
width: float,
cxy: tuple[float, float],
ts: tuple[float, float],
clip_margin: float | None = None,
rotation_deg: float = 0.0,
mirror_y: bool = False,
tangent_extensions: tuple[float, float] = (0.0, 0.0),
) -> list[Polygon]:
if isinstance(collision_type, Polygon):
return [_transform_custom_collision_polygon(collision_type, cxy, rotation_deg, mirror_y)]
if collision_type == "arc":
return [arc_poly]
if collision_type != "clipped_bbox":
return [box(*arc_poly.bounds)]
if clip_margin is None:
return [_clip_bbox_polygonal(cxy, radius, width, ts, tangent_extensions)]
bbox = box(*arc_poly.bounds)
shrink = min(clip_margin, max(radius, width))
clipped = bbox.buffer(-shrink, join_style="mitre") if shrink > 0 else bbox
return [clipped if not clipped.is_empty else bbox]
def _buffer_geometry(polygons: list[Polygon], dilation: float) -> list[Polygon]:
return [polygon.buffer(dilation) for polygon in polygons] if dilation > 0 else polygons
class Straight:
@staticmethod
def generate(
start_port: Port,
length: float,
width: float,
dilation: float = 0.0,
) -> ComponentResult:
rot2 = rotation_matrix2(start_port.r)
length_f = _normalize_length(length)
end_port = _advance_port(start_port, rot2, length_f)
half_w = width / 2.0
pts = numpy.array(((0.0, half_w), (length_f, half_w), (length_f, -half_w), (0.0, -half_w)))
poly_points = (pts @ rot2.T) + numpy.array((start_port.x, start_port.y))
geometry = [Polygon(poly_points)]
if dilation > 0:
half_w_d = half_w + dilation
pts_d = numpy.array(
(
(-dilation, half_w_d),
(length_f + dilation, half_w_d),
(length_f + dilation, -half_w_d),
(-dilation, -half_w_d),
)
)
poly_points_d = (pts_d @ rot2.T) + numpy.array((start_port.x, start_port.y))
dilated_geometry = [Polygon(poly_points_d)]
else:
dilated_geometry = geometry
return ComponentResult(
start_port=start_port,
collision_geometry=geometry,
end_port=end_port,
length=abs(length_f),
move_type="straight",
move_spec=StraightSeed(length=length_f),
physical_geometry=geometry,
dilated_collision_geometry=dilated_geometry,
dilated_physical_geometry=dilated_geometry,
width=width,
standard_faces=length_f > 0 and length_f.is_integer(),
)
class Bend90:
@staticmethod
def generate(
start_port: Port,
radius: float,
width: float,
direction: Literal["CW", "CCW"],
sagitta: float = 0.01,
collision_type: BendCollisionModel = "arc",
physical_geometry_type: BendPhysicalGeometry = "arc",
clip_margin: float | None = None,
dilation: float = 0.0,
) -> ComponentResult:
if not bend_fits_width(radius, width):
raise ValueError("Bend radius must be at least half the net width")
rot2 = rotation_matrix2(start_port.r)
sign = 1 if direction == "CCW" else -1
grid_span = bend90_grid_span(radius)
tangent_length = grid_span - radius
center_local = numpy.array((tangent_length, sign * radius))
center_xy = (rot2 @ center_local) + numpy.array((start_port.x, start_port.y))
center = (float(center_xy[0]), float(center_xy[1]))
end_port = _advance_port(start_port, rot2, grid_span, sign * grid_span, sign * 90)
start_theta = start_port.r - sign * 90
end_theta = start_port.r
ts = (float(start_theta), float(end_theta))
port_faces = (start_port, end_port)
arc_polys = _get_arc_polygons(center, radius, width, ts, sagitta, port_faces=port_faces)
collision_polys = _apply_collision_model(
arc_polys[0],
collision_type,
radius,
width,
center,
ts,
clip_margin=clip_margin,
rotation_deg=float(start_port.r),
mirror_y=(sign < 0),
tangent_extensions=(tangent_length, tangent_length),
)
if isinstance(physical_geometry_type, Polygon):
physical_geometry = _apply_collision_model(
arc_polys[0],
physical_geometry_type,
radius,
width,
center,
ts,
rotation_deg=float(start_port.r),
mirror_y=(sign < 0),
)
else:
physical_geometry = arc_polys
dilated_arcs = arc_polys
if dilation > 0 and (physical_geometry is arc_polys or collision_type == "arc"):
if bend_fits_width(radius, width + 2 * dilation):
dilated_arcs = _get_arc_polygons(
center,
radius,
width,
ts,
sagitta,
dilation=dilation,
port_faces=port_faces,
)
else:
dilated_arcs = _buffer_geometry(arc_polys, dilation)
dilated_physical_geometry = dilated_arcs if physical_geometry is arc_polys else _buffer_geometry(physical_geometry, dilation)
dilated_collision_geometry = dilated_arcs if collision_type == "arc" else _buffer_geometry(collision_polys, dilation)
return ComponentResult(
start_port=start_port,
collision_geometry=collision_polys,
end_port=end_port,
length=_bend90_length(radius),
move_type="bend90",
move_spec=Bend90Seed(radius=radius, direction=direction),
physical_geometry=physical_geometry,
dilated_collision_geometry=dilated_collision_geometry,
dilated_physical_geometry=dilated_physical_geometry,
width=width,
standard_faces=physical_geometry is arc_polys,
)
class SBend:
@staticmethod
def _arcs(
start_port: Port,
rotation: NDArray[numpy.int32],
radius: float,
offset: float,
theta: float,
span: float,
grid_span: int,
width: float,
sagitta: float,
) -> list[Polygon]:
# Reflect the first arc about the midpoint and reverse it to get the
# second arc. Reuse the midpoint and its normal for both polygons.
sign = 1 if offset > 0 else -1
angles = numpy.linspace(0, theta, _get_num_segments(radius + width / 2, float(numpy.degrees(theta)), sagitta) + 1)
sin, cos = numpy.sin(angles), numpy.cos(angles)
first = numpy.column_stack((radius * sin, sign * radius * (1 - cos)))
first[-1] = (span / 2, offset / 2)
normal = numpy.column_stack((-sign * sin, cos))
second = numpy.asarray((span, offset)) - first[::-1]
second[0] = first[-1]
second_normal = normal[::-1]
# Keep the radius fixed and extend the final tangent to the grid.
# An integer-span bend needs no extension.
if grid_span - span > TOLERANCE_LINEAR:
second = numpy.vstack((second, (grid_span, offset)))
second_normal = numpy.vstack((second_normal, (0, 1)))
else:
second[-1] = (grid_span, offset)
origin = numpy.asarray((start_port.x, start_port.y))
polygons = []
for centerline, normals in ((first, normal), (second, second_normal)):
edge = width / 2 * normals
points = numpy.concatenate((centerline + edge, (centerline - edge)[::-1]))
polygons.append(Polygon(points @ rotation.T + origin))
return polygons
@staticmethod
def generate(
start_port: Port,
offset: float,
radius: float,
width: float,
sagitta: float = 0.01,
collision_type: BendCollisionModelName = "arc",
outline: Polygon | None = None,
clip_margin: float | None = None,
dilation: float = 0.0,
) -> ComponentResult:
seed = SBendSeed(offset, radius)
offset, radius = seed.offset, seed.radius
if not bend_fits_width(radius, width):
raise ValueError("Bend radius must be at least half the net width")
sign = 1 if offset >= 0 else -1
theta = 2 * asin(sqrt(abs(offset) / radius) / 2)
dx = sbend_span(offset, radius)
grid_span = sbend_grid_span(offset, radius)
tail = grid_span - dx
rot2 = rotation_matrix2(start_port.r)
end_port = _advance_port(start_port, rot2, grid_span, offset)
if outline is not None:
physical = _transform_custom_collision_polygon(outline, (start_port.x, start_port.y), start_port.r, mirror_y=False)
physical_geometry = geometry = [physical]
dilated_physical_geometry = dilated_collision_geometry = _buffer_geometry(physical_geometry, dilation)
else:
physical_geometry = SBend._arcs(start_port, rot2, radius, offset, theta, dx, grid_span, width, sagitta)
if dilation > 0 and bend_fits_width(radius, width + 2 * dilation):
dilated_physical_geometry = SBend._arcs(
start_port, rot2, radius, offset, theta, dx, grid_span, width + 2 * dilation, sagitta,
)
else:
dilated_physical_geometry = _buffer_geometry(physical_geometry, dilation)
if collision_type == "arc":
geometry, dilated_collision_geometry = physical_geometry, dilated_physical_geometry
else:
if not isinstance(collision_type, str):
raise TypeError("Custom S-bend geometry requires a complete outline")
theta_deg = float(numpy.degrees(theta))
origin = numpy.array((start_port.x, start_port.y))
center1 = rot2 @ numpy.array((0.0, sign * radius)) + origin
center2 = rot2 @ numpy.array((dx, offset - sign * radius)) + origin
center1_xy = (float(center1[0]), float(center1[1]))
center2_xy = (float(center2[0]), float(center2[1]))
ts1 = (float(start_port.r - sign * 90), float(start_port.r - sign * 90 + sign * theta_deg))
second_base = start_port.r + (90 if sign > 0 else 270)
ts2 = (float(second_base + sign * theta_deg), float(second_base))
arc1, arc2 = physical_geometry
geometry = [
_apply_collision_model(arc1, collision_type, radius, width, center1_xy, ts1, clip_margin=clip_margin)[0],
_apply_collision_model(
arc2, collision_type, radius, width, center2_xy, ts2, clip_margin=clip_margin,
tangent_extensions=(0, tail if tail > TOLERANCE_LINEAR else 0),
)[0],
]
dilated_collision_geometry = _buffer_geometry(geometry, dilation)
return ComponentResult(
start_port=start_port,
collision_geometry=geometry,
end_port=end_port,
length=2.0 * radius * theta + max(0.0, tail),
move_type="sbend",
move_spec=seed,
physical_geometry=physical_geometry,
dilated_collision_geometry=dilated_collision_geometry,
dilated_physical_geometry=dilated_physical_geometry,
width=width,
standard_faces=outline is None,
)
def build_component(
start: Port,
width: float,
kind: MoveKind,
parameters: tuple,
*,
collision_type: BendCollisionModel,
physical_geometry_type: BendPhysicalGeometry,
clip_margin: float | None,
dilation: float,
sbend_outline: Polygon | None = None,
physical_length: float | None = None,
) -> ComponentResult:
if kind == "straight":
return Straight.generate(start, parameters[0], width, dilation=dilation)
if kind == "bend90":
component = Bend90.generate(
start, parameters[0], width, parameters[1],
collision_type=collision_type, physical_geometry_type=physical_geometry_type, clip_margin=clip_margin, dilation=dilation,
)
else:
component = SBend.generate(
start, parameters[0], parameters[1], width,
collision_type="arc" if isinstance(collision_type, Polygon) else collision_type,
outline=sbend_outline, clip_margin=clip_margin, dilation=dilation,
)
return replace(component, length=physical_length) if physical_length is not None else component