Skip to content

GPU Acceleration API

Optional WebGPU (wgpu) runtime detection, orthographic projection cameras, B-Rep tessellation, technical-illustration shading, visibility-buffer HLR, and 2D distance-field (SDF) layout.

Runtime Detection & Device Management

build123d_techdraw.gpu.runtime

Opt-in wgpu runtime detection, adapter/device caching, and diagnostics.

All wgpu imports are deferred so build123d-techdraw remains 100% usable without GPU dependencies installed. When build123d-techdraw[gpu] is installed, GPU acceleration is auto-enabled whenever a compatible hardware or software (e.g. Mesa Lavapipe) adapter can be initialized, unless overridden by an explicit gpu=False argument or BUILD123D_TECHDRAW_GPU=0.

GPU_ENV_VAR = 'BUILD123D_TECHDRAW_GPU' module-attribute

is_gpu_installed()

Return True if the optional wgpu package can be imported cleanly.

Source code in src/build123d_techdraw/gpu/runtime.py
def is_gpu_installed() -> bool:
    """Return True if the optional ``wgpu`` package can be imported cleanly."""
    return _import_wgpu() is not None

is_gpu_available(*, allow_software=True)

Return True if a usable wgpu adapter and device can be initialized.

Hardware adapters are preferred. When allow_software=True (the default), software Vulkan/WebGPU drivers such as Mesa Lavapipe are accepted as a fallback so headless CI environments work seamlessly.

Source code in src/build123d_techdraw/gpu/runtime.py
def is_gpu_available(*, allow_software: bool = True) -> bool:
    """Return True if a usable wgpu adapter and device can be initialized.

    Hardware adapters are preferred. When ``allow_software=True`` (the default),
    software Vulkan/WebGPU drivers such as Mesa Lavapipe are accepted as a
    fallback so headless CI environments work seamlessly.
    """
    return _probe_device(allow_software=allow_software, force_fallback=False) is not None

is_gpu_enabled(gpu=None)

Resolve whether GPU acceleration should be used for an operation.

Resolution order:

  1. gpu=False -> always returns False without probing adapters.
  2. gpu=True -> requires wgpu and a working adapter; raises ImportError if wgpu is not installed or RuntimeError if no adapter is available.
  3. gpu=None -> consults BUILD123D_TECHDRAW_GPU:

    • "0" / "false" / "off" / "no" -> False
    • "1" / "true" / "on" / "yes" -> require GPU (same as gpu=True)
    • unset / empty / "auto" -> True iff is_gpu_installed() and is_gpu_available().
Source code in src/build123d_techdraw/gpu/runtime.py
def is_gpu_enabled(gpu: bool | None = None) -> bool:
    """Resolve whether GPU acceleration should be used for an operation.

    Resolution order:

    1. `gpu=False` -> always returns `False` without probing adapters.
    2. `gpu=True` -> requires `wgpu` and a working adapter; raises
       `ImportError` if `wgpu` is not installed or `RuntimeError`
       if no adapter is available.
    3. `gpu=None` -> consults `BUILD123D_TECHDRAW_GPU`:

        - `"0"` / `"false"` / `"off"` / `"no"` -> `False`
        - `"1"` / `"true"` / `"on"` / `"yes"` -> require GPU (same as `gpu=True`)
        - unset / empty / `"auto"` -> `True` iff `is_gpu_installed()` and
          `is_gpu_available()`.
    """
    if gpu is False:
        return False

    require_gpu = gpu is True
    if gpu is None:
        raw_env = os.environ.get(GPU_ENV_VAR)
        if raw_env is not None:
            normalized = raw_env.strip().lower()
            if normalized in _FALSY_ENV:
                return False
            if normalized in _TRUTHY_ENV:
                require_gpu = True
            elif normalized not in _AUTO_ENV:
                raise ValueError(
                    f"Invalid {GPU_ENV_VAR} value {raw_env!r}; expected one of "
                    "'0', '1', 'false', 'true', 'off', 'on', or 'auto'."
                )

    if require_gpu:
        if not is_gpu_installed():
            raise ImportError(_INSTALL_HINT)
        if not is_gpu_available():
            raise RuntimeError(
                "GPU acceleration was explicitly enabled, but no compatible "
                "Vulkan, Metal, DirectX 12, or software (Lavapipe) wgpu adapter "
                "could be initialized."
            )
        return True

    return is_gpu_installed() and is_gpu_available()

get_gpu_device(*, allow_software=True, force_fallback=False)

Return the cached (adapter, device) pair for wgpu execution.

Raises:

Type Description
ImportError

If wgpu is not installed.

RuntimeError

If no compatible wgpu adapter/device could be created.

Source code in src/build123d_techdraw/gpu/runtime.py
def get_gpu_device(
    *,
    allow_software: bool = True,
    force_fallback: bool = False,
) -> tuple[wgpu.GPUAdapter, wgpu.GPUDevice]:
    """Return the cached ``(adapter, device)`` pair for wgpu execution.

    Raises:
        ImportError: If ``wgpu`` is not installed.
        RuntimeError: If no compatible wgpu adapter/device could be created.
    """
    if not is_gpu_installed():
        raise ImportError(_INSTALL_HINT)
    pair = _probe_device(allow_software=allow_software, force_fallback=force_fallback)
    if pair is None:
        mode = (
            "software fallback"
            if force_fallback
            else ("hardware or software" if allow_software else "hardware")
        )
        raise RuntimeError(f"No compatible {mode} wgpu adapter could be initialized.")
    return pair

gpu_info(*, allow_software=True)

Return diagnostic metadata describing the active wgpu runtime environment.

Source code in src/build123d_techdraw/gpu/runtime.py
def gpu_info(*, allow_software: bool = True) -> dict[str, Any]:
    """Return diagnostic metadata describing the active wgpu runtime environment."""
    wgpu_mod = _import_wgpu()
    installed = wgpu_mod is not None
    wgpu_version = str(wgpu_mod.__version__) if wgpu_mod is not None else None

    pair = _probe_device(allow_software=allow_software, force_fallback=False) if installed else None
    available = pair is not None

    try:
        enabled = is_gpu_enabled(None)
    except (ImportError, RuntimeError, ValueError):
        enabled = False

    if pair is None:
        return {
            "installed": installed,
            "available": False,
            "enabled": enabled,
            "backend": None,
            "adapter_name": None,
            "vendor": None,
            "description": None,
            "device_type": None,
            "is_software": False,
            "wgpu_version": wgpu_version,
        }

    adapter, _device = pair
    info = _adapter_info_dict(adapter)
    return {
        "installed": installed,
        "available": available,
        "enabled": enabled,
        "backend": str(info.get("backend_type", "Unknown")),
        "adapter_name": str(info.get("device", "")),
        "vendor": str(info.get("vendor", "")),
        "description": str(info.get("description", "")),
        "device_type": str(info.get("adapter_type", "Unknown")),
        "is_software": _is_software_adapter(adapter),
        "wgpu_version": wgpu_version,
    }

reset_gpu_cache()

Clear cached wgpu adapter/device probes (primarily for tests).

Source code in src/build123d_techdraw/gpu/runtime.py
def reset_gpu_cache() -> None:
    """Clear cached wgpu adapter/device probes (primarily for tests)."""
    _DEVICE_CACHE.clear()

Tessellation & Edge Sampling

build123d_techdraw.gpu.mesh

OCCT-to-GPU triangle mesh tessellation and B-Rep/silhouette edge sampling.

Both tessellate_shape and sample_shape_edges traverse assembly parts and faces in the exact same deterministic order so 1-based face_ids in TessellatedMesh match face_id_a / face_id_b in SampledEdge 1-to-1 for GPU hidden-line removal (HLR) depth/ID buffer lookups.

TessellatedMesh dataclass

GPU-ready triangle mesh extracted from a build123d / OCCT B-Rep shape.

Source code in src/build123d_techdraw/gpu/mesh.py
@dataclass
class TessellatedMesh:
    """GPU-ready triangle mesh extracted from a build123d / OCCT B-Rep shape."""

    positions: NDArray[np.float32]  # (V, 3)
    normals: NDArray[np.float32]  # (V, 3)
    indices: NDArray[np.uint32]  # (T, 3)
    face_ids: NDArray[np.uint32]  # (T,) 1-based face ID per triangle
    part_ids: NDArray[np.uint32]  # (T,) 0-based part/solid ID per triangle
    part_names: list[str]
    bbox_min: Vec3
    bbox_max: Vec3

    @property
    def num_vertices(self) -> int:
        """Number of vertices in the mesh."""
        return int(self.positions.shape[0])

    @property
    def num_triangles(self) -> int:
        """Number of triangles in the mesh."""
        return int(self.indices.shape[0])

num_vertices property

Number of vertices in the mesh.

num_triangles property

Number of triangles in the mesh.

SampledEdge dataclass

A discretized 3D B-Rep edge or analytic silhouette polyline.

Source code in src/build123d_techdraw/gpu/mesh.py
@dataclass(frozen=True)
class SampledEdge:
    """A discretized 3D B-Rep edge or analytic silhouette polyline."""

    edge_id: int
    face_id_a: int  # 1-based face ID, or 0 if free edge
    face_id_b: int  # 1-based face ID, or 0 if boundary / analytic silhouette
    points_3d: NDArray[np.float32]  # (N, 3), N >= 2
    is_silhouette_candidate: bool = False
    is_smooth: bool = False
    geom_type: str = "other"

SampledEdgeSet dataclass

Collection of discretized 3D edges and optional analytic silhouettes for a shape.

Source code in src/build123d_techdraw/gpu/mesh.py
@dataclass
class SampledEdgeSet:
    """Collection of discretized 3D edges and optional analytic silhouettes for a shape."""

    edges: list[SampledEdge]
    bbox_min: Vec3
    bbox_max: Vec3
    num_faces: int

    @property
    def total_points(self) -> int:
        """Total number of 3D polyline sample points across all edges."""
        return sum(int(e.points_3d.shape[0]) for e in self.edges)

    @property
    def total_segments(self) -> int:
        """Total number of polyline line segments across all edges."""
        return sum(max(0, int(e.points_3d.shape[0]) - 1) for e in self.edges)

    def pack_segments(
        self,
    ) -> tuple[NDArray[np.float32], NDArray[np.float32], NDArray[np.uint32]]:
        """Pack all polyline segments into flat GPU-ready arrays.

        Returns:
            ``(starts, ends, meta)`` where ``starts`` and ``ends`` have shape ``(S, 3)``
            (``float32``) and ``meta`` has shape ``(S, 4)`` (``uint32``) containing
            ``[edge_id, face_id_a, face_id_b, flags]`` per segment.
            ``flags`` bit 0 = ``is_silhouette_candidate``, bit 1 = ``is_smooth``.
        """
        total_segs = self.total_segments
        if total_segs == 0:
            empty_pts = np.zeros((0, 3), dtype=np.float32)
            empty_meta = np.zeros((0, 4), dtype=np.uint32)
            return empty_pts, empty_pts.copy(), empty_meta

        starts = np.empty((total_segs, 3), dtype=np.float32)
        ends = np.empty((total_segs, 3), dtype=np.float32)
        meta = np.empty((total_segs, 4), dtype=np.uint32)

        cursor = 0
        for edge in self.edges:
            n_segs = int(edge.points_3d.shape[0]) - 1
            if n_segs <= 0:
                continue
            starts[cursor : cursor + n_segs] = edge.points_3d[:-1]
            ends[cursor : cursor + n_segs] = edge.points_3d[1:]
            flags = (1 if edge.is_silhouette_candidate else 0) | (2 if edge.is_smooth else 0)
            meta[cursor : cursor + n_segs, 0] = edge.edge_id
            meta[cursor : cursor + n_segs, 1] = edge.face_id_a
            meta[cursor : cursor + n_segs, 2] = edge.face_id_b
            meta[cursor : cursor + n_segs, 3] = flags
            cursor += n_segs

        return starts, ends, meta

total_points property

Total number of 3D polyline sample points across all edges.

total_segments property

Total number of polyline line segments across all edges.

pack_segments()

Pack all polyline segments into flat GPU-ready arrays.

Returns:

Type Description
NDArray[float32]

(starts, ends, meta) where starts and ends have shape (S, 3)

NDArray[float32]

(float32) and meta has shape (S, 4) (uint32) containing

NDArray[uint32]

[edge_id, face_id_a, face_id_b, flags] per segment.

tuple[NDArray[float32], NDArray[float32], NDArray[uint32]]

flags bit 0 = is_silhouette_candidate, bit 1 = is_smooth.

Source code in src/build123d_techdraw/gpu/mesh.py
def pack_segments(
    self,
) -> tuple[NDArray[np.float32], NDArray[np.float32], NDArray[np.uint32]]:
    """Pack all polyline segments into flat GPU-ready arrays.

    Returns:
        ``(starts, ends, meta)`` where ``starts`` and ``ends`` have shape ``(S, 3)``
        (``float32``) and ``meta`` has shape ``(S, 4)`` (``uint32``) containing
        ``[edge_id, face_id_a, face_id_b, flags]`` per segment.
        ``flags`` bit 0 = ``is_silhouette_candidate``, bit 1 = ``is_smooth``.
    """
    total_segs = self.total_segments
    if total_segs == 0:
        empty_pts = np.zeros((0, 3), dtype=np.float32)
        empty_meta = np.zeros((0, 4), dtype=np.uint32)
        return empty_pts, empty_pts.copy(), empty_meta

    starts = np.empty((total_segs, 3), dtype=np.float32)
    ends = np.empty((total_segs, 3), dtype=np.float32)
    meta = np.empty((total_segs, 4), dtype=np.uint32)

    cursor = 0
    for edge in self.edges:
        n_segs = int(edge.points_3d.shape[0]) - 1
        if n_segs <= 0:
            continue
        starts[cursor : cursor + n_segs] = edge.points_3d[:-1]
        ends[cursor : cursor + n_segs] = edge.points_3d[1:]
        flags = (1 if edge.is_silhouette_candidate else 0) | (2 if edge.is_smooth else 0)
        meta[cursor : cursor + n_segs, 0] = edge.edge_id
        meta[cursor : cursor + n_segs, 1] = edge.face_id_a
        meta[cursor : cursor + n_segs, 2] = edge.face_id_b
        meta[cursor : cursor + n_segs, 3] = flags
        cursor += n_segs

    return starts, ends, meta

tessellate_shape(shape, *, linear_deflection=0.05, angular_deflection=0.2, split_sharp_edges_deg=35.0)

Tessellate a build123d or OCCT shape into a GPU-ready TessellatedMesh.

Uses BRepMesh_IncrementalMesh + BRep_Tool.Triangulation_s with analytical OCCT surface normals (falling back to area-weighted triangle normals at degenerate poles) and optional sharp-edge preservation.

Parameters:

Name Type Description Default
shape Shape[Any] | TopoDS_Shape | Any

build123d Shape (Part, Solid, Compound, Face, etc.) or raw OCCT TopoDS_Shape.

required
linear_deflection float

Maximum chordal deviation in model units (mm).

0.05
angular_deflection float

Maximum angular deviation in radians.

0.2
split_sharp_edges_deg float | None

Dihedral angle threshold in degrees above which edges remain sharp (split normals). Default 35.0 keeps 45° chamfers and 90° corners crisp while smoothing tangent/shallow bends. Pass None to average normals across all coincident vertices within each part.

35.0
Source code in src/build123d_techdraw/gpu/mesh.py
def tessellate_shape(
    shape: Shape[Any] | TopoDS_Shape | Any,
    *,
    linear_deflection: float = 0.05,
    angular_deflection: float = 0.2,
    split_sharp_edges_deg: float | None = 35.0,
) -> TessellatedMesh:
    """Tessellate a build123d or OCCT shape into a GPU-ready `TessellatedMesh`.

    Uses ``BRepMesh_IncrementalMesh`` + ``BRep_Tool.Triangulation_s`` with analytical
    OCCT surface normals (falling back to area-weighted triangle normals at degenerate
    poles) and optional sharp-edge preservation.

    Args:
        shape: build123d ``Shape`` (``Part``, ``Solid``, ``Compound``, ``Face``, etc.)
            or raw OCCT ``TopoDS_Shape``.
        linear_deflection: Maximum chordal deviation in model units (mm).
        angular_deflection: Maximum angular deviation in radians.
        split_sharp_edges_deg: Dihedral angle threshold in degrees above which edges
            remain sharp (split normals). Default ``35.0`` keeps 45° chamfers and 90°
            corners crisp while smoothing tangent/shallow bends. Pass ``None`` to
            average normals across all coincident vertices within each part.
    """
    if linear_deflection <= 0.0:
        raise ValueError(f"linear_deflection must be positive, got {linear_deflection}.")
    if angular_deflection <= 0.0:
        raise ValueError(f"angular_deflection must be positive, got {angular_deflection}.")

    parts = _extract_parts(shape)
    part_names = [name for _pid, name, _topo in parts]

    pos_chunks: list[NDArray[np.float32]] = []
    norm_chunks: list[NDArray[np.float32]] = []
    idx_chunks: list[NDArray[np.uint32]] = []
    face_id_chunks: list[NDArray[np.uint32]] = []
    part_id_chunks: list[NDArray[np.uint32]] = []
    vert_part_chunks: list[NDArray[np.uint32]] = []

    vertex_offset = 0
    face_id_offset = 0

    for part_id, _part_name, part_topo in parts:
        BRepMesh_IncrementalMesh(part_topo, linear_deflection, False, angular_deflection, True)

        face_map = IndexedMap_TopoDS_Shape_TopTools_ShapeMapHasher()
        TopExp.MapShapes_s(part_topo, TopAbs_FACE, face_map)
        n_faces = face_map.Extent()

        for local_face_idx in range(1, n_faces + 1):
            global_face_id = face_id_offset + local_face_idx
            face = TopoDS.Face(face_map.FindKey(local_face_idx))

            loc = TopLoc_Location()
            tri = BRep_Tool.Triangulation_s(face, loc)
            if tri is None:
                continue

            nb_nodes = tri.NbNodes()
            nb_tris = tri.NbTriangles()
            if nb_nodes == 0 or nb_tris == 0:
                continue

            trsf = loc.Transformation()
            flip = (face.Orientation() == TopAbs_REVERSED) ^ trsf.IsNegative()

            face_pos = np.empty((nb_nodes, 3), dtype=np.float32)
            for i in range(1, nb_nodes + 1):
                pt = tri.Node(i).Transformed(trsf)
                face_pos[i - 1, 0] = pt.X()
                face_pos[i - 1, 1] = pt.Y()
                face_pos[i - 1, 2] = pt.Z()

            local_tris = np.empty((nb_tris, 3), dtype=np.uint32)
            for t in range(1, nb_tris + 1):
                i1, i2, i3 = tri.Triangle(t).Get()
                if flip:
                    i2, i3 = i3, i2
                local_tris[t - 1, 0] = i1 - 1
                local_tris[t - 1, 1] = i2 - 1
                local_tris[t - 1, 2] = i3 - 1

            # Analytical surface normals via OCCT, falling back to geometric normals at poles.
            BRepLib_ToolTriangulatedShape.ComputeNormals_s(face, tri)
            geom_normals = _compute_area_weighted_normals(face_pos, local_tris)

            if tri.HasNormals():
                face_norm = np.empty((nb_nodes, 3), dtype=np.float32)
                for i in range(1, nb_nodes + 1):
                    nd = tri.Normal(i).Transformed(trsf)
                    if flip:
                        nd = nd.Reversed()
                    nx, ny, nz = float(nd.X()), float(nd.Y()), float(nd.Z())
                    mag = math.sqrt(nx * nx + ny * ny + nz * nz)
                    if mag > 1e-9 and math.isfinite(mag):
                        face_norm[i - 1, 0] = nx / mag
                        face_norm[i - 1, 1] = ny / mag
                        face_norm[i - 1, 2] = nz / mag
                    else:
                        face_norm[i - 1] = geom_normals[i - 1]
            else:
                face_norm = geom_normals

            pos_chunks.append(face_pos)
            norm_chunks.append(face_norm)
            idx_chunks.append(local_tris + np.uint32(vertex_offset))
            face_id_chunks.append(np.full(nb_tris, global_face_id, dtype=np.uint32))
            part_id_chunks.append(np.full(nb_tris, part_id, dtype=np.uint32))
            vert_part_chunks.append(np.full(nb_nodes, part_id, dtype=np.uint32))
            vertex_offset += nb_nodes

        face_id_offset += n_faces

    if not pos_chunks:
        empty_f = np.zeros((0, 3), dtype=np.float32)
        empty_i = np.zeros((0, 3), dtype=np.uint32)
        empty_u = np.zeros((0,), dtype=np.uint32)
        return TessellatedMesh(
            positions=empty_f,
            normals=empty_f.copy(),
            indices=empty_i,
            face_ids=empty_u,
            part_ids=empty_u.copy(),
            part_names=part_names,
            bbox_min=(0.0, 0.0, 0.0),
            bbox_max=(0.0, 0.0, 0.0),
        )

    positions = np.ascontiguousarray(np.concatenate(pos_chunks, axis=0), dtype=np.float32)
    normals = np.ascontiguousarray(np.concatenate(norm_chunks, axis=0), dtype=np.float32)
    indices = np.ascontiguousarray(np.concatenate(idx_chunks, axis=0), dtype=np.uint32)
    face_ids = np.ascontiguousarray(np.concatenate(face_id_chunks, axis=0), dtype=np.uint32)
    part_ids = np.ascontiguousarray(np.concatenate(part_id_chunks, axis=0), dtype=np.uint32)
    vert_parts = np.concatenate(vert_part_chunks, axis=0)

    normals = _smooth_coincident_normals(positions, normals, vert_parts, split_sharp_edges_deg)

    pmin = positions.min(axis=0)
    pmax = positions.max(axis=0)

    return TessellatedMesh(
        positions=positions,
        normals=normals,
        indices=indices,
        face_ids=face_ids,
        part_ids=part_ids,
        part_names=part_names,
        bbox_min=(float(pmin[0]), float(pmin[1]), float(pmin[2])),
        bbox_max=(float(pmax[0]), float(pmax[1]), float(pmax[2])),
    )

sample_shape_edges(shape, *, deflection=0.05, look_from=None)

Extract discretized B-Rep edges and optional analytic silhouettes for GPU HLR.

Parameters:

Name Type Description Default
shape Shape[Any] | TopoDS_Shape | Any

build123d Shape or OCCT TopoDS_Shape.

required
deflection float

Chordal discretization tolerance in model units (mm).

0.05
look_from Vec3 | None

Optional orthographic camera direction (x, y, z) pointing from the model toward the camera (matching VIEW_VECTORS). When provided, analytic silhouette lines/curves are generated for Cylinder, Cone, Sphere, and Torus faces, and B-Rep edges whose adjacent faces straddle the silhouette boundary are flagged is_silhouette_candidate=True.

None
Source code in src/build123d_techdraw/gpu/mesh.py
def sample_shape_edges(
    shape: Shape[Any] | TopoDS_Shape | Any,
    *,
    deflection: float = 0.05,
    look_from: Vec3 | None = None,
) -> SampledEdgeSet:
    """Extract discretized B-Rep edges and optional analytic silhouettes for GPU HLR.

    Args:
        shape: build123d ``Shape`` or OCCT ``TopoDS_Shape``.
        deflection: Chordal discretization tolerance in model units (mm).
        look_from: Optional orthographic camera direction ``(x, y, z)`` pointing from the
            model toward the camera (matching ``VIEW_VECTORS``). When provided, analytic
            silhouette lines/curves are generated for Cylinder, Cone, Sphere, and Torus
            faces, and B-Rep edges whose adjacent faces straddle the silhouette boundary
            are flagged ``is_silhouette_candidate=True``.
    """
    if deflection <= 0.0:
        raise ValueError(f"deflection must be positive, got {deflection}.")

    v_dir: NDArray[np.float64] | None = None
    if look_from is not None:
        raw_v = np.asarray(look_from, dtype=np.float64)
        norm_v = float(np.linalg.norm(raw_v))
        if norm_v < 1e-12:
            raise ValueError(f"look_from vector must be non-zero, got {look_from}.")
        v_dir = raw_v / norm_v

    parts = _extract_parts(shape)
    edges: list[SampledEdge] = []
    next_edge_id = 1
    face_id_offset = 0

    for _part_id, _part_name, part_topo in parts:
        face_map = IndexedMap_TopoDS_Shape_TopTools_ShapeMapHasher()
        TopExp.MapShapes_s(part_topo, TopAbs_FACE, face_map)
        n_faces = face_map.Extent()

        ef_map = IndexedDataMap_TopoDS_Shape_List_TopoDS_Shape_TopTools_ShapeMapHasher()
        TopExp.MapShapesAndAncestors_s(part_topo, TopAbs_EDGE, TopAbs_FACE, ef_map)

        # 1. Discretize all non-degenerated B-Rep edges with exact 1-based adjacent face IDs.
        for e_idx in range(1, ef_map.Extent() + 1):
            edge = TopoDS.Edge(ef_map.FindKey(e_idx))
            if BRep_Tool.Degenerated_s(edge):
                continue

            adj_faces: list[tuple[int, TopoDS_Face]] = []
            seen_ids: set[int] = set()
            for raw_face in ef_map.FindFromIndex(e_idx):
                local_fid = face_map.FindIndex(raw_face)
                if local_fid > 0:
                    global_fid = face_id_offset + local_fid
                    if global_fid not in seen_ids:
                        seen_ids.add(global_fid)
                        adj_faces.append((global_fid, TopoDS.Face(raw_face)))

            face_id_a = adj_faces[0][0] if len(adj_faces) >= 1 else 0
            face_id_b = adj_faces[1][0] if len(adj_faces) >= 2 else 0

            is_smooth = False
            is_silhouette_cand = False
            if len(adj_faces) >= 2:
                na = _face_normal_at_edge_mid(edge, adj_faces[0][1])
                nb = _face_normal_at_edge_mid(edge, adj_faces[1][1])
                if na is not None and nb is not None:
                    if float(np.dot(na, nb)) >= math.cos(math.radians(5.0)):
                        is_smooth = True
                    if v_dir is not None:
                        da = float(np.dot(na, v_dir))
                        db = float(np.dot(nb, v_dir))
                        # Straddles front-facing / back-facing boundary relative to camera.
                        if (da > 1e-6 and db < -1e-6) or (da < -1e-6 and db > 1e-6):
                            is_silhouette_cand = True
            elif len(adj_faces) == 1:
                if BRep_Tool.IsClosed_s(edge, adj_faces[0][1]):
                    # Periodic UV seam on a closed surface (cylinder/cone/sphere/torus).
                    is_smooth = True
                    is_silhouette_cand = False
                else:
                    # True open/boundary edge on an open shell or sheet.
                    is_silhouette_cand = True

            pts, geom_name = _discretize_edge(edge, deflection)
            if pts.shape[0] < 2:
                continue

            edges.append(
                SampledEdge(
                    edge_id=next_edge_id,
                    face_id_a=face_id_a,
                    face_id_b=face_id_b,
                    points_3d=pts,
                    is_silhouette_candidate=is_silhouette_cand,
                    is_smooth=is_smooth,
                    geom_type=geom_name,
                )
            )
            next_edge_id += 1

        # 2. Analytic silhouettes on curved faces when look_from is provided.
        if v_dir is not None:
            for local_fid in range(1, n_faces + 1):
                face = TopoDS.Face(face_map.FindKey(local_fid))
                global_fid = face_id_offset + local_fid
                sil_curves = _extract_analytic_silhouettes(face, v_dir, deflection)
                for pts in sil_curves:
                    if pts.shape[0] < 2:
                        continue
                    edges.append(
                        SampledEdge(
                            edge_id=next_edge_id,
                            face_id_a=global_fid,
                            face_id_b=0,
                            points_3d=pts,
                            is_silhouette_candidate=True,
                            is_smooth=False,
                            geom_type="silhouette",
                        )
                    )
                    next_edge_id += 1

        face_id_offset += n_faces

    if not edges:
        return SampledEdgeSet(
            edges=[],
            bbox_min=(0.0, 0.0, 0.0),
            bbox_max=(0.0, 0.0, 0.0),
            num_faces=face_id_offset,
        )

    all_min = np.min(np.stack([e.points_3d.min(axis=0) for e in edges], axis=0), axis=0)
    all_max = np.max(np.stack([e.points_3d.max(axis=0) for e in edges], axis=0), axis=0)
    return SampledEdgeSet(
        edges=edges,
        bbox_min=(float(all_min[0]), float(all_min[1]), float(all_min[2])),
        bbox_max=(float(all_max[0]), float(all_max[1]), float(all_max[2])),
        num_faces=face_id_offset,
    )

Orthographic Camera

build123d_techdraw.gpu.camera

Orthographic camera math aligned pixel-for-pixel with build123d.Drawing and SheetView.

Coordinate conventions

Given (look_from, look_up) matching build123d_techdraw.core.view.VIEW_VECTORS:

  • eye_dir = normalize(look_from) points from the model toward the camera.
  • forward = -eye_dir is the camera viewing direction (into the scene).
  • right = normalize(cross(normalize(look_up), eye_dir)) matches gp_Ax2 X direction.
  • up = normalize(cross(eye_dir, right)) matches gp_Ax2 Y direction.

Matrices use standard mathematical row-major layout in NumPy (clip = view_proj @ p) with WebGPU/Vulkan clip-space depth z in [0, 1] (0 at z_near, 1 at z_far) and +y upward in NDC (mapping +up to the top of rendered raster images, matching SVG <image> top-down pixel coordinates). Use OrthoCamera.uniform_view_proj when uploading mat4x4<f32> uniforms to WGSL (column-major memory order).

OrthoCamera dataclass

Orthographic WebGPU camera matching SheetView / build123d.Drawing projection.

Source code in src/build123d_techdraw/gpu/camera.py
@dataclass(frozen=True)
class OrthoCamera:
    """Orthographic WebGPU camera matching ``SheetView`` / ``build123d.Drawing`` projection."""

    view_matrix: NDArray[np.float32]
    proj_matrix: NDArray[np.float32]
    view_proj: NDArray[np.float32]
    right: Vec3
    up: Vec3
    forward: Vec3
    model_width: float
    model_height: float
    model_center_2d: tuple[float, float]
    z_near: float
    z_far: float
    pixels_per_mm: float
    width_px: int
    height_px: int
    view_width_mm: float
    view_height_mm: float

    def uniform_view_proj(self) -> NDArray[np.float32]:
        """Return ``view_proj`` in contiguous column-major layout for WGSL ``mat4x4<f32>``."""
        return np.ascontiguousarray(self.view_proj.T, dtype=np.float32)

    def uniform_view_matrix(self) -> NDArray[np.float32]:
        """Return ``view_matrix`` in contiguous column-major layout for WGSL ``mat4x4<f32>``."""
        return np.ascontiguousarray(self.view_matrix.T, dtype=np.float32)

    def project_points_ndc(self, points_3d: NDArray[np.floating[Any]]) -> NDArray[np.float32]:
        """Project ``(N, 3)`` world points into WebGPU NDC ``(x_ndc, y_ndc, z_ndc)``."""
        pts = np.asarray(points_3d, dtype=np.float64)
        if pts.ndim != 2 or pts.shape[1] != 3:
            raise ValueError(f"Expected points_3d shape (N, 3), got {pts.shape}.")
        hom = np.empty((pts.shape[0], 4), dtype=np.float64)
        hom[:, :3] = pts
        hom[:, 3] = 1.0
        clip = hom @ self.view_proj.astype(np.float64).T
        return np.ascontiguousarray(clip[:, :3], dtype=np.float32)

    def project_points_px(self, points_3d: NDArray[np.floating[Any]]) -> NDArray[np.float32]:
        """Project ``(N, 3)`` world points into top-left image pixels ``(px, py, z_ndc)``."""
        ndc = self.project_points_ndc(points_3d).astype(np.float64)
        out = np.empty_like(ndc, dtype=np.float32)
        out[:, 0] = ((ndc[:, 0] + 1.0) * 0.5 * self.width_px).astype(np.float32)
        out[:, 1] = ((1.0 - ndc[:, 1]) * 0.5 * self.height_px).astype(np.float32)
        out[:, 2] = ndc[:, 2].astype(np.float32)
        return out

    def project_points_2d(
        self,
        points_3d: NDArray[np.floating[Any]],
        *,
        origin: Vec3 = (0.0, 0.0, 0.0),
    ) -> NDArray[np.float64]:
        """Project ``(N, 3)`` world points onto the view ``(right, up)`` plane around ``origin``.

        When ``origin`` equals ``shape.center()``, the resulting ``(u, v)`` coordinates
        match ``build123d.Drawing(..., look_from=..., look_up=...)`` directly.
        """
        pts = np.asarray(points_3d, dtype=np.float64)
        if pts.ndim != 2 or pts.shape[1] != 3:
            raise ValueError(f"Expected points_3d shape (N, 3), got {pts.shape}.")
        rel = pts - np.asarray(origin, dtype=np.float64)
        r = np.asarray(self.right, dtype=np.float64)
        u = np.asarray(self.up, dtype=np.float64)
        out = np.empty((pts.shape[0], 2), dtype=np.float64)
        out[:, 0] = rel @ r
        out[:, 1] = rel @ u
        return out

uniform_view_proj()

Return view_proj in contiguous column-major layout for WGSL mat4x4<f32>.

Source code in src/build123d_techdraw/gpu/camera.py
def uniform_view_proj(self) -> NDArray[np.float32]:
    """Return ``view_proj`` in contiguous column-major layout for WGSL ``mat4x4<f32>``."""
    return np.ascontiguousarray(self.view_proj.T, dtype=np.float32)

uniform_view_matrix()

Return view_matrix in contiguous column-major layout for WGSL mat4x4<f32>.

Source code in src/build123d_techdraw/gpu/camera.py
def uniform_view_matrix(self) -> NDArray[np.float32]:
    """Return ``view_matrix`` in contiguous column-major layout for WGSL ``mat4x4<f32>``."""
    return np.ascontiguousarray(self.view_matrix.T, dtype=np.float32)

project_points_ndc(points_3d)

Project (N, 3) world points into WebGPU NDC (x_ndc, y_ndc, z_ndc).

Source code in src/build123d_techdraw/gpu/camera.py
def project_points_ndc(self, points_3d: NDArray[np.floating[Any]]) -> NDArray[np.float32]:
    """Project ``(N, 3)`` world points into WebGPU NDC ``(x_ndc, y_ndc, z_ndc)``."""
    pts = np.asarray(points_3d, dtype=np.float64)
    if pts.ndim != 2 or pts.shape[1] != 3:
        raise ValueError(f"Expected points_3d shape (N, 3), got {pts.shape}.")
    hom = np.empty((pts.shape[0], 4), dtype=np.float64)
    hom[:, :3] = pts
    hom[:, 3] = 1.0
    clip = hom @ self.view_proj.astype(np.float64).T
    return np.ascontiguousarray(clip[:, :3], dtype=np.float32)

project_points_px(points_3d)

Project (N, 3) world points into top-left image pixels (px, py, z_ndc).

Source code in src/build123d_techdraw/gpu/camera.py
def project_points_px(self, points_3d: NDArray[np.floating[Any]]) -> NDArray[np.float32]:
    """Project ``(N, 3)`` world points into top-left image pixels ``(px, py, z_ndc)``."""
    ndc = self.project_points_ndc(points_3d).astype(np.float64)
    out = np.empty_like(ndc, dtype=np.float32)
    out[:, 0] = ((ndc[:, 0] + 1.0) * 0.5 * self.width_px).astype(np.float32)
    out[:, 1] = ((1.0 - ndc[:, 1]) * 0.5 * self.height_px).astype(np.float32)
    out[:, 2] = ndc[:, 2].astype(np.float32)
    return out

project_points_2d(points_3d, *, origin=(0.0, 0.0, 0.0))

Project (N, 3) world points onto the view (right, up) plane around origin.

When origin equals shape.center(), the resulting (u, v) coordinates match build123d.Drawing(..., look_from=..., look_up=...) directly.

Source code in src/build123d_techdraw/gpu/camera.py
def project_points_2d(
    self,
    points_3d: NDArray[np.floating[Any]],
    *,
    origin: Vec3 = (0.0, 0.0, 0.0),
) -> NDArray[np.float64]:
    """Project ``(N, 3)`` world points onto the view ``(right, up)`` plane around ``origin``.

    When ``origin`` equals ``shape.center()``, the resulting ``(u, v)`` coordinates
    match ``build123d.Drawing(..., look_from=..., look_up=...)`` directly.
    """
    pts = np.asarray(points_3d, dtype=np.float64)
    if pts.ndim != 2 or pts.shape[1] != 3:
        raise ValueError(f"Expected points_3d shape (N, 3), got {pts.shape}.")
    rel = pts - np.asarray(origin, dtype=np.float64)
    r = np.asarray(self.right, dtype=np.float64)
    u = np.asarray(self.up, dtype=np.float64)
    out = np.empty((pts.shape[0], 2), dtype=np.float64)
    out[:, 0] = rel @ r
    out[:, 1] = rel @ u
    return out

compute_ortho_camera(bbox_min, bbox_max, look_from, look_up, width_px, height_px, *, padding_mm=0.0)

Compute an orthographic WebGPU camera framing the 3D AABB [bbox_min, bbox_max].

The camera basis matches build123d.Drawing(shape, look_from=..., look_up=...) and build123d_techdraw.core.view.VIEW_VECTORS so rasterized GPU views align pixel-for-pixel with projected vector views.

Source code in src/build123d_techdraw/gpu/camera.py
def compute_ortho_camera(
    bbox_min: Vec3,
    bbox_max: Vec3,
    look_from: Vec3,
    look_up: Vec3,
    width_px: int,
    height_px: int,
    *,
    padding_mm: float = 0.0,
) -> OrthoCamera:
    """Compute an orthographic WebGPU camera framing the 3D AABB ``[bbox_min, bbox_max]``.

    The camera basis matches `build123d.Drawing(shape, look_from=..., look_up=...)` and
    `build123d_techdraw.core.view.VIEW_VECTORS` so rasterized GPU views align
    pixel-for-pixel with projected vector views.
    """
    x0, y0, z0 = (float(bbox_min[0]), float(bbox_min[1]), float(bbox_min[2]))
    x1, y1, z1 = (float(bbox_max[0]), float(bbox_max[1]), float(bbox_max[2]))
    corners = np.array(
        [
            [x0, y0, z0],
            [x1, y0, z0],
            [x0, y1, z0],
            [x1, y1, z0],
            [x0, y0, z1],
            [x1, y0, z1],
            [x0, y1, z1],
            [x1, y1, z1],
        ],
        dtype=np.float64,
    )
    return _build_ortho_camera(
        corners,
        look_from,
        look_up,
        width_px,
        height_px,
        padding_mm=padding_mm,
    )

compute_ortho_camera_for_points(points_3d, look_from, look_up, width_px, height_px, *, padding_mm=0.0)

Compute an orthographic WebGPU camera tightly framing a (N, 3) 3D point cloud.

Prefer this over compute_ortho_camera for isometric or angled views of non-box shapes (cylinders, L-brackets, assemblies) when exact tight alignment with build123d.Drawing.visible_lines.bounding_box() is required.

Source code in src/build123d_techdraw/gpu/camera.py
def compute_ortho_camera_for_points(
    points_3d: NDArray[np.floating[Any]],
    look_from: Vec3,
    look_up: Vec3,
    width_px: int,
    height_px: int,
    *,
    padding_mm: float = 0.0,
) -> OrthoCamera:
    """Compute an orthographic WebGPU camera tightly framing a ``(N, 3)`` 3D point cloud.

    Prefer this over `compute_ortho_camera` for isometric or angled views of
    non-box shapes (cylinders, L-brackets, assemblies) when exact tight alignment
    with ``build123d.Drawing.visible_lines.bounding_box()`` is required.
    """
    pts = np.asarray(points_3d, dtype=np.float64)
    return _build_ortho_camera(
        pts,
        look_from,
        look_up,
        width_px,
        height_px,
        padding_mm=padding_mm,
    )

Technical Shading

build123d_techdraw.gpu.shading

WGSL technical-illustration shading for raster layers drawn under exact vector edges.

A shaded view is rendered offscreen with wgpu in three passes:

  1. Geometry G-buffer: the tessellated B-Rep is rasterized orthographically with the OrthoCamera basis used by build123d.Drawing, writing per-part albedo (rgba8unorm), view-space normals (rgba16float) and depth32float. X-ray views instead accumulate Fresnel-weighted coverage of every surface layer with additive blending, so internal bores show through.
  2. Screen-space ambient occlusion: a hemisphere-kernel pass over depth + normals darkens bores, fillets, counterbores and contact seams so 3D form reads on a 2D sheet.
  3. Composite: one style-specific lighting pass per theme (Gooch, toon, blueprint, ...).

The frame is supersampled and box-filtered (premultiplied alpha) into a transparent RGBA PIL.Image.Image. ShadedRender.to_svg places it in the view's local build123d.Drawing coordinates, so it can be drawn before #layer_visible and the exact vector outlines stay sharp on top. wgpu is imported lazily: this module stays importable without the gpu extra.

ENGINEERING_BOM_PALETTE = ('#8A9BB0', '#4C8DD6', '#D4A24C', '#C0704F', '#6FAE8B', '#A58BD0', '#D7D9D2', '#E07A7A') module-attribute

ViewStyle

Bases: Enum

How a projected view is drawn: exact vectors only, or a GPU-shaded raster layer.

Source code in src/build123d_techdraw/gpu/shading.py
class ViewStyle(Enum):
    """How a projected view is drawn: exact vectors only, or a GPU-shaded raster layer."""

    WIREFRAME = "wireframe"
    """Classic exact vector drawing (default, no GPU work)."""
    SHADED = "shaded"
    """Smooth technical shading without a vector edge overlay."""
    SHADED_WITH_EDGES = "shaded_with_edges"
    """Smooth technical shading underneath the exact vector edges."""
    GOOCH = "gooch"
    """Gooch cool-to-warm technical illustration shading + subtle SSAO + vector edges."""
    TOON = "toon"
    """Quantized cel bands + vector edges."""
    BLUEPRINT_SHADED = "blueprint_shaded"
    """Holographic blueprint shading (cyan in dark theme, gray-blue in white) + vector edges."""
    XRAY = "xray"
    """Fresnel translucent shading revealing internal features + vector edges."""

    @classmethod
    def coerce(cls, value: ViewStyle | str) -> ViewStyle:
        """Return `value` as a `ViewStyle`, accepting its case-insensitive string value."""
        if isinstance(value, ViewStyle):
            return value
        try:
            return cls(value.strip().lower())
        except ValueError as exc:
            choices = ", ".join(repr(s.value) for s in cls)
            raise ValueError(f"Unknown view style {value!r}; expected one of {choices}.") from exc

WIREFRAME = 'wireframe' class-attribute instance-attribute

Classic exact vector drawing (default, no GPU work).

SHADED = 'shaded' class-attribute instance-attribute

Smooth technical shading without a vector edge overlay.

SHADED_WITH_EDGES = 'shaded_with_edges' class-attribute instance-attribute

Smooth technical shading underneath the exact vector edges.

GOOCH = 'gooch' class-attribute instance-attribute

Gooch cool-to-warm technical illustration shading + subtle SSAO + vector edges.

TOON = 'toon' class-attribute instance-attribute

Quantized cel bands + vector edges.

BLUEPRINT_SHADED = 'blueprint_shaded' class-attribute instance-attribute

Holographic blueprint shading (cyan in dark theme, gray-blue in white) + vector edges.

XRAY = 'xray' class-attribute instance-attribute

Fresnel translucent shading revealing internal features + vector edges.

coerce(value) classmethod

Return value as a ViewStyle, accepting its case-insensitive string value.

Source code in src/build123d_techdraw/gpu/shading.py
@classmethod
def coerce(cls, value: ViewStyle | str) -> ViewStyle:
    """Return `value` as a `ViewStyle`, accepting its case-insensitive string value."""
    if isinstance(value, ViewStyle):
        return value
    try:
        return cls(value.strip().lower())
    except ValueError as exc:
        choices = ", ".join(repr(s.value) for s in cls)
        raise ValueError(f"Unknown view style {value!r}; expected one of {choices}.") from exc

ShadedRender dataclass

Result of render_shaded_view: one transparent raster per requested theme.

rect is (u_min, v_min, u_max, v_max) in model millimetres on the build123d.Drawing projection plane (u along the view's right axis, v along its up axis, both relative to the projection origin), i.e. the exact frame the vector edges of the matching SheetView are expressed in.

Source code in src/build123d_techdraw/gpu/shading.py
@dataclass(frozen=True)
class ShadedRender:
    """Result of `render_shaded_view`: one transparent raster per requested theme.

    ``rect`` is ``(u_min, v_min, u_max, v_max)`` in model millimetres on the
    ``build123d.Drawing`` projection plane (``u`` along the view's right axis, ``v`` along its
    up axis, both relative to the projection origin), i.e. the exact frame the vector edges of
    the matching ``SheetView`` are expressed in.
    """

    style: ViewStyle
    images: Mapping[Theme, Image.Image]
    rect: tuple[float, float, float, float]
    adapter_name: str

    def to_svg(self) -> str:
        """Return a ``<g class="shaded-view">`` of ``<image>`` layers in Drawing coordinates.

        With more than one theme each image carries ``shaded-layer-dark`` /
        ``shaded-layer-white`` so the sheet CSS shows only the layer matching the active
        theme; a single-theme render is always visible.
        """
        from build123d_techdraw.renderers.theme import SHADED_LAYER_CLASSES

        u0, v0, u1, v1 = self.rect
        dual = len(self.images) > 1
        layers = []
        for theme, image in self.images.items():
            css = f"shaded-layer {SHADED_LAYER_CLASSES[theme]}" if dual else "shaded-layer"
            layers.append(
                f'<image class="{css}" x="{u0:.4f}" y="{-v1:.4f}" width="{u1 - u0:.4f}" '
                f'height="{v1 - v0:.4f}" preserveAspectRatio="none" '
                f'href="data:image/png;base64,{_png_base64(image)}"/>'
            )
        return f'<g class="shaded-view shaded-{self.style.value}">{"".join(layers)}</g>'

to_svg()

Return a <g class="shaded-view"> of <image> layers in Drawing coordinates.

With more than one theme each image carries shaded-layer-dark / shaded-layer-white so the sheet CSS shows only the layer matching the active theme; a single-theme render is always visible.

Source code in src/build123d_techdraw/gpu/shading.py
def to_svg(self) -> str:
    """Return a ``<g class="shaded-view">`` of ``<image>`` layers in Drawing coordinates.

    With more than one theme each image carries ``shaded-layer-dark`` /
    ``shaded-layer-white`` so the sheet CSS shows only the layer matching the active
    theme; a single-theme render is always visible.
    """
    from build123d_techdraw.renderers.theme import SHADED_LAYER_CLASSES

    u0, v0, u1, v1 = self.rect
    dual = len(self.images) > 1
    layers = []
    for theme, image in self.images.items():
        css = f"shaded-layer {SHADED_LAYER_CLASSES[theme]}" if dual else "shaded-layer"
        layers.append(
            f'<image class="{css}" x="{u0:.4f}" y="{-v1:.4f}" width="{u1 - u0:.4f}" '
            f'height="{v1 - v0:.4f}" preserveAspectRatio="none" '
            f'href="data:image/png;base64,{_png_base64(image)}"/>'
        )
    return f'<g class="shaded-view shaded-{self.style.value}">{"".join(layers)}</g>'

render_shaded_view(shape, look_from, look_up, *, style=ViewStyle.SHADED_WITH_EDGES, shading_dpi=300, color_by_part=False, part_colors=None, ssao=True, gpu=None, shading_theme=None, scale=1.0, origin=None, max_size_px=2048)

Render a transparent technical-illustration raster of shape with wgpu.

Parameters:

Name Type Description Default
shape Shape[Any] | TessellatedMesh

build123d shape (Part, Solid, multi-part Compound) or a pre-built TessellatedMesh.

required
look_from, look_up

Camera vectors, as in build123d.Drawing / VIEW_VECTORS.

required
style ViewStyle | str

Any shaded ViewStyle (WIREFRAME has nothing to render).

SHADED_WITH_EDGES
shading_dpi int

Raster resolution in pixels per inch of paper; the longest side is capped at max_size_px so renders stay fast and memory-light.

300
color_by_part bool

Colour each solid of an assembly from ENGINEERING_BOM_PALETTE.

False
part_colors PartColors | None

Explicit colours per part, by index (sequence) or part label (mapping).

None
ssao bool

Enable screen-space ambient occlusion (ignored by XRAY).

True
gpu bool | None

None uses the GPU unless BUILD123D_TECHDRAW_GPU=0; False is an error.

None
shading_theme Theme | str | None

Render one theme only; None renders both DARK_BLUEPRINT and ISO_WHITE so a dual-theme SVG can switch between them.

None
scale float

View scale (paper mm per model mm), used to convert shading_dpi.

1.0
origin Vec3 | None

Projection origin; defaults to shape.center() like build123d.Drawing (or the world origin for a mesh).

None
max_size_px int

Maximum output size in pixels along either axis.

2048

Raises:

Type Description
ImportError

If wgpu is not installed (pip install build123d-techdraw[gpu]).

RuntimeError

If GPU rendering is disabled (gpu=False / environment) or no adapter is available.

ValueError

For ViewStyle.WIREFRAME, an empty shape or invalid arguments.

Source code in src/build123d_techdraw/gpu/shading.py
def render_shaded_view(
    shape: Shape[Any] | TessellatedMesh,
    look_from: Vec3,
    look_up: Vec3,
    *,
    style: ViewStyle | str = ViewStyle.SHADED_WITH_EDGES,
    shading_dpi: int = 300,
    color_by_part: bool = False,
    part_colors: PartColors | None = None,
    ssao: bool = True,
    gpu: bool | None = None,
    shading_theme: Theme | str | None = None,
    scale: float = 1.0,
    origin: Vec3 | None = None,
    max_size_px: int = 2048,
) -> ShadedRender:
    """Render a transparent technical-illustration raster of ``shape`` with ``wgpu``.

    Args:
        shape: build123d shape (`Part`, `Solid`, multi-part `Compound`) or a pre-built
            `TessellatedMesh`.
        look_from, look_up: Camera vectors, as in `build123d.Drawing` / `VIEW_VECTORS`.
        style: Any shaded `ViewStyle` (`WIREFRAME` has nothing to render).
        shading_dpi: Raster resolution in pixels per inch of *paper*; the longest side is
            capped at `max_size_px` so renders stay fast and memory-light.
        color_by_part: Colour each solid of an assembly from `ENGINEERING_BOM_PALETTE`.
        part_colors: Explicit colours per part, by index (sequence) or part label (mapping).
        ssao: Enable screen-space ambient occlusion (ignored by ``XRAY``).
        gpu: ``None`` uses the GPU unless ``BUILD123D_TECHDRAW_GPU=0``; ``False`` is an error.
        shading_theme: Render one theme only; ``None`` renders both ``DARK_BLUEPRINT`` and
            ``ISO_WHITE`` so a dual-theme SVG can switch between them.
        scale: View scale (paper mm per model mm), used to convert ``shading_dpi``.
        origin: Projection origin; defaults to ``shape.center()`` like ``build123d.Drawing``
            (or the world origin for a mesh).
        max_size_px: Maximum output size in pixels along either axis.

    Raises:
        ImportError: If ``wgpu`` is not installed (``pip install build123d-techdraw[gpu]``).
        RuntimeError: If GPU rendering is disabled (``gpu=False`` / environment) or no
            adapter is available.
        ValueError: For ``ViewStyle.WIREFRAME``, an empty shape or invalid arguments.
    """
    view_style = ViewStyle.coerce(style)
    if view_style is ViewStyle.WIREFRAME:
        raise ValueError("ViewStyle.WIREFRAME is drawn with vectors only; choose a shaded style.")
    if shading_dpi <= 0 or scale <= 0.0 or max_size_px <= 0:
        raise ValueError("shading_dpi, scale and max_size_px must be positive.")
    _require_gpu(view_style, gpu)
    from build123d_techdraw.renderers.theme import Theme

    themes = (
        (Theme.DARK_BLUEPRINT, Theme.ISO_WHITE)
        if shading_theme is None
        else (_coerce_theme(shading_theme),)
    )

    px_per_model_mm = scale * shading_dpi / _MM_PER_INCH
    if isinstance(shape, TessellatedMesh):
        mesh = shape
        center: Vec3 = origin if origin is not None else (0.0, 0.0, 0.0)
    else:
        bbox = shape.bounding_box()
        deflection = max(0.5 / px_per_model_mm, float(bbox.diagonal) * 1e-4, 1e-3)
        mesh = tessellate_shape(
            shape, linear_deflection=min(deflection, float(bbox.diagonal) * 0.01 + 1e-3)
        )
        c = shape.center() if isinstance(shape, _HasCenter) else bbox.center()
        center = origin if origin is not None else (float(c.X), float(c.Y), float(c.Z))
    if mesh.num_triangles == 0:
        raise ValueError("Cannot shade a shape without faces.")

    # Size the raster from the unpadded projected extent, then frame with a few pixels of margin.
    probe = compute_ortho_camera_for_points(mesh.positions, look_from, look_up, 64, 64)
    longest = max(probe.model_width, probe.model_height) * px_per_model_mm
    if longest + 2.0 * _PADDING_PX > max_size_px:
        px_per_model_mm *= (max_size_px - 2.0 * _PADDING_PX) / longest
    pad_mm = _PADDING_PX / px_per_model_mm
    width = max(1, math.ceil((probe.model_width + 2.0 * pad_mm) * px_per_model_mm))
    height = max(1, math.ceil((probe.model_height + 2.0 * pad_mm) * px_per_model_mm))
    factor = _SUPERSAMPLE if width * height <= _SUPERSAMPLE_MAX_PIXELS else 1
    camera = compute_ortho_camera_for_points(
        mesh.positions, look_from, look_up, width * factor, height * factor, padding_mm=pad_mm
    )

    part_rgba = resolve_part_colors(
        mesh.part_names, color_by_part=color_by_part, part_colors=part_colors
    )
    frames, adapter_name = _render_frames(mesh, camera, part_rgba, view_style, themes, ssao=ssao)
    images = {
        theme: Image.fromarray(_downsample(rgba, factor), mode="RGBA")
        for theme, rgba in frames.items()
    }

    o = np.asarray(center, dtype=np.float64)
    cu = camera.model_center_2d[0] - float(o @ np.asarray(camera.right))
    cv = camera.model_center_2d[1] - float(o @ np.asarray(camera.up))
    hw, hh = 0.5 * camera.view_width_mm, 0.5 * camera.view_height_mm
    return ShadedRender(
        style=view_style,
        images=images,
        rect=(cu - hw, cv - hh, cu + hw, cv + hh),
        adapter_name=adapter_name,
    )

Visibility-Buffer HLR

build123d_techdraw.gpu.hlr

GPU visibility-buffer hidden-line removal (HLR) producing crisp vector output.

The engine replaces OCCT HLRBRep_Algo with a three-pass wgpu pipeline:

  1. Raster pass - the tessellated shape is drawn orthographically into an offscreen depth32float attachment plus two colour targets: an r32float copy of the fragment depth and an r32uint 1-based B-Rep face ID per pixel.
  2. Compute pass - every B-Rep edge, analytic silhouette and mesh silhouette is cut into ~1 px sample intervals. A WGSL compute shader projects each interval midpoint and inspects the 3x3 pixel neighbourhood: the sample is visible if any neighbour shows background, a surface behind it, or one of the edge's own adjacent faces at (nearly) the edge depth; otherwise it is hidden.
  3. Vector pass - the per-sample flags are de-speckled, hidden runs coinciding with visible lines (and duplicate visible lines) are removed, contiguous runs are stitched into polylines, simplified with Ramer-Douglas-Peucker and emitted with the exact SVG DOM structure of build123d.ExportSVG used by the OCCT path, so every downstream consumer (views, breaks, details, PDF/DXF renderers, themes) works unchanged.

Model-space output coordinates match build123d.Drawing: (u, v) on the view plane around shape.center(), +u right and +v up (SVG flips with scale(1,-1)).

HLRMode = Literal['exact', 'gpu', 'auto'] module-attribute

Hidden-line removal backend: OCCT HLRBRep_Algo, GPU visibility buffer, or automatic.

HLROptions

Bases: TypedDict

Hidden-line removal keyword options accepted by view factories (**hlr_options).

Source code in src/build123d_techdraw/gpu/hlr.py
class HLROptions(TypedDict, total=False):
    """Hidden-line removal keyword options accepted by view factories (``**hlr_options``)."""

    hlr: HLRMode
    hlr_resolution: int
    hlr_gpu_face_threshold: int
    gpu: bool | None

GPUHLRStats dataclass

Problem size and wall-clock timings (seconds) of one GPU HLR projection.

Source code in src/build123d_techdraw/gpu/hlr.py
@dataclass(frozen=True)
class GPUHLRStats:
    """Problem size and wall-clock timings (seconds) of one GPU HLR projection."""

    num_faces: int
    num_triangles: int
    num_edges: int
    num_samples: int
    num_visible_samples: int
    num_hidden_samples: int
    num_visible_polylines: int
    num_hidden_polylines: int
    raster_width: int
    raster_height: int
    tessellate_s: float
    edges_s: float
    gpu_s: float
    vectorize_s: float
    total_s: float

GPUHLRResult dataclass

Vector output of project_shape_gpu_hlr in build123d.Drawing coordinates.

Source code in src/build123d_techdraw/gpu/hlr.py
@dataclass(frozen=True)
class GPUHLRResult:
    """Vector output of `project_shape_gpu_hlr` in `build123d.Drawing` coordinates."""

    visible_polylines_2d: list[Polyline2D]
    hidden_polylines_2d: list[Polyline2D]
    inner_svg: str
    vb_min_x: float
    vb_min_y: float
    vb_w: float
    vb_h: float
    exact_w: float
    exact_h: float
    visible_circles: tuple[tuple[float, float, float], ...]
    stats: GPUHLRStats

count_shape_faces(shape)

Return the number of distinct B-Rep faces of shape.

Source code in src/build123d_techdraw/gpu/hlr.py
def count_shape_faces(shape: Shape[Any] | TopoDS_Shape) -> int:
    """Return the number of distinct B-Rep faces of ``shape``."""
    topo = shape.wrapped if isinstance(shape, Shape) else shape
    if topo is None or topo.IsNull():
        return 0
    face_map = IndexedMap_TopoDS_Shape_TopTools_ShapeMapHasher()
    TopExp.MapShapes_s(topo, TopAbs_FACE, face_map)
    return int(face_map.Extent())

resolve_hlr_backend(shape, hlr, *, gpu=None, face_threshold=250)

Return True if shape should be projected with GPU HLR rather than OCCT.

  • "exact": always OCCT HLRBRep_Algo.
  • "gpu": always GPU; raises if gpu=False or no wgpu adapter is available (gpu=None is treated as an explicit GPU request).
  • "auto": GPU when is_gpu_enabled (gpu / BUILD123D_TECHDRAW_GPU) and the shape has at least face_threshold faces; otherwise OCCT.
Source code in src/build123d_techdraw/gpu/hlr.py
def resolve_hlr_backend(
    shape: Shape[Any] | TopoDS_Shape,
    hlr: HLRMode,
    *,
    gpu: bool | None = None,
    face_threshold: int = 250,
) -> bool:
    """Return True if ``shape`` should be projected with GPU HLR rather than OCCT.

    - ``"exact"``: always OCCT ``HLRBRep_Algo``.
    - ``"gpu"``: always GPU; raises if ``gpu=False`` or no wgpu adapter is available
      (``gpu=None`` is treated as an explicit GPU request).
    - `"auto"`: GPU when `is_gpu_enabled` (`gpu` / `BUILD123D_TECHDRAW_GPU`)
      and the shape has at least ``face_threshold`` faces; otherwise OCCT.
    """
    if hlr not in _HLR_MODES:
        raise ValueError(f"Invalid hlr mode {hlr!r}; expected one of {_HLR_MODES}.")
    if hlr == "exact":
        return False
    if hlr == "gpu":
        _require_gpu(gpu)
        return True
    try:
        enabled = is_gpu_enabled(gpu)
    except (ImportError, RuntimeError):
        if gpu is True:
            raise
        enabled = False
    return enabled and count_shape_faces(shape) >= face_threshold

project_shape_gpu_hlr(shape, look_from, look_up, *, show_hidden=True, resolution=2048, deflection=None, gpu=None)

Project shape with GPU visibility-buffer hidden-line removal.

Parameters:

Name Type Description Default
shape Any

build123d shape (Part, Solid, Compound assembly, ...).

required
look_from Vec3

Direction from the model toward the camera (VIEW_VECTORS).

required
look_up Vec3

Up direction of the view.

required
show_hidden bool

Emit hidden lines (dashed layer_hidden) when True.

True
resolution int

Long side, in pixels, of the depth / face-ID visibility buffer. Visibility transitions are located to about one pixel of this raster.

2048
deflection float | None

Tessellation / edge discretisation tolerance in model units; defaults to 4e-4 of the bounding-box diagonal.

None
gpu bool | None

False raises; None / True require a wgpu adapter.

None

Raises:

Type Description
ValueError

If gpu=False or resolution is too small.

ImportError

If wgpu is not installed.

RuntimeError

If no wgpu adapter can be initialised.

Source code in src/build123d_techdraw/gpu/hlr.py
def project_shape_gpu_hlr(
    shape: Any,
    look_from: Vec3,
    look_up: Vec3,
    *,
    show_hidden: bool = True,
    resolution: int = 2048,
    deflection: float | None = None,
    gpu: bool | None = None,
) -> GPUHLRResult:
    """Project ``shape`` with GPU visibility-buffer hidden-line removal.

    Args:
        shape: build123d shape (``Part``, ``Solid``, ``Compound`` assembly, ...).
        look_from: Direction from the model toward the camera (``VIEW_VECTORS``).
        look_up: Up direction of the view.
        show_hidden: Emit hidden lines (dashed ``layer_hidden``) when True.
        resolution: Long side, in pixels, of the depth / face-ID visibility buffer.
            Visibility transitions are located to about one pixel of this raster.
        deflection: Tessellation / edge discretisation tolerance in model units;
            defaults to ``4e-4`` of the bounding-box diagonal.
        gpu: ``False`` raises; ``None`` / ``True`` require a wgpu adapter.

    Raises:
        ValueError: If ``gpu=False`` or ``resolution`` is too small.
        ImportError: If ``wgpu`` is not installed.
        RuntimeError: If no wgpu adapter can be initialised.
    """
    if resolution < 64:
        raise ValueError(f"resolution must be >= 64 px, got {resolution}.")
    _require_gpu(gpu)
    _adapter, device = get_gpu_device()

    t_start = time.perf_counter()
    bbox = shape.bounding_box()
    diag = max(float(bbox.diagonal), 1e-6)
    defl = _default_deflection(diag) if deflection is None else float(deflection)
    if defl <= 0.0:
        raise ValueError(f"deflection must be positive, got {defl}.")
    center = shape.center()
    origin: Vec3 = (float(center.X), float(center.Y), float(center.Z))

    mesh = tessellate_shape(
        shape, linear_deflection=defl, angular_deflection=0.25, split_sharp_edges_deg=0.0
    )
    t_mesh = time.perf_counter()

    edge_set = sample_shape_edges(shape, deflection=0.5 * defl, look_from=look_from)
    analytic = {e.face_id_a for e in edge_set.edges if e.geom_type == "silhouette"}
    lf = np.asarray(look_from, dtype=np.float64)
    edges = _drawable_edges(edge_set)
    edges += _mesh_silhouettes(
        mesh, lf / float(np.linalg.norm(lf)), analytic, len(edge_set.edges) + 1
    )
    t_edges = time.perf_counter()

    empty = mesh.num_triangles == 0 or not edges
    if empty:
        return _assemble([], [], (), mesh, edge_set, 0, 0, 0, 0, (t_start, t_mesh, t_edges))

    pad_px = max(4, int(math.ceil(2.0 * defl * resolution / diag)) + 2)
    camera = _raster_size(mesh, look_from, look_up, resolution, pad_px)
    px_mm = 1.0 / camera.pixels_per_mm
    depth_range = camera.z_far - camera.z_near
    samples = _build_samples(edges, camera, origin, step_px=1.0)

    textures = _rasterize(device, camera, mesh)
    flags = _classify(
        device,
        camera,
        textures,
        samples,
        bias=max(2.0 * defl, 1.5 * px_mm) / depth_range,
        own_bias=max(4.0 * defl, 4.0 * px_mm) / depth_range,
    )
    t_gpu = time.perf_counter()

    n_visible_raw = int(np.count_nonzero(flags == _VISIBLE))
    flags = _despeckle(flags, samples.edge_idx)
    hidden_smooth = np.fromiter(
        (e.is_smooth or not show_hidden for e in edges), dtype=np.bool_, count=len(edges)
    )
    flags = np.where((flags == _HIDDEN) & hidden_smooth[samples.edge_idx], _DROPPED, flags).astype(
        np.uint32
    )
    flags = _remove_coincident(flags, samples, camera)
    tol = min(0.02, max(1e-3, 1e-4 * diag))
    visible, hidden = _stitch(flags, samples, edges, tol)
    circles = _fit_visible_circles(edges, flags, samples, camera, origin)

    return _assemble(
        visible,
        hidden,
        circles,
        mesh,
        edge_set,
        len(edges),
        int(flags.shape[0]),
        n_visible_raw,
        camera.width_px,
        (t_start, t_mesh, t_edges, t_gpu),
        raster_height=camera.height_px,
    )

Distance-Field (SDF / JFA)

build123d_techdraw.gpu.sdf

2D Euclidean Distance-Field (SDF) sheet occupancy and Jump Flooding Algorithm (JFA).

Rasterizes a DrawingSheet into a high-resolution binary obstacle mask — including exact projected 2D view geometry contours (so concave L/C/T-shaped parts expose true whitespace pockets instead of coarse AABBs), margins, ISO 7200 title block, revision/BOM tables, view labels, and existing annotations — and computes an exact millimeter clearance field via a WebGPU (WGSL) Jump Flooding Algorithm (JFA+1) compute shader, with automatic exact CPU fallback via scipy.ndimage.distance_transform_edt.

SheetDistanceField

2D Euclidean Signed/Unsigned Distance Field (clearance in mm) over a DrawingSheet.

Attributes:

Name Type Description
distance_mm NDArray[float32]

(H, W) float32 array giving Euclidean clearance in millimetres from each pixel to the nearest occupied obstacle.

obstacle_mask NDArray[bool_]

(H, W) bool array (True = occupied obstacle).

resolution_px_per_mm float

Raster resolution in pixels per sheet millimetre.

backend BackendName

Execution backend that computed the field ("gpu" or "cpu").

width_mm float

Sheet width in millimetres.

height_mm float

Sheet height in millimetres.

Source code in src/build123d_techdraw/gpu/sdf.py
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
class SheetDistanceField:
    """2D Euclidean Signed/Unsigned Distance Field (clearance in mm) over a ``DrawingSheet``.

    Attributes:
        distance_mm: ``(H, W)`` ``float32`` array giving Euclidean clearance in millimetres
            from each pixel to the nearest occupied obstacle.
        obstacle_mask: ``(H, W)`` ``bool`` array (``True`` = occupied obstacle).
        resolution_px_per_mm: Raster resolution in pixels per sheet millimetre.
        backend: Execution backend that computed the field (``"gpu"`` or ``"cpu"``).
        width_mm: Sheet width in millimetres.
        height_mm: Sheet height in millimetres.
    """

    def __init__(
        self,
        distance_mm: NDArray[np.float32],
        obstacle_mask: NDArray[np.bool_],
        *,
        resolution_px_per_mm: float,
        backend: BackendName,
        width_mm: float,
        height_mm: float,
        geometry_mask: NDArray[np.bool_] | None = None,
        contour_mask: NDArray[np.bool_] | None = None,
        frame_mask: NDArray[np.bool_] | None = None,
        label_mask: NDArray[np.bool_] | None = None,
        drawable_bounds: BBox2D | None = None,
    ) -> None:
        self.distance_mm: NDArray[np.float32] = np.ascontiguousarray(distance_mm, dtype=np.float32)
        self.obstacle_mask: NDArray[np.bool_] = np.ascontiguousarray(obstacle_mask, dtype=np.bool_)
        self.resolution_px_per_mm: float = float(resolution_px_per_mm)
        self.backend: BackendName = backend
        self.width_mm: float = float(width_mm)
        self.height_mm: float = float(height_mm)

        shape_hw = self.obstacle_mask.shape
        self._geometry_mask: NDArray[np.bool_] = (
            np.ascontiguousarray(geometry_mask, dtype=np.bool_)
            if geometry_mask is not None
            else np.zeros(shape_hw, dtype=np.bool_)
        )
        self._contour_mask: NDArray[np.bool_] = (
            np.ascontiguousarray(contour_mask, dtype=np.bool_)
            if contour_mask is not None
            else np.zeros(shape_hw, dtype=np.bool_)
        )
        self._frame_mask: NDArray[np.bool_] = (
            np.ascontiguousarray(frame_mask, dtype=np.bool_)
            if frame_mask is not None
            else np.zeros(shape_hw, dtype=np.bool_)
        )
        self._label_mask: NDArray[np.bool_] = (
            np.ascontiguousarray(label_mask, dtype=np.bool_)
            if label_mask is not None
            else np.zeros(shape_hw, dtype=np.bool_)
        )
        self.drawable_bounds: BBox2D = (
            drawable_bounds
            if drawable_bounds is not None
            else (0.0, 0.0, self.width_mm, self.height_mm)
        )
        self.placed_boxes: list[BBox2D] = []
        self._leader_segments: list[tuple[tuple[float, float], tuple[float, float]]] = []

        # Precompute pixel index coordinate vectors for fast exact incremental box updates.
        h, w = int(shape_hw[0]), int(shape_hw[1])
        self._xs_px: NDArray[np.int32] = np.arange(w, dtype=np.int32)
        self._ys_px: NDArray[np.int32] = np.arange(h, dtype=np.int32)

    @property
    def height_px(self) -> int:
        """Raster height in pixels."""
        return int(self.distance_mm.shape[0])

    @property
    def width_px(self) -> int:
        """Raster width in pixels."""
        return int(self.distance_mm.shape[1])

    def query_clearance(self, x_mm: float, y_mm: float) -> float:
        """Return the Euclidean clearance in millimetres at sheet coordinate ``(x_mm, y_mm)``."""
        if x_mm < 0.0 or y_mm < 0.0 or x_mm >= self.width_mm or y_mm >= self.height_mm:
            return 0.0
        ix = min(self.width_px - 1, max(0, int(math.floor(x_mm * self.resolution_px_per_mm))))
        iy = min(self.height_px - 1, max(0, int(math.floor(y_mm * self.resolution_px_per_mm))))
        return float(self.distance_mm[iy, ix])

    def box_min_clearance(
        self,
        min_x: float,
        min_y: float,
        max_x: float,
        max_y: float,
    ) -> float:
        """Return the minimum SDF clearance (mm) anywhere inside the given sheet-mm rectangle."""
        x0, x1 = (min_x, max_x) if min_x <= max_x else (max_x, min_x)
        y0, y1 = (min_y, max_y) if min_y <= max_y else (max_y, min_y)
        if x0 < 0.0 or y0 < 0.0 or x1 > self.width_mm or y1 > self.height_mm:
            return 0.0
        res = self.resolution_px_per_mm
        ix0 = max(0, min(self.width_px - 1, int(math.floor(x0 * res))))
        ix1 = max(ix0 + 1, min(self.width_px, int(math.ceil(x1 * res))))
        iy0 = max(0, min(self.height_px - 1, int(math.floor(y0 * res))))
        iy1 = max(iy0 + 1, min(self.height_px, int(math.ceil(y1 * res))))
        return float(np.min(self.distance_mm[iy0:iy1, ix0:ix1]))

    def mark_occupied_box(self, bbox: BBox2D, pad_mm: float = 1.0) -> None:
        """Mark ``bbox`` (expanded by ``pad_mm``) occupied and update ``distance_mm`` exactly.

        Uses the exact analytical Euclidean distance to an axis-aligned pixel rectangle
        ``D_new = min(D_old, d_rect)``, which is mathematically identical to re-running a
        full EDT/JFA transform over the updated mask while completing in sub-millisecond time.
        """
        norm_bbox = (
            min(bbox[0], bbox[2]),
            min(bbox[1], bbox[3]),
            max(bbox[0], bbox[2]),
            max(bbox[1], bbox[3]),
        )
        self.placed_boxes.append(norm_bbox)

        x0, y0, x1, y1 = _mark_mask_bbox(
            self.obstacle_mask,
            norm_bbox,
            self.resolution_px_per_mm,
            pad_mm=pad_mm,
        )
        if x1 <= x0 or y1 <= y0:
            return

        # Exact pixel distance to the occupied pixel block [x0, x1 - 1] x [y0, y1 - 1].
        dx_px = np.maximum(0, np.maximum(x0 - self._xs_px, self._xs_px - (x1 - 1)))
        dy_px = np.maximum(0, np.maximum(y0 - self._ys_px, self._ys_px - (y1 - 1)))
        dx_sq = dx_px.astype(np.float32) ** 2
        dy_sq = dy_px.astype(np.float32) ** 2
        dist_rect_mm = np.sqrt(dy_sq[:, None] + dx_sq[None, :]) / np.float32(
            self.resolution_px_per_mm
        )
        np.minimum(self.distance_mm, dist_rect_mm, out=self.distance_mm)

    def register_leader_segment(
        self,
        start_xy: tuple[float, float],
        end_xy: tuple[float, float],
    ) -> None:
        """Record a placed leader line segment so future callouts avoid crossing it."""
        self._leader_segments.append((start_xy, end_xy))

    def _leader_obstacle_length_mm(
        self,
        start_xy: tuple[float, float],
        end_xy: tuple[float, float],
        *,
        start_skip_mm: float = 1.5,
        end_skip_mm: float = 0.8,
    ) -> tuple[float, float, float]:
        """Measure ``(total_obstacle_mm, geometry_obstacle_mm, label_obstacle_mm)`` along a leader."""
        dx = end_xy[0] - start_xy[0]
        dy = end_xy[1] - start_xy[1]
        seg_len = math.hypot(dx, dy)
        if seg_len <= start_skip_mm + end_skip_mm + 1e-6:
            return 0.0, 0.0, 0.0

        t0 = start_skip_mm / seg_len
        t1 = 1.0 - (end_skip_mm / seg_len)
        active_len = seg_len * (t1 - t0)
        n_samples = max(6, int(math.ceil(active_len * self.resolution_px_per_mm)))
        ts = np.linspace(t0, t1, n_samples, dtype=np.float64)
        xs = start_xy[0] + ts * dx
        ys = start_xy[1] + ts * dy

        res = self.resolution_px_per_mm
        ixs = np.clip(np.floor(xs * res).astype(np.int32), 0, self.width_px - 1)
        iys = np.clip(np.floor(ys * res).astype(np.int32), 0, self.height_px - 1)

        obs_frac = float(np.mean(self.obstacle_mask[iys, ixs]))
        geom_frac = float(np.mean(self._geometry_mask[iys, ixs]))
        label_frac = float(np.mean(self._label_mask[iys, ixs]))
        return obs_frac * active_len, geom_frac * active_len, label_frac * active_len

    def _count_leader_crossings(
        self,
        start_xy: tuple[float, float],
        end_xy: tuple[float, float],
    ) -> int:
        """Count how many previously registered leader segments intersect ``(start_xy, end_xy)``."""
        return sum(
            1
            for seg_a, seg_b in self._leader_segments
            if _segments_intersect(start_xy, end_xy, seg_a, seg_b)
        )

    def _score_candidate_box(
        self,
        target_xy: tuple[float, float],
        box: BBox2D,
        *,
        leader_end: tuple[float, float],
        dist_mm: float,
        angle_deg: float,
        min_dist_mm: float,
        preferred_angles_deg: Sequence[float] | None,
        avoid_leader_crossings: bool,
    ) -> tuple[bool, float]:
        """Score a candidate annotation box; returns ``(is_clear, score)``."""
        # Reject out-of-drawable-bounds boxes immediately.
        db = self.drawable_bounds
        if box[0] < db[0] or box[1] < db[1] or box[2] > db[2] or box[3] > db[3]:
            return False, -1e9

        min_clr = self.box_min_clearance(box[0], box[1], box[2], box[3])
        cx = 0.5 * (box[0] + box[2])
        cy = 0.5 * (box[1] + box[3])
        center_clr = self.query_clearance(cx, cy)

        is_clear = min_clr > 0.0
        if is_clear:
            # Strong reward for safe clearance up to 6 mm without flinging far into empty space.
            score = 1000.0 + min(min_clr, 6.0) * 14.0 + min(center_clr, 12.0) * 1.5
        else:
            # Fallback tie-breaker when no fully clear spot exists: prefer higher center clearance.
            score = -500.0 + center_clr * 8.0

        # Distance preference: keep leaders compact and crisp around the feature.
        ideal_dist = min_dist_mm + 4.0
        score -= abs(dist_mm - ideal_dist) * 0.55
        if dist_mm > ideal_dist:
            score -= (dist_mm - ideal_dist) * 0.25

        # Leader obstacle & crossing penalties
        if avoid_leader_crossings:
            obs_mm, geom_mm, label_mm = self._leader_obstacle_length_mm(target_xy, leader_end)
            score -= obs_mm * 3.0 + geom_mm * 2.5 + label_mm * 12.0
            crossings = self._count_leader_crossings(target_xy, leader_end)
            if crossings > 0:
                score -= crossings * 120.0

        # Angular preference (user-specified or gentle ISO oblique-leader preference)
        if preferred_angles_deg:
            best_ang = min(_angle_diff_deg(angle_deg, p) for p in preferred_angles_deg)
            score += max(0.0, 1.0 - best_ang / 60.0) * 12.0
        else:
            # Slight preference for crisp oblique angles (~45/135/225/315 deg) per ISO drafting.
            score += abs(math.sin(2.0 * math.radians(angle_deg))) * 2.0

        return is_clear, score

    def find_best_callout_position(
        self,
        target_xy: tuple[float, float],
        box_size_mm: tuple[float, float],
        *,
        min_dist_mm: float = 10.0,
        max_dist_mm: float = 55.0,
        preferred_angles_deg: Sequence[float] | None = None,
        avoid_leader_crossings: bool = True,
        validator: Callable[[tuple[float, float]], bool] | None = None,
    ) -> tuple[float, float]:
        """Find the highest-clearance collision-free center ``(cx, cy)`` for a callout box.

        Evaluates candidate rings around ``target_xy`` using exact SDF box clearance,
        leader-line obstacle sampling, leader-crossing detection, and distance/angle
        preferences so callouts naturally discover concave part pockets while keeping
        leaders short and unobstructed.
        """
        tx, ty = float(target_xy[0]), float(target_xy[1])
        bw = max(1.0, float(box_size_mm[0]))
        bh = max(1.0, float(box_size_mm[1]))
        half_w = 0.5 * bw
        half_h = 0.5 * bh

        lo_dist = max(2.0, float(min_dist_mm))
        hi_dist = max(lo_dist, float(max_dist_mm))

        angles = _build_candidate_angles(7.5, preferred_angles_deg)

        def _search_range(
            r_lo: float, r_hi: float, step_mm: float
        ) -> tuple[tuple[float, float] | None, int, float]:
            n_rings = max(1, int(math.ceil((r_hi - r_lo) / step_mm)) + 1)
            radii = np.linspace(r_lo, r_hi, n_rings)
            best_pos: tuple[float, float] | None = None
            # Priority tier: 2 = SDF-clear & validator-valid, 1 = validator-valid, 0 = fallback
            best_tier = -1
            best_score = -1e18

            for r_val in radii:
                r = float(r_val)
                for ang in angles:
                    rad = math.radians(ang)
                    cx = tx + r * math.cos(rad)
                    cy = ty + r * math.sin(rad)
                    box = (cx - half_w, cy - half_h, cx + half_w, cy + half_h)
                    leader_end = _closest_point_on_box((tx, ty), box)
                    is_clear, score = self._score_candidate_box(
                        (tx, ty),
                        box,
                        leader_end=leader_end,
                        dist_mm=r,
                        angle_deg=ang,
                        min_dist_mm=lo_dist,
                        preferred_angles_deg=preferred_angles_deg,
                        avoid_leader_crossings=avoid_leader_crossings,
                    )
                    is_valid = validator((cx, cy)) if validator is not None else True
                    if is_clear and is_valid:
                        tier = 2
                    elif is_valid:
                        tier = 1
                    else:
                        tier = 0

                    if tier > best_tier or (tier == best_tier and score > best_score):
                        best_tier = tier
                        best_score = score
                        best_pos = (cx, cy)
            return best_pos, best_tier, best_score

        best_pos, best_tier, best_score = _search_range(lo_dist, hi_dist, 3.0)

        # If the initial search ring was completely blocked (very crowded sheet), widen once.
        if best_tier < 2:
            wider_hi = max(hi_dist * 1.75, 95.0)
            alt_pos, alt_tier, alt_score = _search_range(hi_dist + 3.0, wider_hi, 4.0)
            if alt_pos is not None and (
                alt_tier > best_tier or (alt_tier == best_tier and alt_score > best_score)
            ):
                best_pos = alt_pos

        if best_pos is None:
            # Extreme fallback: clamp slightly offset inside drawable bounds.
            db = self.drawable_bounds
            cx = min(max(tx + lo_dist, db[0] + half_w), db[2] - half_w)
            cy = min(max(ty - lo_dist, db[1] + half_h), db[3] - half_h)
            return (cx, cy)

        return best_pos

    def find_best_leader_elbow(
        self,
        target_xy: tuple[float, float],
        shelf_length_mm: float,
        text_height_mm: float = 8.0,
        *,
        min_dist_mm: float = 12.0,
        max_dist_mm: float = 60.0,
        preferred_angles_deg: Sequence[float] | None = None,
        avoid_leader_crossings: bool = True,
        validator: Callable[[tuple[float, float]], bool] | None = None,
    ) -> tuple[float, float]:
        """Find an optimal ``(elbow_dx, elbow_dy)`` offset for a ``LeaderNote`` / ``HoleCallout``.

        Scores each candidate elbow by the SDF clearance of its horizontal text shelf,
        leader obstacle/crossing avoidance, and optional linter-compatibility ``validator``.
        """
        tx, ty = float(target_xy[0]), float(target_xy[1])
        shelf_len = max(10.0, float(shelf_length_mm))
        text_h = max(6.0, float(text_height_mm))
        lo_dist = max(4.0, float(min_dist_mm))
        hi_dist = max(lo_dist, float(max_dist_mm))

        angles = _build_candidate_angles(5.0, preferred_angles_deg)

        def _search(
            r_lo: float, r_hi: float, step_mm: float
        ) -> tuple[tuple[float, float] | None, int, float]:
            n_rings = max(1, int(math.ceil((r_hi - r_lo) / step_mm)) + 1)
            radii = np.linspace(r_lo, r_hi, n_rings)
            best_off: tuple[float, float] | None = None
            # Priority tier: 2 = SDF-clear & validator-valid, 1 = validator-valid, 0 = fallback
            best_tier = -1
            best_score = -1e18

            for r_val in radii:
                r = float(r_val)
                for ang in angles:
                    rad = math.radians(ang)
                    dx = r * math.cos(rad)
                    dy = r * math.sin(rad)
                    # Avoid near-zero horizontal elbow so shelf direction is unambiguous.
                    if abs(dx) < 1.2:
                        continue
                    ex = tx + dx
                    ey = ty + dy
                    sx = ex + (shelf_len if dx >= 0.0 else -shelf_len)
                    # Visual shelf box covers the text seated above ey and a small margin below.
                    shelf_box = (
                        min(ex, sx),
                        ey - text_h + 1.5,
                        max(ex, sx),
                        ey + 2.0,
                    )
                    is_clear, score = self._score_candidate_box(
                        (tx, ty),
                        shelf_box,
                        leader_end=(ex, ey),
                        dist_mm=r,
                        angle_deg=ang,
                        min_dist_mm=lo_dist,
                        preferred_angles_deg=preferred_angles_deg,
                        avoid_leader_crossings=avoid_leader_crossings,
                    )
                    is_valid = validator((dx, dy)) if validator is not None else True
                    if is_clear and is_valid:
                        tier = 2
                    elif is_valid:
                        tier = 1
                    else:
                        tier = 0

                    if tier > best_tier or (tier == best_tier and score > best_score):
                        best_tier = tier
                        best_score = score
                        best_off = (dx, dy)
            return best_off, best_tier, best_score

        best_off, best_tier, best_score = _search(lo_dist, hi_dist, 3.5)
        if best_tier < 2:
            wider_hi = max(hi_dist * 1.8, 125.0)
            alt_off, alt_tier, alt_score = _search(hi_dist + 3.5, wider_hi, 4.5)
            if alt_off is not None and (
                alt_tier > best_tier or (alt_tier == best_tier and alt_score > best_score)
            ):
                best_off = alt_off
                best_tier = alt_tier
                best_score = alt_score

        # Also check shorter leaders (down to 6 mm) for tight concave pockets if still unplaced.
        if best_tier < 2 and lo_dist > 6.5:
            tight_off, tight_tier, tight_score = _search(6.0, lo_dist - 1.5, 2.0)
            if tight_off is not None and (
                tight_tier > best_tier or (tight_tier == best_tier and tight_score > best_score)
            ):
                best_off = tight_off

        if best_off is None:
            return (lo_dist * 0.8, -lo_dist * 0.6)
        return best_off

    def render_heatmap_image(
        self,
        *,
        theme: Theme | None = None,
        placed_boxes: Sequence[BBox2D] | None = None,
        max_clearance_mm: float = 40.0,
        contour_step_mm: float = 5.0,
    ) -> Image.Image:
        """Render a blueprint-styled 2D clearance heatmap PNG for visualization and CI diffs.

        Displays the continuous Euclidean clearance field with iso-distance contour rings,
        occupied margins/title-block/tables, crisp projected part geometry silhouettes, and
        highlighted placed annotation boxes.
        """
        from build123d_techdraw.renderers.theme import Theme as _Theme

        resolved_theme = _Theme.DARK_BLUEPRINT if theme is None else theme
        is_dark = resolved_theme == _Theme.DARK_BLUEPRINT
        lut = _DARK_BLUEPRINT_LUT if is_dark else _ISO_WHITE_LUT

        norm = np.clip(self.distance_mm / max(1.0, float(max_clearance_mm)), 0.0, 1.0)
        idx = np.clip(np.rint(norm * 255.0), 0, 255).astype(np.uint8)
        rgb = lut[idx].copy()

        # Draw crisp iso-distance clearance contour bands in free space.
        free = ~self.obstacle_mask
        if contour_step_mm > 0.0:
            contour_px = _band_contour_mask(self.distance_mm, free, contour_step_mm)
            major_px = _band_contour_mask(self.distance_mm, free, contour_step_mm * 2.0)

            if is_dark:
                rgb[contour_px] = np.clip(
                    rgb[contour_px].astype(np.int16) + np.array([18, 28, 34]), 0, 255
                ).astype(np.uint8)
                rgb[major_px] = np.clip(
                    rgb[major_px].astype(np.int16) + np.array([34, 48, 56]), 0, 255
                ).astype(np.uint8)
            else:
                rgb[contour_px] = np.clip(
                    rgb[contour_px].astype(np.int16) - np.array([22, 20, 16]), 0, 255
                ).astype(np.uint8)
                rgb[major_px] = np.clip(
                    rgb[major_px].astype(np.int16) - np.array([42, 38, 32]), 0, 255
                ).astype(np.uint8)

        # Style occupied zones distinctly: UI frames, solid part geometry, and crisp contours.
        if is_dark:
            rgb[self.obstacle_mask] = np.array([15, 27, 46], dtype=np.uint8)
            rgb[self._frame_mask] = np.array([11, 21, 36], dtype=np.uint8)
            rgb[self._geometry_mask] = np.array([24, 42, 68], dtype=np.uint8)
            rgb[self._contour_mask] = np.array([248, 252, 255], dtype=np.uint8)
        else:
            rgb[self.obstacle_mask] = np.array([226, 232, 240], dtype=np.uint8)
            rgb[self._frame_mask] = np.array([241, 245, 249], dtype=np.uint8)
            rgb[self._geometry_mask] = np.array([203, 213, 225], dtype=np.uint8)
            rgb[self._contour_mask] = np.array([15, 23, 42], dtype=np.uint8)

        rgba = np.empty((self.height_px, self.width_px, 4), dtype=np.uint8)
        rgba[:, :, :3] = rgb
        rgba[:, :, 3] = 255
        img = Image.fromarray(rgba, mode="RGBA")
        overlay = Image.new("RGBA", img.size, (0, 0, 0, 0))
        draw = ImageDraw.Draw(overlay)
        res = self.resolution_px_per_mm

        # Sheet drawable border frame line
        db = self.drawable_bounds
        frame_col = (56, 189, 248, 220) if is_dark else (15, 23, 42, 220)
        draw.rectangle(
            [db[0] * res, db[1] * res, db[2] * res, db[3] * res],
            outline=frame_col,
            width=max(1, int(round(0.7 * res))),
        )

        # Draw registered leader segments
        leader_col = (244, 63, 94, 235) if is_dark else (220, 38, 38, 235)
        for p0, p1 in self._leader_segments:
            draw.line(
                [p0[0] * res, p0[1] * res, p1[0] * res, p1[1] * res],
                fill=leader_col,
                width=max(1, int(round(0.45 * res))),
            )

        # Draw placed annotation boxes (both tracked on this SDF and any extra passed in)
        all_boxes: list[BBox2D] = list(self.placed_boxes)
        if placed_boxes:
            all_boxes.extend(placed_boxes)

        box_fill = (16, 185, 129, 72) if is_dark else (220, 38, 38, 48)
        box_outline = (52, 211, 153, 245) if is_dark else (220, 38, 38, 240)
        for bb in all_boxes:
            x0, y0 = min(bb[0], bb[2]) * res, min(bb[1], bb[3]) * res
            x1, y1 = max(bb[0], bb[2]) * res, max(bb[1], bb[3]) * res
            draw.rectangle(
                [x0, y0, x1, y1],
                fill=box_fill,
                outline=box_outline,
                width=max(1, int(round(0.6 * res))),
            )

        return Image.alpha_composite(img, overlay)

height_px property

Raster height in pixels.

width_px property

Raster width in pixels.

query_clearance(x_mm, y_mm)

Return the Euclidean clearance in millimetres at sheet coordinate (x_mm, y_mm).

Source code in src/build123d_techdraw/gpu/sdf.py
def query_clearance(self, x_mm: float, y_mm: float) -> float:
    """Return the Euclidean clearance in millimetres at sheet coordinate ``(x_mm, y_mm)``."""
    if x_mm < 0.0 or y_mm < 0.0 or x_mm >= self.width_mm or y_mm >= self.height_mm:
        return 0.0
    ix = min(self.width_px - 1, max(0, int(math.floor(x_mm * self.resolution_px_per_mm))))
    iy = min(self.height_px - 1, max(0, int(math.floor(y_mm * self.resolution_px_per_mm))))
    return float(self.distance_mm[iy, ix])

box_min_clearance(min_x, min_y, max_x, max_y)

Return the minimum SDF clearance (mm) anywhere inside the given sheet-mm rectangle.

Source code in src/build123d_techdraw/gpu/sdf.py
def box_min_clearance(
    self,
    min_x: float,
    min_y: float,
    max_x: float,
    max_y: float,
) -> float:
    """Return the minimum SDF clearance (mm) anywhere inside the given sheet-mm rectangle."""
    x0, x1 = (min_x, max_x) if min_x <= max_x else (max_x, min_x)
    y0, y1 = (min_y, max_y) if min_y <= max_y else (max_y, min_y)
    if x0 < 0.0 or y0 < 0.0 or x1 > self.width_mm or y1 > self.height_mm:
        return 0.0
    res = self.resolution_px_per_mm
    ix0 = max(0, min(self.width_px - 1, int(math.floor(x0 * res))))
    ix1 = max(ix0 + 1, min(self.width_px, int(math.ceil(x1 * res))))
    iy0 = max(0, min(self.height_px - 1, int(math.floor(y0 * res))))
    iy1 = max(iy0 + 1, min(self.height_px, int(math.ceil(y1 * res))))
    return float(np.min(self.distance_mm[iy0:iy1, ix0:ix1]))

mark_occupied_box(bbox, pad_mm=1.0)

Mark bbox (expanded by pad_mm) occupied and update distance_mm exactly.

Uses the exact analytical Euclidean distance to an axis-aligned pixel rectangle D_new = min(D_old, d_rect), which is mathematically identical to re-running a full EDT/JFA transform over the updated mask while completing in sub-millisecond time.

Source code in src/build123d_techdraw/gpu/sdf.py
def mark_occupied_box(self, bbox: BBox2D, pad_mm: float = 1.0) -> None:
    """Mark ``bbox`` (expanded by ``pad_mm``) occupied and update ``distance_mm`` exactly.

    Uses the exact analytical Euclidean distance to an axis-aligned pixel rectangle
    ``D_new = min(D_old, d_rect)``, which is mathematically identical to re-running a
    full EDT/JFA transform over the updated mask while completing in sub-millisecond time.
    """
    norm_bbox = (
        min(bbox[0], bbox[2]),
        min(bbox[1], bbox[3]),
        max(bbox[0], bbox[2]),
        max(bbox[1], bbox[3]),
    )
    self.placed_boxes.append(norm_bbox)

    x0, y0, x1, y1 = _mark_mask_bbox(
        self.obstacle_mask,
        norm_bbox,
        self.resolution_px_per_mm,
        pad_mm=pad_mm,
    )
    if x1 <= x0 or y1 <= y0:
        return

    # Exact pixel distance to the occupied pixel block [x0, x1 - 1] x [y0, y1 - 1].
    dx_px = np.maximum(0, np.maximum(x0 - self._xs_px, self._xs_px - (x1 - 1)))
    dy_px = np.maximum(0, np.maximum(y0 - self._ys_px, self._ys_px - (y1 - 1)))
    dx_sq = dx_px.astype(np.float32) ** 2
    dy_sq = dy_px.astype(np.float32) ** 2
    dist_rect_mm = np.sqrt(dy_sq[:, None] + dx_sq[None, :]) / np.float32(
        self.resolution_px_per_mm
    )
    np.minimum(self.distance_mm, dist_rect_mm, out=self.distance_mm)

register_leader_segment(start_xy, end_xy)

Record a placed leader line segment so future callouts avoid crossing it.

Source code in src/build123d_techdraw/gpu/sdf.py
def register_leader_segment(
    self,
    start_xy: tuple[float, float],
    end_xy: tuple[float, float],
) -> None:
    """Record a placed leader line segment so future callouts avoid crossing it."""
    self._leader_segments.append((start_xy, end_xy))

find_best_callout_position(target_xy, box_size_mm, *, min_dist_mm=10.0, max_dist_mm=55.0, preferred_angles_deg=None, avoid_leader_crossings=True, validator=None)

Find the highest-clearance collision-free center (cx, cy) for a callout box.

Evaluates candidate rings around target_xy using exact SDF box clearance, leader-line obstacle sampling, leader-crossing detection, and distance/angle preferences so callouts naturally discover concave part pockets while keeping leaders short and unobstructed.

Source code in src/build123d_techdraw/gpu/sdf.py
def find_best_callout_position(
    self,
    target_xy: tuple[float, float],
    box_size_mm: tuple[float, float],
    *,
    min_dist_mm: float = 10.0,
    max_dist_mm: float = 55.0,
    preferred_angles_deg: Sequence[float] | None = None,
    avoid_leader_crossings: bool = True,
    validator: Callable[[tuple[float, float]], bool] | None = None,
) -> tuple[float, float]:
    """Find the highest-clearance collision-free center ``(cx, cy)`` for a callout box.

    Evaluates candidate rings around ``target_xy`` using exact SDF box clearance,
    leader-line obstacle sampling, leader-crossing detection, and distance/angle
    preferences so callouts naturally discover concave part pockets while keeping
    leaders short and unobstructed.
    """
    tx, ty = float(target_xy[0]), float(target_xy[1])
    bw = max(1.0, float(box_size_mm[0]))
    bh = max(1.0, float(box_size_mm[1]))
    half_w = 0.5 * bw
    half_h = 0.5 * bh

    lo_dist = max(2.0, float(min_dist_mm))
    hi_dist = max(lo_dist, float(max_dist_mm))

    angles = _build_candidate_angles(7.5, preferred_angles_deg)

    def _search_range(
        r_lo: float, r_hi: float, step_mm: float
    ) -> tuple[tuple[float, float] | None, int, float]:
        n_rings = max(1, int(math.ceil((r_hi - r_lo) / step_mm)) + 1)
        radii = np.linspace(r_lo, r_hi, n_rings)
        best_pos: tuple[float, float] | None = None
        # Priority tier: 2 = SDF-clear & validator-valid, 1 = validator-valid, 0 = fallback
        best_tier = -1
        best_score = -1e18

        for r_val in radii:
            r = float(r_val)
            for ang in angles:
                rad = math.radians(ang)
                cx = tx + r * math.cos(rad)
                cy = ty + r * math.sin(rad)
                box = (cx - half_w, cy - half_h, cx + half_w, cy + half_h)
                leader_end = _closest_point_on_box((tx, ty), box)
                is_clear, score = self._score_candidate_box(
                    (tx, ty),
                    box,
                    leader_end=leader_end,
                    dist_mm=r,
                    angle_deg=ang,
                    min_dist_mm=lo_dist,
                    preferred_angles_deg=preferred_angles_deg,
                    avoid_leader_crossings=avoid_leader_crossings,
                )
                is_valid = validator((cx, cy)) if validator is not None else True
                if is_clear and is_valid:
                    tier = 2
                elif is_valid:
                    tier = 1
                else:
                    tier = 0

                if tier > best_tier or (tier == best_tier and score > best_score):
                    best_tier = tier
                    best_score = score
                    best_pos = (cx, cy)
        return best_pos, best_tier, best_score

    best_pos, best_tier, best_score = _search_range(lo_dist, hi_dist, 3.0)

    # If the initial search ring was completely blocked (very crowded sheet), widen once.
    if best_tier < 2:
        wider_hi = max(hi_dist * 1.75, 95.0)
        alt_pos, alt_tier, alt_score = _search_range(hi_dist + 3.0, wider_hi, 4.0)
        if alt_pos is not None and (
            alt_tier > best_tier or (alt_tier == best_tier and alt_score > best_score)
        ):
            best_pos = alt_pos

    if best_pos is None:
        # Extreme fallback: clamp slightly offset inside drawable bounds.
        db = self.drawable_bounds
        cx = min(max(tx + lo_dist, db[0] + half_w), db[2] - half_w)
        cy = min(max(ty - lo_dist, db[1] + half_h), db[3] - half_h)
        return (cx, cy)

    return best_pos

find_best_leader_elbow(target_xy, shelf_length_mm, text_height_mm=8.0, *, min_dist_mm=12.0, max_dist_mm=60.0, preferred_angles_deg=None, avoid_leader_crossings=True, validator=None)

Find an optimal (elbow_dx, elbow_dy) offset for a LeaderNote / HoleCallout.

Scores each candidate elbow by the SDF clearance of its horizontal text shelf, leader obstacle/crossing avoidance, and optional linter-compatibility validator.

Source code in src/build123d_techdraw/gpu/sdf.py
def find_best_leader_elbow(
    self,
    target_xy: tuple[float, float],
    shelf_length_mm: float,
    text_height_mm: float = 8.0,
    *,
    min_dist_mm: float = 12.0,
    max_dist_mm: float = 60.0,
    preferred_angles_deg: Sequence[float] | None = None,
    avoid_leader_crossings: bool = True,
    validator: Callable[[tuple[float, float]], bool] | None = None,
) -> tuple[float, float]:
    """Find an optimal ``(elbow_dx, elbow_dy)`` offset for a ``LeaderNote`` / ``HoleCallout``.

    Scores each candidate elbow by the SDF clearance of its horizontal text shelf,
    leader obstacle/crossing avoidance, and optional linter-compatibility ``validator``.
    """
    tx, ty = float(target_xy[0]), float(target_xy[1])
    shelf_len = max(10.0, float(shelf_length_mm))
    text_h = max(6.0, float(text_height_mm))
    lo_dist = max(4.0, float(min_dist_mm))
    hi_dist = max(lo_dist, float(max_dist_mm))

    angles = _build_candidate_angles(5.0, preferred_angles_deg)

    def _search(
        r_lo: float, r_hi: float, step_mm: float
    ) -> tuple[tuple[float, float] | None, int, float]:
        n_rings = max(1, int(math.ceil((r_hi - r_lo) / step_mm)) + 1)
        radii = np.linspace(r_lo, r_hi, n_rings)
        best_off: tuple[float, float] | None = None
        # Priority tier: 2 = SDF-clear & validator-valid, 1 = validator-valid, 0 = fallback
        best_tier = -1
        best_score = -1e18

        for r_val in radii:
            r = float(r_val)
            for ang in angles:
                rad = math.radians(ang)
                dx = r * math.cos(rad)
                dy = r * math.sin(rad)
                # Avoid near-zero horizontal elbow so shelf direction is unambiguous.
                if abs(dx) < 1.2:
                    continue
                ex = tx + dx
                ey = ty + dy
                sx = ex + (shelf_len if dx >= 0.0 else -shelf_len)
                # Visual shelf box covers the text seated above ey and a small margin below.
                shelf_box = (
                    min(ex, sx),
                    ey - text_h + 1.5,
                    max(ex, sx),
                    ey + 2.0,
                )
                is_clear, score = self._score_candidate_box(
                    (tx, ty),
                    shelf_box,
                    leader_end=(ex, ey),
                    dist_mm=r,
                    angle_deg=ang,
                    min_dist_mm=lo_dist,
                    preferred_angles_deg=preferred_angles_deg,
                    avoid_leader_crossings=avoid_leader_crossings,
                )
                is_valid = validator((dx, dy)) if validator is not None else True
                if is_clear and is_valid:
                    tier = 2
                elif is_valid:
                    tier = 1
                else:
                    tier = 0

                if tier > best_tier or (tier == best_tier and score > best_score):
                    best_tier = tier
                    best_score = score
                    best_off = (dx, dy)
        return best_off, best_tier, best_score

    best_off, best_tier, best_score = _search(lo_dist, hi_dist, 3.5)
    if best_tier < 2:
        wider_hi = max(hi_dist * 1.8, 125.0)
        alt_off, alt_tier, alt_score = _search(hi_dist + 3.5, wider_hi, 4.5)
        if alt_off is not None and (
            alt_tier > best_tier or (alt_tier == best_tier and alt_score > best_score)
        ):
            best_off = alt_off
            best_tier = alt_tier
            best_score = alt_score

    # Also check shorter leaders (down to 6 mm) for tight concave pockets if still unplaced.
    if best_tier < 2 and lo_dist > 6.5:
        tight_off, tight_tier, tight_score = _search(6.0, lo_dist - 1.5, 2.0)
        if tight_off is not None and (
            tight_tier > best_tier or (tight_tier == best_tier and tight_score > best_score)
        ):
            best_off = tight_off

    if best_off is None:
        return (lo_dist * 0.8, -lo_dist * 0.6)
    return best_off

render_heatmap_image(*, theme=None, placed_boxes=None, max_clearance_mm=40.0, contour_step_mm=5.0)

Render a blueprint-styled 2D clearance heatmap PNG for visualization and CI diffs.

Displays the continuous Euclidean clearance field with iso-distance contour rings, occupied margins/title-block/tables, crisp projected part geometry silhouettes, and highlighted placed annotation boxes.

Source code in src/build123d_techdraw/gpu/sdf.py
def render_heatmap_image(
    self,
    *,
    theme: Theme | None = None,
    placed_boxes: Sequence[BBox2D] | None = None,
    max_clearance_mm: float = 40.0,
    contour_step_mm: float = 5.0,
) -> Image.Image:
    """Render a blueprint-styled 2D clearance heatmap PNG for visualization and CI diffs.

    Displays the continuous Euclidean clearance field with iso-distance contour rings,
    occupied margins/title-block/tables, crisp projected part geometry silhouettes, and
    highlighted placed annotation boxes.
    """
    from build123d_techdraw.renderers.theme import Theme as _Theme

    resolved_theme = _Theme.DARK_BLUEPRINT if theme is None else theme
    is_dark = resolved_theme == _Theme.DARK_BLUEPRINT
    lut = _DARK_BLUEPRINT_LUT if is_dark else _ISO_WHITE_LUT

    norm = np.clip(self.distance_mm / max(1.0, float(max_clearance_mm)), 0.0, 1.0)
    idx = np.clip(np.rint(norm * 255.0), 0, 255).astype(np.uint8)
    rgb = lut[idx].copy()

    # Draw crisp iso-distance clearance contour bands in free space.
    free = ~self.obstacle_mask
    if contour_step_mm > 0.0:
        contour_px = _band_contour_mask(self.distance_mm, free, contour_step_mm)
        major_px = _band_contour_mask(self.distance_mm, free, contour_step_mm * 2.0)

        if is_dark:
            rgb[contour_px] = np.clip(
                rgb[contour_px].astype(np.int16) + np.array([18, 28, 34]), 0, 255
            ).astype(np.uint8)
            rgb[major_px] = np.clip(
                rgb[major_px].astype(np.int16) + np.array([34, 48, 56]), 0, 255
            ).astype(np.uint8)
        else:
            rgb[contour_px] = np.clip(
                rgb[contour_px].astype(np.int16) - np.array([22, 20, 16]), 0, 255
            ).astype(np.uint8)
            rgb[major_px] = np.clip(
                rgb[major_px].astype(np.int16) - np.array([42, 38, 32]), 0, 255
            ).astype(np.uint8)

    # Style occupied zones distinctly: UI frames, solid part geometry, and crisp contours.
    if is_dark:
        rgb[self.obstacle_mask] = np.array([15, 27, 46], dtype=np.uint8)
        rgb[self._frame_mask] = np.array([11, 21, 36], dtype=np.uint8)
        rgb[self._geometry_mask] = np.array([24, 42, 68], dtype=np.uint8)
        rgb[self._contour_mask] = np.array([248, 252, 255], dtype=np.uint8)
    else:
        rgb[self.obstacle_mask] = np.array([226, 232, 240], dtype=np.uint8)
        rgb[self._frame_mask] = np.array([241, 245, 249], dtype=np.uint8)
        rgb[self._geometry_mask] = np.array([203, 213, 225], dtype=np.uint8)
        rgb[self._contour_mask] = np.array([15, 23, 42], dtype=np.uint8)

    rgba = np.empty((self.height_px, self.width_px, 4), dtype=np.uint8)
    rgba[:, :, :3] = rgb
    rgba[:, :, 3] = 255
    img = Image.fromarray(rgba, mode="RGBA")
    overlay = Image.new("RGBA", img.size, (0, 0, 0, 0))
    draw = ImageDraw.Draw(overlay)
    res = self.resolution_px_per_mm

    # Sheet drawable border frame line
    db = self.drawable_bounds
    frame_col = (56, 189, 248, 220) if is_dark else (15, 23, 42, 220)
    draw.rectangle(
        [db[0] * res, db[1] * res, db[2] * res, db[3] * res],
        outline=frame_col,
        width=max(1, int(round(0.7 * res))),
    )

    # Draw registered leader segments
    leader_col = (244, 63, 94, 235) if is_dark else (220, 38, 38, 235)
    for p0, p1 in self._leader_segments:
        draw.line(
            [p0[0] * res, p0[1] * res, p1[0] * res, p1[1] * res],
            fill=leader_col,
            width=max(1, int(round(0.45 * res))),
        )

    # Draw placed annotation boxes (both tracked on this SDF and any extra passed in)
    all_boxes: list[BBox2D] = list(self.placed_boxes)
    if placed_boxes:
        all_boxes.extend(placed_boxes)

    box_fill = (16, 185, 129, 72) if is_dark else (220, 38, 38, 48)
    box_outline = (52, 211, 153, 245) if is_dark else (220, 38, 38, 240)
    for bb in all_boxes:
        x0, y0 = min(bb[0], bb[2]) * res, min(bb[1], bb[3]) * res
        x1, y1 = max(bb[0], bb[2]) * res, max(bb[1], bb[3]) * res
        draw.rectangle(
            [x0, y0, x1, y1],
            fill=box_fill,
            outline=box_outline,
            width=max(1, int(round(0.6 * res))),
        )

    return Image.alpha_composite(img, overlay)

compute_distance_field_from_mask(obstacle_mask, *, resolution_px_per_mm=2.0, gpu=None)

Compute a 2D millimeter distance field from a boolean (H, W) obstacle mask.

Uses the WebGPU JFA+1 compute shader when is_gpu_enabled returns True and falls back to exact CPU scipy.ndimage.distance_transform_edt otherwise.

Source code in src/build123d_techdraw/gpu/sdf.py
def compute_distance_field_from_mask(
    obstacle_mask: NDArray[np.bool_],
    *,
    resolution_px_per_mm: float = 2.0,
    gpu: bool | None = None,
) -> tuple[NDArray[np.float32], BackendName]:
    """Compute a 2D millimeter distance field from a boolean ``(H, W)`` obstacle mask.

    Uses the WebGPU JFA+1 compute shader when `is_gpu_enabled` returns `True`
    and falls back to exact CPU `scipy.ndimage.distance_transform_edt` otherwise.
    """
    if resolution_px_per_mm <= 0.0:
        raise ValueError(f"resolution_px_per_mm must be positive, got {resolution_px_per_mm}.")
    mask_bool = np.ascontiguousarray(obstacle_mask, dtype=np.bool_)
    if mask_bool.ndim != 2 or mask_bool.shape[0] == 0 or mask_bool.shape[1] == 0:
        raise ValueError(f"Expected non-empty 2D obstacle_mask, got shape {mask_bool.shape}.")

    if is_gpu_enabled(gpu):
        return _compute_sdf_gpu(mask_bool, resolution_px_per_mm), "gpu"
    return _compute_sdf_cpu(mask_bool, resolution_px_per_mm), "cpu"

compute_sheet_sdf(sheet, *, resolution_px_per_mm=2.0, gpu=None, include_annotations=True, include_labels=True, include_notes=True, geometry_stroke_mm=0.8)

Build a 2D Euclidean clearance field (SheetDistanceField) for sheet.

Rasterizes:

  • Sheet border / margin exclusion bands,
  • ISO 7200 title block, revision table, BOM table, and general notes block,
  • Exact projected 2D geometry contours and solid silhouettes of every SheetView,
  • View title labels and existing annotations' bounding boxes.

Computes Euclidean millimeter clearance on GPU via WGSL Jump Flooding (JFA+1) when is_gpu_enabled(gpu) is True, seamlessly falling back to exact CPU SciPy EDT when gpu=False or [gpu] is unavailable.

Source code in src/build123d_techdraw/gpu/sdf.py
def compute_sheet_sdf(
    sheet: DrawingSheet,
    *,
    resolution_px_per_mm: float = 2.0,
    gpu: bool | None = None,
    include_annotations: bool = True,
    include_labels: bool = True,
    include_notes: bool = True,
    geometry_stroke_mm: float = 0.8,
) -> SheetDistanceField:
    """Build a 2D Euclidean clearance field (`SheetDistanceField`) for `sheet`.

    Rasterizes:

    - Sheet border / margin exclusion bands,
    - ISO 7200 title block, revision table, BOM table, and general notes block,
    - Exact projected 2D geometry contours and solid silhouettes of every `SheetView`,
    - View title labels and existing annotations' bounding boxes.

    Computes Euclidean millimeter clearance on GPU via WGSL Jump Flooding (JFA+1) when
    `is_gpu_enabled(gpu)` is `True`, seamlessly falling back to exact CPU SciPy EDT
    when `gpu=False` or `[gpu]` is unavailable.
    """
    if resolution_px_per_mm <= 0.0:
        raise ValueError(f"resolution_px_per_mm must be positive, got {resolution_px_per_mm}.")

    res = float(resolution_px_per_mm)
    width_mm = float(sheet.width_mm)
    height_mm = float(sheet.height_mm)
    width_px = max(1, int(round(width_mm * res)))
    height_px = max(1, int(round(height_mm * res)))

    obstacle_mask = np.zeros((height_px, width_px), dtype=np.bool_)
    frame_mask = np.zeros((height_px, width_px), dtype=np.bool_)
    geometry_mask = np.zeros((height_px, width_px), dtype=np.bool_)
    contour_mask = np.zeros((height_px, width_px), dtype=np.bool_)
    label_mask = np.zeros((height_px, width_px), dtype=np.bool_)

    drawable_bounds: BBox2D = (
        float(sheet.left_margin),
        float(sheet.top_margin),
        float(width_mm - sheet.right_margin),
        float(height_mm - sheet.bottom_margin),
    )

    # 1. Sheet margins / border exclusion zone
    left_px = max(0, min(width_px, int(math.ceil(drawable_bounds[0] * res))))
    top_px = max(0, min(height_px, int(math.ceil(drawable_bounds[1] * res))))
    right_px = max(0, min(width_px, int(math.floor(drawable_bounds[2] * res))))
    bottom_px = max(0, min(height_px, int(math.floor(drawable_bounds[3] * res))))

    if left_px > 0:
        frame_mask[:, :left_px] = True
    if right_px < width_px:
        frame_mask[:, right_px:] = True
    if top_px > 0:
        frame_mask[:top_px, :] = True
    if bottom_px < height_px:
        frame_mask[bottom_px:, :] = True

    # 2. ISO 7200 title block, revision table, BOM table, and general notes block
    for ui_box in (
        _sheet_title_block_bbox(sheet),
        _sheet_revision_table_bbox(sheet),
        _sheet_bom_table_bbox(sheet),
        _sheet_notes_bbox(sheet) if include_notes else None,
    ):
        if ui_box is not None:
            _mark_mask_bbox(frame_mask, ui_box, res, pad_mm=1.0)

    obstacle_mask |= frame_mask

    # 3. Actual projected 2D geometry contours + solid interiors of every SheetView
    for view in sheet.views:
        v_solid, v_contours = _rasterize_view_geometry(
            view,
            width_mm=width_mm,
            height_mm=height_mm,
            res=res,
            stroke_mm=geometry_stroke_mm,
        )
        geometry_mask |= v_solid
        contour_mask |= v_contours

        if include_labels:
            lbl_bb = _view_label_bbox(view)
            if lbl_bb is not None:
                _mark_mask_bbox(label_mask, lbl_bb, res, pad_mm=0.5)
                _mark_mask_bbox(obstacle_mask, lbl_bb, res, pad_mm=0.5)

    obstacle_mask |= geometry_mask

    # 4. Existing annotations' bounding boxes (excluding CenterMark)
    if include_annotations:
        for ann in sheet.annotations:
            if isinstance(ann, CenterMark):
                continue
            ann_bb = ann.bounding_box_2d()
            if ann_bb is not None:
                _mark_mask_bbox(obstacle_mask, ann_bb, res, pad_mm=1.0)

    distance_mm, backend = compute_distance_field_from_mask(
        obstacle_mask,
        resolution_px_per_mm=res,
        gpu=gpu,
    )

    return SheetDistanceField(
        distance_mm=distance_mm,
        obstacle_mask=obstacle_mask,
        resolution_px_per_mm=res,
        backend=backend,
        width_mm=width_mm,
        height_mm=height_mm,
        geometry_mask=geometry_mask,
        contour_mask=contour_mask,
        frame_mask=frame_mask,
        label_mask=label_mask,
        drawable_bounds=drawable_bounds,
    )