Skip to content

Annotations API

build123d_techdraw.annotations.base

Common base class for every annotation placed on a SheetView or DrawingSheet.

Annotation

Bases: ABC

Paper-space annotation rendered on top of a drawing sheet.

Subclasses implement to_svg and usually override _attach_to_view to resolve anchors against the view before calling _register. Annotations that bind to 3D topology override _rebind_to_view so SheetView.update_shape can re-resolve them, and every annotation the linter should see overrides bounding_box_2d.

Source code in src/build123d_techdraw/annotations/base.py
class Annotation(ABC):
    """Paper-space annotation rendered on top of a drawing sheet.

    Subclasses implement `to_svg` and usually override `_attach_to_view` to resolve
    anchors against the view before calling `_register`. Annotations that bind to 3D
    topology override `_rebind_to_view` so `SheetView.update_shape` can re-resolve them,
    and every annotation the linter should see overrides `bounding_box_2d`.
    """

    view: SheetView | None = None
    anchor_stale: bool = False
    stale_reason: str | None = None

    @abstractmethod
    def to_svg(self) -> str:
        """Render the annotation as an SVG fragment in sheet (paper mm) coordinates."""

    def bounding_box_2d(self) -> BBox2D | None:
        """Approximate paper-space bounds for the sheet linter, or ``None`` if not tracked."""
        return None

    def _attach_to_view(self, view: SheetView) -> None:
        """Bind to ``view`` (resolving anchors where applicable) and register on it."""
        self.view = view
        self._register(view)

    def _rebind_to_view(self, view: SheetView) -> None:  # noqa: ARG002
        """Re-resolve against ``view`` after its shape changed. No-op for unanchored annotations."""
        return

    def _attach_to_sheet(self, sheet: DrawingSheet) -> None:  # noqa: ARG002
        """Hook called when the annotation is added to ``sheet``'s annotation list."""
        return

    def _register(self, view: SheetView) -> None:
        """Append to ``view.annotations`` and to the owning (or current) sheet's annotations."""
        if self not in view.annotations:
            view.annotations.append(self)
        sheet = view.sheet or CURRENT_SHEET.get()
        if sheet is not None and self not in sheet.annotations:
            sheet.annotations.append(self)
            self._attach_to_sheet(sheet)

to_svg() abstractmethod

Render the annotation as an SVG fragment in sheet (paper mm) coordinates.

Source code in src/build123d_techdraw/annotations/base.py
@abstractmethod
def to_svg(self) -> str:
    """Render the annotation as an SVG fragment in sheet (paper mm) coordinates."""

bounding_box_2d()

Approximate paper-space bounds for the sheet linter, or None if not tracked.

Source code in src/build123d_techdraw/annotations/base.py
def bounding_box_2d(self) -> BBox2D | None:
    """Approximate paper-space bounds for the sheet linter, or ``None`` if not tracked."""
    return None

build123d_techdraw.annotations.dimensions

ISO 129 compliant engineering dimensioning in true 2D paper space.

DimensionType

Bases: Enum

Source code in src/build123d_techdraw/annotations/dimensions.py
class DimensionType(Enum):
    HORIZONTAL = "horizontal"
    VERTICAL = "vertical"
    ALIGNED = "aligned"
    RADIAL = "radial"
    DIAMETER = "diameter"
    HALF_DIAMETER = "half_diameter"
    ANGULAR = "angular"
    ORDINATE = "ordinate"

LinearDimension

Bases: Annotation

Linear dimension (Horizontal, Vertical, or Aligned) in true 2D paper space.

Source code in src/build123d_techdraw/annotations/dimensions.py
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
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
class LinearDimension(Annotation):
    """Linear dimension (Horizontal, Vertical, or Aligned) in true 2D paper space."""

    def __init__(
        self,
        target_or_start: Any = None,
        target2_or_end: Any = None,
        offset: float = 8.0,
        dim_type: DimensionType | str = DimensionType.ALIGNED,
        text: str | None = None,
        tolerance: str | Tolerance | None = None,
        prefix: str = "",
        suffix: str = "",
        font_size: float = 3.2,
        arrow_size: float = 2.5,
        start: tuple[float, float] | None = None,
        end: tuple[float, float] | None = None,
        direction: str | None = None,
        nominal: float | None = None,
        view: SheetView | None = None,
        *,
        anchor: Any = None,
        anchor1: Any = None,
        anchor2: Any = None,
    ):
        if target_or_start is None:
            target_or_start = anchor1 if anchor1 is not None else anchor
        if target2_or_end is None and anchor2 is not None:
            target2_or_end = anchor2

        self.offset = offset
        self.requested_offset = offset
        self.dim_type = (
            dim_type if isinstance(dim_type, DimensionType) else DimensionType(dim_type.lower())
        )
        self.nominal = nominal
        self._explicit_text = text is not None or nominal is not None
        self._last_auto_text: str | None = None
        if text is None and nominal is not None:
            self.text: str | None = format_dimension_value(float(nominal))
        else:
            self.text = text
        self.tolerance = str(tolerance) if tolerance is not None else None
        self.prefix = prefix
        self.suffix = suffix
        self.font_size = font_size
        self.arrow_size = arrow_size
        self.direction = direction
        self.view = view
        self.target: Any = None
        self.target2: Any = None
        self.resolved = False
        self._explicit_coords = False
        self.has_break = False
        self.anchor_stale = False
        self.stale_reason: str | None = None

        if start is not None and end is not None:
            self.start = (float(start[0]), float(start[1]))
            self.end = (float(end[0]), float(end[1]))
            self.resolved = True
            self._explicit_coords = True
        elif (
            target_or_start is not None
            and target2_or_end is not None
            and not is_topological_entity(target_or_start)
            and not is_topological_entity(target2_or_end)
            and isinstance(target_or_start, (tuple, list))
            and isinstance(target2_or_end, (tuple, list))
        ):
            self.start = (float(target_or_start[0]), float(target_or_start[1]))
            self.end = (float(target2_or_end[0]), float(target2_or_end[1]))
            self.resolved = True
            self._explicit_coords = True
        else:
            self.start = (0.0, 0.0)
            self.end = (0.0, 0.0)
            self.target = target_or_start
            self.target2 = target2_or_end

        target_view = view or CURRENT_VIEW.get()
        if target_view is not None:
            self._attach_to_view(target_view)
        else:
            target_sheet = CURRENT_SHEET.get()
            if target_sheet is not None and self not in target_sheet.annotations:
                target_sheet.annotations.append(self)

    def _rebind_to_view(self, view: SheetView) -> None:
        """Re-resolve semantic anchors or topological entities against an updated view."""
        if not self._explicit_coords:
            self.resolved = False
            if not self._explicit_text:
                self._last_auto_text = self.text
                self.text = None
            self._attach_to_view(view)

    def _attach_to_view(self, view: SheetView) -> None:
        self.view = view
        if self.direction:
            d_str = self.direction.lower()
            if d_str == "horizontal":
                self.dim_type = DimensionType.HORIZONTAL
            elif d_str == "vertical":
                self.dim_type = DimensionType.VERTICAL
            elif d_str == "aligned":
                self.dim_type = DimensionType.ALIGNED

        if not self.resolved and self.target is not None:
            from build123d_techdraw.annotations.resolver import resolve_edge_to_sheet

            v_shape = view.shape
            self.target = ensure_anchor(self.target, v_shape) or self.target
            self.target2 = ensure_anchor(self.target2, v_shape) or self.target2

            prev_start = self.start
            prev_end = self.end
            prev_text = self._last_auto_text

            if self.target2 is None:
                has_prev = prev_start != (0.0, 0.0) or prev_end != (0.0, 0.0)
                edge_len: float | None
                unresolved_reason: str | None = None
                try:
                    s0, s1, edge_len = resolve_edge_to_sheet(self.target, view)
                except TypeError as exc:
                    # A single target must resolve to an edge. Never invent a second
                    # point (e.g. the view centre): keep the last good geometry if the
                    # anchor went stale, otherwise leave the dimension unresolved.
                    s0, s1, edge_len = prev_start, prev_end, None
                    unresolved_reason = str(exc)

                stale_anchor = (
                    self.target
                    if isinstance(self.target, Anchor) and self.target.is_stale
                    else None
                )
                stale = stale_anchor is not None
                if stale_anchor is not None:
                    self.anchor_stale = True
                    self.stale_reason = stale_anchor.stale_reason
                    if prev_text is not None and not self._explicit_text:
                        self.text = prev_text
                else:
                    self.anchor_stale = False
                    self.stale_reason = None

                if edge_len is None and not (stale and has_prev):
                    self.stale_reason = (
                        self.stale_reason
                        or "Single-target linear dimension requires an edge; "
                        f"target did not resolve to one ({unresolved_reason})."
                    )
                    if not stale:
                        warnings.warn(
                            f"LinearDimension target {type(self.target).__name__} does not "
                            "resolve to an edge; the dimension is left unresolved. Pass an "
                            "edge, or two points/vertices to measure between.",
                            UserWarning,
                            stacklevel=3,
                        )
                    self._register(view)
                    return

                self.start = s0
                self.end = s1
                if self.text is None and edge_len is not None:
                    self.text = format_dimension_value(edge_len)
                dx = abs(s1[0] - s0[0])
                dy = abs(s1[1] - s0[1])
                if self.dim_type == DimensionType.ALIGNED and self.direction is None:
                    if dy < 1e-2:
                        self.dim_type = DimensionType.HORIZONTAL
                    elif dx < 1e-2:
                        self.dim_type = DimensionType.VERTICAL
            else:
                p0_3d = resolve_point_3d(self.target, view)
                p1_3d = resolve_point_3d(self.target2, view)
                # Reuse the resolved 3D points; only 2D tuples need resolve_point_to_sheet
                s0 = (
                    view.to_sheet_3d(*p0_3d)
                    if p0_3d is not None
                    else resolve_point_to_sheet(self.target, view)
                )
                s1 = (
                    view.to_sheet_3d(*p1_3d)
                    if p1_3d is not None
                    else resolve_point_to_sheet(self.target2, view)
                )

                stale1 = isinstance(self.target, Anchor) and self.target.is_stale
                stale2 = isinstance(self.target2, Anchor) and self.target2.is_stale
                if stale1 or stale2:
                    self.anchor_stale = True
                    self.stale_reason = stale_reason_of(self.target, self.target2)
                    s0 = stale_point_to_sheet(self.target, view) or s0
                    s1 = stale_point_to_sheet(self.target2, view) or s1
                    if prev_text is not None and not self._explicit_text:
                        self.text = prev_text
                else:
                    self.anchor_stale = False
                    self.stale_reason = None

                self.start = s0
                self.end = s1
                if self.text is None:
                    if self.dim_type in (DimensionType.HORIZONTAL, DimensionType.VERTICAL):
                        horizontal = self.dim_type == DimensionType.HORIZONTAL
                        if p0_3d is not None and p1_3d is not None:
                            # Measure in model space along the view's projection axis so
                            # breaks (which shorten the paper span) do not leak in.
                            model_dist = _view_axis_delta(view, p0_3d, p1_3d, horizontal)
                        else:
                            paper_span = abs(s1[0] - s0[0]) if horizontal else abs(s1[1] - s0[1])
                            model_dist = paper_span / view.scale if view.scale else paper_span
                    elif p0_3d is not None and p1_3d is not None:
                        model_dist = math.dist(p0_3d, p1_3d)
                    else:
                        paper_dist = math.hypot(s1[0] - s0[0], s1[1] - s0[1])
                        model_dist = paper_dist / view.scale if view.scale else paper_dist
                    self.text = format_dimension_value(float(model_dist))
            self.resolved = True
        elif not self.resolved and self.target is None:
            unbroken_w = view.unbroken_width
            unbroken_h = view.unbroken_height
            if self.dim_type == DimensionType.VERTICAL:
                x_ref = view.min_x if self.offset < 0 else view.max_x
                self.start = (x_ref, view.min_y)
                self.end = (x_ref, view.max_y)
                if self.text is None:
                    model_h = unbroken_h / view.scale if view.scale else unbroken_h
                    if self.nominal is None:
                        self.nominal = float(model_h)
                    self.text = format_dimension_value(float(model_h))
            else:
                self.dim_type = DimensionType.HORIZONTAL
                y_ref = view.min_y if self.offset < 0 else view.max_y
                self.start = (view.min_x, y_ref)
                self.end = (view.max_x, y_ref)
                if self.text is None:
                    model_w = unbroken_w / view.scale if view.scale else view.width
                    if self.nominal is None:
                        self.nominal = float(model_w)
                    self.text = format_dimension_value(float(model_w))
                if self.offset > 0:
                    view.bottom_annotation_y = max(
                        view.bottom_annotation_y, y_ref + self.offset + 4.0
                    )
            self.resolved = True

        if self.resolved:
            self._update_break_flag(view)
            self._keep_clear_of_view(view)
        self._register(view)

    def _update_break_flag(self, view: SheetView) -> None:
        """Flag a horizontal/vertical dimension whose span crosses a break of ``view``."""
        if self.dim_type == DimensionType.HORIZONTAL:
            lo, hi = sorted((self.start[0], self.end[0]))
            gaps = view.break_gap_centers("X")
        elif self.dim_type == DimensionType.VERTICAL:
            lo, hi = sorted((self.start[1], self.end[1]))
            gaps = view.break_gap_centers("Y")
        else:
            self.has_break = False
            return
        self.has_break = any(lo < g < hi for g in gaps)

    def _text_band(self, line_pos: float) -> tuple[float, float]:
        """Extent of dimension line + text perpendicular to the line, for a line at ``line_pos``.

        Text sits above a horizontal dimension line and, rotated counter-clockwise, to the left
        of a vertical one, so the band always extends towards smaller paper coordinates.
        """
        return (line_pos - 1.4 - self.font_size, line_pos)

    def _line_geometry(self) -> tuple[float, float, float, float] | None:
        """``(base, line, span_lo, span_hi)`` across/along the line for H/V dimensions."""
        x1, y1 = self.start
        x2, y2 = self.end
        if self.dim_type == DimensionType.VERTICAL:
            base = (x1 + x2) / 2.0
            return (base, base + self.offset, min(y1, y2), max(y1, y2))
        if self.dim_type == DimensionType.HORIZONTAL:
            base = (y1 + y2) / 2.0
            return (base, base + self.offset, min(x1, x2), max(x1, x2))
        return None

    def _keep_clear_of_view(self, view: SheetView) -> None:
        """Push a dimension line that lands on or inside the view outline out of the view.

        ISO 129-1 places dimension lines outside the outline where possible. When the requested
        offset puts the line or its text on/inside the view's outline, the line is moved to the
        first free row beyond the outline on the requested side: ``FIRST_DIM_OFFSET_MM`` from
        the outline, then every ``DIM_STACK_STEP_MM`` past rows already taken by parallel
        dimensions of the view. Dimensions already outside the outline keep their offset.
        """
        from build123d_techdraw.layout.auto_dimension import (
            DIM_STACK_STEP_MM,
            FIRST_DIM_OFFSET_MM,
        )

        self.offset = self.requested_offset
        geom = self._line_geometry()
        if geom is None:
            return
        base, line, span_lo, span_hi = geom
        vertical = self.dim_type == DimensionType.VERTICAL
        along_lo, along_hi = (view.min_y, view.max_y) if vertical else (view.min_x, view.max_x)
        across_lo, across_hi = (view.min_x, view.max_x) if vertical else (view.min_y, view.max_y)
        if span_hi <= along_lo or span_lo >= along_hi:
            return
        touch = 1.0
        band = self._text_band(line)
        if band[1] <= across_lo - touch or band[0] >= across_hi + touch:
            return

        side = -1.0 if self.requested_offset < 0 else 1.0
        edge = across_lo if side < 0 else across_hi
        taken: list[tuple[float, float]] = []
        for ann in view.annotations:
            if ann is self or not isinstance(ann, LinearDimension):
                continue
            if ann.dim_type != self.dim_type or not ann.resolved:
                continue
            other = ann._line_geometry()
            if other is None or other[3] <= span_lo or other[2] >= span_hi:
                continue
            taken.append(ann._text_band(other[1]))
        target = edge + side * FIRST_DIM_OFFSET_MM
        for _ in range(20):
            lo, hi = self._text_band(target)
            if not any(lo < t_hi + touch and t_lo - touch < hi for t_lo, t_hi in taken):
                break
            target += side * DIM_STACK_STEP_MM
        self.offset = target - base

    def _jog_positions(self, lo: float, hi: float, axis: str) -> list[float]:
        """Positions of break jogs on a dimension line spanning ``lo``..``hi`` along ``axis``.

        Jogs sit where the view is actually broken; without view information (or if no break
        gap falls on the line) a single jog is drawn at the middle.
        """
        if not self.has_break:
            return []
        margin = _JOG_HALF_WIDTH_MM + self.arrow_size
        jogs: list[float] = []
        if self.view is not None:
            jogs = [g for g in self.view.break_gap_centers(axis) if lo + margin < g < hi - margin]
        return jogs or [(lo + hi) / 2.0]

    def _full_text(self, dist: float) -> str:
        disp_val = self.text if self.text is not None else format_dimension_value(dist)
        full_str = f"{self.prefix}{disp_val}{self.suffix}"
        if self.tolerance:
            full_str += f" {self.tolerance}"
        return full_str

    def _text_overflows(self, dist: float, full_str: str) -> bool:
        """True when the text does not fit between the terminations of a non-narrow dim."""
        if dist < 2.0 * self.arrow_size + 4.0:
            return False
        return _estimate_text_width(full_str, self.font_size) + 2.0 > dist

    def bounding_box_2d(self) -> BBox2D:
        x1, y1 = self.start
        x2, y2 = self.end
        if self.dim_type == DimensionType.HORIZONTAL:
            dim_y = (y1 + y2) / 2.0 + self.offset
            hi_x = max(x1, x2)
            dist = hi_x - min(x1, x2)
            full_str = self._full_text(dist)
            if not self.has_break and self._text_overflows(dist, full_str):
                hi_x += _estimate_text_width(full_str, self.font_size) + 3.0
            return (min(x1, x2), dim_y - 3.5, hi_x, dim_y + 2.0)
        if self.dim_type == DimensionType.VERTICAL:
            dim_x = (x1 + x2) / 2.0 + self.offset
            lo_y = min(y1, y2)
            dist = max(y1, y2) - lo_y
            full_str = self._full_text(dist)
            if not self.has_break and self._text_overflows(dist, full_str):
                lo_y -= _estimate_text_width(full_str, self.font_size) + 3.0
            return (dim_x - 3.5, lo_y, dim_x + 2.0, max(y1, y2))
        return (min(x1, x2) - 2.0, min(y1, y2) - 2.0, max(x1, x2) + 2.0, max(y1, y2) + 2.0)

    def to_svg(self) -> str:
        if not self.resolved and self.target is not None:
            # Target could not be resolved to geometry: draw nothing rather than garbage.
            return ""
        x1, y1 = self.start
        x2, y2 = self.end
        ext_gap = 1.5
        ext_overshoot = 2.0

        if self.dim_type == DimensionType.HORIZONTAL:
            # Horizontal dimension across x1, x2
            left_x = min(x1, x2)
            right_x = max(x1, x2)
            base_y = (y1 + y2) / 2.0
            dim_y = base_y + self.offset
            dist = right_x - left_x

            disp_val = self.text if self.text is not None else format_dimension_value(dist)
            full_str = f"{self.prefix}{disp_val}{self.suffix}"
            if self.tolerance:
                full_str += f" {self.tolerance}"

            gap_dir = 1.0 if self.offset >= 0 else -1.0
            ext_y_start = base_y + gap_dir * ext_gap
            ext_y_end = dim_y + gap_dir * ext_overshoot

            is_narrow = dist < (2.0 * self.arrow_size + 4.0)
            if is_narrow:
                arrow_elems = [
                    f'<line x1="{left_x - 5.0:.2f}" y1="{dim_y:.2f}" x2="{left_x:.2f}" y2="{dim_y:.2f}" class="dim-line" stroke-width="0.3"/>',
                    render_arrowhead(left_x, dim_y, 1.0, 0.0, length=self.arrow_size),
                    f'<line x1="{right_x:.2f}" y1="{dim_y:.2f}" x2="{right_x + 5.0:.2f}" y2="{dim_y:.2f}" class="dim-line" stroke-width="0.3"/>',
                    render_arrowhead(right_x, dim_y, -1.0, 0.0, length=self.arrow_size),
                ]
                text_x = right_x + 6.0 if dist < 8.0 else (left_x + right_x) / 2.0
                text_anchor = "start" if dist < 8.0 else "middle"
                text_elem = f'<text x="{text_x:.2f}" y="{dim_y - 1.2:.2f}" class="dim-text" text-anchor="{text_anchor}" font-size="{self.font_size:.2f}">{html.escape(full_str)}</text>'
                jogs: list[float] = []
            else:
                jogs = self._jog_positions(left_x, right_x, "X")
                arrow_elems = [
                    render_arrowhead(left_x, dim_y, -1.0, 0.0, length=self.arrow_size),
                    render_arrowhead(right_x, dim_y, 1.0, 0.0, length=self.arrow_size),
                ]
                text_w = _estimate_text_width(full_str, self.font_size)
                if not jogs and self._text_overflows(dist, full_str):
                    # ISO 129-1: text too long for the space goes on an extension of the
                    # dimension line beyond the right-hand termination.
                    run_end = right_x + text_w + 3.0
                    arrow_elems.append(
                        f'<line x1="{right_x:.2f}" y1="{dim_y:.2f}" x2="{run_end:.2f}" y2="{dim_y:.2f}" class="dim-line" stroke-width="0.3"/>'
                    )
                    text_x = right_x + 1.5 + text_w / 2.0
                else:
                    text_x = _text_centre_clear_of_jogs(
                        left_x, right_x, jogs, text_w, self.arrow_size
                    )
                text_elem = f'<text x="{text_x:.2f}" y="{dim_y - 1.2:.2f}" class="dim-text" text-anchor="middle" font-size="{self.font_size:.2f}">{html.escape(full_str)}</text>'

            # Dimension line
            if jogs:
                jw, jh = _JOG_HALF_WIDTH_MM, 2.5
                parts: list[str] = []
                seg_start = left_x
                for jog_x in jogs:
                    parts.append(
                        f'<line x1="{seg_start:.2f}" y1="{dim_y:.2f}" x2="{jog_x - jw:.2f}" y2="{dim_y:.2f}" class="dim-line" stroke-width="0.3"/>'
                        f'<polyline points="{jog_x - jw:.2f},{dim_y:.2f} {jog_x - jw / 3.0:.2f},{dim_y - jh:.2f} {jog_x + jw / 3.0:.2f},{dim_y + jh:.2f} {jog_x + jw:.2f},{dim_y:.2f}" class="dim-line break-jog" stroke-width="0.3" fill="none"/>'
                    )
                    seg_start = jog_x + jw
                parts.append(
                    f'<line x1="{seg_start:.2f}" y1="{dim_y:.2f}" x2="{right_x:.2f}" y2="{dim_y:.2f}" class="dim-line" stroke-width="0.3"/>'
                )
                dim_line_elem = "".join(parts)
            else:
                dim_line_elem = f'<line x1="{left_x:.2f}" y1="{dim_y:.2f}" x2="{right_x:.2f}" y2="{dim_y:.2f}" class="dim-line" stroke-width="0.3"/>'

            elements = [
                # Extension lines
                f'<line x1="{left_x:.2f}" y1="{ext_y_start:.2f}" x2="{left_x:.2f}" y2="{ext_y_end:.2f}" class="dim-line" stroke-width="0.25"/>',
                f'<line x1="{right_x:.2f}" y1="{ext_y_start:.2f}" x2="{right_x:.2f}" y2="{ext_y_end:.2f}" class="dim-line" stroke-width="0.25"/>',
                # Dimension line
                dim_line_elem,
                *arrow_elems,
                text_elem,
            ]
            return "".join(elements)

        elif self.dim_type == DimensionType.VERTICAL:
            # Vertical dimension across y1, y2
            top_y = min(y1, y2)
            bottom_y = max(y1, y2)
            base_x = (x1 + x2) / 2.0
            dim_x = base_x + self.offset
            dist = bottom_y - top_y

            disp_val = self.text if self.text is not None else format_dimension_value(dist)
            full_str = f"{self.prefix}{disp_val}{self.suffix}"
            if self.tolerance:
                full_str += f" {self.tolerance}"

            gap_dir = 1.0 if self.offset >= 0 else -1.0
            ext_x_start = base_x + gap_dir * ext_gap
            ext_x_end = dim_x + gap_dir * ext_overshoot

            mid_y = (top_y + bottom_y) / 2.0
            is_narrow = dist < (2.0 * self.arrow_size + 4.0)
            if is_narrow:
                arrow_elems = [
                    f'<line x1="{dim_x:.2f}" y1="{top_y - 5.0:.2f}" x2="{dim_x:.2f}" y2="{top_y:.2f}" class="dim-line" stroke-width="0.3"/>',
                    render_arrowhead(dim_x, top_y, 0.0, 1.0, length=self.arrow_size),
                    f'<line x1="{dim_x:.2f}" y1="{bottom_y:.2f}" x2="{dim_x:.2f}" y2="{bottom_y + 5.0:.2f}" class="dim-line" stroke-width="0.3"/>',
                    render_arrowhead(dim_x, bottom_y, 0.0, -1.0, length=self.arrow_size),
                ]
            else:
                arrow_elems = [
                    render_arrowhead(dim_x, top_y, 0.0, -1.0, length=self.arrow_size),
                    render_arrowhead(dim_x, bottom_y, 0.0, 1.0, length=self.arrow_size),
                ]

            jogs = [] if is_narrow else self._jog_positions(top_y, bottom_y, "Y")
            if not is_narrow and not jogs and self._text_overflows(dist, full_str):
                # Text too long for the space: on an extension beyond the upper termination.
                text_w = _estimate_text_width(full_str, self.font_size)
                run_end = top_y - text_w - 3.0
                arrow_elems.append(
                    f'<line x1="{dim_x:.2f}" y1="{run_end:.2f}" x2="{dim_x:.2f}" y2="{top_y:.2f}" class="dim-line" stroke-width="0.3"/>'
                )
                mid_y = top_y - 1.5 - text_w / 2.0
            if jogs:
                mid_y = _text_centre_clear_of_jogs(
                    top_y,
                    bottom_y,
                    jogs,
                    _estimate_text_width(full_str, self.font_size),
                    self.arrow_size,
                )
                jw, jh = 2.5, _JOG_HALF_WIDTH_MM
                v_parts: list[str] = []
                seg_start = top_y
                for jog_y in jogs:
                    v_parts.append(
                        f'<line x1="{dim_x:.2f}" y1="{seg_start:.2f}" x2="{dim_x:.2f}" y2="{jog_y - jh:.2f}" class="dim-line" stroke-width="0.3"/>'
                        f'<polyline points="{dim_x:.2f},{jog_y - jh:.2f} {dim_x - jw:.2f},{jog_y - jh / 3.0:.2f} {dim_x + jw:.2f},{jog_y + jh / 3.0:.2f} {dim_x:.2f},{jog_y + jh:.2f}" class="dim-line break-jog" stroke-width="0.3" fill="none"/>'
                    )
                    seg_start = jog_y + jh
                v_parts.append(
                    f'<line x1="{dim_x:.2f}" y1="{seg_start:.2f}" x2="{dim_x:.2f}" y2="{bottom_y:.2f}" class="dim-line" stroke-width="0.3"/>'
                )
                dim_line_elem = "".join(v_parts)
            else:
                dim_line_elem = f'<line x1="{dim_x:.2f}" y1="{top_y:.2f}" x2="{dim_x:.2f}" y2="{bottom_y:.2f}" class="dim-line" stroke-width="0.3"/>'

            elements = [
                # Extension lines
                f'<line x1="{ext_x_start:.2f}" y1="{top_y:.2f}" x2="{ext_x_end:.2f}" y2="{top_y:.2f}" class="dim-line" stroke-width="0.25"/>',
                f'<line x1="{ext_x_start:.2f}" y1="{bottom_y:.2f}" x2="{ext_x_end:.2f}" y2="{bottom_y:.2f}" class="dim-line" stroke-width="0.25"/>',
                # Dimension line
                dim_line_elem,
                *arrow_elems,
                # Rotated dimension text
                f'<text x="{dim_x - 1.4:.2f}" y="{mid_y:.2f}" transform="rotate(-90 {dim_x - 1.4:.2f} {mid_y:.2f})" class="dim-text" text-anchor="middle" font-size="{self.font_size:.2f}">{html.escape(full_str)}</text>',
            ]
            return "".join(elements)

        else:
            # General aligned dimension along arbitrary vector
            dx = x2 - x1
            dy = y2 - y1
            length = math.hypot(dx, dy)
            if length == 0.0:
                return ""
            ux = dx / length
            uy = dy / length
            # Perpendicular normal
            nx = -uy
            ny = ux

            dim_x1 = x1 + nx * self.offset
            dim_y1 = y1 + ny * self.offset
            dim_x2 = x2 + nx * self.offset
            dim_y2 = y2 + ny * self.offset

            disp_val = self.text if self.text is not None else format_dimension_value(length)
            full_str = f"{self.prefix}{disp_val}{self.suffix}"
            if self.tolerance:
                full_str += f" {self.tolerance}"

            gap_dir = 1.0 if self.offset >= 0 else -1.0
            ext1_start_x = x1 + nx * gap_dir * ext_gap
            ext1_start_y = y1 + ny * gap_dir * ext_gap
            ext1_end_x = dim_x1 + nx * gap_dir * ext_overshoot
            ext1_end_y = dim_y1 + ny * gap_dir * ext_overshoot

            ext2_start_x = x2 + nx * gap_dir * ext_gap
            ext2_start_y = y2 + ny * gap_dir * ext_gap
            ext2_end_x = dim_x2 + nx * gap_dir * ext_overshoot
            ext2_end_y = dim_y2 + ny * gap_dir * ext_overshoot

            mid_x = (dim_x1 + dim_x2) / 2.0
            mid_y = (dim_y1 + dim_y2) / 2.0
            angle_deg = math.degrees(math.atan2(dy, dx))
            # Keep text readable (never upside down)
            if angle_deg > 90.0 or angle_deg <= -90.0:
                angle_deg += 180.0

            text_offset_dist = 1.5
            text_x = mid_x + nx * text_offset_dist
            text_y = mid_y + ny * text_offset_dist

            elements = [
                # Extension lines
                f'<line x1="{ext1_start_x:.2f}" y1="{ext1_start_y:.2f}" x2="{ext1_end_x:.2f}" y2="{ext1_end_y:.2f}" class="dim-line" stroke-width="0.25"/>',
                f'<line x1="{ext2_start_x:.2f}" y1="{ext2_start_y:.2f}" x2="{ext2_end_x:.2f}" y2="{ext2_end_y:.2f}" class="dim-line" stroke-width="0.25"/>',
                # Dimension line
                f'<line x1="{dim_x1:.2f}" y1="{dim_y1:.2f}" x2="{dim_x2:.2f}" y2="{dim_y2:.2f}" class="dim-line" stroke-width="0.3"/>',
                # Arrowheads
                render_arrowhead(dim_x1, dim_y1, -ux, -uy, length=self.arrow_size),
                render_arrowhead(dim_x2, dim_y2, ux, uy, length=self.arrow_size),
                # Aligned text
                f'<text x="{text_x:.2f}" y="{text_y:.2f}" transform="rotate({angle_deg:.1f} {text_x:.2f} {text_y:.2f})" class="dim-text" text-anchor="middle" font-size="{self.font_size:.2f}">{html.escape(full_str)}</text>',
            ]
            return "".join(elements)

RadialDimension

Bases: Annotation

Radius dimension (R) pointing to circular arc.

Source code in src/build123d_techdraw/annotations/dimensions.py
class RadialDimension(Annotation):
    """Radius dimension (R) pointing to circular arc."""

    def __init__(
        self,
        target_or_center: Any = None,
        radius: float | None = None,
        angle_deg: float = 45.0,
        prefix: str = "",
        suffix: str = "",
        text: str | None = None,
        tolerance: str | Tolerance | None = None,
        shelf_length: float = 12.0,
        arrow_size: float = 2.5,
        font_size: float = 3.2,
        center: tuple[float, float] | None = None,
        nominal: float | None = None,
        view: SheetView | None = None,
        *,
        anchor: Any = None,
    ):
        if target_or_center is None and anchor is not None:
            target_or_center = anchor

        self.angle_deg = angle_deg
        self.prefix = prefix
        self.suffix = suffix
        self.nominal = nominal
        self._explicit_text = text is not None or nominal is not None
        self._last_auto_text: str | None = None
        if text is None and nominal is not None:
            self.text: str | None = f"R{format_dimension_value(float(nominal))}"
        else:
            self.text = text
        self.tolerance = str(tolerance) if tolerance is not None else None
        self.shelf_length = shelf_length
        self.arrow_size = arrow_size
        self.font_size = font_size
        self.view = view
        self.target: Any = None
        self.resolved = False
        self._explicit_coords = False
        self.anchor_stale = False
        self.stale_reason: str | None = None

        if center is not None and radius is not None:
            self.center = (float(center[0]), float(center[1]))
            self.radius = float(radius)
            self.resolved = True
            self._explicit_coords = True
        elif (
            target_or_center is not None
            and radius is not None
            and not is_topological_entity(target_or_center)
            and isinstance(target_or_center, (tuple, list))
        ):
            self.center = (float(target_or_center[0]), float(target_or_center[1]))
            self.radius = float(radius)
            self.resolved = True
            self._explicit_coords = True
        else:
            self.center = (0.0, 0.0)
            self.radius = float(radius) if radius is not None else 0.0
            self.target = target_or_center

        target_view = view or CURRENT_VIEW.get()
        if target_view is not None:
            self._attach_to_view(target_view)
        else:
            target_sheet = CURRENT_SHEET.get()
            if target_sheet is not None and self not in target_sheet.annotations:
                target_sheet.annotations.append(self)

    def _rebind_to_view(self, view: SheetView) -> None:
        if not self._explicit_coords:
            self.resolved = False
            if not self._explicit_text:
                self._last_auto_text = self.text
                self.text = None
            self._attach_to_view(view)

    def _attach_to_view(self, view: SheetView) -> None:
        self.view = view
        if not self.resolved and self.target is not None:
            from build123d_techdraw.annotations.resolver import resolve_circle_or_cylinder_to_sheet

            if not isinstance(self.target, (tuple, list)):
                self.target = ensure_anchor(self.target, view.shape) or self.target
            prev_text = self._last_auto_text

            try:
                paper_c, paper_r, model_r = resolve_circle_or_cylinder_to_sheet(self.target, view)
                self.center = paper_c
                self.radius = paper_r
                if self.text is None:
                    self.text = f"R{format_dimension_value(model_r)}"
            except TypeError:
                self.center = resolve_point_to_sheet(self.target, view)

            if isinstance(self.target, Anchor) and self.target.is_stale:
                self.anchor_stale = True
                self.stale_reason = self.target.stale_reason
                self.center = stale_point_to_sheet(self.target, view) or self.center
                stale_r = stale_radius_to_paper(self.target, view)
                if stale_r is not None:
                    self.radius = stale_r
                if prev_text is not None and not self._explicit_text:
                    self.text = prev_text
            else:
                self.anchor_stale = False
                self.stale_reason = None
            self.resolved = True
        elif not self.resolved and self.target is None:
            self.center = (view.center_x, view.center_y)
            self.resolved = True

        self._register(view)

    def to_svg(self) -> str:
        cx, cy = self.center
        rad = math.radians(self.angle_deg)
        ux = math.cos(rad)
        uy = -math.sin(rad)  # SVG y is inverted

        arc_x = cx + ux * self.radius
        arc_y = cy + uy * self.radius

        # Leader extension beyond arc
        leader_len = 10.0
        elbow_x = arc_x + ux * leader_len
        elbow_y = arc_y + uy * leader_len

        shelf_dir = 1.0 if ux >= 0 else -1.0
        shelf_x = elbow_x + shelf_dir * self.shelf_length

        disp_val = self.text if self.text is not None else f"R{format_dimension_value(self.radius)}"
        full_str = f"{self.prefix}{disp_val}{self.suffix}"
        if self.tolerance:
            full_str += f" {self.tolerance}"

        text_anchor = "start" if shelf_dir > 0 else "end"
        text_x = elbow_x + (2.0 if shelf_dir > 0 else -2.0)
        text_y = elbow_y - 1.2

        elements = [
            # Leader line from arc to elbow and shelf
            f'<polyline points="{arc_x:.2f},{arc_y:.2f} {elbow_x:.2f},{elbow_y:.2f} {shelf_x:.2f},{elbow_y:.2f}" class="dim-line" stroke-width="0.3" fill="none"/>',
            # Arrowhead touching the arc
            render_arrowhead(arc_x, arc_y, -ux, -uy, length=self.arrow_size),
            # Text
            f'<text x="{text_x:.2f}" y="{text_y:.2f}" class="dim-text" text-anchor="{text_anchor}" font-size="{self.font_size:.2f}">{html.escape(full_str)}</text>',
        ]
        return f'<g class="radial-dim">{"".join(elements)}</g>'

DiameterDimension

Bases: Annotation

Diameter dimension (⌀) across full circle or with leader.

Source code in src/build123d_techdraw/annotations/dimensions.py
class DiameterDimension(Annotation):
    """Diameter dimension (⌀) across full circle or with leader."""

    def __init__(
        self,
        target_or_center: Any = None,
        diameter: float | None = None,
        angle_deg: float = 45.0,
        prefix: str = "",
        suffix: str = "",
        text: str | None = None,
        tolerance: str | Tolerance | None = None,
        shelf_length: float = 12.0,
        arrow_size: float = 2.5,
        font_size: float = 3.2,
        center: tuple[float, float] | None = None,
        nominal: float | None = None,
        view: SheetView | None = None,
        *,
        anchor: Any = None,
    ):
        if target_or_center is None and anchor is not None:
            target_or_center = anchor

        self.angle_deg = angle_deg
        self.prefix = prefix
        self.suffix = suffix
        self.nominal = nominal
        self._explicit_text = text is not None or nominal is not None
        self._last_auto_text: str | None = None
        if text is None and nominal is not None:
            self.text: str | None = f"⌀{format_dimension_value(float(nominal))}"
        else:
            self.text = text
        self.tolerance = str(tolerance) if tolerance is not None else None
        self.shelf_length = shelf_length
        self.arrow_size = arrow_size
        self.font_size = font_size
        self.view = view
        self.target: Any = None
        self.resolved = False
        self._explicit_coords = False
        self.anchor_stale = False
        self.stale_reason: str | None = None
        self._leader_cache: tuple[tuple[object, ...], float] | None = None
        self._contour_cache: tuple[tuple[object, ...], list[Segment2D]] | None = None
        self._placing_leader = False

        if center is not None and diameter is not None:
            self.center = (float(center[0]), float(center[1]))
            self.diameter = float(diameter)
            self.resolved = True
            self._explicit_coords = True
        elif (
            target_or_center is not None
            and diameter is not None
            and not is_topological_entity(target_or_center)
            and isinstance(target_or_center, (tuple, list))
        ):
            self.center = (float(target_or_center[0]), float(target_or_center[1]))
            self.diameter = float(diameter)
            self.resolved = True
            self._explicit_coords = True
        else:
            self.center = (0.0, 0.0)
            self.diameter = float(diameter) if diameter is not None else 0.0
            self.target = target_or_center

        target_view = view or CURRENT_VIEW.get()
        if target_view is not None:
            self._attach_to_view(target_view)
        else:
            target_sheet = CURRENT_SHEET.get()
            if target_sheet is not None and self not in target_sheet.annotations:
                target_sheet.annotations.append(self)

    def _rebind_to_view(self, view: SheetView) -> None:
        if not self._explicit_coords:
            self.resolved = False
            if not self._explicit_text:
                self._last_auto_text = self.text
                self.text = None
            self._attach_to_view(view)

    def _attach_to_view(self, view: SheetView) -> None:
        self.view = view
        if not self.resolved and self.target is not None:
            from build123d_techdraw.annotations.resolver import resolve_circle_or_cylinder_to_sheet

            if not isinstance(self.target, (tuple, list)):
                self.target = ensure_anchor(self.target, view.shape) or self.target
            prev_text = self._last_auto_text

            try:
                paper_c, paper_r, model_r = resolve_circle_or_cylinder_to_sheet(self.target, view)
                self.center = paper_c
                self.diameter = 2.0 * paper_r
                if self.text is None:
                    self.text = f"⌀{format_dimension_value(2.0 * model_r)}"
            except TypeError:
                self.center = resolve_point_to_sheet(self.target, view)

            if isinstance(self.target, Anchor) and self.target.is_stale:
                self.anchor_stale = True
                self.stale_reason = self.target.stale_reason
                self.center = stale_point_to_sheet(self.target, view) or self.center
                stale_r = stale_radius_to_paper(self.target, view)
                if stale_r is not None:
                    self.diameter = 2.0 * stale_r
                if prev_text is not None and not self._explicit_text:
                    self.text = prev_text
            else:
                self.anchor_stale = False
                self.stale_reason = None
            self.resolved = True
        elif not self.resolved and self.target is None:
            self.center = (view.center_x, view.center_y)
            self.resolved = True

        self._register(view)

    _DEFAULT_LEADER_MM = 10.0
    _CLEARANCE_MM = 1.0

    def _display_text(self) -> str:
        disp_val = (
            self.text if self.text is not None else f"⌀{format_dimension_value(self.diameter)}"
        )
        full_str = f"{self.prefix}{disp_val}{self.suffix}"
        if self.tolerance:
            full_str += f" {self.tolerance}"
        return full_str

    def _direction(self) -> tuple[float, float]:
        rad = math.radians(self.angle_deg)
        return (math.cos(rad), -math.sin(rad))

    def _landing(self, leader_len: float) -> tuple[float, float, float, BBox2D]:
        """Elbow point, shelf end X and the shelf + text box for a given leader length."""
        cx, cy = self.center
        ux, uy = self._direction()
        reach = self.diameter / 2.0 + leader_len
        elbow_x = cx + ux * reach
        elbow_y = cy + uy * reach
        shelf_dir = 1.0 if ux >= 0 else -1.0
        text_w = _estimate_text_width(self._display_text(), self.font_size)
        far_x = elbow_x + shelf_dir * max(self.shelf_length, 2.0 + text_w)
        box = (
            min(elbow_x, far_x),
            elbow_y - 1.2 - self.font_size,
            max(elbow_x, far_x),
            elbow_y,
        )
        shelf_x = elbow_x + shelf_dir * self.shelf_length
        return elbow_x, elbow_y, shelf_x, box

    def _obstacles(self, view: SheetView) -> tuple[list[Segment2D], list[BBox2D]]:
        """Drawn geometry (as segments) and other annotation boxes the landing must avoid."""
        key: tuple[object, ...] = (
            id(view.shape),
            view.center_x,
            view.center_y,
            view.scale,
            tuple((b.interval, b.gap) for b in view.breaks),
        )
        if self._contour_cache is None or self._contour_cache[0] != key:
            self._contour_cache = (key, _view_contour_segments(view))
        segments = list(self._contour_cache[1])
        boxes: list[BBox2D] = []
        for ann in view.annotations:
            if ann is self or isinstance(ann, DiameterDimension):
                continue
            if isinstance(ann, BoltCircle):
                segments.extend(_circle_segments(ann.center, ann.diameter / 2.0))
                continue
            bbox = ann.bounding_box_2d()
            if bbox is not None:
                boxes.append(bbox)
        return segments, boxes

    def _leader_length(self) -> float:
        """Leader length (mm, beyond the circle) that lands the shelf and text in clear space.

        The default short leader is kept when its text is clear of the view's geometry and of
        other annotations (a clear interior region). Otherwise the leader is extended along
        ``angle_deg`` until the landing is clear, at most to just outside the view outline.
        """
        view = self.view
        if view is None or self._placing_leader:
            return self._DEFAULT_LEADER_MM
        key: tuple[object, ...] = (
            self.center,
            self.diameter,
            self.angle_deg,
            self._display_text(),
            view.center_x,
            view.center_y,
            view.scale,
            id(view.shape),
            len(view.annotations),
        )
        if self._leader_cache is not None and self._leader_cache[0] == key:
            return self._leader_cache[1]

        self._placing_leader = True
        try:
            cx, cy = self.center
            ux, uy = self._direction()
            # Distance along the ray at which it leaves the view's bounding box.
            exits = []
            if ux > 1e-9:
                exits.append((view.max_x - cx) / ux)
            elif ux < -1e-9:
                exits.append((view.min_x - cx) / ux)
            if uy > 1e-9:
                exits.append((view.max_y - cy) / uy)
            elif uy < -1e-9:
                exits.append((view.min_y - cy) / uy)
            exit_dist = max(0.0, min(exits)) if exits else 0.0
            max_len = max(
                self._DEFAULT_LEADER_MM,
                exit_dist - self.diameter / 2.0 + self.font_size + 1.2 + 2.0 * self._CLEARANCE_MM,
            )

            segments, boxes = self._obstacles(view)
            # Only obstacles near any candidate landing matter.
            reach_box = _union_boxes(
                self._landing(self._DEFAULT_LEADER_MM)[3], self._landing(max_len)[3]
            )
            near = [s for s in segments if _segment_hits_box(s, reach_box)]
            pad = self._CLEARANCE_MM

            def clear(length: float) -> bool:
                b = self._landing(length)[3]
                padded = (b[0] - pad, b[1] - pad, b[2] + pad, b[3] + pad)
                if any(_boxes_overlap(padded, other) for other in boxes):
                    return False
                return not any(_segment_hits_box(s, padded) for s in near)

            length = self._DEFAULT_LEADER_MM
            while length < max_len and not clear(length):
                length += 1.0
            length = min(length, max_len)
        finally:
            self._placing_leader = False
        self._leader_cache = (key, length)
        return length

    def bounding_box_2d(self) -> BBox2D:
        cx, cy = self.center
        ux, uy = self._direction()
        r = self.diameter / 2.0
        _, _, shelf_x, box = self._landing(self._leader_length())
        xs = [cx - ux * r, cx + ux * r, shelf_x, box[0], box[2]]
        ys = [cy - uy * r, cy + uy * r, box[1], box[3]]
        return (min(xs), min(ys), max(xs), max(ys))

    def to_svg(self) -> str:
        cx, cy = self.center
        radius = self.diameter / 2.0
        ux, uy = self._direction()

        p1_x = cx - ux * radius
        p1_y = cy - uy * radius
        p2_x = cx + ux * radius
        p2_y = cy + uy * radius

        elbow_x, elbow_y, shelf_x, _ = self._landing(self._leader_length())
        shelf_dir = 1.0 if ux >= 0 else -1.0
        full_str = self._display_text()

        text_anchor = "start" if shelf_dir > 0 else "end"
        text_x = elbow_x + (2.0 if shelf_dir > 0 else -2.0)
        text_y = elbow_y - 1.2

        elements = [
            # Diametral line through circle
            f'<line x1="{p1_x:.2f}" y1="{p1_y:.2f}" x2="{p2_x:.2f}" y2="{p2_y:.2f}" class="dim-line" stroke-width="0.3"/>',
            # Leader to shelf
            f'<polyline points="{p2_x:.2f},{p2_y:.2f} {elbow_x:.2f},{elbow_y:.2f} {shelf_x:.2f},{elbow_y:.2f}" class="dim-line" stroke-width="0.3" fill="none"/>',
            # Dual arrowheads inside circle
            render_arrowhead(p1_x, p1_y, -ux, -uy, length=self.arrow_size),
            render_arrowhead(p2_x, p2_y, ux, uy, length=self.arrow_size),
            # Text
            f'<text x="{text_x:.2f}" y="{text_y:.2f}" class="dim-text" text-anchor="{text_anchor}" font-size="{self.font_size:.2f}">{html.escape(full_str)}</text>',
        ]
        return f'<g class="diameter-dim">{"".join(elements)}</g>'

format_dimension_value(value, precision=2)

Format dimension numerical value cleanly without redundant trailing zeros.

Source code in src/build123d_techdraw/annotations/dimensions.py
def format_dimension_value(value: float, precision: int = 2) -> str:
    """Format dimension numerical value cleanly without redundant trailing zeros."""
    formatted = f"{value:.{precision}f}"
    if "." in formatted:
        formatted = formatted.rstrip("0").rstrip(".")
    return formatted

build123d_techdraw.annotations.gdt

ISO 1101 and ASME Y14.5 Geometric Dimensioning and Tolerancing (GD&T) annotations.

GDTCharacteristic

Bases: Enum

Geometric tolerance characteristics according to ISO 1101.

Source code in src/build123d_techdraw/annotations/gdt.py
class GDTCharacteristic(Enum):
    """Geometric tolerance characteristics according to ISO 1101."""

    POSITION = "⌖"
    FLATNESS = "⏥"
    STRAIGHTNESS = "—"
    CIRCULARITY = "○"
    CYLINDRICITY = "⌭"
    PROFILE_SURFACE = "⌓"
    PROFILE_LINE = "⌒"
    PERPENDICULARITY = "⟂"
    PARALLELISM = "∥"
    ANGULARITY = "∠"
    CONCENTRICITY = "◎"
    SYMMETRY = "⌯"
    CIRCULAR_RUNOUT = "↗"
    TOTAL_RUNOUT = "⇗"

FeatureControlFrame

Bases: Annotation

ISO 1101 Feature Control Frame ([ Symbol | Tolerance | Datum A | Datum B | Datum C ]).

Raises:

Type Description
ValueError

if a form characteristic (FORM_CHARACTERISTICS: straightness, flatness, circularity, cylindricity) is given datum references. ISO 1101 form tolerances apply to the feature alone and never reference a datum.

Source code in src/build123d_techdraw/annotations/gdt.py
class FeatureControlFrame(Annotation):
    """ISO 1101 Feature Control Frame ([ Symbol | Tolerance | Datum A | Datum B | Datum C ]).

    Raises:
        ValueError: if a form characteristic (``FORM_CHARACTERISTICS``: straightness, flatness,
            circularity, cylindricity) is given datum references. ISO 1101 form tolerances
            apply to the feature alone and never reference a datum.
    """

    def __init__(
        self,
        characteristic: GDTCharacteristic = GDTCharacteristic.FLATNESS,
        tolerance_value: str = "0.05",
        datum_a: str | None = None,
        datum_b: str | None = None,
        datum_c: str | None = None,
        position: tuple[float, float] | None = None,
        target: Any = None,
        leader_offset: tuple[float, float] = (12.0, -10.0),
        frame_height: float = 6.0,
        symbol_font_size: float = 3.6,
        text_font_size: float = 3.0,
        leader_target: tuple[float, float] | None = None,
        datum_refs: list[str] | None = None,
        view: SheetView | None = None,
        *,
        anchor: Any = None,
    ):
        if target is None and anchor is not None:
            target = anchor

        self.characteristic = characteristic
        self.tolerance_value = tolerance_value
        self.frame_height = frame_height
        self.symbol_font_size = symbol_font_size
        self.text_font_size = text_font_size
        self.leader_offset = leader_offset
        self.view = view
        self.target = target if target is not None else leader_target
        self.resolved = False
        self._explicit_coords = False
        self.anchor_stale = False
        self.stale_reason: str | None = None

        if datum_refs:
            self.datum_a = datum_refs[0] if len(datum_refs) > 0 else None
            self.datum_b = datum_refs[1] if len(datum_refs) > 1 else None
            self.datum_c = datum_refs[2] if len(datum_refs) > 2 else None
        else:
            self.datum_a = datum_a
            self.datum_b = datum_b
            self.datum_c = datum_c

        if characteristic in FORM_CHARACTERISTICS and (
            self.datum_a or self.datum_b or self.datum_c
        ):
            raise ValueError(
                f"{characteristic.name} is an ISO 1101 form tolerance and must not reference a "
                "datum; use an orientation tolerance (e.g. PARALLELISM) to relate it to a datum."
            )

        if position is not None:
            self.position = (float(position[0]), float(position[1]))
            self.position_explicit = True
        else:
            self.position = (100.0, 100.0)
            self.position_explicit = False

        self.leader_target: tuple[float, float] | None
        if leader_target is not None and not is_topological_entity(leader_target):
            self.leader_target = (float(leader_target[0]), float(leader_target[1]))
            self.resolved = True
            self._explicit_coords = True
        else:
            self.leader_target = None

        target_view = view or CURRENT_VIEW.get()
        if target_view is not None:
            self._attach_to_view(target_view)
        else:
            target_sheet = CURRENT_SHEET.get()
            if target_sheet is not None and self not in target_sheet.annotations:
                target_sheet.annotations.append(self)

    def _rebind_to_view(self, view: SheetView) -> None:
        if not self._explicit_coords:
            self.resolved = False
            self._attach_to_view(view)

    def _attach_to_view(self, view: SheetView) -> None:
        self.view = view
        if not self.resolved and self.target is not None:
            if not isinstance(self.target, (tuple, list)):
                self.target = ensure_anchor(self.target, view.shape) or self.target
            target_pt = resolve_point_to_sheet(self.target, view)
            if isinstance(self.target, Anchor) and self.target.is_stale:
                self.anchor_stale = True
                self.stale_reason = self.target.stale_reason
                target_pt = stale_point_to_sheet(self.target, view) or target_pt
            else:
                self.anchor_stale = False
                self.stale_reason = None

            self.leader_target = target_pt
            if not self.position_explicit:
                self.position = (
                    target_pt[0] + self.leader_offset[0],
                    target_pt[1] + self.leader_offset[1],
                )
            self.resolved = True
        elif not self.resolved and self.target is None and not self.position_explicit:
            self.position = (view.center_x, view.center_y)
            self.resolved = True

        self._register(view)

    def bounding_box_2d(self) -> BBox2D:
        x, y = self.position
        w = 35.0  # approximate frame width
        return (x, y, x + w, y + self.frame_height)

    def to_svg(self) -> str:
        x, y = self.position
        h = self.frame_height

        # Calculate cell widths
        sym_w = 7.0
        tol_w = max(14.0, len(self.tolerance_value) * 2.2 + 4.0)

        datums: list[str] = []
        for d in [self.datum_a, self.datum_b, self.datum_c]:
            if d:
                datums.append(d)

        datum_w = 7.0
        total_w = sym_w + tol_w + len(datums) * datum_w

        leader_svg = ""
        if self.leader_target is not None:
            tx, ty = self.leader_target
            att_x = x if tx < x else (x + total_w if tx > x + total_w else x + total_w / 2.0)
            att_y = y + h / 2.0
            dx = att_x - tx
            dy = att_y - ty
            dist = math.hypot(dx, dy)
            arrow_svg = (
                render_arrowhead(tx, ty, -dx, -dy, length=2.5, half_width=0.7) if dist > 0 else ""
            )
            leader_svg = f"""
            {arrow_svg}
            <line x1="{tx:.2f}" y1="{ty:.2f}" x2="{att_x:.2f}" y2="{att_y:.2f}" class="dim-line" stroke-width="0.3"/>
            """

        elements: list[str] = [
            leader_svg,
            f'<rect x="{x:.2f}" y="{y:.2f}" width="{total_w:.2f}" height="{h:.2f}" class="title-bg" stroke-width="0.35"/>',
            f'<line x1="{x + sym_w:.2f}" y1="{y:.2f}" x2="{x + sym_w:.2f}" y2="{y + h:.2f}" class="border-sub" stroke-width="0.3"/>',
            # Characteristic symbol
            f'<text x="{x + sym_w / 2.0:.2f}" y="{y + h * 0.68:.2f}" class="tb-title" text-anchor="middle" font-size="{self.symbol_font_size:.2f}">{self.characteristic.value}</text>',
            # Tolerance value
            f'<text x="{x + sym_w + tol_w / 2.0:.2f}" y="{y + h * 0.68:.2f}" class="dim-text" text-anchor="middle" font-size="{self.text_font_size:.2f}">{html.escape(self.tolerance_value)}</text>',
        ]

        curr_x = x + sym_w + tol_w
        for d in datums:
            elements.append(
                f'<line x1="{curr_x:.2f}" y1="{y:.2f}" x2="{curr_x:.2f}" y2="{y + h:.2f}" class="border-sub" stroke-width="0.3"/>'
            )
            elements.append(
                f'<text x="{curr_x + datum_w / 2.0:.2f}" y="{y + h * 0.68:.2f}" class="tb-field-val-bold" text-anchor="middle" font-size="{self.text_font_size:.2f}">{html.escape(d)}</text>'
            )
            curr_x += datum_w

        return f'<g class="gdt-fcf">{"".join(elements)}</g>'

DatumFeatureSymbol

Bases: Annotation

ISO 5459 datum feature indicator: a filled triangle on the feature joined to a framed letter.

The triangle's base sits on the feature's outline (target) and the frame is placed on the side outside the material. With direction=None (the default) and a topological target, that side is found from the face's outward normal projected into the view (or, for edges, vertices and face-on faces, from the side away from the view centre). Pass "up", "down", "left" or "right" to force a side; explicit 2D coordinates without a direction default to "up".

Source code in src/build123d_techdraw/annotations/gdt.py
class DatumFeatureSymbol(Annotation):
    """ISO 5459 datum feature indicator: a filled triangle on the feature joined to a framed letter.

    The triangle's base sits on the feature's outline (``target``) and the frame is placed on the
    side *outside the material*. With ``direction=None`` (the default) and a topological target,
    that side is found from the face's outward normal projected into the view (or, for edges,
    vertices and face-on faces, from the side away from the view centre). Pass ``"up"``,
    ``"down"``, ``"left"`` or ``"right"`` to force a side; explicit 2D coordinates without a
    direction default to ``"up"``.
    """

    def __init__(
        self,
        label: str = "A",
        target: Any = None,
        stem_length: float = 7.0,
        box_size: float = 5.5,
        direction: str | None = None,
        view: SheetView | None = None,
        *,
        anchor: Any = None,
    ):
        if target is None and anchor is not None:
            target = anchor

        if direction is not None and direction not in DATUM_DIRECTIONS:
            raise ValueError(
                f"direction must be one of {DATUM_DIRECTIONS} or None, got {direction!r}"
            )

        self.label = label
        self.stem_length = stem_length
        self.box_size = box_size
        self._auto_direction = direction is None
        self.direction: str = direction if direction is not None else "up"
        self.view = view
        self.raw_target = target
        self.target: tuple[float, float] = (0.0, 0.0)
        self.resolved = False
        self._explicit_coords = False
        self.anchor_stale = False
        self.stale_reason: str | None = None

        if (
            target is not None
            and not is_topological_entity(target)
            and isinstance(target, (tuple, list))
        ):
            self.target = (float(target[0]), float(target[1]))
            self.resolved = True
            self._explicit_coords = True

        target_view = view or CURRENT_VIEW.get()
        if target_view is not None:
            self._attach_to_view(target_view)
        else:
            target_sheet = CURRENT_SHEET.get()
            if target_sheet is not None and self not in target_sheet.annotations:
                target_sheet.annotations.append(self)

    def _rebind_to_view(self, view: SheetView) -> None:
        if not self._explicit_coords:
            self.resolved = False
            self._attach_to_view(view)

    def _attach_to_view(self, view: SheetView) -> None:
        self.view = view
        if not self.resolved and self.raw_target is not None:
            if not isinstance(self.raw_target, (tuple, list)):
                self.raw_target = ensure_anchor(self.raw_target, view.shape) or self.raw_target
            self.target = resolve_point_to_sheet(self.raw_target, view)
            if isinstance(self.raw_target, Anchor) and self.raw_target.is_stale:
                self.anchor_stale = True
                self.stale_reason = self.raw_target.stale_reason
                self.target = stale_point_to_sheet(self.raw_target, view) or self.target
            else:
                self.anchor_stale = False
                self.stale_reason = None
            if self._auto_direction:
                entity = (
                    self.raw_target.last_resolved_entity
                    if isinstance(self.raw_target, Anchor)
                    else self.raw_target
                )
                dx, dy = outward_sheet_direction(entity, self.target, view)
                self.direction = _sheet_direction_name(dx, dy)
            self.resolved = True
        elif not self.resolved and self.raw_target is None:
            self.target = (view.center_x, view.min_y)
            if self._auto_direction:
                self.direction = "up"
            self.resolved = True

        self._register(view)

    def _geometry(
        self,
    ) -> tuple[list[tuple[float, float]], tuple[float, float], tuple[float, float]]:
        """Return (triangle points, stem end, frame top-left corner) in sheet mm.

        The triangle's base lies on the feature outline at ``target`` and its apex points away
        from the material, towards the frame (ISO 5459).
        """
        tx, ty = self.target
        half = 2.4  # half base width
        height = half * 1.5
        ux, uy = {"up": (0.0, -1.0), "down": (0.0, 1.0), "left": (-1.0, 0.0)}.get(
            self.direction, (1.0, 0.0)
        )
        # Perpendicular to the outward direction, along the feature outline.
        px, py = -uy, ux
        tri = [
            (tx + px * half, ty + py * half),
            (tx - px * half, ty - py * half),
            (tx + ux * height, ty + uy * height),
        ]
        stem_end = (tx + ux * self.stem_length, ty + uy * self.stem_length)
        b = self.box_size
        if self.direction == "up":
            box = (stem_end[0] - b / 2.0, stem_end[1] - b)
        elif self.direction == "down":
            box = (stem_end[0] - b / 2.0, stem_end[1])
        elif self.direction == "left":
            box = (stem_end[0] - b, stem_end[1] - b / 2.0)
        else:
            box = (stem_end[0], stem_end[1] - b / 2.0)
        return tri, stem_end, box

    def bounding_box_2d(self) -> BBox2D:
        tri, _stem_end, (box_x, box_y) = self._geometry()
        xs = [p[0] for p in tri] + [box_x, box_x + self.box_size]
        ys = [p[1] for p in tri] + [box_y, box_y + self.box_size]
        return (min(xs), min(ys), max(xs), max(ys))

    def to_svg(self) -> str:
        tx, ty = self.target
        tri, (stem_end_x, stem_end_y), (box_x, box_y) = self._geometry()
        tri_pts = " ".join(f"{px:.2f},{py:.2f}" for px, py in tri)

        elements = [
            f'<polygon points="{tri_pts}" class="dim-arrow"/>',
            f'<line x1="{tx:.2f}" y1="{ty:.2f}" x2="{stem_end_x:.2f}" y2="{stem_end_y:.2f}" class="dim-line" stroke-width="0.35"/>',
            f'<rect x="{box_x:.2f}" y="{box_y:.2f}" width="{self.box_size:.2f}" height="{self.box_size:.2f}" class="title-bg" stroke-width="0.4"/>',
            f'<text x="{box_x + self.box_size / 2.0:.2f}" y="{box_y + self.box_size * 0.72:.2f}" class="tb-field-val-bold" text-anchor="middle" font-size="3.4">{html.escape(self.label)}</text>',
        ]

        return f'<g class="datum-symbol">{"".join(elements)}</g>'

build123d_techdraw.annotations.surface

ISO 1302 surface roughness and texture symbols.

MaterialRemoval

Bases: Enum

Source code in src/build123d_techdraw/annotations/surface.py
class MaterialRemoval(Enum):
    ANY = "any"  # Basic symbol (open checkmark)
    REQUIRED = "required"  # Triangle closed (machining required)
    PROHIBITED = "prohibited"  # Circle in vertex (no material removal)

SurfaceFinishSymbol

Bases: Annotation

ISO 1302 / ISO 21920-1 surface texture (roughness) symbol.

The symbol's vertex must touch the surface it applies to (its outline, an extension line of it, or a leader end). Pass target (a Face, Edge, Vertex or Anchor) to place the vertex on the projected feature: a planar face seen edge-on projects its centre onto its outline, so the tick sits exactly on the surface line and follows the view when it moves or the model changes. position places the vertex at fixed sheet coordinates (mm).

Source code in src/build123d_techdraw/annotations/surface.py
class SurfaceFinishSymbol(Annotation):
    """ISO 1302 / ISO 21920-1 surface texture (roughness) symbol.

    The symbol's vertex must touch the surface it applies to (its outline, an extension line of
    it, or a leader end). Pass ``target`` (a ``Face``, ``Edge``, ``Vertex`` or ``Anchor``) to
    place the vertex on the projected feature: a planar face seen edge-on projects its centre
    onto its outline, so the tick sits exactly on the surface line and follows the view when it
    moves or the model changes. ``position`` places the vertex at fixed sheet coordinates (mm).
    """

    def __init__(
        self,
        target_or_pos: Any = None,
        ra_value: str = "Ra 3.2",
        material_removal: MaterialRemoval = MaterialRemoval.REQUIRED,
        process: str | None = None,
        scale: float = 1.0,
        position: tuple[float, float] | None = None,
        target: Any = None,
        view: SheetView | None = None,
        *,
        anchor: Any = None,
    ):
        if target is None and anchor is not None:
            target = anchor

        self.ra_value = ra_value
        self.material_removal = material_removal
        self.process = process
        self.scale = scale
        self.view = view
        self.resolved = False
        self._explicit_coords = False
        self.anchor_stale = False
        self.stale_reason: str | None = None

        effective_target = target if target is not None else target_or_pos

        if position is not None:
            self.position = (float(position[0]), float(position[1]))
            self.target = None
            self.resolved = True
            self._explicit_coords = True
        elif (
            effective_target is not None
            and not is_topological_entity(effective_target)
            and isinstance(effective_target, (tuple, list))
        ):
            self.position = (float(effective_target[0]), float(effective_target[1]))
            self.target = None
            self.resolved = True
            self._explicit_coords = True
        else:
            self.position = (0.0, 0.0)
            self.target = effective_target

        target_view = view or CURRENT_VIEW.get()
        if target_view is not None:
            self._attach_to_view(target_view)
        else:
            target_sheet = CURRENT_SHEET.get()
            if target_sheet is not None and self not in target_sheet.annotations:
                target_sheet.annotations.append(self)

    def _rebind_to_view(self, view: SheetView) -> None:
        if not self._explicit_coords:
            self.resolved = False
            self._attach_to_view(view)

    def _attach_to_view(self, view: SheetView) -> None:
        self.view = view
        if not self.resolved and self.target is not None:
            if not isinstance(self.target, (tuple, list)):
                self.target = ensure_anchor(self.target, view.shape) or self.target
            self.position = resolve_point_to_sheet(self.target, view)
            if isinstance(self.target, Anchor) and self.target.is_stale:
                self.anchor_stale = True
                self.stale_reason = self.target.stale_reason
                self.position = stale_point_to_sheet(self.target, view) or self.position
            else:
                self.anchor_stale = False
                self.stale_reason = None
            self.resolved = True
        elif not self.resolved and self.target is None:
            self.position = (view.center_x, view.min_y)
            self.resolved = True

        self._register(view)

    def _shelf_length(self) -> float:
        s = self.scale
        return max(12.0 * s, len(self.ra_value) * 2.2 * s + 4.0 * s)

    def bounding_box_2d(self) -> BBox2D:
        """Paper-space bounds: from the short leg to the end of the shelf, vertex to lettering."""
        x, y = self.position
        s = self.scale
        min_x = x - 2.5 * s
        max_x = x + 5.0 * s + self._shelf_length()
        text_top = y - 8.66 * s - 1.2 * s - 2.8 * s
        if self.process:
            text_top -= 3.2 * s
        return (min_x, text_top, max_x, y)

    def to_svg(self) -> str:
        x, y = self.position
        s = self.scale

        # Standard ISO 1302 60-degree tick geometry
        p_vertex = (x, y)
        p_left = (x - 2.5 * s, y - 4.33 * s)
        p_right = (x + 5.0 * s, y - 8.66 * s)
        shelf_len = self._shelf_length()
        p_shelf_end = (p_right[0] + shelf_len, p_right[1])

        elements = [
            # Short left leg
            f'<line x1="{p_vertex[0]:.2f}" y1="{p_vertex[1]:.2f}" x2="{p_left[0]:.2f}" y2="{p_left[1]:.2f}" class="dim-line" stroke-width="0.35"/>',
            # Long right leg
            f'<line x1="{p_vertex[0]:.2f}" y1="{p_vertex[1]:.2f}" x2="{p_right[0]:.2f}" y2="{p_right[1]:.2f}" class="dim-line" stroke-width="0.35"/>',
            # Horizontal shelf bar
            f'<line x1="{p_right[0]:.2f}" y1="{p_right[1]:.2f}" x2="{p_shelf_end[0]:.2f}" y2="{p_shelf_end[1]:.2f}" class="dim-line" stroke-width="0.35"/>',
        ]

        if self.material_removal == MaterialRemoval.REQUIRED:
            # Closing horizontal bar across tick
            elements.append(
                f'<line x1="{p_left[0]:.2f}" y1="{p_left[1]:.2f}" x2="{x + 2.5 * s:.2f}" y2="{y - 4.33 * s:.2f}" class="dim-line" stroke-width="0.35"/>'
            )
        elif self.material_removal == MaterialRemoval.PROHIBITED:
            # Circle centered in checkmark
            elements.append(
                f'<circle cx="{x + 1.2 * s:.2f}" cy="{y - 3.2 * s:.2f}" r="{1.5 * s:.2f}" fill="none" class="dim-line" stroke-width="0.3"/>'
            )

        # Ra text above the shelf bar
        text_x = p_right[0] + 1.5 * s
        text_y = p_right[1] - 1.2 * s
        elements.append(
            f'<text x="{text_x:.2f}" y="{text_y:.2f}" class="dim-text" font-size="{2.8 * s:.2f}">{html.escape(self.ra_value)}</text>'
        )

        # Optional process description above Ra
        if self.process:
            elements.append(
                f'<text x="{text_x:.2f}" y="{text_y - 3.2 * s:.2f}" class="tb-field-val" font-size="{2.2 * s:.2f}">{html.escape(self.process)}</text>'
            )

        return f'<g class="surface-finish-symbol">{"".join(elements)}</g>'

bounding_box_2d()

Paper-space bounds: from the short leg to the end of the shelf, vertex to lettering.

Source code in src/build123d_techdraw/annotations/surface.py
def bounding_box_2d(self) -> BBox2D:
    """Paper-space bounds: from the short leg to the end of the shelf, vertex to lettering."""
    x, y = self.position
    s = self.scale
    min_x = x - 2.5 * s
    max_x = x + 5.0 * s + self._shelf_length()
    text_top = y - 8.66 * s - 1.2 * s - 2.8 * s
    if self.process:
        text_top -= 3.2 * s
    return (min_x, text_top, max_x, y)

build123d_techdraw.annotations.centerlines

ISO centerlines, center crosshairs, and bolt pitch circles (PCD).

Centerline

Bases: Annotation

ISO 128 compliant long-dash dot-dash centerline.

Source code in src/build123d_techdraw/annotations/centerlines.py
class Centerline(Annotation):
    """ISO 128 compliant long-dash dot-dash centerline."""

    def __init__(
        self,
        target_or_start: Any = None,
        target2_or_end: Any = None,
        stroke_width: float = 0.25,
        start: tuple[float, float] | None = None,
        end: tuple[float, float] | None = None,
        overhang: float = 4.0,
        view: SheetView | None = None,
        *,
        anchor: Any = None,
        anchor1: Any = None,
        anchor2: Any = None,
    ):
        if target_or_start is None:
            target_or_start = anchor1 if anchor1 is not None else anchor
        if target2_or_end is None and anchor2 is not None:
            target2_or_end = anchor2

        self.stroke_width = stroke_width
        self.overhang = overhang
        self.view = view
        self.target: Any = None
        self.target2: Any = None
        self.resolved = False
        self._explicit_coords = False
        self.anchor_stale = False
        self.stale_reason: str | None = None

        if start is not None and end is not None:
            self.start = (float(start[0]), float(start[1]))
            self.end = (float(end[0]), float(end[1]))
            self.resolved = True
            self._explicit_coords = True
        elif (
            target_or_start is not None
            and target2_or_end is not None
            and not is_topological_entity(target_or_start)
            and not is_topological_entity(target2_or_end)
            and isinstance(target_or_start, (tuple, list))
            and isinstance(target2_or_end, (tuple, list))
        ):
            self.start = (float(target_or_start[0]), float(target_or_start[1]))
            self.end = (float(target2_or_end[0]), float(target2_or_end[1]))
            self.resolved = True
            self._explicit_coords = True
        else:
            self.start = (0.0, 0.0)
            self.end = (0.0, 0.0)
            self.target = target_or_start
            self.target2 = target2_or_end

        target_view = view or CURRENT_VIEW.get()
        if target_view is not None:
            self._attach_to_view(target_view)
        else:
            target_sheet = CURRENT_SHEET.get()
            if target_sheet is not None and self not in target_sheet.annotations:
                target_sheet.annotations.append(self)

    def _rebind_to_view(self, view: SheetView) -> None:
        if not self._explicit_coords:
            self.resolved = False
            self._attach_to_view(view)

    def _attach_to_view(self, view: SheetView) -> None:
        self.view = view
        if not self.resolved and self.target is not None:
            import build123d as bd

            v_shape = view.shape
            self.target = ensure_anchor(self.target, v_shape) or self.target
            self.target2 = ensure_anchor(self.target2, v_shape) or self.target2

            eff_target = self.target
            if isinstance(self.target, Anchor) and self.target2 is None:
                eff_target = self.target.resolve_entity(v_shape)
                if eff_target is None and self.target.is_stale:
                    # Last-known model-space entity; projected through the current view below.
                    eff_target = self.target.last_resolved_entity

            if isinstance(eff_target, bd.Face) and eff_target.geom_type == bd.GeomType.CYLINDER:
                axis = eff_target.axis_of_rotation
                if axis:
                    bb = eff_target.bounding_box()
                    p0 = view.to_sheet_3d(
                        float(axis.position.X), float(axis.position.Y), float(bb.min.Z)
                    )
                    p1 = view.to_sheet_3d(
                        float(axis.position.X), float(axis.position.Y), float(bb.max.Z)
                    )
                    # Apply overhang in sheet space along line
                    dx = p1[0] - p0[0]
                    dy = p1[1] - p0[1]
                    d = math.hypot(dx, dy)
                    if d > 1e-3:
                        ux = dx / d
                        uy = dy / d
                        self.start = (p0[0] - ux * self.overhang, p0[1] - uy * self.overhang)
                        self.end = (p1[0] + ux * self.overhang, p1[1] + uy * self.overhang)
                    else:
                        self.start = p0
                        self.end = p1
            elif self.target2 is not None:
                p0 = resolve_point_to_sheet(self.target, view)
                p1 = resolve_point_to_sheet(self.target2, view)
                self.start = p0
                self.end = p1

            stale1 = isinstance(self.target, Anchor) and self.target.is_stale
            stale2 = isinstance(self.target2, Anchor) and self.target2.is_stale
            if stale1 or stale2:
                self.anchor_stale = True
                self.stale_reason = stale_reason_of(self.target, self.target2)
            else:
                self.anchor_stale = False
                self.stale_reason = None
            self.resolved = True
        elif not self.resolved and self.target is None:
            self.start = (view.min_x - self.overhang, view.center_y)
            self.end = (view.max_x + self.overhang, view.center_y)
            self.resolved = True

        self._register(view)

    def to_svg(self) -> str:
        x1, y1 = self.start
        x2, y2 = self.end
        return (
            f'<line x1="{x1:.2f}" y1="{y1:.2f}" x2="{x2:.2f}" y2="{y2:.2f}" '
            f'class="line-center" stroke-dasharray="10,2,2,2" stroke-width="{self.stroke_width:.2f}"/>'
        )

CenterMark

Bases: Annotation

ISO centermark crosshair with central intersection and overhang.

Source code in src/build123d_techdraw/annotations/centerlines.py
class CenterMark(Annotation):
    """ISO centermark crosshair with central intersection and overhang."""

    def __init__(
        self,
        target_or_center: Any = None,
        size: float | None = None,
        stroke_width: float = 0.25,
        center: tuple[float, float] | None = None,
        cy: float | None = None,
        view: SheetView | None = None,
        *,
        anchor: Any = None,
    ):
        if target_or_center is None and anchor is not None:
            target_or_center = anchor

        self._explicit_size = size is not None
        self.size = size if size is not None else 6.0
        self.stroke_width = stroke_width
        self.view = view
        self.target: Any = None
        self.resolved = False
        self._explicit_coords = False
        self.anchor_stale = False
        self.stale_reason: str | None = None

        if center is not None:
            self.center = (float(center[0]), float(center[1]))
            self.resolved = True
            self._explicit_coords = True
        elif cy is not None and isinstance(target_or_center, (int, float)):
            self.center = (float(target_or_center), float(cy))
            self.resolved = True
            self._explicit_coords = True
        elif (
            target_or_center is not None
            and not is_topological_entity(target_or_center)
            and isinstance(target_or_center, (tuple, list))
            and len(target_or_center) == 2
        ):
            self.center = (float(target_or_center[0]), float(target_or_center[1]))
            self.resolved = True
            self._explicit_coords = True
        else:
            self.center = (0.0, 0.0)
            self.target = target_or_center

        target_view = view or CURRENT_VIEW.get()
        if target_view is not None:
            self._attach_to_view(target_view)
        else:
            target_sheet = CURRENT_SHEET.get()
            if target_sheet is not None and self not in target_sheet.annotations:
                target_sheet.annotations.append(self)

    def _rebind_to_view(self, view: SheetView) -> None:
        if not self._explicit_coords:
            self.resolved = False
            if not self._explicit_size:
                self.size = 6.0
            self._attach_to_view(view)

    def _attach_to_view(self, view: SheetView) -> None:
        self.view = view
        if not self.resolved and self.target is not None:
            if not isinstance(self.target, (tuple, list)):
                self.target = ensure_anchor(self.target, view.shape) or self.target
            try:
                paper_c, paper_r, _ = resolve_circle_or_cylinder_to_sheet(self.target, view)
                self.center = paper_c
                if not self._explicit_size:
                    self.size = (paper_r + 2.0) * 2.0
            except TypeError:
                self.center = resolve_point_to_sheet(self.target, view)

            if isinstance(self.target, Anchor) and self.target.is_stale:
                self.anchor_stale = True
                self.stale_reason = self.target.stale_reason
                self.center = stale_point_to_sheet(self.target, view) or self.center
                stale_r = stale_radius_to_paper(self.target, view)
                if stale_r is not None and not self._explicit_size:
                    self.size = (stale_r + 2.0) * 2.0
            else:
                self.anchor_stale = False
                self.stale_reason = None
            self.resolved = True
        elif not self.resolved and self.target is None:
            self.center = (view.center_x, view.center_y)
            self.resolved = True

        self._register(view)

    def bounding_box_2d(self) -> BBox2D:
        cx, cy = self.center
        s = self.size / 2.0
        return (cx - s, cy - s, cx + s, cy + s)

    def to_svg(self) -> str:
        cx, cy = self.center
        half = self.size / 2.0
        return f"""
        <g class="centermark">
            <line x1="{cx - half:.2f}" y1="{cy:.2f}" x2="{cx + half:.2f}" y2="{cy:.2f}" class="line-center" stroke-width="{self.stroke_width:.2f}"/>
            <line x1="{cx:.2f}" y1="{cy - half:.2f}" x2="{cx:.2f}" y2="{cy + half:.2f}" class="line-center" stroke-width="{self.stroke_width:.2f}"/>
        </g>
        """

BoltCircle

Bases: Annotation

Bolt Circle / Pitch Circle Diameter (PCD) annotation with radial hole crosshairs.

Source code in src/build123d_techdraw/annotations/centerlines.py
class BoltCircle(Annotation):
    """Bolt Circle / Pitch Circle Diameter (PCD) annotation with radial hole crosshairs."""

    def __init__(
        self,
        target_or_center: Any = None,
        diameter: float | None = None,
        num_holes: int = 4,
        start_angle_deg: float = 0.0,
        hole_cross_size: float = 4.0,
        stroke_width: float = 0.25,
        center: tuple[float, float] | None = None,
        view: SheetView | None = None,
        *,
        anchor: Any = None,
    ):
        if target_or_center is None and anchor is not None:
            target_or_center = anchor

        self.num_holes = num_holes
        self.start_angle_deg = start_angle_deg
        self.hole_cross_size = hole_cross_size
        self.stroke_width = stroke_width
        self.view = view
        self.target: Any = None
        self.resolved = False
        self._explicit_diameter = diameter is not None
        self._explicit_coords = False
        self.anchor_stale = False
        self.stale_reason: str | None = None

        if center is not None and diameter is not None:
            self.center = (float(center[0]), float(center[1]))
            self.diameter = float(diameter)
            self.resolved = True
            self._explicit_coords = True
        elif (
            target_or_center is not None
            and diameter is not None
            and not is_topological_entity(target_or_center)
            and isinstance(target_or_center, (tuple, list))
        ):
            self.center = (float(target_or_center[0]), float(target_or_center[1]))
            self.diameter = float(diameter)
            self.resolved = True
            self._explicit_coords = True
        else:
            self.center = (0.0, 0.0)
            self.diameter = float(diameter or 0.0)
            self.target = target_or_center

        target_view = view or CURRENT_VIEW.get()
        if target_view is not None:
            self._attach_to_view(target_view)
        else:
            target_sheet = CURRENT_SHEET.get()
            if target_sheet is not None and self not in target_sheet.annotations:
                target_sheet.annotations.append(self)

    def _rebind_to_view(self, view: SheetView) -> None:
        if not self._explicit_coords:
            self.resolved = False
            if not self._explicit_diameter:
                self.diameter = 0.0
            self._attach_to_view(view)

    def _attach_to_view(self, view: SheetView) -> None:
        self.view = view
        if not self.resolved and self.target is not None:
            if not isinstance(self.target, (tuple, list)):
                self.target = ensure_anchor(self.target, view.shape) or self.target
            try:
                paper_c, paper_r, _ = resolve_circle_or_cylinder_to_sheet(self.target, view)
                self.center = paper_c
                if self.diameter == 0.0:
                    self.diameter = 2.0 * paper_r
            except TypeError:
                self.center = resolve_point_to_sheet(self.target, view)

            if isinstance(self.target, Anchor) and self.target.is_stale:
                self.anchor_stale = True
                self.stale_reason = self.target.stale_reason
                self.center = stale_point_to_sheet(self.target, view) or self.center
                stale_r = stale_radius_to_paper(self.target, view)
                if stale_r is not None and not self._explicit_diameter:
                    self.diameter = 2.0 * stale_r
            else:
                self.anchor_stale = False
                self.stale_reason = None
            self.resolved = True
        elif not self.resolved and self.target is None:
            self.center = (view.center_x, view.center_y)
            self.resolved = True

        self._register(view)

    def to_svg(self) -> str:
        cx, cy = self.center
        radius = self.diameter / 2.0
        elements: list[str] = [
            f'<circle cx="{cx:.2f}" cy="{cy:.2f}" r="{radius:.2f}" class="line-center" fill="none" stroke-dasharray="8,2,2,2" stroke-width="{self.stroke_width:.2f}"/>'
        ]

        if self.num_holes > 0:
            step_deg = 360.0 / self.num_holes
            for i in range(self.num_holes):
                angle_rad = math.radians(self.start_angle_deg + i * step_deg)
                hx = cx + radius * math.cos(angle_rad)
                hy = cy - radius * math.sin(angle_rad)
                half = self.hole_cross_size / 2.0
                elements.append(
                    f'<line x1="{hx - half:.2f}" y1="{hy:.2f}" x2="{hx + half:.2f}" y2="{hy:.2f}" class="line-center" stroke-width="{self.stroke_width:.2f}"/>'
                )
                elements.append(
                    f'<line x1="{hx:.2f}" y1="{hy - half:.2f}" x2="{hx:.2f}" y2="{hy + half:.2f}" class="line-center" stroke-width="{self.stroke_width:.2f}"/>'
                )

        return f'<g class="bolt-circle">{"".join(elements)}</g>'

build123d_techdraw.annotations.callouts

Callouts, leader notes, hole/thread callouts, BOM balloons, and section cutting lines.

LeaderNote

Bases: Annotation

Multi-line leader note with pointer dot/arrow, elbow, and horizontal shelf.

Source code in src/build123d_techdraw/annotations/callouts.py
class LeaderNote(Annotation):
    """Multi-line leader note with pointer dot/arrow, elbow, and horizontal shelf."""

    def __init__(
        self,
        target_or_text: Any = None,
        lines_or_target: Any = None,
        elbow_offset: tuple[float, float] = (15.0, -12.0),
        shelf_length: float = 20.0,
        align_right: bool | None = None,
        terminator: str = "dot",
        font_size: float = 2.8,
        target: Any = None,
        lines: list[str] | str | None = None,
        text: str | list[str] | None = None,
        leader_offset: tuple[float, float] | None = None,
        view: SheetView | None = None,
        *,
        anchor: Any = None,
    ):
        if target is None and anchor is not None:
            target = anchor

        self.shelf_length = shelf_length
        self.align_right = align_right
        self.terminator = terminator
        self.font_size = font_size
        self.requested_elbow_offset: tuple[float, float] = leader_offset or elbow_offset
        self.elbow_offset = self.requested_elbow_offset
        self.view = view
        self.raw_target: Any = None
        self.target: tuple[float, float] = (0.0, 0.0)
        self.resolved = False
        self._explicit_coords = False
        self.anchor_stale = False
        self.stale_reason: str | None = None

        # Parse text / lines
        raw_text = text or lines
        if raw_text is None:
            if isinstance(target_or_text, (str, list)):
                raw_text = target_or_text
                self.raw_target = target or lines_or_target
            elif isinstance(lines_or_target, (str, list)):
                raw_text = lines_or_target
                self.raw_target = target or target_or_text
        else:
            self.raw_target = target or target_or_text

        if isinstance(raw_text, str):
            self.lines = [raw_text]
        elif isinstance(raw_text, list):
            self.lines = list(raw_text)
        else:
            self.lines = ["NOTE"]

        if (
            self.raw_target is not None
            and not is_topological_entity(self.raw_target)
            and isinstance(self.raw_target, (tuple, list))
            and len(self.raw_target) == 2
        ):
            self.target = (float(self.raw_target[0]), float(self.raw_target[1]))
            self.resolved = True
            self._explicit_coords = True

        target_view = view or CURRENT_VIEW.get()
        if target_view is not None:
            self._attach_to_view(target_view)
        else:
            target_sheet = CURRENT_SHEET.get()
            if target_sheet is not None and self not in target_sheet.annotations:
                target_sheet.annotations.append(self)

    @property
    def text(self) -> str:
        return " ".join(self.lines)

    def _rebind_to_view(self, view: SheetView) -> None:
        if not self._explicit_coords:
            self.resolved = False
            self._attach_to_view(view)

    def _attach_to_view(
        self, view: SheetView, *, resolved_target: tuple[float, float] | None = None
    ) -> None:
        """Attach to ``view``, resolving ``raw_target`` to sheet coordinates.

        Subclasses that already resolved ``raw_target`` (an Anchor) on this view may pass
        the resulting sheet point as ``resolved_target`` to skip a second resolution.
        """
        self.view = view
        if not self.resolved and self.raw_target is not None:
            if not isinstance(self.raw_target, (tuple, list)):
                self.raw_target = ensure_anchor(self.raw_target, view.shape) or self.raw_target
            self.target = (
                resolved_target
                if resolved_target is not None
                else resolve_point_to_sheet(self.raw_target, view)
            )
            if isinstance(self.raw_target, Anchor) and self.raw_target.is_stale:
                self.anchor_stale = True
                self.stale_reason = self.raw_target.stale_reason
                self.target = stale_point_to_sheet(self.raw_target, view) or self.target
            else:
                self.anchor_stale = False
                self.stale_reason = None
            self.resolved = True
        elif not self.resolved and self.raw_target is None:
            self.target = (view.center_x, view.center_y)
            self.resolved = True

        # Keep the landing shelf and text clear of the view's projected edges.
        self.elbow_offset = clear_elbow_offset(
            view,
            self.target,
            self.requested_elbow_offset,
            self.lines,
            self.font_size,
            self.shelf_length,
            self.align_right,
            obstacles=self._other_annotation_boxes(view),
        )
        self._register(view)

    def _other_annotation_boxes(self, view: SheetView) -> list[BBox2D]:
        """Boxes of the other annotations already placed on ``view``'s sheet (or the view)."""
        sheet = view.sheet or CURRENT_SHEET.get()
        pool = sheet.annotations if sheet is not None else view.annotations
        boxes: list[BBox2D] = []
        for ann in pool:
            if ann is self or isinstance(ann, CenterMark):
                continue
            box = ann.bounding_box_2d()
            if box is not None:
                boxes.append(box)
        return boxes

    def bounding_box_2d(self) -> BBox2D:
        return leader_bbox_2d(self.target, self.elbow_offset, self.shelf_length)

    def to_svg(self) -> str:
        tx, ty = self.target
        ex = tx + self.elbow_offset[0]
        ey = ty + self.elbow_offset[1]

        going_left = (self.elbow_offset[0] < 0) if self.align_right is None else self.align_right
        sx = ex + (-self.shelf_length if going_left else self.shelf_length)

        elements: list[str] = []

        # Terminator at target
        if self.terminator == "arrow":
            dir_x = tx - ex
            dir_y = ty - ey
            elements.append(render_arrowhead(tx, ty, dir_x, dir_y, length=2.2, half_width=0.6))
        else:
            elements.append(
                f'<circle cx="{tx:.2f}" cy="{ty:.2f}" r="0.6" class="leader-dot" fill="currentColor"/>'
            )

        # Leader polyline
        elements.append(
            f'<polyline points="{tx:.2f},{ty:.2f} {ex:.2f},{ey:.2f} {sx:.2f},{ey:.2f}" class="dim-line" stroke-width="0.3" fill="none"/>'
        )

        # Text lines
        text_x = ex - 2.0 if going_left else ex + 2.0
        text_anchor = "end" if going_left else "start"

        for i, line in enumerate(self.lines):
            ly = ey - 1.2 - ((len(self.lines) - 1 - i) * 3.4)
            elements.append(
                f'<text x="{text_x:.2f}" y="{ly:.2f}" class="leader-text" text-anchor="{text_anchor}" font-size="{self.font_size:.2f}">{html.escape(line)}</text>'
            )

        return f'<g class="leader-note">{"".join(elements)}</g>'

BOMBalloon

Bases: Annotation

ISO BOM balloon callout circle connected to component via leader.

Source code in src/build123d_techdraw/annotations/callouts.py
class BOMBalloon(Annotation):
    """ISO BOM balloon callout circle connected to component via leader."""

    def __init__(
        self,
        item_no: int | None = None,
        target: Any = None,
        balloon_center: tuple[float, float] | None = None,
        radius: float = 4.5,
        terminator: str = "dot",
        leader_offset: tuple[float, float] = (15.0, -15.0),
        view: SheetView | None = None,
        *,
        item: int | None = None,
        elbow_offset: tuple[float, float] | None = None,
        balloon_no: int | None = None,
        position: tuple[float, float] | None = None,
        anchor: Any = None,
    ):
        if target is None and anchor is not None:
            target = anchor
        resolved_no = (
            item
            if item is not None
            else (item_no if item_no is not None else (balloon_no if balloon_no is not None else 1))
        )
        self.item_no = int(resolved_no)
        self.radius = radius
        self.terminator = terminator
        self.leader_offset = elbow_offset if elbow_offset is not None else leader_offset
        self.view = view

        self.raw_target = target
        self.raw_position = position
        self.target: tuple[float, float] = (0.0, 0.0)
        self.resolved = False
        self._explicit_coords = False
        self.anchor_stale = False
        self.stale_reason: str | None = None

        if balloon_center is not None:
            self.balloon_center = (float(balloon_center[0]), float(balloon_center[1]))
            self.center_explicit = True
        elif target is not None and position is not None:
            self.balloon_center = (float(position[0]), float(position[1]))
            self.center_explicit = True
        else:
            self.balloon_center = (0.0, 0.0)
            self.center_explicit = False

        if position is not None and target is None:
            self.target = (float(position[0]), float(position[1]))
            if not self.center_explicit:
                self.balloon_center = (
                    self.target[0] + self.leader_offset[0],
                    self.target[1] + self.leader_offset[1],
                )
            self.resolved = True
            self._explicit_coords = True

        target_view = view or CURRENT_VIEW.get()
        if target_view is not None:
            self._attach_to_view(target_view)
        else:
            if (
                target is not None
                and not is_topological_entity(target)
                and isinstance(target, (tuple, list))
                and len(target) == 2
            ):
                self.target = (float(target[0]), float(target[1]))
                if not self.center_explicit:
                    self.balloon_center = (
                        self.target[0] + self.leader_offset[0],
                        self.target[1] + self.leader_offset[1],
                    )
                self.resolved = True
                self._explicit_coords = True
            target_sheet = CURRENT_SHEET.get()
            if target_sheet is not None and self not in target_sheet.annotations:
                target_sheet.annotations.append(self)

    @property
    def balloon_no(self) -> int:
        return self.item_no

    @balloon_no.setter
    def balloon_no(self, val: int) -> None:
        self.item_no = int(val)

    @property
    def position(self) -> tuple[float, float]:
        return self.target

    def _rebind_to_view(self, view: SheetView) -> None:
        if not self._explicit_coords:
            self.resolved = False
            self._attach_to_view(view)

    def _attach_to_view(self, view: SheetView) -> None:
        self.view = view
        if not self.resolved and self.raw_target is not None:
            if isinstance(self.raw_target, (tuple, list)):
                if len(self.raw_target) == 2:
                    self.target = view.to_sheet_coords(
                        float(self.raw_target[0]), float(self.raw_target[1])
                    )
                elif len(self.raw_target) == 3:
                    self.target = view.to_sheet_3d(
                        float(self.raw_target[0]),
                        float(self.raw_target[1]),
                        float(self.raw_target[2]),
                    )
                else:
                    self.target = (float(self.raw_target[0]), float(self.raw_target[1]))
            else:
                self.raw_target = ensure_anchor(self.raw_target, view.shape) or self.raw_target
                self.target = resolve_point_to_sheet(self.raw_target, view)
                if isinstance(self.raw_target, Anchor) and self.raw_target.is_stale:
                    self.anchor_stale = True
                    self.stale_reason = self.raw_target.stale_reason
                    self.target = stale_point_to_sheet(self.raw_target, view) or self.target
                else:
                    self.anchor_stale = False
                    self.stale_reason = None

            if not self.center_explicit:
                self.balloon_center = (
                    self.target[0] + self.leader_offset[0],
                    self.target[1] + self.leader_offset[1],
                )
            self.resolved = True
        elif not self.resolved and self.raw_target is None:
            self.target = (view.center_x, view.center_y)
            if not self.center_explicit:
                self.balloon_center = (
                    self.target[0] + self.leader_offset[0],
                    self.target[1] + self.leader_offset[1],
                )
            self.resolved = True

        self._register(view)

    def bounding_box_2d(self) -> BBox2D:
        bx, by = self.balloon_center
        r = self.radius
        return (bx - r, by - r, bx + r, by + r)

    def to_svg(self) -> str:
        tx, ty = self.target
        bx, by = self.balloon_center
        r = self.radius

        # Calculate intersection with balloon perimeter
        dx = bx - tx
        dy = by - ty
        dist = math.hypot(dx, dy)
        if dist > r:
            end_x = bx - (dx / dist) * r
            end_y = by - (dy / dist) * r
        else:
            end_x, end_y = bx, by

        if self.terminator == "arrow" and dist > 0.0:
            term_elem = render_arrowhead(tx, ty, -dx, -dy, length=2.5, half_width=0.7)
        else:
            term_elem = f'<circle cx="{tx:.2f}" cy="{ty:.2f}" r="0.8" class="balloon-dot"/>'

        return f"""
        <g class="bom-balloon">
            {term_elem}
            <line x1="{tx:.2f}" y1="{ty:.2f}" x2="{end_x:.2f}" y2="{end_y:.2f}" class="balloon-leader" stroke-width="0.3"/>
            <circle cx="{bx:.2f}" cy="{by:.2f}" r="{r:.2f}" class="balloon-circle" stroke-width="0.4"/>
            <text x="{bx:.2f}" y="{by + 1.2:.2f}" class="balloon-text" text-anchor="middle" font-size="3.6" font-weight="bold">{self.item_no}</text>
        </g>
        """

SectionCuttingLine

Bases: Annotation

ISO 128-3 cutting plane line with thick ends, corner bends, and viewing arrows.

Source code in src/build123d_techdraw/annotations/callouts.py
class SectionCuttingLine(Annotation):
    """ISO 128-3 cutting plane line with thick ends, corner bends, and viewing arrows."""

    def __init__(
        self,
        points: Sequence[Any],
        label: str = "A",
        arrow_dir: str | tuple[float, float] = "up",
        thick_length: float = 8.0,
        arrow_length: float = 6.0,
        view: SheetView | None = None,
    ):
        if len(points) < 2:
            raise ValueError("SectionCuttingLine requires at least 2 points.")

        self.label = label
        self.arrow_dir = arrow_dir
        self.thick_length = thick_length
        self.arrow_length = arrow_length
        self.view = view
        self.raw_points: list[Any] = list(points)
        self.points: list[tuple[float, float]] = []
        self.anchor_stale = False
        self.stale_reason: str | None = None

        target_view = view or CURRENT_VIEW.get()
        if target_view is not None:
            self._attach_to_view(target_view)
        else:
            resolved_points: list[tuple[float, float]] = []
            for pt in points:
                if isinstance(pt, (tuple, list)) and len(pt) >= 2:
                    resolved_points.append((float(pt[0]), float(pt[1])))
                else:
                    raise TypeError(
                        "SectionCuttingLine requires 2D (x, y) tuples when no view is attached."
                    )
            self.points = resolved_points
            target_sheet = CURRENT_SHEET.get()
            if target_sheet is not None and self not in target_sheet.annotations:
                target_sheet.annotations.append(self)

    def _rebind_to_view(self, view: SheetView) -> None:
        self._attach_to_view(view)

    def _attach_to_view(self, view: SheetView) -> None:
        self.view = view
        resolved_points: list[tuple[float, float]] = []
        stale_reasons: list[str] = []
        view_shape = view.shape

        for idx, pt in enumerate(self.raw_points):
            pt = ensure_anchor(pt, view_shape) or pt
            self.raw_points[idx] = pt
            resolved_pt = resolve_point_to_sheet(pt, view)
            if isinstance(pt, Anchor) and pt.is_stale:
                stale_reasons.append(pt.stale_reason or "Stale anchor")
                resolved_pt = stale_point_to_sheet(pt, view) or resolved_pt
            resolved_points.append(resolved_pt)

        self.points = resolved_points
        self.anchor_stale = bool(stale_reasons)
        self.stale_reason = "; ".join(stale_reasons) if stale_reasons else None

        self._register(view)

    def _arrow_normal(self, ux: float, uy: float) -> tuple[float, float]:
        if isinstance(self.arrow_dir, (tuple, list)):
            adx, ady = float(self.arrow_dir[0]), float(self.arrow_dir[1])
            alen = math.hypot(adx, ady)
            return (adx / alen, ady / alen) if alen > 0.0 else (0.0, 1.0)
        if self.arrow_dir in ("up", "left"):
            return -uy, ux
        return uy, -ux

    def to_svg(self) -> str:
        pts = self.points
        if len(pts) < 2:
            return ""

        segments: list[tuple[tuple[float, float], tuple[float, float], float, float, float]] = []
        for i in range(len(pts) - 1):
            x1, y1 = pts[i]
            x2, y2 = pts[i + 1]
            dx, dy = x2 - x1, y2 - y1
            seg_len = math.hypot(dx, dy)
            if seg_len > 1e-9:
                segments.append(((x1, y1), (x2, y2), dx / seg_len, dy / seg_len, seg_len))

        if not segments:
            return ""

        elements: list[str] = []
        num_segs = len(segments)
        bend_len = self.thick_length * 0.6

        for idx, ((x1, y1), (x2, y2), ux, uy, seg_len) in enumerate(segments):
            start_thick = min(self.thick_length if idx == 0 else bend_len, seg_len / 3.0)
            end_thick = min(self.thick_length if idx == num_segs - 1 else bend_len, seg_len / 3.0)

            sx, sy = x1 + ux * start_thick, y1 + uy * start_thick
            ex, ey = x2 - ux * end_thick, y2 - uy * end_thick

            # Central chain-thin line
            elements.append(
                f'<line x1="{sx:.2f}" y1="{sy:.2f}" x2="{ex:.2f}" y2="{ey:.2f}" '
                f'class="line-center" stroke-dasharray="10,2,2,2" stroke-width="0.35"/>'
            )
            # Start thick segment (outer end or corner bend)
            elements.append(
                f'<line x1="{x1:.2f}" y1="{y1:.2f}" x2="{sx:.2f}" y2="{sy:.2f}" '
                f'class="line-section-thick" stroke-width="0.8"/>'
            )
            # End thick segment (outer end or corner bend)
            elements.append(
                f'<line x1="{ex:.2f}" y1="{ey:.2f}" x2="{x2:.2f}" y2="{y2:.2f}" '
                f'class="line-section-thick" stroke-width="0.8"/>'
            )

        # Viewing direction arrows & labels at the two outer ends
        al = self.arrow_length
        (p0, _, ux0, uy0, _) = segments[0]
        nx0, ny0 = self._arrow_normal(ux0, uy0)
        (_, p_last, ux_last, uy_last, _) = segments[-1]
        nx_last, ny_last = self._arrow_normal(ux_last, uy_last)

        for (px, py), (nx, ny) in ((p0, (nx0, ny0)), (p_last, (nx_last, ny_last))):
            ax, ay = px + nx * al, py + ny * al
            lx, ly = px + nx * (al + 3.5), py + ny * (al + 3.5) + 1.5
            elements.append(
                f'<line x1="{px:.2f}" y1="{py:.2f}" x2="{ax:.2f}" y2="{ay:.2f}" '
                f'class="line-section-thick" stroke-width="0.6"/>'
            )
            elements.append(render_arrowhead(ax, ay, nx, ny, length=3.0, half_width=0.9))
            elements.append(
                f'<text x="{lx:.2f}" y="{ly:.2f}" class="section-label-text" '
                f'font-size="5.0" font-weight="bold" text-anchor="middle">{html.escape(self.label)}</text>'
            )

        return f'<g class="section-cutting-plane">{"".join(elements)}</g>'

build123d_techdraw.annotations.sheet_metal

Sheet metal flat-pattern annotations: bend lines, punch markers, and manufacturing schedules.

BendLineAnnotation

Bases: Annotation

Paper-space sheet metal bend centerline annotation with UP/DOWN styling and callout.

Source code in src/build123d_techdraw/annotations/sheet_metal.py
class BendLineAnnotation(Annotation):
    """Paper-space sheet metal bend centerline annotation with UP/DOWN styling and callout."""

    def __init__(
        self,
        bend: RecognizedBend | None = None,
        *,
        start: tuple[float, float] | None = None,
        end: tuple[float, float] | None = None,
        direction: BendDirection | str = BendDirection.UP,
        angle_deg: float = 90.0,
        inner_radius: float = 1.0,
        tag: str = "",
        bend_allowance: float | None = None,
        k_factor: float | None = None,
        tangent1: tuple[tuple[float, float], tuple[float, float]] | None = None,
        tangent2: tuple[tuple[float, float], tuple[float, float]] | None = None,
        show_label: bool = True,
        label_text: str | None = None,
        include_tag: bool = True,
        include_allowance: bool = False,
        show_bend_extents: bool = False,
        overhang: float = 2.0,
        label_mode: Literal["auto", "inline", "leader"] = "auto",
        leader_offset: tuple[float, float] | None = None,
        coords_are_model: bool = True,
        view: SheetView | None = None,
    ) -> None:
        self.bend = bend
        if bend is not None:
            self._model_start = (float(bend.start_2d[0]), float(bend.start_2d[1]))
            self._model_end = (float(bend.end_2d[0]), float(bend.end_2d[1]))
            self.direction = bend.direction
            self.angle_deg = bend.angle_deg
            self.inner_radius = bend.inner_radius
            self.tag = bend.tag
            self.bend_allowance: float | None = bend.bend_allowance
            self.k_factor: float | None = bend.k_factor
            self._model_tangent1: tuple[tuple[float, float], tuple[float, float]] | None = (
                bend.tangent1_start_2d,
                bend.tangent1_end_2d,
            )
            self._model_tangent2: tuple[tuple[float, float], tuple[float, float]] | None = (
                bend.tangent2_start_2d,
                bend.tangent2_end_2d,
            )
        else:
            if start is None or end is None:
                raise ValueError("Provide either 'bend' or explicit 'start' and 'end' coordinates.")
            self._model_start = (float(start[0]), float(start[1]))
            self._model_end = (float(end[0]), float(end[1]))
            self.direction = (
                direction
                if isinstance(direction, BendDirection)
                else BendDirection(str(direction).strip().upper())
            )
            self.angle_deg = float(angle_deg)
            self.inner_radius = float(inner_radius)
            self.tag = str(tag)
            self.bend_allowance = bend_allowance
            self.k_factor = k_factor
            self._model_tangent1 = tangent1
            self._model_tangent2 = tangent2

        self.show_label = show_label
        self.label_text = label_text
        self.include_tag = include_tag
        self.include_allowance = include_allowance
        self.show_bend_extents = show_bend_extents
        self.overhang = float(overhang)
        self.label_mode = label_mode
        self.leader_offset = (
            (float(leader_offset[0]), float(leader_offset[1]))
            if leader_offset is not None
            else None
        )
        self.coords_are_model = coords_are_model

        self.start: tuple[float, float] = self._model_start
        self.end: tuple[float, float] = self._model_end
        self.tangent1: tuple[tuple[float, float], tuple[float, float]] | None = self._model_tangent1
        self.tangent2: tuple[tuple[float, float], tuple[float, float]] | None = self._model_tangent2
        self.view: SheetView | None = view

        target_view = view or CURRENT_VIEW.get()
        if target_view is not None:
            self._attach_to_view(target_view)
        else:
            target_sheet = CURRENT_SHEET.get()
            if target_sheet is not None and self not in target_sheet.annotations:
                target_sheet.annotations.append(self)

    def _attach_to_view(self, view: SheetView) -> None:
        self.view = view
        if self.coords_are_model:
            self.start = view.to_sheet_coords(*self._model_start)
            self.end = view.to_sheet_coords(*self._model_end)
            if self._model_tangent1 is not None:
                self.tangent1 = (
                    view.to_sheet_coords(*self._model_tangent1[0]),
                    view.to_sheet_coords(*self._model_tangent1[1]),
                )
            if self._model_tangent2 is not None:
                self.tangent2 = (
                    view.to_sheet_coords(*self._model_tangent2[0]),
                    view.to_sheet_coords(*self._model_tangent2[1]),
                )
        else:
            self.start = self._model_start
            self.end = self._model_end
            self.tangent1 = self._model_tangent1
            self.tangent2 = self._model_tangent2
        self._register(view)

    def _rebind_to_view(self, view: SheetView) -> None:
        self._attach_to_view(view)

    def formatted_label(self) -> str:
        """Return the resolved callout text for this bend line."""
        if self.label_text is not None:
            return self.label_text
        if self.bend is not None:
            return self.bend.format_callout(
                include_tag=self.include_tag,
                include_allowance=self.include_allowance,
            )
        core = (
            f"{self.direction.value} {_fmt_num(self.angle_deg, 1)}° "
            f"R{_fmt_num(self.inner_radius, 2)}"
        )
        if self.include_allowance and self.bend_allowance is not None:
            core += f" (BA {_fmt_num(self.bend_allowance, 2)})"
        if self.include_tag and self.tag:
            return f"{self.tag}: {core}"
        return core

    def _resolved_geometry(
        self,
    ) -> tuple[
        tuple[float, float],
        tuple[float, float],
        float,
        float,
        str,
        str,
        float,
    ]:
        """Return ``(p1_ext, p2_ext, mx, my, effective_mode, label, label_width)``."""
        x1, y1 = self.start
        x2, y2 = self.end
        dx = x2 - x1
        dy = y2 - y1
        dist = math.hypot(dx, dy)
        if dist > 1e-6:
            ux, uy = dx / dist, dy / dist
            p1 = (x1 - ux * self.overhang, y1 - uy * self.overhang)
            p2 = (x2 + ux * self.overhang, y2 + uy * self.overhang)
        else:
            p1 = (x1, y1)
            p2 = (x2, y2)
        mx = 0.5 * (x1 + x2)
        my = 0.5 * (y1 + y2)

        lbl = self.formatted_label()
        lbl_w = max(8.0, len(lbl) * 1.55 + 2.0)

        if self.label_mode == "inline":
            eff_mode = "inline"
        elif self.label_mode == "leader":
            eff_mode = "leader"
        else:
            eff_mode = "inline" if dist >= lbl_w + 6.0 else "leader"
        return p1, p2, mx, my, eff_mode, lbl, lbl_w

    def bounding_box_2d(self) -> BBox2D | None:
        p1, p2, mx, my, eff_mode, _, lbl_w = self._resolved_geometry()
        if not self.show_label:
            return (min(p1[0], p2[0]), min(p1[1], p2[1]), max(p1[0], p2[0]), max(p1[1], p2[1]))

        if eff_mode == "inline":
            ang_rad = math.atan2(self.end[1] - self.start[1], self.end[0] - self.start[0])
            ang_deg = math.degrees(ang_rad)
            while ang_deg <= -90.0:
                ang_deg += 180.0
            while ang_deg > 90.0:
                ang_deg -= 180.0
            rad = math.radians(ang_deg)
            hw = 0.5 * lbl_w
            hh = 1.7
            rx = abs(hw * math.cos(rad)) + abs(hh * math.sin(rad))
            ry = abs(hw * math.sin(rad)) + abs(hh * math.cos(rad))
            return (mx - rx, my - ry, mx + rx, my + ry)

        dx_off, dy_off = self.leader_offset if self.leader_offset is not None else (12.0, -10.0)
        ex = mx + dx_off
        ey = my + dy_off
        shelf_w = lbl_w + 2.0
        sx = ex + (shelf_w if dx_off >= 0.0 else -shelf_w)
        return (min(ex, sx), ey - 3.6, max(ex, sx), ey + 0.6)

    def to_svg(self) -> str:
        p1, p2, mx, my, eff_mode, lbl, lbl_w = self._resolved_geometry()
        is_up = self.direction == BendDirection.UP
        line_cls = "line-bend-up" if is_up else "line-bend-down"
        text_cls = "bend-note-up" if is_up else "bend-note-down"

        parts: list[str] = []
        if self.show_bend_extents:
            for tan in (self.tangent1, self.tangent2):
                if tan is not None:
                    (tx1, ty1), (tx2, ty2) = tan
                    parts.append(
                        f'<line x1="{tx1:.2f}" y1="{ty1:.2f}" x2="{tx2:.2f}" y2="{ty2:.2f}" '
                        'class="line-bend-tangent" stroke-width="0.18"/>'
                    )

        parts.append(
            f'<line x1="{p1[0]:.2f}" y1="{p1[1]:.2f}" x2="{p2[0]:.2f}" y2="{p2[1]:.2f}" '
            f'class="{line_cls}" stroke-width="0.25"/>'
        )

        if self.show_label and lbl:
            if eff_mode == "inline":
                ang_deg = math.degrees(
                    math.atan2(self.end[1] - self.start[1], self.end[0] - self.start[0])
                )
                while ang_deg <= -90.0:
                    ang_deg += 180.0
                while ang_deg > 90.0:
                    ang_deg -= 180.0
                text_y = 0.0 if abs(ang_deg) > 0.01 else 0.85
                tf = (
                    f"translate({mx:.2f}, {my:.2f}) rotate({ang_deg:.2f})"
                    if abs(ang_deg) > 0.01
                    else f"translate({mx:.2f}, {my:.2f})"
                )
                parts.append(
                    f'<g transform="{tf}">'
                    f'<rect x="{-lbl_w * 0.5:.2f}" y="-1.70" width="{lbl_w:.2f}" height="3.40" '
                    'rx="0.4" class="bend-knockout"/>'
                    f'<text x="0" y="{text_y:.2f}" class="bend-note-text {text_cls}" '
                    f'font-size="2.5" text-anchor="middle">{html.escape(lbl)}</text>'
                    "</g>"
                )
            else:
                dx_off, dy_off = (
                    self.leader_offset if self.leader_offset is not None else (12.0, -10.0)
                )
                ex = mx + dx_off
                ey = my + dy_off
                shelf_w = lbl_w + 2.0
                sx = ex + (shelf_w if dx_off >= 0.0 else -shelf_w)
                tx = 0.5 * (ex + sx)
                parts.append(f'<circle cx="{mx:.2f}" cy="{my:.2f}" r="0.65" class="{text_cls}"/>')
                parts.append(
                    f'<polyline points="{mx:.2f},{my:.2f} {ex:.2f},{ey:.2f} {sx:.2f},{ey:.2f}" '
                    f'class="{line_cls}" stroke-dasharray="none" stroke-width="0.25" fill="none"/>'
                )
                parts.append(
                    f'<text x="{tx:.2f}" y="{ey - 1.0:.2f}" class="bend-note-text {text_cls}" '
                    f'font-size="2.5" text-anchor="middle">{html.escape(lbl)}</text>'
                )

        return f'<g class="bend-annotation">{"".join(parts)}</g>'

formatted_label()

Return the resolved callout text for this bend line.

Source code in src/build123d_techdraw/annotations/sheet_metal.py
def formatted_label(self) -> str:
    """Return the resolved callout text for this bend line."""
    if self.label_text is not None:
        return self.label_text
    if self.bend is not None:
        return self.bend.format_callout(
            include_tag=self.include_tag,
            include_allowance=self.include_allowance,
        )
    core = (
        f"{self.direction.value} {_fmt_num(self.angle_deg, 1)}° "
        f"R{_fmt_num(self.inner_radius, 2)}"
    )
    if self.include_allowance and self.bend_allowance is not None:
        core += f" (BA {_fmt_num(self.bend_allowance, 2)})"
    if self.include_tag and self.tag:
        return f"{self.tag}: {core}"
    return core

PunchMarker

Bases: Annotation

Paper-space CNC punch / cutout marker with crosshair, tooling symbol, and tag.

Source code in src/build123d_techdraw/annotations/sheet_metal.py
class PunchMarker(Annotation):
    """Paper-space CNC punch / cutout marker with crosshair, tooling symbol, and tag."""

    def __init__(
        self,
        punch: RecognizedPunch | None = None,
        *,
        center: tuple[float, float] | None = None,
        punch_type: PunchType | str = PunchType.ROUND,
        tag: str = "",
        width: float = 0.0,
        length: float = 0.0,
        angle_deg: float = 0.0,
        callout: str | None = None,
        show_tag: bool = True,
        show_callout: bool = False,
        leader_offset: tuple[float, float] = (14.0, -10.0),
        crosshair_extension: float = 2.0,
        coords_are_model: bool = True,
        view: SheetView | None = None,
    ) -> None:
        self.punch = punch
        if punch is not None:
            self._model_center = (float(punch.center_2d[0]), float(punch.center_2d[1]))
            self.punch_type = punch.punch_type
            self.tag = punch.tag
            self.width = punch.width
            self.length = punch.length
            self.angle_deg = punch.angle_deg
            self.callout = callout if callout is not None else punch.format_callout()
        else:
            if center is None:
                raise ValueError("Provide either 'punch' or explicit 'center' coordinates.")
            self._model_center = (float(center[0]), float(center[1]))
            self.punch_type = (
                punch_type
                if isinstance(punch_type, PunchType)
                else PunchType(str(punch_type).strip().upper())
            )
            self.tag = str(tag)
            self.width = float(width)
            self.length = float(length) if length > 0.0 else float(width)
            self.angle_deg = float(angle_deg)
            self.callout = callout if callout is not None else (self.tag or self.punch_type.value)

        self.show_tag = show_tag
        self.show_callout = show_callout
        self.leader_offset = (float(leader_offset[0]), float(leader_offset[1]))
        self.crosshair_extension = float(crosshair_extension)
        self.coords_are_model = coords_are_model

        self.center: tuple[float, float] = self._model_center
        self.view: SheetView | None = view

        target_view = view or CURRENT_VIEW.get()
        if target_view is not None:
            self._attach_to_view(target_view)
        else:
            target_sheet = CURRENT_SHEET.get()
            if target_sheet is not None and self not in target_sheet.annotations:
                target_sheet.annotations.append(self)

    def _attach_to_view(self, view: SheetView) -> None:
        self.view = view
        self.center = (
            view.to_sheet_coords(*self._model_center)
            if self.coords_are_model
            else self._model_center
        )
        self._register(view)

    def _rebind_to_view(self, view: SheetView) -> None:
        self._attach_to_view(view)

    def _tag_position(self) -> tuple[float, float]:
        """Compute upper-right tag text anchor position clear of the punch contour."""
        cx, cy = self.center
        scale = self.view.scale if self.view is not None else 1.0
        hl = 0.5 * self.length * scale
        hw = 0.5 * self.width * scale
        rad = math.radians(self.angle_deg)
        rx = abs(hl * math.cos(rad)) + abs(hw * math.sin(rad))
        ry = abs(hl * math.sin(rad)) + abs(hw * math.cos(rad))
        dx = max(2.0, rx + 1.0) if max(rx, ry) > 1.8 else 2.0
        dy = -max(1.4, ry + 0.8) if max(rx, ry) > 1.8 else -1.4
        return (cx + dx, cy + dy)

    def bounding_box_2d(self) -> BBox2D | None:
        cx, cy = self.center
        if self.show_callout and self.callout:
            dx, dy = self.leader_offset
            ex, ey = cx + dx, cy + dy
            shelf_w = max(12.0, len(self.callout) * 1.5 + 3.0)
            sx = ex + (shelf_w if dx >= 0.0 else -shelf_w)
            return (min(ex, sx), ey - 3.5, max(ex, sx), ey + 0.5)
        if self.show_tag and self.tag:
            tx, ty = self._tag_position()
            tw = max(4.0, len(self.tag) * 1.45)
            return (tx - 0.2, ty - 2.4, tx + tw, ty + 0.4)
        return (cx - 2.0, cy - 2.0, cx + 2.0, cy + 2.0)

    def to_svg(self) -> str:
        cx, cy = self.center
        arm = 2.0 + self.crosshair_extension
        rad = math.radians(-self.angle_deg)  # SVG Y is down
        ca, sa = math.cos(rad), math.sin(rad)

        # Oriented crosshair lines
        hx1, hy1 = cx - arm * ca, cy - arm * sa
        hx2, hy2 = cx + arm * ca, cy + arm * sa
        vx1, vy1 = cx + arm * sa, cy - arm * ca
        vx2, vy2 = cx - arm * sa, cy + arm * ca

        parts: list[str] = [
            f'<line x1="{hx1:.2f}" y1="{hy1:.2f}" x2="{hx2:.2f}" y2="{hy2:.2f}" '
            'class="punch-marker" stroke-width="0.22"/>',
            f'<line x1="{vx1:.2f}" y1="{vy1:.2f}" x2="{vx2:.2f}" y2="{vy2:.2f}" '
            'class="punch-marker" stroke-width="0.22"/>',
        ]

        # Compact tooling glyph centered at (cx, cy)
        rot_attr = f" rotate({-self.angle_deg:.2f})" if abs(self.angle_deg) > 0.01 else ""
        if self.punch_type == PunchType.ROUND:
            parts.append(
                f'<circle cx="{cx:.2f}" cy="{cy:.2f}" r="0.90" class="punch-marker" stroke-width="0.22"/>'
            )
        elif self.punch_type == PunchType.OBROUND:
            parts.append(
                f'<g transform="translate({cx:.2f}, {cy:.2f}){rot_attr}">'
                '<rect x="-1.60" y="-0.75" width="3.20" height="1.50" rx="0.75" '
                'class="punch-marker" stroke-width="0.22"/></g>'
            )
        elif self.punch_type in (PunchType.SQUARE, PunchType.RECTANGLE):
            rw = 2.40 if self.punch_type == PunchType.RECTANGLE else 1.80
            parts.append(
                f'<g transform="translate({cx:.2f}, {cy:.2f}){rot_attr}">'
                f'<rect x="{-rw * 0.5:.2f}" y="-0.90" width="{rw:.2f}" height="1.80" '
                'class="punch-marker" stroke-width="0.22"/></g>'
            )
        elif self.punch_type == PunchType.D_HOLE:
            parts.append(
                f'<g transform="translate({cx:.2f}, {cy:.2f}){rot_attr}">'
                '<path d="M -0.4 -0.9 A 0.9 0.9 0 1 1 -0.4 0.9 Z" '
                'class="punch-marker" stroke-width="0.22"/></g>'
            )
        else:
            parts.append(
                f'<g transform="translate({cx:.2f}, {cy:.2f}){rot_attr}">'
                '<polygon points="0,-1.2 1.2,0 0,1.2 -1.2,0" '
                'class="punch-marker" stroke-width="0.22"/></g>'
            )

        if self.show_callout and self.callout:
            dx, dy = self.leader_offset
            ex, ey = cx + dx, cy + dy
            shelf_w = max(12.0, len(self.callout) * 1.5 + 3.0)
            sx = ex + (shelf_w if dx >= 0.0 else -shelf_w)
            tx = 0.5 * (ex + sx)
            parts.append(f'<circle cx="{cx:.2f}" cy="{cy:.2f}" r="0.55" class="leader-dot"/>')
            parts.append(
                f'<polyline points="{cx:.2f},{cy:.2f} {ex:.2f},{ey:.2f} {sx:.2f},{ey:.2f}" '
                'class="dim-line" stroke-width="0.25" fill="none"/>'
            )
            parts.append(
                f'<text x="{tx:.2f}" y="{ey - 1.0:.2f}" class="punch-tag-text" '
                f'font-size="2.3" text-anchor="middle">{html.escape(self.callout)}</text>'
            )
        elif self.show_tag and self.tag:
            tx, ty = self._tag_position()
            parts.append(
                f'<text x="{tx:.2f}" y="{ty:.2f}" class="punch-tag-text" '
                f'font-size="2.2" text-anchor="start">{html.escape(self.tag)}</text>'
            )

        return f'<g class="punch-annotation">{"".join(parts)}</g>'

BendTable

Bases: Table

Engineering Bend Schedule table listing bend tags, directions, angles, radii, K, BA, BD.

Source code in src/build123d_techdraw/annotations/sheet_metal.py
class BendTable(Table):
    """Engineering Bend Schedule table listing bend tags, directions, angles, radii, K, BA, BD."""

    def __init__(
        self,
        source: FlatPattern | Sequence[RecognizedBend],
        position: tuple[float, float] = (0.0, 0.0),
        *,
        title: str | None = None,
        include_k_factor: bool = True,
        include_deduction: bool = True,
        view: SheetView | None = None,
        sheet: DrawingSheet | None = None,
    ) -> None:
        if isinstance(source, FlatPattern):
            bends = list(source.bends)
            resolved_title = (
                title
                if title is not None
                else (
                    f"BEND SCHEDULE (t={_fmt_num(source.thickness, 2)}mm · "
                    f"BLANK {_fmt_num(source.blank_width, 1)}×{_fmt_num(source.blank_height, 1)}mm)"
                )
            )
        else:
            bends = list(source)
            resolved_title = title if title is not None else "BEND SCHEDULE"

        headers = ["TAG", "DIR", "ANGLE", "INNER R"]
        col_widths = [13.0, 14.0, 15.0, 16.0]
        alignments = ["center", "center", "right", "right"]
        if include_k_factor:
            headers.append("K")
            col_widths.append(13.0)
            alignments.append("right")
        headers.append("BA (mm)")
        col_widths.append(18.0)
        alignments.append("right")
        if include_deduction:
            headers.append("BD (mm)")
            col_widths.append(18.0)
            alignments.append("right")

        rows: list[list[Any]] = []
        cell_styles: dict[tuple[int, int], dict[str, Any]] = {}
        for r_idx, b in enumerate(bends):
            row: list[str] = [
                b.tag or f"B{r_idx + 1}",
                b.direction.value,
                f"{_fmt_num(b.angle_deg, 1)}°",
                f"R{_fmt_num(b.inner_radius, 2)}",
            ]
            if include_k_factor:
                row.append(_fmt_num(b.k_factor, 2))
            row.append(_fmt_num(b.bend_allowance, 2))
            if include_deduction:
                row.append(_fmt_num(b.bend_deduction, 2))
            rows.append(row)
            dir_cls = "bend-note-up" if b.direction == BendDirection.UP else "bend-note-down"
            cell_styles[(r_idx, 1)] = {"css_class": dir_cls, "font_weight": "700"}

        if not rows:
            rows = [["—", "NONE", "—", "—"] + ["—"] * (len(headers) - 4)]

        super().__init__(
            headers=headers,
            rows=rows,
            position=position,
            col_widths=col_widths,
            title=resolved_title,
            alignments=alignments,
            row_height=4.8,
            header_height=5.0,
            title_height=5.6,
            font_size=2.3,
            header_font_size=2.0,
            title_font_size=2.5,
            cell_padding=2.0,
            cell_styles=cell_styles,
            word_wrap=False,
            view=view,
            sheet=sheet,
        )

PunchTable

Bases: Table

Engineering Punch / Cutout Tooling Schedule (grouped summary or itemized coordinates).

Source code in src/build123d_techdraw/annotations/sheet_metal.py
class PunchTable(Table):
    """Engineering Punch / Cutout Tooling Schedule (grouped summary or itemized coordinates)."""

    def __init__(
        self,
        source: FlatPattern | Sequence[RecognizedPunch],
        position: tuple[float, float] = (0.0, 0.0),
        *,
        title: str = "PUNCH TOOLING SCHEDULE",
        grouped: bool = True,
        view: SheetView | None = None,
        sheet: DrawingSheet | None = None,
    ) -> None:
        punches = list(source.punches) if isinstance(source, FlatPattern) else list(source)

        if grouped:
            headers = ["TAG", "TYPE", "SIZE (mm)", "ANGLE", "QTY"]
            col_widths = [18.0, 22.0, 26.0, 14.0, 12.0]
            alignments = ["left", "left", "left", "right", "right"]

            buckets: dict[tuple[str, str, float, str | None], list[RecognizedPunch]] = {}
            for p in punches:
                key = (
                    p.punch_type.value,
                    p.format_size(),
                    round(p.angle_deg, 1),
                    p.tool_id,
                )
                buckets.setdefault(key, []).append(p)

            rows: list[list[Any]] = []
            for p_type_str, size_str, ang_val, _ in buckets:
                group = buckets[(p_type_str, size_str, ang_val, _)]
                tags = ", ".join(p.tag for p in group if p.tag)
                if len(tags) > 10 and len(group) > 1:
                    tags = f"{group[0].tag}–{group[-1].tag}"
                ang_str = f"{_fmt_num(ang_val, 1)}°" if abs(ang_val) > 0.05 else "0°"
                rows.append([tags or "—", p_type_str, size_str, ang_str, str(len(group))])
        else:
            headers = ["TAG", "TYPE", "SIZE (mm)", "X (mm)", "Y (mm)"]
            col_widths = [14.0, 22.0, 26.0, 18.0, 18.0]
            alignments = ["center", "left", "left", "right", "right"]
            rows = [
                [
                    p.tag or f"P{i + 1}",
                    p.punch_type.value,
                    p.format_size(),
                    _fmt_num(p.center_2d[0], 2),
                    _fmt_num(p.center_2d[1], 2),
                ]
                for i, p in enumerate(punches)
            ]

        if not rows:
            rows = [["—", "NONE", "—", "—", "—"]]

        super().__init__(
            headers=headers,
            rows=rows,
            position=position,
            col_widths=col_widths,
            title=title,
            alignments=alignments,
            row_height=4.8,
            header_height=5.0,
            title_height=5.6,
            font_size=2.3,
            header_font_size=2.0,
            title_font_size=2.5,
            cell_padding=2.0,
            word_wrap=False,
            view=view,
            sheet=sheet,
        )