diff --git a/src/draftwright/_pmi_linear_geometry.py b/src/draftwright/_pmi_linear_geometry.py index f8428a8b..e4bbd9d0 100644 --- a/src/draftwright/_pmi_linear_geometry.py +++ b/src/draftwright/_pmi_linear_geometry.py @@ -4,7 +4,11 @@ import math -from draftwright._pmi_topology import _parallel_planar_reference_witness +from draftwright._pmi_topology import ( + _is_mixed_planar_bore, + _parallel_planar_reference_witness, + _planar_bore_axis_witness, +) from draftwright.model.ir import _linear_projection_view _LINEAR_AXIS_ABS_TOL = 0.005 @@ -24,6 +28,22 @@ def _proved_planar_linear(groups, stations, nominal, kind, frame, shape_bbox): None, ("parallel planar source faces have no proven shared witness",), ) + if axis is None and kind == "linear" and _is_mixed_planar_bore(groups): + bore_support = _planar_bore_axis_witness(groups, frame, shape_bbox) + if bore_support is None: + points, dominant, reasons = _dimension_reference_stations( + tuple(stations), nominal, kind + ) + return ( + points, + dominant, + None, + ( + *reasons, + "plane-to-bore location has no proven face-supported axis witness", + ), + ) + stations, axis, view = bore_support if witness: stations = tuple( tuple( diff --git a/src/draftwright/_pmi_topology.py b/src/draftwright/_pmi_topology.py index 4b09177f..e468c9a9 100644 --- a/src/draftwright/_pmi_topology.py +++ b/src/draftwright/_pmi_topology.py @@ -6,7 +6,7 @@ from __future__ import annotations -from draftwright._pmi_datum_geometry import _frame_vector +from draftwright._pmi_datum_geometry import _frame_point, _frame_vector from draftwright._pmi_support_blockers import _failure_reason try: @@ -144,6 +144,109 @@ def _point_inside_x_face(face, x, y, z, frame): return False +def _planar_bore_axis_witness(groups, frame, shape_bbox): + """Prove a location from one principal plane to one finite Z-bore axis. + + A cylindrical face's bbox centre is its axial *height*, not the location + station. The plane must actually contain the axis-aligned witness point; + a bounding-box overlap alone would invent a witness through a trimmed face. + """ + from OCP.BRepAdaptor import BRepAdaptor_Surface + from OCP.BRepClass import BRepClass_FaceClassifier + from OCP.GeomAbs import GeomAbs_Cylinder, GeomAbs_Plane + from OCP.gp import gp_Pnt + from OCP.TopAbs import TopAbs_IN, TopAbs_ON + from OCP.TopoDS import TopoDS + + if len(groups) != 2 or any(len(group) != 1 for group in groups): + return None + try: + faces = tuple(TopoDS.Face_s(group[0]) for group in groups) + surfaces = tuple(BRepAdaptor_Surface(face) for face in faces) + kinds = tuple(surface.GetType() for surface in surfaces) + if kinds not in ((GeomAbs_Plane, GeomAbs_Cylinder), (GeomAbs_Cylinder, GeomAbs_Plane)): + return None + plane_i = kinds.index(GeomAbs_Plane) + bore_i = 1 - plane_i + normal = surfaces[plane_i].Plane().Axis().Direction() + normal = _frame_vector((normal.X(), normal.Y(), normal.Z()), frame) + axis = max(range(3), key=lambda index: abs(normal[index])) + if axis not in (0, 1) or abs(abs(normal[axis]) - 1) > 1e-6: + return None + bore = surfaces[bore_i].Cylinder().Axis() + direction = bore.Direction() + direction = _frame_vector((direction.X(), direction.Y(), direction.Z()), frame) + if abs(abs(direction[2]) - 1) > 1e-6 or max(abs(value) for value in direction[:2]) > 1e-6: + return None + point = bore.Location() + centre = _frame_point((point.X(), point.Y(), point.Z()), frame) + boxes = tuple( + shape_bbox(group[0]) if frame is None else shape_bbox(group[0], frame) + for group in groups + ) + plane_box, bore_box = boxes[plane_i], boxes[bore_i] + z0 = max(plane_box[2], bore_box[2]) + z1 = min(plane_box[5], bore_box[5]) + if z1 - z0 <= 1e-6: + return None + station = (plane_box[axis] + plane_box[axis + 3]) / 2 + if plane_box[axis + 3] - plane_box[axis] > 1e-5: + return None + witness = list(centre) + witness[axis] = station + witness[2] = (z0 + z1) / 2 + world = witness if frame is None else frame.to_world(tuple(witness)) + classifier = BRepClass_FaceClassifier() + classifier.Perform(faces[plane_i], gp_Pnt(*world), 1e-7) + if classifier.State() not in (TopAbs_IN, TopAbs_ON): + return None + points = [tuple(witness), tuple(witness)] + bore_point = list(witness) + bore_point[axis] = centre[axis] + points[bore_i] = tuple(bore_point) + return tuple(points), "XYZ"[axis], "plan" + except Exception: + return None + + +def _is_mixed_planar_bore(groups): + """Recognise the mixed support even when its location proof fails.""" + from OCP.BRepAdaptor import BRepAdaptor_Surface + from OCP.GeomAbs import GeomAbs_Cylinder, GeomAbs_Plane + from OCP.TopoDS import TopoDS + + if len(groups) != 2 or any(len(group) != 1 for group in groups): + return False + try: + kinds = tuple(BRepAdaptor_Surface(TopoDS.Face_s(group[0])).GetType() for group in groups) + return kinds in ((GeomAbs_Plane, GeomAbs_Cylinder), (GeomAbs_Cylinder, GeomAbs_Plane)) + except Exception: + return False + + +def _common_principal_cylinder_axis(references): + """Return a shared principal axis only when every exact cylinder proves it.""" + axes = [] + for reference in references: + vector = reference.axis_direction + axis = max(range(3), key=lambda index: abs(vector[index])) + if abs(abs(vector[axis]) - 1.0) > 1e-6 or any( + abs(vector[index]) > 1e-6 for index in range(3) if index != axis + ): + return "" + axes.append("XYZ"[axis]) + return axes[0] if axes and len(set(axes)) == 1 else "" + + +def _optional_cylinder_support(probe): + """Keep an optional axis probe from erasing otherwise valid source PMI.""" + try: + references, reasons = probe() + return references if not reasons else () + except Exception: + return () + + def _supported_planar_view(axis: str, group_boxes) -> tuple[str | None, str | None]: """Select only projection views whose shared witness touches both groups.""" if axis in {"X", "Z"}: diff --git a/src/draftwright/annotations/_common.py b/src/draftwright/annotations/_common.py index 74ea7a5c..8f7d8317 100644 --- a/src/draftwright/annotations/_common.py +++ b/src/draftwright/annotations/_common.py @@ -82,6 +82,7 @@ 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, @@ -89,6 +90,7 @@ 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, @@ -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") diff --git a/src/draftwright/annotations/_gdt.py b/src/draftwright/annotations/_gdt.py index 5c98740b..440d03f8 100644 --- a/src/draftwright/annotations/_gdt.py +++ b/src/draftwright/annotations/_gdt.py @@ -22,6 +22,7 @@ from draftwright.annotations._common import ( PRIORITY, CorridorCandidate, + DeferredCompactCandidate, _anno_box, _box_hits, annotation_ink_clear, @@ -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: @@ -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, ...]: @@ -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. @@ -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: @@ -583,44 +594,78 @@ 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, @@ -628,21 +673,21 @@ def _build(pos, _px=px, _py=py, _hz=horizontal, _it=item): 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, @@ -650,22 +695,22 @@ def _build_at(elbow, _px=px, _py=py, _it=item, _g=fallback_glyph): 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, @@ -673,13 +718,14 @@ def _build_routed(bends, elbow, _px=px, _py=py, _it=item, _g=fallback_glyph): 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, diff --git a/src/draftwright/annotations/_placement_occupancy.py b/src/draftwright/annotations/_placement_occupancy.py index 51da529b..cab4a174 100644 --- a/src/draftwright/annotations/_placement_occupancy.py +++ b/src/draftwright/annotations/_placement_occupancy.py @@ -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 ( @@ -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`)? @@ -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 diff --git a/src/draftwright/annotations/_pmi_dimensions.py b/src/draftwright/annotations/_pmi_dimensions.py index af097bca..0024a533 100644 --- a/src/draftwright/annotations/_pmi_dimensions.py +++ b/src/draftwright/annotations/_pmi_dimensions.py @@ -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 diff --git a/src/draftwright/build_policy.py b/src/draftwright/build_policy.py index 2197ab3d..c299d02a 100644 --- a/src/draftwright/build_policy.py +++ b/src/draftwright/build_policy.py @@ -533,11 +533,12 @@ def _scale_attempt( def _principal_view_exceeds_page(scale, page, bounds, views) -> bool: - """Rule out a fixed-scale build whose unannotated principal cannot fit. + """Rule out a fixed-scale build whose bare principal projections cannot fit. - This uses only the part's world-space bounding box and the full page, leaving - margins and annotation footprints out of the bound. A rejected candidate - therefore cannot be rescued by a different arrangement or ink placement. + Use only the part's world-space box and the *full* page: omitting even the + mandatory gutters, margins and annotation footprints makes this a necessary + bound, never a speculative fit verdict. No ink solve can rescue a rejected + scale. """ extents = { "x": bounds.max.X - bounds.min.X, diff --git a/src/draftwright/builder.py b/src/draftwright/builder.py index 7973c809..6dfe04bf 100644 --- a/src/draftwright/builder.py +++ b/src/draftwright/builder.py @@ -2488,10 +2488,7 @@ def try_without_iso(self): except (ValueError, Standard_Failure) as exc: if not _is_expected_candidate_build_failure(exc): raise - _log.info( - "fixed-page optional-ISO replan rejected (build failed: %s)", - exc, - ) + _log.info("fixed-page optional-ISO replan rejected (build failed: %s)", exc) self.record_attempt( None, "error", @@ -2538,7 +2535,7 @@ def try_without_iso(self): # sequence of larger standard pages. Each page chooses its scale # through the established fixed-page policy and must pass the # same axial, structural, and required-outcome gates above. A - # A detail may be introduced or retained here: it is itself a + # detail may be introduced or retained here: it is itself a # semantic recovery view, and this correction must not reject a # complete candidate merely because removing the optional ISO # made room for that required detail. diff --git a/src/draftwright/compose.py b/src/draftwright/compose.py index d8c1c94a..d0fc55b5 100644 --- a/src/draftwright/compose.py +++ b/src/draftwright/compose.py @@ -788,6 +788,22 @@ def _reserve_planned_angles( ) +def _reserve_unhinted_linear_corridors(corridors, kind, axis) -> None: + """Reserve the same default/fallback strips the linear PMI renderer tries.""" + if kind == "linear" and axis == "X": + # Imported AP242 X dimensions commonly have no route hint. Without these + # bands even a required overall tolerance has a zero-capacity strip (#2192). + _reserve_corridor(corridors, "front", "above") + _reserve_corridor(corridors, "front", "below") + elif kind == "linear" and axis == "Y": + _reserve_corridor(corridors, "side", "above") + _reserve_corridor(corridors, "side", "below") + _reserve_corridor(corridors, "plan", "below") + elif kind not in ("diameter", "radius", "angular") and axis == "Z": + _reserve_corridor(corridors, "front", "left") + _reserve_corridor(corridors, "front", "right") + + def _reserve_authored_dimensions( model, boxes: list[AnnoBox], @@ -798,6 +814,10 @@ def _reserve_authored_dimensions( text_position: str, text_orientation: str, ) -> None: + # Report/off modes retain imported records for diagnostics but do not draw + # them. Their corridors must not enlarge the sheet for invisible ink. + if not getattr(model, "pmi_annotations_enabled", True): + return # Measured placement hints are semantic corridor requirements and therefore part of # compose-before-pack, not merely renderer filters. Resolve every valid explicit route; # a view-only hint conservatively reserves both supported sides, while the legacy @@ -821,11 +841,8 @@ def _reserve_authored_dimensions( if view_hint is None and side_hint is None and angular_reference is None: if kind == "linear" and axis == "?" and target_view is not None: pass - elif kind not in ("diameter", "radius", "angular") and axis == "Z": - _reserve_corridor(corridors, "front", "left") - _reserve_corridor(corridors, "front", "right") - continue else: + _reserve_unhinted_linear_corridors(corridors, kind, axis) continue if target_view is None: continue diff --git a/src/draftwright/model/detect.py b/src/draftwright/model/detect.py index a2cc5967..8be58007 100644 --- a/src/draftwright/model/detect.py +++ b/src/draftwright/model/detect.py @@ -389,7 +389,12 @@ def build_pmi_features( pmi_origin = ((x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2) else: pmi_origin = (bbox.center().X, bbox.center().Y, bbox.center().Z) - ax = r.dominant_axis.lower() if r.dominant_axis in ("X", "Y", "Z") else "z" + proven_axis = ( + r.reference_axis + if r.source_category == "geometric_tolerance" and r.reference_axis + else r.dominant_axis + ) + ax = proven_axis.lower() if proven_axis in ("X", "Y", "Z") else "z" if r.kind in AUTHORED_DIMENSION_KINDS: out.append( AuthoredDimension( diff --git a/src/draftwright/pmi.py b/src/draftwright/pmi.py index c002e14d..31be34e2 100644 --- a/src/draftwright/pmi.py +++ b/src/draftwright/pmi.py @@ -114,9 +114,11 @@ _without_direct_xcaf_reference_failures, ) from draftwright._pmi_topology import ( + _common_principal_cylinder_axis, _CommonLabelTopologyResolver, _DatumTopologyResolver, _DimensionSupportResolver, + _optional_cylinder_support, _SurfaceLabelTopologyResolver, ) from draftwright._pmi_topology import ( @@ -183,13 +185,13 @@ class PmiRecord: datum_contexts: Tolerance semantic names in which a datum definition is referenced. reference_item_ids: Exact Part21 representation items bound to a datum feature. reference_item_groups: Ordered Part21 support groups bound to a dimension. - reference_axis: Axis normal to a planar datum support or along a cylindrical one. + reference_axis: Principal datum normal or exact cylindrical GD&T support axis. reference_surface_kind: Proven datum support type, ``plane`` or ``cylinder``. reference_normal: Outward normal of a planar datum; empty for cylindrical supports. semantic_name: Stable source name for a semantic manufacturing requirement. shape_aspect_ids: Part21 shape aspects associating a semantic requirement to geometry. - cylindrical_refs: Canonical finite-cylinder topology referenced by a Size_Diameter - requirement. Empty for other dimension families or unresolved geometry. + cylindrical_refs: Exact finite-cylinder supports for Size_Diameter or GD&T; + empty when unsupported or unresolved. reference_bboxes: Per-item bounds for exact imported manufacturing supports. circular_refs: Canonical circular-edge topology referenced by a Size_Diameter requirement whose semantic association names edges rather than faces. @@ -1462,6 +1464,10 @@ def _geometric_tolerance_record( reference_geometry = _reference_geometry(label, shape_tool, frame) points, ref_bbox, dominant_axis, reference_reasons = reference_geometry partial_reasons.extend(reference_reasons) + # Exact cylinders, not their diameter-wide boxes, determine GD&T view axes. + cylinders = _optional_cylinder_support( + lambda: _cylindrical_references(label, shape_tool, frame) + ) datum_refs, datum_reasons = _datum_references(label, dim_tol_tool) partial_reasons.extend(datum_reasons) lowering_blockers = tuple(dict.fromkeys(partial_reasons)) @@ -1478,6 +1484,8 @@ def _geometric_tolerance_record( datum_refs=datum_refs, part21_id=part21_id, source_category="geometric_tolerance", + cylindrical_refs=cylinders, + reference_axis=_common_principal_cylinder_axis(cylinders), gtol_modifiers=gtol_modifiers, lowering_blockers=lowering_blockers, ), diff --git a/tests/test_gdt_ink_shared.py b/tests/test_gdt_ink_shared.py index 4bee997d..9028754e 100644 --- a/tests/test_gdt_ink_shared.py +++ b/tests/test_gdt_ink_shared.py @@ -2,6 +2,7 @@ from types import SimpleNamespace +import pytest from build123d_drafting import FeatureControlFrame, Leader from build123d_drafting.helpers import Draft @@ -141,6 +142,31 @@ def _assert_capacity_fixture_fits_each_alone(monkeypatch, outer_limit): assert remaining == [] +def test_deferred_compaction_rejects_out_of_page_label_before_build(monkeypatch): + monkeypatch.setattr(_common, "strip_obstacles", lambda *_args, **_kwargs: []) + monkeypatch.setattr(_common, "pending_title_block_box", lambda _drawing: None) + drawing = _Drawing() + strip = Strip(anchor=0.0, outer_limit=50.0, direction=1.0, gap=8.0, spacing=3.0) + deferred = _common.DeferredCompactCandidate( + (101.0, 20.0, 110.0, 25.0), + lambda: pytest.fail("a provably off-page retry built CAD ink"), + ) + remaining = _common.place_strip_candidates( + drawing, + strip, + "plan", + "y", + [("frame", _frame)], + tier=5.0, + ctx=drawing, + force=True, + sizes={"frame": (10.0, 5.0)}, + compact_candidates={"frame": lambda _original: (deferred,)}, + ) + assert remaining == [] + assert [name for name, _item in drawing.added] == ["frame"] + + def test_frame_moves_as_whole_when_same_batch_dimension_crosses_its_glyph(monkeypatch): unchecked, unchecked_remaining = _solve(monkeypatch, repair=False, required=False) assert unchecked_remaining == [], [(name, item.pos) for name, item in unchecked.added] diff --git a/tests/test_gdt_placement.py b/tests/test_gdt_placement.py index 46a91b57..0c320af1 100644 --- a/tests/test_gdt_placement.py +++ b/tests/test_gdt_placement.py @@ -52,6 +52,93 @@ def _leader_path_length(leader): ) +def test_gdt_retry_reuses_validated_glyph_without_changing_placed_ink(monkeypatch): + from draftwright._core import Strip + from draftwright.annotations import _gdt + + draft = Draft(font_size=3.0) + frame = ControlFrame( + frame=Frame((0.0, 0.0, 0.0), "z"), + characteristic="position", + tolerance="0.1", + view="plan", + side="above", + datums=("A",), + diameter=True, + ) + glyph = _gdt._gdt_glyph(frame, draft) + origin_box = glyph.bounding_box() + strip = Strip(anchor=20.0, outer_limit=90.0, direction=1.0, gap=8.0, spacing=3.0) + real_visual_tolerance = _gdt._gdt_visual_tolerance + validated = [] + + def counted_visual_tolerance(*args, **kwargs): + validated.append(True) + return real_visual_tolerance(*args, **kwargs) + + monkeypatch.setattr(_gdt, "_gdt_visual_tolerance", counted_visual_tolerance) + build, _, _, compact, _ = _gdt._gdt_candidate_builders( + frame, + draft, + Leader, + glyph, + 30.0, + 20.0, + True, + strip, + (origin_box.size.X, origin_box.size.Y), + 5.0, + None, + ) + monkeypatch.setattr( + _gdt, "_gdt_glyph", lambda *_args: pytest.fail("placement rebuilt a validated glyph") + ) + assert len(validated) == 1 + for tier in (35.0, 45.0, 35.0): + placed = build(tier) + fresh = Leader( + tip=(30.0, 20.0), + elbow=(30.0, tier), + label="", + draft=draft, + callout=glyph, + ) + _gdt._attach_gdt_text_evidence(fresh, glyph, frame, draft) + assert placed.label_bbox == pytest.approx(fresh.label_bbox) + assert placed.segments == fresh.segments + assert placed.pdf_text_relative_specs + assert placed.pdf_text_relative_specs == fresh.pdf_text_relative_specs + # Only the direct reference attachment above adds validations; the three + # placement retries must reuse the builder's single checked result. + assert len(validated) == 4 + proposals = list(compact(build(55.0)))[:3] + assert proposals + other = build(55.0) + + class EmptyDrawing: + @staticmethod + def iter_annotations(): + return () + + @staticmethod + def view_of(_name): + return "plan" + + for proposal in proposals: + actual = proposal.materialize() + assert proposal.label_bbox == pytest.approx(actual.label_bbox) + assert proposal.segments == tuple(actual.segments) + assert proposal.tip == actual.tip + assert proposal.elbow == actual.elbow + assert _gdt.annotation_ink_clear( + EmptyDrawing(), proposal, additional=(other,) + ) == _gdt.annotation_ink_clear(EmptyDrawing(), actual, additional=(other,)) + unchanged = glyph.bounding_box() + assert (unchanged.min.X, unchanged.min.Y, unchanged.max.X, unchanged.max.Y) == pytest.approx( + (origin_box.min.X, origin_box.min.Y, origin_box.max.X, origin_box.max.Y) + ) + + def test_control_frame_places_first_class(): frame = ControlFrame( frame=Frame((0.0, 0.0, 0.0), "z"), diff --git a/tests/test_issue_563_placement_intent.py b/tests/test_issue_563_placement_intent.py index b4640949..87da5c8e 100644 --- a/tests/test_issue_563_placement_intent.py +++ b/tests/test_issue_563_placement_intent.py @@ -419,6 +419,27 @@ def test_compose_reserves_every_supported_measured_corridor_family(): assert footprint.sv_top > 0 and footprint.sv_bottom > 0 +def test_unhinted_source_linear_dimensions_reserve_their_render_routes_issue_2192(): + sheet = Sheet(Box(120, 80, 12)).authored_dimensions() + for axis, points in ( + ("X", ((-60, 0, 6), (60, 0, 6))), + ("Y", ((0, -40, 6), (0, 0, 6))), + ): + sheet.measured_dimension( + kind="linear", + value=120 if axis == "X" else 40, + label="120 ±0.05" if axis == "X" else "40", + dominant_axis=axis, + ref_bbox=(-60, -40, 0, 60, 40, 12), + ref_pts=points, + ) + + footprint = _footprint_from_boxes(_compose_anno_boxes(sheet.model(), n_steps=0)) + assert footprint.fv_top > 0 and footprint.fv_bottom > 0 + assert footprint.sv_top > 0 and footprint.sv_bottom > 0 + assert footprint.pv_bottom > 0 + + def test_compose_ignores_an_unresolved_defensive_target(monkeypatch): import draftwright.compose as compose diff --git a/tests/test_pmi.py b/tests/test_pmi.py index d372e853..61119334 100644 --- a/tests/test_pmi.py +++ b/tests/test_pmi.py @@ -50,6 +50,104 @@ def ctc04_extraction_report(): class TestExtractPmi: + def test_position_record_keeps_exact_cylinder_axis_issue_2192(self, monkeypatch): + import draftwright.pmi as pmi_module + + monkeypatch.setattr(pmi_module, "_geometric_tolerance_modifiers", lambda _obj: ((), ())) + monkeypatch.setattr(pmi_module, "_geometric_tolerance_qualifiers", lambda _obj: ((), ())) + monkeypatch.setattr(pmi_module, "_unpreserved_geometric_tolerance_fields", lambda _obj: ()) + monkeypatch.setattr( + pmi_module, + "_reference_geometry", + lambda *_args: (((0.0, 0.0, 4.0),), (-11, -11, 0, 11, 11, 8), "X", ()), + ) + monkeypatch.setattr( + pmi_module, + "_cylindrical_references", + lambda *_args: ((SimpleNamespace(axis_direction=(0.0, 0.0, 1.0)),), ()), + ) + monkeypatch.setattr(pmi_module, "_datum_references", lambda *_args: ((), ())) + record, reasons = pmi_module._geometric_tolerance_record( + object(), SimpleNamespace(GetValue=lambda: 2.0), 10, object(), object(), "gtol:bore" + ) + assert not reasons + assert record.dominant_axis == "X" and record.reference_axis == "Z" + assert len(record.cylindrical_refs) == 1 + + def test_position_frame_uses_proven_bore_axis_not_bbox_width_issue_2192(self): + from draftwright._pmi_topology import _common_principal_cylinder_axis + from draftwright.model import build_pmi_features + + z_bore = SimpleNamespace(axis_direction=(0.0, 0.0, 1.0)) + assert _common_principal_cylinder_axis((z_bore, z_bore)) == "Z" + assert ( + _common_principal_cylinder_axis( + (z_bore, SimpleNamespace(axis_direction=(1.0, 0.0, 0.0))) + ) + == "" + ) + record = PmiRecord( + kind="position", + type_code=8, + value=2.0, + source_category="geometric_tolerance", + source_id="geometric_tolerance:bore", + dominant_axis="X", # the 22 mm diameter exceeds the 8 mm axial height + reference_axis="Z", + ref_pts=((0.0, 0.0, 4.0),), + ref_bbox=(-11.0, -11.0, 0.0, 11.0, 11.0, 8.0), + ) + (frame,) = build_pmi_features((record,), Box(120, 80, 12).bounding_box()) + assert (frame.view, frame.frame.axis) == ("plan", "z") + + def test_plane_to_bore_axis_location_uses_exact_face_witness_issue_2192(self): + from build123d import Axis, Cylinder, GeomType, Pos, Rot + + from draftwright._pmi_linear_geometry import _proved_planar_linear + from draftwright.pmi import _shape_bbox + + plane = (Pos(-59, 0, 6) * Box(2, 80, 12)).faces().sort_by(Axis.X)[0].wrapped + bore = (Pos(0, 0, 4) * Cylinder(11, 8)).faces().filter_by(GeomType.CYLINDER)[0].wrapped + centres = ((-60.0, 0.0, 6.0), (0.0, 0.0, 4.0)) + points, axis, view, blockers = _proved_planar_linear( + ((plane,), (bore,)), centres, 60.0, "linear", None, _shape_bbox + ) + assert (axis, view, blockers) == ("X", "plan", ()) + assert points[0] == pytest.approx((-60.0, 0.0, 4.0)) + assert points[1] == pytest.approx((0.0, 0.0, 4.0)) + + # A matching nominal is not enough: the bore axis must touch the + # authored plane face and the cylindrical axis must be principal. + distant = (Pos(-59, 30, 6) * Box(2, 10, 12)).faces().sort_by(Axis.X)[0].wrapped + _, axis, _, blockers = _proved_planar_linear( + ((distant,), (bore,)), + ((-60.0, 30.0, 6.0), centres[1]), + 60.0, + "linear", + None, + _shape_bbox, + ) + assert axis == "?" and blockers + tilted = ( + (Pos(0, 0, 4) * Rot(Y=20) * Cylinder(11, 8)) + .faces() + .filter_by(GeomType.CYLINDER)[0] + .wrapped + ) + _, axis, view, _blockers = _proved_planar_linear( + ((plane,), (tilted,)), centres, 60.0, "linear", None, _shape_bbox + ) + assert (axis, view) != ("X", "plan") + + # A plane bbox can cover the axis while the trimmed face has a hole + # there. The oblique centre fallback must not silently certify it. + cut = Pos(-59, 0, 4) * Rot(Y=90) * Cylinder(3, 4) + holed_plane = ((Pos(-59, 0, 6) * Box(2, 80, 12)) - cut).faces().sort_by(Axis.X)[0].wrapped + _, _, _, blockers = _proved_planar_linear( + ((holed_plane,), (bore,)), centres, 60.0, "linear", None, _shape_bbox + ) + assert any("no proven face-supported axis witness" in reason for reason in blockers) + def test_parallel_x_faces_do_not_use_bbox_overlap_through_a_hole_issue_2193(self): from build123d import Axis, Pos from OCP.BRepClass import BRepClass_FaceClassifier @@ -199,6 +297,35 @@ def capture(_drawing, _ctx, options, _axis, _label, _record): ) assert queued and all(option["view"] == "plan" for option in queued) + def test_plan_y_witness_uses_source_station_not_broad_face_bbox_issue_2192(self): + from draftwright.annotations._pmi_dimensions import _pmi_witness_from_bbox + + def identity(value): + return value + + analysis = SimpleNamespace( + proj=SimpleNamespace( + front_x=identity, + front_z=identity, + side_x=identity, + side_z=identity, + plan_x=identity, + plan_y=identity, + ) + ) + stations = (-25.0, 0.0, 25.0) + witnesses = [] + for station in stations: + record = SimpleNamespace( + dominant_axis="Y", + ref_pts=((station, -40.0, 6.0), (station, 0.0, 6.0)), + ref_bbox=(-60.0, -40.0, 0.0, 60.0, 40.0, 12.0), + ) + witnesses.append(_pmi_witness_from_bbox(record, "plan", analysis)) + + assert [witness[0][0] for witness in witnesses] == list(stations) + assert all(witness[0][1] == -40.0 and witness[1][1] == 0.0 for witness in witnesses) + def test_nist_ctc01_returns_records(self, ctc01_extraction_report): recs = ctc01_extraction_report.records assert len(recs) > 0 diff --git a/tests/test_pmi_gtol_lowering.py b/tests/test_pmi_gtol_lowering.py index 1fc043dc..40cd2f01 100644 --- a/tests/test_pmi_gtol_lowering.py +++ b/tests/test_pmi_gtol_lowering.py @@ -20,7 +20,7 @@ from draftwright.builder import build_drawing, detect_part_model from draftwright.linting.pmi_coverage import lint_pmi_rendering from draftwright.model import build_pmi_features -from draftwright.model.ir import ControlFrame, Frame, PmiFeature +from draftwright.model.ir import ControlFrame, CylindricalReference, Frame, PmiFeature from draftwright.pmi import PmiExtractionReport, PmiRecord from draftwright.sheet_emit import _feature_block, _feature_line @@ -789,7 +789,13 @@ def _execute_feature_line(feature): sheet = SimpleNamespace(add=captured.append) exec( _feature_line(feature), - {"sheet": sheet, "ControlFrame": ControlFrame, "Frame": Frame, "PmiFeature": PmiFeature}, + { + "sheet": sheet, + "ControlFrame": ControlFrame, + "CylindricalReference": CylindricalReference, + "Frame": Frame, + "PmiFeature": PmiFeature, + }, ) (restored,) = captured return restored