Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion src/draftwright/annotations/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,15 @@
from draftwright.annotations._placement_occupancy import ( # noqa: F401 — stable _common imports
_PAGE_SPANNING_RIDERS,
CROSSABLE_TYPES,
DeferredCompactCandidate,
annotation_ink_clear,
annotation_ink_obstacles,
annotation_obstacle_boxes,
annotation_text_ink_clear,
balloon_annotation_label_boxes,
balloon_geometry_hits_annotation_labels,
box_within_page_and_clear,
compact_probe_clear,
corridor_blockers,
full_strip_message,
is_page_spanning_rider,
Expand Down Expand Up @@ -2253,7 +2255,15 @@ def _compact_strip_candidate_ink(run) -> None:
index = next((i for i, (key, _dim) in enumerate(solved) if key == name), None)
original = solved[index][1] if index is not None else None
others = [item for key, item in solved if key != name]
for candidate in alternatives(original):
for proposal in alternatives(original):
if isinstance(proposal, DeferredCompactCandidate):
if not compact_probe_clear(
dwg, proposal, others, (forbid or {}).get(name), label_clear
):
continue
candidate = proposal.materialize()
else:
candidate = proposal
if (
original is not None
and hasattr(candidate, "arc_radius")
Expand Down
146 changes: 96 additions & 50 deletions src/draftwright/annotations/_gdt.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from draftwright.annotations._common import (
PRIORITY,
CorridorCandidate,
DeferredCompactCandidate,
_anno_box,
_box_hits,
annotation_ink_clear,
Expand Down Expand Up @@ -80,8 +81,7 @@ class _GdtDropState:

def _gdt_glyph(item, draft):
"""Build the ISO 1101/5459/1302 glyph sketch for one GD&T IR item at the origin
(the :class:`Leader` repositions it). A fresh sketch per call — the leader translate
must not alias a shared object across the strip solve's repeated probe builds."""
(the :class:`Leader` repositions a moved copy of it)."""
if item.kind == "control_frame":
tolerance = item.display_tolerance or item.tolerance
if item.spherical_diameter:
Expand Down Expand Up @@ -324,17 +324,30 @@ def _gdt_visual_finish(glyph, draft, value: str) -> str:
return ""


def _attach_gdt_text_evidence(leader, glyph, item, draft) -> None:
"""Keep the placed glyph's value beside PDF text for independent PMI lint."""
leader.pdf_text_relative_specs = _gdt_pdf_text_specs(glyph, item, draft)
def _gdt_text_evidence(glyph, item, draft) -> dict[str, object]:
"""Validate one immutable glyph once, independently of its leader position."""
evidence: dict[str, object] = {
"pdf_text_relative_specs": _gdt_pdf_text_specs(glyph, item, draft)
}
if item.kind == "finish":
leader.gdt_visual_finish = _gdt_visual_finish(glyph, draft, item.ra)
evidence["gdt_visual_finish"] = _gdt_visual_finish(glyph, draft, item.ra)
if item.kind == "control_frame":
zone = _gdt_visual_zone(glyph, draft)
leader.gdt_visual_tolerance = _gdt_visual_tolerance(
glyph, draft, zone, modifier=bool(item.modifier)
)
leader.gdt_visual_zone = zone if leader.gdt_visual_tolerance else ""
tolerance = _gdt_visual_tolerance(glyph, draft, zone, modifier=bool(item.modifier))
evidence["gdt_visual_tolerance"] = tolerance
evidence["gdt_visual_zone"] = zone if tolerance else ""
return evidence


def _apply_gdt_text_evidence(leader, evidence: dict[str, object]) -> None:
"""Keep the validated glyph's value beside PDF text for independent PMI lint."""
for name, value in evidence.items():
setattr(leader, name, value)


def _attach_gdt_text_evidence(leader, glyph, item, draft) -> None:
"""Attach independently checked glyph evidence to a placed leader."""
_apply_gdt_text_evidence(leader, _gdt_text_evidence(glyph, item, draft))


def _gdt_retry_sides(side: str, *, normal_side_only: bool) -> tuple[str, ...]:
Expand Down Expand Up @@ -538,7 +551,7 @@ def _retry():


def _gdt_compact_candidates(
original, build, strip, size, horizontal, item, site, tier, material_field
original, build, ink_at, strip, size, horizontal, item, site, tier, material_field
):
"""Nearest-first same-strip landings checked later against exact ink.

Expand All @@ -564,14 +577,12 @@ def _gdt_compact_candidates(
if travel >= distance - 1e-6:
break
pos = site + strip.direction * travel
candidate = build(pos)
proposal = ink_at(pos)
# A symbol inside the whole-view box must sit in projected
# whitespace, not on a blank face with no visible edge. The
# shared postsolve also checks visible edges and exact ink.
if _datum_label_has_whitespace(
candidate.label_bbox, strip, horizontal, material_field
):
yield candidate
if _datum_label_has_whitespace(proposal.label_bbox, strip, horizontal, material_field):
yield proposal
near = strip.anchor + strip.direction * (strip.gap + extent / 2.0)
distance = (original_pos - near) * strip.direction
if distance <= 1e-6:
Expand All @@ -583,103 +594,138 @@ def _gdt_compact_candidates(
pos = near + strip.direction * travel
if abs(pos - original_pos) <= 1e-6:
return
yield build(pos)
yield ink_at(pos)


def _gdt_candidate_builders(
item, draft, leader_ctor, fallback_glyph, px, py, horizontal, strip, size, tier, material_field
):
"""Build one glyph's primary and fallback leaders plus bounded strip retries."""
# Every retry moves the same validated glyph. Its value/zone checks are expensive
# OCC operations, but do not depend on the eventual leader elbow.
evidence = _gdt_text_evidence(fallback_glyph, item, draft) if item.kind != "note" else {}
glyph_box = fallback_glyph.bounding_box()

def _build(pos, _px=px, _py=py, _hz=horizontal, _it=item):
g = _gdt_glyph(_it, draft)
tip = (_px, _py)
def _elbow(pos, _hz=horizontal):
# Keep the analytical preflight and actual helper's zero-shaft guard identical.
if _hz:
delta = pos - py
return px, pos if abs(delta) >= _MIN_LEADER else py + math.copysign(
_MIN_LEADER, delta or 1.0
)
delta = pos - px
return pos if abs(delta) >= _MIN_LEADER else px + math.copysign(
_MIN_LEADER, delta or 1.0
), py

def _label_bbox_at(pos):
elbow_x, elbow_y = _elbow(pos)
shelf_dir = 1.0 if elbow_x >= px else -1.0
anchor_x = glyph_box.min.X if shelf_dir > 0 else glyph_box.max.X
dx = elbow_x + shelf_dir * draft.pad_around_text - anchor_x
dy = elbow_y - (glyph_box.min.Y + glyph_box.max.Y) / 2.0
return (
glyph_box.min.X + dx,
glyph_box.min.Y + dy,
glyph_box.max.X + dx,
glyph_box.max.Y + dy,
)

def _ink_at(pos):
elbow = _elbow(pos)
shelf_dir = 1.0 if elbow[0] >= px else -1.0
shelf_end = (elbow[0] + shelf_dir * draft.pad_around_text, elbow[1])
return DeferredCompactCandidate(
label_bbox=_label_bbox_at(pos),
materialize=lambda _pos=pos: _build(_pos),
tip=(px, py),
elbow=elbow,
segments=(((px, py), elbow), (elbow, shelf_end)),
analytical_straight_leader=True,
)

def _build(pos, _hz=horizontal):
tip = (px, py)
# A zero-length leader shaft (the projected site coincides with the solved tier —
# `pos == py` above/below, `pos == px` left/right) makes OCC's edge builder raise,
# which would crash the whole build on a public-IR declaration. Guarantee a
# minimum shaft along the stacking axis (nudge outward; 0.05 mm is invisible) so
# `_build` is total — the drop-don't-crash invariant holds for every build call.
if _hz:
dy = pos - _py
pos = pos if abs(dy) >= _MIN_LEADER else _py + math.copysign(_MIN_LEADER, dy or 1.0)
elbow = (_px, pos)
else:
dx = pos - _px
pos = pos if abs(dx) >= _MIN_LEADER else _px + math.copysign(_MIN_LEADER, dx or 1.0)
elbow = (pos, _py)
elbow = _elbow(pos, _hz)
leader = leader_ctor(
tip=tip,
elbow=elbow,
label="",
draft=draft,
callout=g,
all_around=getattr(_it, "all_around", False),
all_over=getattr(_it, "all_over", False),
callout=fallback_glyph,
all_around=getattr(item, "all_around", False),
all_over=getattr(item, "all_over", False),
)
if _it.kind == "note":
if item.kind == "note":
# The outer leader intentionally has label="" because the visible
# payload is a TextBlock callout. Preserve the authored note and measure
# the embedded Text renderer's face-dependent newline pitch for PDF.
leader.pdf_text = _font_safe_text(_it.text)
leader.pdf_text = _font_safe_text(item.text)
leader.pdf_text_font_style = "REGULAR"
leader.pdf_text_line_spacing = _text_line_spacing_em(
draft.font_size,
getattr(draft, "font_path", DEFAULT_FONT_PATH),
getattr(draft, "font", "Arial"),
)
else:
_attach_gdt_text_evidence(leader, g, _it, draft)
_apply_gdt_text_evidence(leader, evidence)
return leader

def _build_at(elbow, _px=px, _py=py, _it=item, _g=fallback_glyph):
def _build_at(elbow):
leader = leader_ctor(
tip=(_px, _py),
tip=(px, py),
elbow=(*elbow, 0),
label="",
draft=draft,
callout=_g,
all_around=getattr(_it, "all_around", False),
all_over=getattr(_it, "all_over", False),
callout=fallback_glyph,
all_around=getattr(item, "all_around", False),
all_over=getattr(item, "all_over", False),
)
if _it.kind == "note":
leader.pdf_text = _font_safe_text(_it.text)
if item.kind == "note":
leader.pdf_text = _font_safe_text(item.text)
leader.pdf_text_font_style = "REGULAR"
leader.pdf_text_line_spacing = _text_line_spacing_em(
draft.font_size,
getattr(draft, "font_path", DEFAULT_FONT_PATH),
getattr(draft, "font", "Arial"),
)
else:
_attach_gdt_text_evidence(leader, _g, _it, draft)
_apply_gdt_text_evidence(leader, evidence)
return leader

def _build_routed(bends, elbow, _px=px, _py=py, _it=item, _g=fallback_glyph):
def _build_routed(bends, elbow):
leader = RoutedLeader(
(_px, _py),
(px, py),
bends,
elbow,
"",
draft,
callout=_g,
all_around=getattr(_it, "all_around", False),
all_over=getattr(_it, "all_over", False),
callout=fallback_glyph,
all_around=getattr(item, "all_around", False),
all_over=getattr(item, "all_over", False),
)
if _it.kind == "note":
leader.pdf_text = _font_safe_text(_it.text)
if item.kind == "note":
leader.pdf_text = _font_safe_text(item.text)
leader.pdf_text_font_style = "REGULAR"
leader.pdf_text_line_spacing = _text_line_spacing_em(
draft.font_size,
getattr(draft, "font_path", DEFAULT_FONT_PATH),
getattr(draft, "font", "Arial"),
)
else:
_attach_gdt_text_evidence(leader, _g, _it, draft)
_apply_gdt_text_evidence(leader, evidence)
return leader

def _compact_candidates(original):
return _gdt_compact_candidates(
original,
_build,
_ink_at,
strip,
size,
horizontal,
Expand Down
46 changes: 44 additions & 2 deletions src/draftwright/annotations/_placement_occupancy.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@

import math
from collections.abc import Iterable
from dataclasses import dataclass
from itertools import chain
from typing import Any

from build123d_drafting.helpers import Dimension, Leader, Note, SafeDimension

from draftwright._core import Analysis, _analysis_margins, place_annotation
from draftwright._core import Analysis, _analysis_margins, _drawing_bounds, place_annotation
from draftwright._geometry import _boxes_overlap, _segment_clips_box, _segments_cross_or_overlap
from draftwright.annotations._dimension_ink import DimensionInkCandidate
from draftwright.annotations._placement_geometry import (
Expand Down Expand Up @@ -44,6 +46,43 @@
_PAGE_SPANNING_RIDERS = ("is_sheet_frame", "is_zone_grid")


@dataclass(frozen=True)
class DeferredCompactCandidate:
"""Exact leader ink metadata before constructing a costly retry annotation."""

label_bbox: tuple[float, float, float, float]
materialize: Any
tip: tuple[float, float] | None = None
elbow: tuple[float, float] | None = None
segments: tuple = ()
analytical_straight_leader: bool = False


def compact_probe_clear(dwg, proposal, others, forbid_box, label_clear) -> bool:
"""Reject decisive label, page, furniture and straight-shaft collisions cheaply."""
label = proposal.label_bbox
page = _drawing_bounds(dwg)
if (
label[0] < page[0]
or label[1] < page[1]
or label[2] > page[2]
or label[3] > page[3]
or (forbid_box is not None and _box_hits(label, (forbid_box,)))
or (label_clear is not None and not label_clear(label))
):
return False
for item in (*others, *(annotation for _, annotation in dwg.iter_annotations())):
try:
foreign = getattr(item, "label_bbox", None)
except Exception: # noqa: BLE001 — the exact check fails closed below
continue
if foreign is not None and len(foreign) == 4 and _boxes_overlap(label, foreign):
return False
return not proposal.analytical_straight_leader or annotation_ink_clear(
dwg, proposal, additional=others
)


def is_page_spanning_rider(annotation) -> bool:
"""Is *annotation* one of the page-spanning riders (see :data:`_PAGE_SPANNING_RIDERS`)?

Expand Down Expand Up @@ -613,7 +652,10 @@ def annotation_ink_clear(dwg, candidate, *, view=None, additional=(), against=No
candidate_elbow = getattr(candidate, "elbow", None)
annotation_elbow = getattr(annotation, "elbow", None)
shares_leader_trunk = (
type(candidate) is Leader
(
type(candidate) is Leader
or getattr(candidate, "analytical_straight_leader", False)
)
and type(annotation) is Leader
and candidate_tip is not None
and annotation_tip is not None
Expand Down
16 changes: 12 additions & 4 deletions src/draftwright/annotations/_pmi_dimensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -433,11 +433,19 @@ def _pmi_witness_from_bbox(rec, view: str, a: Analysis):
p2 = (SX(hi), SZ((zmin + zmax) / 2), 0)
avg_t = SZ((zmin + zmax) / 2)
elif view == "plan" and ax == "Y":
avg_x = (xmin + xmax) / 2
# AP242 may attach broad plate faces to a local Y measurement. Their
# combined bbox can cover the whole part, so its midpoint collapses
# distinct witness pairs onto one X station. The proved reference points
# are the dimension's actual stations (as for plan/X above).
point_x = sum(point[0] for point in pts) / len(pts)
# Some authored records supply reference points on an abstract datum
# line outside their support box. Keep the support box as the fallback
# in that case; use the actual stations when they lie on the geometry.
witness_x = point_x if xmin - 1e-6 <= point_x <= xmax + 1e-6 else (xmin + xmax) / 2
lo, hi = min(point[1] for point in pts), max(point[1] for point in pts)
p1 = (PX(avg_x), PY(lo), 0)
p2 = (PX(avg_x), PY(hi), 0)
avg_t = PX(avg_x)
p1 = (PX(witness_x), PY(lo), 0)
p2 = (PX(witness_x), PY(hi), 0)
avg_t = PX(witness_x)
else:
return None

Expand Down
Loading
Loading