Skip to content

Layout API

build123d_techdraw.layout.multiview

High-level declarative multiview layout helpers and automated assembly BOM tools.

MultiviewLayout dataclass

Bases: SheetDirective

Container holding views created by add_standard_multiview.

Source code in src/build123d_techdraw/layout/multiview.py
@dataclass
class MultiviewLayout(SheetDirective):
    """Container holding views created by add_standard_multiview."""

    scale: float
    scale_str: str
    sheet: DrawingSheet
    front: SheetView | None = None
    top: SheetView | None = None
    right: SheetView | None = None
    bottom: SheetView | None = None
    left: SheetView | None = None
    rear: SheetView | None = None
    isometric: SheetView | None = None
    views: dict[ViewType, SheetView] = field(default_factory=dict)

    def _apply_to_sheet(self, sheet: DrawingSheet) -> None:
        for v in self.views.values():
            sheet.add_view(v)

    def add_overall_dimensions(
        self,
        offset: float = 12.0,
        tolerance: str | None = None,
    ) -> list[Any]:
        """Automatically add overall envelope dimensions (Length, Height, Depth) to the views."""
        dims: list[Any] = []
        if self.front is not None:
            # Length (horizontal) and Height (vertical) on Front view
            dim_w = self.front.add_overall_horizontal(offset_y=offset, tolerance=tolerance)
            dim_h = self.front.add_overall_vertical(offset_x=-offset, tolerance=tolerance)
            dims.extend([dim_w, dim_h])

        if self.top is not None:
            # Depth on Top view (vertical axis in Top view)
            dim_d = self.top.add_overall_vertical(offset_x=offset, tolerance=tolerance)
            dims.append(dim_d)
        elif self.right is not None:
            # Depth on Right view (horizontal axis in Right view)
            dim_d = self.right.add_overall_horizontal(offset_y=offset, tolerance=tolerance)
            dims.append(dim_d)

        return dims

    def auto_dimension(
        self,
        shape: Any | None = None,
        tolerance: str | None = None,
    ) -> list[Any]:
        """Run smart collision-avoiding auto-dimensioning across all views in this layout."""
        from build123d_techdraw.layout.auto_dimension import auto_dimension_views

        target_shape = shape
        if target_shape is None:
            for v in self.views.values():
                target_shape = v.shape
                if target_shape is not None:
                    break
        if target_shape is None:
            return []
        return auto_dimension_views(
            sheet=self.sheet,
            shape=target_shape,
            views_map=self.views,
            tolerance=tolerance,
        )

add_overall_dimensions(offset=12.0, tolerance=None)

Automatically add overall envelope dimensions (Length, Height, Depth) to the views.

Source code in src/build123d_techdraw/layout/multiview.py
def add_overall_dimensions(
    self,
    offset: float = 12.0,
    tolerance: str | None = None,
) -> list[Any]:
    """Automatically add overall envelope dimensions (Length, Height, Depth) to the views."""
    dims: list[Any] = []
    if self.front is not None:
        # Length (horizontal) and Height (vertical) on Front view
        dim_w = self.front.add_overall_horizontal(offset_y=offset, tolerance=tolerance)
        dim_h = self.front.add_overall_vertical(offset_x=-offset, tolerance=tolerance)
        dims.extend([dim_w, dim_h])

    if self.top is not None:
        # Depth on Top view (vertical axis in Top view)
        dim_d = self.top.add_overall_vertical(offset_x=offset, tolerance=tolerance)
        dims.append(dim_d)
    elif self.right is not None:
        # Depth on Right view (horizontal axis in Right view)
        dim_d = self.right.add_overall_horizontal(offset_y=offset, tolerance=tolerance)
        dims.append(dim_d)

    return dims

auto_dimension(shape=None, tolerance=None)

Run smart collision-avoiding auto-dimensioning across all views in this layout.

Source code in src/build123d_techdraw/layout/multiview.py
def auto_dimension(
    self,
    shape: Any | None = None,
    tolerance: str | None = None,
) -> list[Any]:
    """Run smart collision-avoiding auto-dimensioning across all views in this layout."""
    from build123d_techdraw.layout.auto_dimension import auto_dimension_views

    target_shape = shape
    if target_shape is None:
        for v in self.views.values():
            target_shape = v.shape
            if target_shape is not None:
                break
    if target_shape is None:
        return []
    return auto_dimension_views(
        sheet=self.sheet,
        shape=target_shape,
        views_map=self.views,
        tolerance=tolerance,
    )

add_standard_multiview(sheet, shape, views=None, layout=FIRST_ANGLE, scale='auto', spacing=25.0, center=None, show_hidden=False, show_labels=True, show_scale_label=False, auto_dimensions=False, auto_centerlines=False, enforce_iso_scale=True, infer_threads=False, parallel='auto', max_workers=None, iso_style=ViewStyle.WIREFRAME, shading_dpi=300, color_by_part=False, part_colors=None, ssao=True, gpu=None)

Generate a standard orthographic multi-view layout on a drawing sheet.

Parameters:

Name Type Description Default
sheet DrawingSheet

Target DrawingSheet.

required
shape Solid | Compound | Any

3D build123d part or assembly.

required
views list[ViewType] | None

List of ViewType values to generate. Defaults to Front, Top, Right, and Isometric.

None
layout str

Projection method used to arrange the views (ISO 5456-2). Use 'first_angle' (default, ISO 128-3 / ISO 5456-2 "method E": Top view below the Front view, Right view to the left, Left view to the right) or 'third_angle' (ASME Y14.3 / US "method A": Top view above the Front view, Right view to the right, Left view to the left). The Isometric view is placed in the free corner of the grid, and sheet.title_info.third_angle is set to match.

FIRST_ANGLE
scale float | str

Explicit float scale (e.g. 0.5 for 1:2) or 'auto' to fit the available sheet area.

'auto'
spacing float

Spacing between views in paper millimeters.

25.0
center tuple[float, float] | None

Center of the multiview group in sheet coordinates. Defaults to the sheet center.

None
show_hidden bool

Whether hidden lines are enabled for orthographic views.

False
show_labels bool

Whether view title labels are displayed.

True
show_scale_label bool

Whether view title labels display individual scale.

False
auto_dimensions bool | str

Whether to add overall bounding envelope dimensions automatically (or 'smart' / 'sdf' for feature-aware dimensioning).

False
auto_centerlines bool

Whether to add automatic centerlines on symmetric views.

False
enforce_iso_scale bool

Snap 'auto' scale to the nearest standard ISO 5455 ratio.

True
infer_threads bool

Infer standard metric/unified threads during auto-dimensioning.

False
parallel bool | Literal['auto']

Multi-view projection execution mode: 'auto' (default, uses a process-isolated worker pool when the shape is complex enough to offset worker startup/IPC overhead, or when BUILD123D_TECHDRAW_PARALLEL=1), True (always project views in parallel across worker processes when more than one view is requested), or False (always sequential).

'auto'
max_workers int | None

Optional upper bound on worker processes when projecting in parallel.

None
iso_style ViewStyle | str

Rendering style (ViewStyle) for the isometric view.

WIREFRAME
shading_dpi int

Offscreen raster resolution (paper DPI) for shaded views.

300
color_by_part bool

Assign distinct engineering BOM colors per solid when shading.

False
part_colors PartColors | None

Optional explicit color sequence or label-to-color mapping.

None
ssao bool

Enable screen-space ambient occlusion for shaded views.

True
gpu bool | None

Optional GPU override (True, False, or None for auto-detection).

None

Returns:

Type Description
MultiviewLayout

MultiviewLayout containing the created views and resolved scale metadata.

Source code in src/build123d_techdraw/layout/multiview.py
def add_standard_multiview(
    sheet: DrawingSheet,
    shape: bd.Solid | bd.Compound | Any,
    views: list[ViewType] | None = None,
    layout: str = FIRST_ANGLE,
    scale: float | str = "auto",
    spacing: float = 25.0,
    center: tuple[float, float] | None = None,
    show_hidden: bool = False,
    show_labels: bool = True,
    show_scale_label: bool = False,
    auto_dimensions: bool | str = False,
    auto_centerlines: bool = False,
    enforce_iso_scale: bool = True,
    infer_threads: bool = False,
    parallel: bool | Literal["auto"] = "auto",
    max_workers: int | None = None,
    iso_style: ViewStyle | str = ViewStyle.WIREFRAME,
    shading_dpi: int = 300,
    color_by_part: bool = False,
    part_colors: PartColors | None = None,
    ssao: bool = True,
    gpu: bool | None = None,
) -> MultiviewLayout:
    """Generate a standard orthographic multi-view layout on a drawing sheet.

    Args:
        sheet: Target `DrawingSheet`.
        shape: 3D build123d part or assembly.
        views: List of `ViewType` values to generate. Defaults to Front, Top, Right,
            and Isometric.
        layout: Projection method used to arrange the views (ISO 5456-2). Use
            `'first_angle'` (default, ISO 128-3 / ISO 5456-2 "method E": Top view
            below the Front view, Right view to the left, Left view to the right) or
            `'third_angle'` (ASME Y14.3 / US "method A": Top view above the Front
            view, Right view to the right, Left view to the left). The Isometric view
            is placed in the free corner of the grid, and
            `sheet.title_info.third_angle` is set to match.
        scale: Explicit float scale (e.g. `0.5` for 1:2) or `'auto'` to fit the
            available sheet area.
        spacing: Spacing between views in paper millimeters.
        center: Center of the multiview group in sheet coordinates. Defaults to the
            sheet center.
        show_hidden: Whether hidden lines are enabled for orthographic views.
        show_labels: Whether view title labels are displayed.
        show_scale_label: Whether view title labels display individual scale.
        auto_dimensions: Whether to add overall bounding envelope dimensions
            automatically (or `'smart'` / `'sdf'` for feature-aware dimensioning).
        auto_centerlines: Whether to add automatic centerlines on symmetric views.
        enforce_iso_scale: Snap `'auto'` scale to the nearest standard ISO 5455 ratio.
        infer_threads: Infer standard metric/unified threads during auto-dimensioning.
        parallel: Multi-view projection execution mode: `'auto'` (default, uses a
            process-isolated worker pool when the shape is complex enough to offset
            worker startup/IPC overhead, or when `BUILD123D_TECHDRAW_PARALLEL=1`),
            `True` (always project views in parallel across worker processes when more
            than one view is requested), or `False` (always sequential).
        max_workers: Optional upper bound on worker processes when projecting in
            parallel.
        iso_style: Rendering style (`ViewStyle`) for the isometric view.
        shading_dpi: Offscreen raster resolution (paper DPI) for shaded views.
        color_by_part: Assign distinct engineering BOM colors per solid when shading.
        part_colors: Optional explicit color sequence or label-to-color mapping.
        ssao: Enable screen-space ambient occlusion for shaded views.
        gpu: Optional GPU override (`True`, `False`, or `None` for auto-detection).

    Returns:
        `MultiviewLayout` containing the created views and resolved scale metadata.
    """
    layout_key = layout.lower()
    if layout_key not in (FIRST_ANGLE, THIRD_ANGLE):
        raise ValueError(
            f"Unknown projection layout {layout!r}; use {FIRST_ANGLE!r} or {THIRD_ANGLE!r}."
        )
    is_third_angle = layout_key == THIRD_ANGLE

    if views is None:
        views = [ViewType.FRONT, ViewType.TOP, ViewType.RIGHT, ViewType.ISOMETRIC]

    # Exact unscaled 2D extent (width, height) of every requested view, measured in
    # the same projection frame that SheetView uses when drawing it.
    extents = {v: projected_view_extent(shape, v) for v in views}

    # Standard arrangement grid (ISO 5456-2 / ASME Y14.3).
    #
    # Columns (width = widest projected view in the column):
    #   "main": Front / Top
    #   "side": Right view + Isometric
    #   "far":  Left view, on the opposite side of the main column
    # Rows (height = tallest projected view in the row):
    #   "elev": Front / Right / Left / Rear elevations
    #   "plan": Top view + Isometric
    #
    # Third-angle places each view on the side it is seen from:
    #   columns [far, main, side], rows [plan, elev] -> Top above, Right on the right.
    # First-angle places each view on the opposite side:
    #   columns [side, main, far], rows [elev, plan] -> Top below, Right on the left.
    # In both, the Isometric view fills the otherwise empty corner of the grid.
    col_members: dict[str, tuple[ViewType, ...]] = {
        "main": (ViewType.FRONT, ViewType.TOP, ViewType.BOTTOM, ViewType.REAR),
        "side": (ViewType.RIGHT, ViewType.ISOMETRIC),
        "far": (ViewType.LEFT,),
    }
    row_members: dict[str, tuple[ViewType, ...]] = {
        "elev": (ViewType.FRONT, ViewType.RIGHT, ViewType.LEFT, ViewType.REAR),
        "plan": (ViewType.TOP, ViewType.ISOMETRIC),
    }
    col_widths: dict[str, float] = {
        col: max(extents[v][0] for v in views if v in members)
        for col, members in col_members.items()
        if any(v in members for v in views)
    }
    row_heights: dict[str, float] = {
        row: max(extents[v][1] for v in views if v in members)
        for row, members in row_members.items()
        if any(v in members for v in views)
    }

    col_order = ["far", "main", "side"] if is_third_angle else ["side", "main", "far"]
    row_order = ["plan", "elev"] if is_third_angle else ["elev", "plan"]
    cols = [c for c in col_order if c in col_widths]
    rows = [r for r in row_order if r in row_heights]

    num_cols = len(cols)
    num_rows = len(rows)

    total_unscaled_w = sum(col_widths.values())
    total_unscaled_h = sum(row_heights.values())

    # Exclusion zone at bottom-right for title block and optional stacked BOM table
    has_bom = bool(sheet.bom_items) or any(c.label for c in extract_assembly_components(shape))
    bom_h = (5.5 + len(sheet.bom_items) * 5.2) if sheet.bom_items else 20.0
    if sheet.template is not None:
        tb_bb = sheet.template.title_block_bbox(sheet)
        tb_h_excl = max(0.0, sheet.height_mm - sheet.bottom_margin - tb_bb[1])
    else:
        tb_h_excl = 36.0
    bottom_excl = (
        sheet.bottom_margin
        + tb_h_excl
        + (bom_h + 2.0 if has_bom and sheet.bom_position == "above_title_block" else 0.0)
        + 16.0  # clearance for dimension lines and view labels
    )
    top_excl = sheet.top_margin + 14.0

    avail_w = sheet.width_mm - sheet.left_margin - sheet.right_margin
    avail_h = sheet.height_mm - bottom_excl - top_excl

    if center is None:
        center_x = sheet.left_margin + avail_w * 0.44
        center_y = top_excl + avail_h / 2.0
    else:
        center_x, center_y = center

    # Auto scale computation
    if isinstance(scale, str) and scale.lower() == "auto":
        net_w = avail_w * 0.85 - (num_cols - 1) * spacing
        net_h = avail_h - (num_rows - 1) * spacing
        raw_scale_w = net_w / total_unscaled_w if total_unscaled_w > 0 else 1.0
        raw_scale_h = net_h / total_unscaled_h if total_unscaled_h > 0 else 1.0
        raw_scale = min(raw_scale_w, raw_scale_h)
        calculated_scale = find_closest_iso_scale(raw_scale) if enforce_iso_scale else raw_scale
    else:
        calculated_scale = float(scale)

    scale_str = format_iso_scale(calculated_scale)

    # Scaled grid geometry
    total_group_w = calculated_scale * total_unscaled_w + spacing * max(num_cols - 1, 0)
    total_group_h = calculated_scale * total_unscaled_h + spacing * max(num_rows - 1, 0)

    col_cx: dict[str, float] = {}
    cursor = center_x - total_group_w / 2.0
    for col in cols:
        w = col_widths[col] * calculated_scale
        col_cx[col] = cursor + w / 2.0
        cursor += w + spacing

    row_cy: dict[str, float] = {}
    cursor = center_y - total_group_h / 2.0
    for row in rows:
        h = row_heights[row] * calculated_scale
        row_cy[row] = cursor + h / 2.0
        cursor += h + spacing

    # Ensure bottom-row labels and dimensions do not encroach on bottom-right exclusion zone
    if rows:
        bottom_row = rows[-1]
        bottom_edge = row_cy[bottom_row] + row_heights[bottom_row] * calculated_scale / 2.0 + 16.0
        max_allowed_bottom = sheet.height_mm - bottom_excl + 10.0
        if bottom_edge > max_allowed_bottom:
            dy_shift = bottom_edge - max_allowed_bottom
            for row in rows:
                row_cy[row] -= dy_shift

    layout_obj = MultiviewLayout(
        scale=calculated_scale,
        scale_str=scale_str,
        sheet=sheet,
    )

    sheet.title_info.third_angle = is_third_angle
    sheet.title_info.scale = format_iso_ratio(calculated_scale)

    grid_cells: dict[ViewType, tuple[str, str]] = {
        ViewType.FRONT: ("main", "elev"),
        ViewType.TOP: ("main", "plan"),
        ViewType.RIGHT: ("side", "elev"),
        ViewType.LEFT: ("far", "elev"),
        ViewType.ISOMETRIC: ("side", "plan"),
    }
    pos_map: dict[ViewType, tuple[float, float]] = {
        v: (col_cx[col], row_cy[row]) for v, (col, row) in grid_cells.items() if v in views
    }

    view_specs: list[tuple[ViewType, bool]] = [
        (v_type, show_hidden if v_type != ViewType.ISOMETRIC else False) for v_type in views
    ]
    payloads = _project_views_payloads(
        shape,
        view_specs,
        parallel=parallel,
        max_workers=max_workers,
    )

    for (v_type, v_hidden), payload in zip(view_specs, payloads, strict=True):
        v_center = pos_map.get(v_type, (center_x, center_y))
        v_label = v_type.value.upper() if show_labels else None
        built_view = _build_sheet_view_from_payload(
            shape=shape,
            view_type=v_type,
            payload=payload,
            center_x=v_center[0],
            center_y=v_center[1],
            scale=calculated_scale,
            show_hidden=v_hidden,
            view_label=v_label,
            style=iso_style if v_type == ViewType.ISOMETRIC else ViewStyle.WIREFRAME,
            shading_dpi=shading_dpi,
            color_by_part=color_by_part,
            part_colors=part_colors,
            ssao=ssao,
            gpu=gpu,
        )
        v_obj = sheet.add_view(built_view)
        if show_scale_label:
            v_obj.scale_label = scale_str
        layout_obj.views[v_type] = v_obj
        if v_type == ViewType.FRONT:
            layout_obj.front = v_obj
        elif v_type == ViewType.TOP:
            layout_obj.top = v_obj
        elif v_type == ViewType.RIGHT:
            layout_obj.right = v_obj
        elif v_type == ViewType.LEFT:
            layout_obj.left = v_obj
        elif v_type == ViewType.BOTTOM:
            layout_obj.bottom = v_obj
        elif v_type == ViewType.REAR:
            layout_obj.rear = v_obj
        elif v_type == ViewType.ISOMETRIC:
            layout_obj.isometric = v_obj

    if auto_dimensions:
        from build123d_techdraw.layout.auto_dimension import auto_dimension_views

        auto_dimension_views(
            sheet=sheet,
            shape=shape,
            views_map=layout_obj.views,
            infer_threads=infer_threads,
        )

    if auto_centerlines:
        # 1. Add centermarks to circular projected holes/bosses on 2D views
        for v_type, v_obj in layout_obj.views.items():
            if v_type == ViewType.ISOMETRIC:
                continue
            circles = v_obj._visible_circles
            if circles is None:
                look_from, look_up = VIEW_VECTORS.get(v_type, ((0.0, -1.0, 0.0), (0.0, 0.0, 1.0)))
                circles = []
                try:
                    dwg_v = Drawing(shape, look_from=look_from, look_up=look_up)
                    for edge in dwg_v.visible_lines.edges():
                        if edge.geom_type == bd.GeomType.CIRCLE:
                            c = edge.arc_center
                            circles.append((float(c.X), float(c.Y), float(edge.radius)))
                except Exception:
                    circles = []
            for cx, cy, radius in circles:
                paper_r = radius * v_obj.scale
                # Centermark arms extend 2.0 mm beyond circle perimeter per ISO 128 / ASME Y14.2
                cm_size = (paper_r + 2.0) * 2.0
                v_obj.centermark(cx, cy, size=cm_size)

        # 2. Add vertical centerlines to cylindrical features in Front and Right views
        try:
            cyl_faces = [f for f in shape.faces() if f.geom_type == bd.GeomType.CYLINDER]
            for f in cyl_faces:
                axis = f.axis_of_rotation
                if axis is None:
                    continue
                f_bb = f.bounding_box()
                if abs(axis.direction.Z) > 0.8:
                    if layout_obj.front is not None:
                        layout_obj.front.centerline_vertical(
                            model_x=float(axis.position.X),
                            model_y1=float(f_bb.min.Z),
                            model_y2=float(f_bb.max.Z),
                            overhang=4.0,
                        )
                    if layout_obj.right is not None:
                        layout_obj.right.centerline_vertical(
                            model_x=float(axis.position.Y),
                            model_y1=float(f_bb.min.Z),
                            model_y2=float(f_bb.max.Z),
                            overhang=4.0,
                        )
        except Exception:
            pass

    return layout_obj

generate_assembly_bom(assembly)

Generate structured BOM table entries by grouping and counting assembly components.

Parts are grouped by their label (or shape class name if unlabeled). Part number and material text come from PartInfo (see set_part_info); material falls back to the shape's build123d material.

Source code in src/build123d_techdraw/layout/multiview.py
def generate_assembly_bom(assembly: Shape[Any] | list[Shape[Any]]) -> list[BOMItem]:
    """Generate structured BOM table entries by grouping and counting assembly components.

    Parts are grouped by their `label` (or shape class name if unlabeled). Part number
    and material text come from `PartInfo` (see `set_part_info`); material falls back to
    the shape's build123d `material`.
    """
    components = assembly if isinstance(assembly, list) else extract_assembly_components(assembly)

    bom_items: list[BOMItem] = []
    for item_idx, (name, items) in enumerate(
        _group_components_by_label(components).items(), start=1
    ):
        first = items[0]
        info = get_part_info(first)
        bom_items.append(
            BOMItem(
                item_no=item_idx,
                qty=len(items),
                part_no=(info.part_no if info is not None else "") or f"PART-{item_idx:03d}",
                description=name,
                material=_bom_material(first),
            )
        )
    return bom_items

add_assembly_bom_and_balloons(sheet, assembly, target_view, balloon_distance=30.0, balloon_radius=4.5, balloon_terminator='dot')

Automatically populate sheet BOM items and place radiating balloon callouts on target view.

Parameters:

Name Type Description Default
sheet DrawingSheet

Target DrawingSheet.

required
assembly Compound

Compound assembly containing child components.

required
target_view SheetView

SheetView (typically Isometric or Front) to place balloon callouts on.

required
balloon_distance float

Radial offset in paper mm from the component center to the balloon circle.

30.0
balloon_radius float

Radius of the balloon circle in paper mm.

4.5
balloon_terminator str

Terminator type at target: 'dot' (inside body) or 'arrow' (on edge).

'dot'

Returns:

Type Description
tuple[list[BOMItem], list[BOMBalloon]]

Tuple of (bom_items, balloons) placed on the sheet.

Source code in src/build123d_techdraw/layout/multiview.py
def add_assembly_bom_and_balloons(
    sheet: DrawingSheet,
    assembly: bd.Compound,
    target_view: SheetView,
    balloon_distance: float = 30.0,
    balloon_radius: float = 4.5,
    balloon_terminator: str = "dot",
) -> tuple[list[BOMItem], list[BOMBalloon]]:
    """Automatically populate sheet BOM items and place radiating balloon callouts on target view.

    Args:
        sheet: Target `DrawingSheet`.
        assembly: `Compound` assembly containing child components.
        target_view: `SheetView` (typically Isometric or Front) to place balloon callouts on.
        balloon_distance: Radial offset in paper mm from the component center to the
            balloon circle.
        balloon_radius: Radius of the balloon circle in paper mm.
        balloon_terminator: Terminator type at target: `'dot'` (inside body) or
            `'arrow'` (on edge).

    Returns:
        Tuple of `(bom_items, balloons)` placed on the sheet.
    """
    components = extract_assembly_components(assembly)
    bom_items = generate_assembly_bom(assembly)
    sheet.bom_items = bom_items

    grouped = _group_components_by_label(components)

    balloons: list[BOMBalloon] = []
    num_items = len(bom_items)

    for idx, item in enumerate(bom_items):
        part_list = grouped.get(item.description, [])
        if not part_list:
            continue
        rep_part = part_list[0]

        # Point at the centre of mass; other shape kinds use their bounding-box centre.
        if isinstance(rep_part, (bd.Solid, bd.Compound)):
            pt = rep_part.center()
        else:
            pt = rep_part.bounding_box().center()
        target_pt = target_view.to_sheet_3d(float(pt.X), float(pt.Y), float(pt.Z))

        # Distribute balloons evenly around the perimeter of target_view
        angle = (2.0 * math.pi * idx) / max(num_items, 1)
        bx = target_pt[0] + math.cos(angle) * balloon_distance
        by = target_pt[1] + math.sin(angle) * balloon_distance

        balloon = sheet.add_balloon(
            item_no=item.item_no,
            target=target_pt,
            balloon_center=(bx, by),
            radius=balloon_radius,
            terminator=balloon_terminator,
        )
        balloons.append(balloon)

    return bom_items, balloons

build123d_techdraw.layout.auto_dimension

Smart collision-avoiding auto-dimension placement and canonical view de-duplication.

Implements ISO 129-1 / ASME Y14.5 dimension stacking (10 mm first offset from geometry contour, 7 mm step between parallel dimension lines) and assigns each recognized 3D feature to a single canonical orthographic view to prevent duplicate dimensions across views.

auto_dimension_sheet(sheet, shape=None, *, tolerance=None, infer_threads=False, use_sdf=False, gpu=None, sdf=None)

Automatically dimension all orthographic views currently placed on sheet.

Resolves shape from the first view with an attached 3D model when omitted. Set use_sdf=True to enable GPU/CPU Jump-Flooding SDF smart placement.

Source code in src/build123d_techdraw/layout/auto_dimension.py
def auto_dimension_sheet(
    sheet: DrawingSheet,
    shape: bd.Solid | bd.Compound | Any | None = None,
    *,
    tolerance: str | None = None,
    infer_threads: bool = False,
    use_sdf: bool = False,
    gpu: bool | None = None,
    sdf: SheetDistanceField | None = None,
) -> list[Annotation]:
    """Automatically dimension all orthographic views currently placed on ``sheet``.

    Resolves ``shape`` from the first view with an attached 3D model when omitted.
    Set ``use_sdf=True`` to enable GPU/CPU Jump-Flooding SDF smart placement.
    """
    views_map: dict[ViewType, SheetView] = {}
    resolved_shape = shape
    for view in sheet.views:
        if view.view_type not in views_map:
            views_map[view.view_type] = view
        if resolved_shape is None and view.shape is not None:
            resolved_shape = view.shape
    if resolved_shape is None or not views_map:
        return []
    return auto_dimension_views(
        sheet=sheet,
        shape=resolved_shape,
        views_map=views_map,
        tolerance=tolerance,
        infer_threads=infer_threads,
        use_sdf=use_sdf,
        gpu=gpu,
        sdf=sdf,
    )

auto_dimension_view(view, shape=None, tolerance=None, *, use_sdf=False, gpu=None, sdf=None)

Automatically dimension a single SheetView with collision-avoiding stacking.

Source code in src/build123d_techdraw/layout/auto_dimension.py
def auto_dimension_view(
    view: SheetView,
    shape: bd.Solid | bd.Compound | Any | None = None,
    tolerance: str | None = None,
    *,
    use_sdf: bool = False,
    gpu: bool | None = None,
    sdf: SheetDistanceField | None = None,
) -> list[Annotation]:
    """Automatically dimension a single SheetView with collision-avoiding stacking."""
    target_shape = shape if shape is not None else view.shape
    if target_shape is None or view.sheet is None:
        return []
    return auto_dimension_views(
        sheet=view.sheet,
        shape=target_shape,
        views_map={view.view_type: view},
        tolerance=tolerance,
        use_sdf=use_sdf,
        gpu=gpu,
        sdf=sdf,
    )

place_balloons_sdf(sheet, view, targets, *, gpu=None, radius_mm=4.0, terminator='dot', min_dist_mm=10.0, max_dist_mm=55.0, coord_space='sheet', sdf=None)

Place dense BOM balloons around complex or concave parts using a 2D SDF.

Parameters:

Name Type Description Default
sheet DrawingSheet

Target DrawingSheet.

required
view SheetView | None

Optional SheetView owning the targets (balloons are attached to it).

required
targets Sequence[tuple[int, tuple[float, float]]]

Sequence of (item_no, (x, y)) pairs in sheet mm (or model 2D mm when coord_space="model").

required
gpu bool | None

Optional GPU override (True / False / None auto).

None
radius_mm float

Balloon circle radius in paper millimetres (default 4.0).

4.0
terminator str

Leader terminator style ("dot" or "arrow").

'dot'
min_dist_mm float

Minimum leader reach from target to balloon center (mm).

10.0
max_dist_mm float

Maximum initial search reach from target to balloon center (mm).

55.0
coord_space Literal['sheet', 'model']

Coordinate system of target coordinates ("sheet" or "model").

'sheet'
sdf SheetDistanceField | None

Optional precomputed SheetDistanceField updated in place.

None

Returns:

Type Description
list[BOMBalloon]

List of placed BOMBalloon annotations in the same order as targets.

Source code in src/build123d_techdraw/layout/auto_dimension.py
def place_balloons_sdf(
    sheet: DrawingSheet,
    view: SheetView | None,
    targets: Sequence[tuple[int, tuple[float, float]]],
    *,
    gpu: bool | None = None,
    radius_mm: float = 4.0,
    terminator: str = "dot",
    min_dist_mm: float = 10.0,
    max_dist_mm: float = 55.0,
    coord_space: Literal["sheet", "model"] = "sheet",
    sdf: SheetDistanceField | None = None,
) -> list[BOMBalloon]:
    """Place dense BOM balloons around complex or concave parts using a 2D SDF.

    Args:
        sheet: Target `DrawingSheet`.
        view: Optional `SheetView` owning the targets (balloons are attached to it).
        targets: Sequence of `(item_no, (x, y))` pairs in sheet mm (or model 2D mm when
            `coord_space="model"`).
        gpu: Optional GPU override (`True` / `False` / `None` auto).
        radius_mm: Balloon circle radius in paper millimetres (default `4.0`).
        terminator: Leader terminator style (`"dot"` or `"arrow"`).
        min_dist_mm: Minimum leader reach from target to balloon center (mm).
        max_dist_mm: Maximum initial search reach from target to balloon center (mm).
        coord_space: Coordinate system of target coordinates (`"sheet"` or `"model"`).
        sdf: Optional precomputed `SheetDistanceField` updated in place.

    Returns:
        List of placed `BOMBalloon` annotations in the same order as `targets`.
    """
    if not targets:
        return []

    active_sdf = sdf if sdf is not None else compute_sheet_sdf(sheet, gpu=gpu)
    occupancy = SheetOccupancy(sheet)
    resolved: list[tuple[int, tuple[float, float]]] = [
        (int(item_no), _resolve_target_xy(xy, view, coord_space)) for item_no, xy in targets
    ]

    # Place tightest / most interior targets first so outer balloons don't steal their pockets.
    order = sorted(
        range(len(resolved)),
        key=lambda idx: (_local_ring_clearance(active_sdf, resolved[idx][1]), idx),
    )

    placed_by_idx: dict[int, BOMBalloon] = {}
    box_size = (2.0 * radius_mm, 2.0 * radius_mm)

    def _is_linter_clean_balloon(center_xy: tuple[float, float]) -> bool:
        bx, by = center_xy
        return _bbox_is_linter_clean(
            (bx - radius_mm, by - radius_mm, bx + radius_mm, by + radius_mm), occupancy
        )

    for idx in order:
        item_no, target_sheet = resolved[idx]
        center_xy = active_sdf.find_best_callout_position(
            target_sheet,
            box_size,
            min_dist_mm=min_dist_mm,
            max_dist_mm=max_dist_mm,
            avoid_leader_crossings=True,
            validator=_is_linter_clean_balloon,
        )
        balloon = sheet.add_balloon(
            item_no=item_no,
            target=target_sheet,
            balloon_center=center_xy,
            radius=radius_mm,
            terminator=terminator,
        )
        if view is not None:
            balloon.view = view
            if balloon not in view.annotations:
                view.annotations.append(balloon)

        occupancy.register(balloon)
        active_sdf.mark_occupied_box(balloon.bounding_box_2d(), pad_mm=1.5)
        active_sdf.register_leader_segment(target_sheet, center_xy)
        placed_by_idx[idx] = balloon

    return [placed_by_idx[i] for i in range(len(resolved))]

place_leaders_sdf(sheet, view, targets, *, gpu=None, shelf_length=None, terminator='arrow', font_size=2.8, min_dist_mm=12.0, max_dist_mm=65.0, coord_space='sheet', sdf=None)

Place multiple LeaderNote callouts cleanly using a 2D SDF with zero lint warnings.

Parameters:

Name Type Description Default
sheet DrawingSheet

Target DrawingSheet.

required
view SheetView | None

Optional SheetView owning the targets.

required
targets Sequence[tuple[tuple[float, float], str | Sequence[str]]]

Sequence of ((x, y), text_or_lines) pairs in sheet mm (or model 2D mm when coord_space="model").

required
gpu bool | None

Optional GPU override (True / False / None auto).

None
shelf_length float | None

Fixed horizontal shelf length (mm), or None to auto-size from text.

None
terminator str

Leader terminator style ("arrow" or "dot").

'arrow'
font_size float

Leader text height in paper mm (default 2.8).

2.8
min_dist_mm float

Minimum leader reach from target to elbow (mm).

12.0
max_dist_mm float

Maximum initial search reach from target to elbow (mm).

65.0
coord_space Literal['sheet', 'model']

Coordinate system of target coordinates ("sheet" or "model").

'sheet'
sdf SheetDistanceField | None

Optional precomputed SheetDistanceField updated in place.

None

Returns:

Type Description
list[LeaderNote]

List of placed LeaderNote annotations in the same order as targets.

Source code in src/build123d_techdraw/layout/auto_dimension.py
def place_leaders_sdf(
    sheet: DrawingSheet,
    view: SheetView | None,
    targets: Sequence[tuple[tuple[float, float], str | Sequence[str]]],
    *,
    gpu: bool | None = None,
    shelf_length: float | None = None,
    terminator: str = "arrow",
    font_size: float = 2.8,
    min_dist_mm: float = 12.0,
    max_dist_mm: float = 65.0,
    coord_space: Literal["sheet", "model"] = "sheet",
    sdf: SheetDistanceField | None = None,
) -> list[LeaderNote]:
    """Place multiple `LeaderNote` callouts cleanly using a 2D SDF with zero lint warnings.

    Args:
        sheet: Target `DrawingSheet`.
        view: Optional `SheetView` owning the targets.
        targets: Sequence of `((x, y), text_or_lines)` pairs in sheet mm (or model 2D mm
            when `coord_space="model"`).
        gpu: Optional GPU override (`True` / `False` / `None` auto).
        shelf_length: Fixed horizontal shelf length (mm), or `None` to auto-size from text.
        terminator: Leader terminator style (`"arrow"` or `"dot"`).
        font_size: Leader text height in paper mm (default `2.8`).
        min_dist_mm: Minimum leader reach from target to elbow (mm).
        max_dist_mm: Maximum initial search reach from target to elbow (mm).
        coord_space: Coordinate system of target coordinates (`"sheet"` or `"model"`).
        sdf: Optional precomputed `SheetDistanceField` updated in place.

    Returns:
        List of placed `LeaderNote` annotations in the same order as `targets`.
    """
    if not targets:
        return []

    active_sdf = sdf if sdf is not None else compute_sheet_sdf(sheet, gpu=gpu)
    occupancy = SheetOccupancy(sheet)

    resolved: list[tuple[tuple[float, float], list[str]]] = []
    for raw_xy, raw_text in targets:
        lines = [raw_text] if isinstance(raw_text, str) else [str(s) for s in raw_text]
        resolved.append((_resolve_target_xy(raw_xy, view, coord_space), lines))

    order = sorted(
        range(len(resolved)),
        key=lambda idx: (_local_ring_clearance(active_sdf, resolved[idx][0]), idx),
    )

    placed_by_idx: dict[int, LeaderNote] = {}
    remaining = set(order)

    for idx in order:
        remaining.discard(idx)
        target_sheet, lines = resolved[idx]
        max_chars = max((len(line) for line in lines), default=6)
        eff_shelf = (
            float(shelf_length)
            if shelf_length is not None
            else max(18.0, max_chars * (font_size * 0.62) + 4.5)
        )
        text_h = max(8.0, 3.4 * len(lines) + 3.0)
        peer_boxes = _peer_target_boxes(target_sheet, [resolved[j][0] for j in remaining])

        def _validate_leader(
            off: tuple[float, float],
            *,
            ts: tuple[float, float] = target_sheet,
            sl: float = eff_shelf,
            pb: list[BBox2D] = peer_boxes,
        ) -> bool:
            return _is_linter_clean_leader(ts, off, sl, occupancy, pb)

        elbow_offset = active_sdf.find_best_leader_elbow(
            target_sheet,
            shelf_length_mm=eff_shelf,
            text_height_mm=text_h,
            min_dist_mm=min_dist_mm,
            max_dist_mm=max_dist_mm,
            avoid_leader_crossings=True,
            validator=_validate_leader,
        )

        note = sheet.add_leader_note(
            target=target_sheet,
            lines=lines,
            elbow_offset=elbow_offset,
            shelf_length=eff_shelf,
            terminator=terminator,
        )
        note.font_size = font_size
        if view is not None:
            note.view = view
            if note not in view.annotations:
                view.annotations.append(note)

        occupancy.register(note)
        shelf_box = _leader_shelf_bbox(target_sheet, elbow_offset, eff_shelf, text_height_mm=text_h)
        active_sdf.mark_occupied_box(shelf_box, pad_mm=1.5)
        active_sdf.register_leader_segment(
            target_sheet,
            (target_sheet[0] + elbow_offset[0], target_sheet[1] + elbow_offset[1]),
        )
        placed_by_idx[idx] = note

    return [placed_by_idx[i] for i in range(len(resolved))]

build123d_techdraw.layout.sheet_metal

Sheet metal flat-pattern layout solver and automated blank/bend dimensioning.

SheetMetalLayout dataclass

Bases: SheetDirective

Container returned by add_sheet_metal_views holding the flat pattern, views, and tables.

Source code in src/build123d_techdraw/layout/sheet_metal.py
@dataclass
class SheetMetalLayout(SheetDirective):
    """Container returned by ``add_sheet_metal_views`` holding the flat pattern, views, and tables."""

    scale: float
    scale_str: str
    sheet: DrawingSheet
    flat_view: SheetView
    flat_pattern: FlatPattern
    iso_view: SheetView | None = None
    bend_table: BendTable | None = None
    punch_table: PunchTable | None = None
    views: dict[str, SheetView] = field(default_factory=dict)

    def _apply_to_sheet(self, sheet: DrawingSheet) -> None:
        for v in self.views.values():
            sheet.add_view(v)
        for tbl in (self.bend_table, self.punch_table):
            if tbl is not None and tbl not in sheet.annotations:
                sheet.annotations.append(tbl)
                tbl.sheet = sheet
        sheet.title_info.scale = self.scale_str

    def auto_dimension(
        self,
        *,
        include_overall: bool = True,
        include_bend_stations: bool = True,
        include_punch_dims: bool = False,
        tolerance: str | None = None,
    ) -> list[Annotation]:
        """Auto-dimension the flat pattern view with overall blank and bend-station dims."""
        return auto_dimension_flat_pattern_view(
            self.flat_view,
            flat_pattern=self.flat_pattern,
            include_overall=include_overall,
            include_bend_stations=include_bend_stations,
            include_punch_dims=include_punch_dims,
            tolerance=tolerance,
        )

auto_dimension(*, include_overall=True, include_bend_stations=True, include_punch_dims=False, tolerance=None)

Auto-dimension the flat pattern view with overall blank and bend-station dims.

Source code in src/build123d_techdraw/layout/sheet_metal.py
def auto_dimension(
    self,
    *,
    include_overall: bool = True,
    include_bend_stations: bool = True,
    include_punch_dims: bool = False,
    tolerance: str | None = None,
) -> list[Annotation]:
    """Auto-dimension the flat pattern view with overall blank and bend-station dims."""
    return auto_dimension_flat_pattern_view(
        self.flat_view,
        flat_pattern=self.flat_pattern,
        include_overall=include_overall,
        include_bend_stations=include_bend_stations,
        include_punch_dims=include_punch_dims,
        tolerance=tolerance,
    )

add_sheet_metal_views(sheet, shape, *, k_factor='din6935', thickness=None, base_face=None, scale='auto', enforce_iso_scale=True, include_formed_iso=True, include_bend_annotations=True, include_bend_extents=False, include_bend_table=True, include_punch_markers=True, include_punch_table=True, punch_table_grouped=True, auto_dimensions=True, label_mode='auto', flat_view_label='FLAT PATTERN', iso_view_label='FORMED ISOMETRIC', tolerance=None)

Create a complete sheet metal drawing layout (flat pattern, 3D iso, bend & punch schedules).

Source code in src/build123d_techdraw/layout/sheet_metal.py
def add_sheet_metal_views(
    sheet: DrawingSheet,
    shape: Any,
    *,
    k_factor: float | str = "din6935",
    thickness: float | None = None,
    base_face: bd.Face | None = None,
    scale: float | str = "auto",
    enforce_iso_scale: bool = True,
    include_formed_iso: bool = True,
    include_bend_annotations: bool = True,
    include_bend_extents: bool = False,
    include_bend_table: bool = True,
    include_punch_markers: bool = True,
    include_punch_table: bool = True,
    punch_table_grouped: bool = True,
    auto_dimensions: bool = True,
    label_mode: Literal["auto", "inline", "leader"] = "auto",
    flat_view_label: str = "FLAT PATTERN",
    iso_view_label: str = "FORMED ISOMETRIC",
    tolerance: str | None = None,
) -> SheetMetalLayout:
    """Create a complete sheet metal drawing layout (flat pattern, 3D iso, bend & punch schedules)."""
    if isinstance(shape, FlatPattern):
        fp = shape
        source_3d = fp.source_shape
    else:
        fp = unfold_sheet_metal(
            shape,
            k_factor=k_factor,
            thickness=thickness,
            base_face=base_face,
        )
        source_3d = shape

    w_sheet = sheet.width_mm
    h_sheet = sheet.height_mm
    margin_l = sheet.left_margin
    margin_r = sheet.right_margin
    margin_t = sheet.top_margin
    margin_b = sheet.bottom_margin

    tb_bbox = (
        get_title_block_bbox(sheet)
        if sheet.show_title_block
        else (
            w_sheet - margin_r,
            h_sheet - margin_b,
            w_sheet - margin_r,
            h_sheet - margin_b,
        )
    )
    tb_top_y = tb_bbox[1]
    rev_h = (
        (4.2 + len(sheet.revision_rows) * 4.2 + 4.0)
        if (sheet.show_title_block and sheet.revision_rows)
        else 0.0
    )
    right_col_top_y = margin_t + rev_h + 2.0

    notes_bb = _notes_bbox(sheet)
    notes_top_y = notes_bb[1] - 4.0 if notes_bb is not None else (h_sheet - margin_b - 6.0)

    # Pre-construct schedules to know exact table dimensions for non-overlapping placement
    bend_table: BendTable | None = (
        BendTable(fp, position=(0.0, 0.0), sheet=sheet) if include_bend_table else None
    )
    punch_table: PunchTable | None = (
        PunchTable(fp, position=(0.0, 0.0), grouped=punch_table_grouped, sheet=sheet)
        if (include_punch_table and fp.punches)
        else None
    )

    right_col_w = 0.0
    if bend_table is not None:
        right_col_w = max(right_col_w, bend_table.width)
    if punch_table is not None:
        right_col_w = max(right_col_w, punch_table.width)
    if include_formed_iso and source_3d is not None:
        right_col_w = max(right_col_w, 95.0)

    right_edge = w_sheet - margin_r - 2.0
    left_zone_max_x = (
        (right_edge - right_col_w - 14.0) if right_col_w > 0.0 else (w_sheet - margin_r - 24.0)
    )
    left_zone_min_x = margin_l + 24.0
    left_zone_min_y = margin_t + 22.0
    left_zone_max_y = min(notes_top_y - 16.0, h_sheet - margin_b - 28.0)

    avail_w = max(40.0, left_zone_max_x - left_zone_min_x)
    avail_h = max(40.0, left_zone_max_y - left_zone_min_y)

    if isinstance(scale, str) and scale.lower() == "auto":
        eff_scale = calculate_auto_scale(
            (max(fp.blank_width, 1.0), max(fp.blank_height, 1.0)),
            (avail_w, avail_h),
            margin_factor=0.82,
            enforce_iso_scale=enforce_iso_scale,
        )
    else:
        raw_scale = float(scale)
        eff_scale = find_closest_iso_scale(raw_scale) if enforce_iso_scale else raw_scale

    flat_cx = 0.5 * (left_zone_min_x + left_zone_max_x)
    flat_cy = 0.5 * (left_zone_min_y + left_zone_max_y)

    flat_view = project_flat_pattern_to_view(
        fp,
        center_x=flat_cx,
        center_y=flat_cy,
        scale=eff_scale,
        k_factor=k_factor,
        thickness=fp.thickness,
        base_face=base_face,
        view_label=flat_view_label,
    )
    sheet.add_view(flat_view)

    # Place right-column schedules cleanly above title block
    curr_bottom_y = tb_top_y - 3.0
    if bend_table is not None:
        bt_x = right_edge - bend_table.width
        bt_y = curr_bottom_y - bend_table.height
        bend_table.position = (bt_x, bt_y)
        sheet.add(bend_table)
        curr_bottom_y = bt_y - 4.0

    iso_zone_bottom_y = curr_bottom_y
    if punch_table is not None:
        pt_x = right_edge - punch_table.width
        pt_y = curr_bottom_y - punch_table.height
        # If placing punch_table above bend_table leaves too little space for iso_view, try left of bend_table
        if (
            include_formed_iso
            and source_3d is not None
            and bend_table is not None
            and (pt_y - right_col_top_y) < 58.0
            and (right_edge - bend_table.width - 4.0 - punch_table.width)
            > max(flat_view.max_x + 12.0, notes_bb[2] + 4.0 if notes_bb else 0.0)
        ):
            pt_x = right_edge - bend_table.width - 4.0 - punch_table.width
            pt_y = tb_top_y - 3.0 - punch_table.height
        else:
            iso_zone_bottom_y = pt_y - 4.0
        punch_table.position = (pt_x, pt_y)
        sheet.add(punch_table)

    iso_view: SheetView | None = None
    if include_formed_iso and source_3d is not None and source_3d is not fp.shape_2d:
        iso_left_x = max(flat_view.max_x + 14.0, right_edge - max(right_col_w, 138.0))
        iso_avail_w = max(30.0, right_edge - iso_left_x)
        iso_avail_h = max(30.0, iso_zone_bottom_y - right_col_top_y - 12.0)
        probe_iso = project_shape_to_view(
            source_3d,
            ViewType.ISOMETRIC,
            0.0,
            0.0,
            scale=1.0,
            show_hidden=False,
        )
        iso_scale = calculate_auto_scale(
            (max(probe_iso.width, 1.0), max(probe_iso.height, 1.0)),
            (iso_avail_w, iso_avail_h),
            margin_factor=0.86,
            enforce_iso_scale=enforce_iso_scale,
        )
        iso_cx = 0.5 * (iso_left_x + right_edge)
        iso_cy = 0.5 * (right_col_top_y + iso_zone_bottom_y - 10.0)
        iso_view = project_shape_to_view(
            source_3d,
            ViewType.ISOMETRIC,
            center_x=iso_cx,
            center_y=iso_cy,
            scale=iso_scale,
            show_hidden=False,
            view_label=iso_view_label,
        )
        sheet.add_view(iso_view)

    # Update title block scale
    scale_str = format_iso_ratio(eff_scale)
    sheet.title_info.scale = scale_str

    # Annotate punches first so bend leader placement sees punch tags in SheetOccupancy
    if include_punch_markers and fp.punches:
        flat_view.add_punch_markers(show_tag=True, show_callout=False)

    if include_bend_annotations and fp.bends:
        occupancy = SheetOccupancy(sheet)
        if notes_bb is not None:
            occupancy.ann_bboxes.append(notes_bb)
        for bend in fp.bends:
            b_ann = BendLineAnnotation(
                bend,
                show_bend_extents=include_bend_extents,
                label_mode=label_mode,
                view=flat_view,
            )
            _, _, _, _, eff_mode, _, _ = b_ann._resolved_geometry()
            if eff_mode == "leader" and b_ann.leader_offset is None:
                b_ann.leader_offset = _choose_bend_leader_offset(flat_view, b_ann, occupancy)
            occupancy.register(b_ann)

    if auto_dimensions:
        auto_dimension_flat_pattern_view(
            flat_view,
            flat_pattern=fp,
            include_overall=True,
            include_bend_stations=True,
            include_punch_dims=False,
            tolerance=tolerance,
        )

    views_dict: dict[str, SheetView] = {"flat": flat_view}
    if iso_view is not None:
        views_dict["iso"] = iso_view

    return SheetMetalLayout(
        scale=eff_scale,
        scale_str=scale_str,
        sheet=sheet,
        flat_view=flat_view,
        flat_pattern=fp,
        iso_view=iso_view,
        bend_table=bend_table,
        punch_table=punch_table,
        views=views_dict,
    )

auto_dimension_flat_pattern_view(view, *, flat_pattern=None, include_overall=True, include_bend_stations=True, include_punch_dims=False, tolerance=None)

Place collision-free bend-station and overall blank dimensions on a flat pattern view.

Source code in src/build123d_techdraw/layout/sheet_metal.py
def auto_dimension_flat_pattern_view(
    view: SheetView,
    *,
    flat_pattern: FlatPattern | None = None,
    include_overall: bool = True,
    include_bend_stations: bool = True,
    include_punch_dims: bool = False,
    tolerance: str | None = None,
) -> list[Annotation]:
    """Place collision-free bend-station and overall blank dimensions on a flat pattern view."""
    fp = flat_pattern or view.flat_pattern
    if fp is None or view.sheet is None:
        return []

    sheet = view.sheet
    occupancy = SheetOccupancy(sheet)
    notes_bb = _notes_bbox(sheet)
    if notes_bb is not None:
        occupancy.ann_bboxes.append(notes_bb)

    planned: list[PlannedLinearDim] = []
    w_model = fp.blank_width
    h_model = fp.blank_height

    if include_bend_stations and fp.bends:
        # Vertical bends (running roughly along Y) -> measure X station from left datum x=0
        x_stations: list[float] = []
        # Horizontal bends (running roughly along X) -> measure Y station from bottom datum y=0
        y_stations: list[float] = []
        for b in fp.bends:
            dx = abs(b.end_2d[0] - b.start_2d[0])
            dy = abs(b.end_2d[1] - b.start_2d[1])
            mx, my = b.midpoint_2d
            if (
                dx <= 0.5
                and dy > 1.0
                and 1.0 < mx < w_model - 1.0
                and not any(abs(mx - xs) < 0.5 for xs in x_stations)
            ):
                x_stations.append(mx)
            elif (
                dy <= 0.5
                and dx > 1.0
                and 1.0 < my < h_model - 1.0
                and not any(abs(my - ys) < 0.5 for ys in y_stations)
            ):
                y_stations.append(my)

        x_stations.sort()
        y_stations.sort()

        x0_s = view.to_sheet_x(0.0)
        for xs in x_stations:
            planned.append(
                PlannedLinearDim(
                    view=view,
                    orientation="horizontal",
                    p1_sheet=x0_s,
                    p2_sheet=view.to_sheet_x(xs),
                    span_mm=xs,
                    tolerance=tolerance,
                    preferred_side="top",
                )
            )

        y0_s = view.to_sheet_y(0.0)
        for ys in y_stations:
            planned.append(
                PlannedLinearDim(
                    view=view,
                    orientation="vertical",
                    p1_sheet=view.to_sheet_y(ys),
                    p2_sheet=y0_s,
                    span_mm=ys,
                    tolerance=tolerance,
                    preferred_side="left",
                )
            )

    if include_punch_dims and fp.punches:
        x0_s = view.to_sheet_x(0.0)
        y0_s = view.to_sheet_y(0.0)
        for p in fp.punches[:4]:
            px, py = p.center_2d
            if 1.0 < px < w_model - 1.0:
                planned.append(
                    PlannedLinearDim(
                        view=view,
                        orientation="horizontal",
                        p1_sheet=x0_s,
                        p2_sheet=view.to_sheet_x(px),
                        span_mm=px,
                        preferred_side="bottom",
                    )
                )
            if 1.0 < py < h_model - 1.0:
                planned.append(
                    PlannedLinearDim(
                        view=view,
                        orientation="vertical",
                        p1_sheet=view.to_sheet_y(py),
                        p2_sheet=y0_s,
                        span_mm=py,
                        preferred_side="right",
                    )
                )

    if include_overall and w_model > 1e-3 and h_model > 1e-3:
        planned.append(
            PlannedLinearDim(
                view=view,
                orientation="horizontal",
                p1_sheet=view.min_x,
                p2_sheet=view.max_x,
                span_mm=w_model,
                tolerance=tolerance,
                preferred_side="top",
            )
        )
        planned.append(
            PlannedLinearDim(
                view=view,
                orientation="vertical",
                p1_sheet=view.min_y,
                p2_sheet=view.max_y,
                span_mm=h_model,
                tolerance=tolerance,
                preferred_side="left",
            )
        )

    dims: list[LinearDimension] = _place_stacked_linear_dims(planned, occupancy, sheet.views)
    for dim in dims:
        paper_span = (
            abs(dim.end[0] - dim.start[0])
            if dim.dim_type == DimensionType.HORIZONTAL
            else abs(dim.end[1] - dim.start[1])
        )
        model_val = paper_span / view.scale if view.scale else paper_span
        dim.nominal = model_val
        dim.text = format_dimension_value(model_val)
    return list(dims)