From b69dbe95fd2e499aab464066741036d32e576ba0 Mon Sep 17 00:00:00 2001 From: Masoud Masoumi Date: Thu, 29 Oct 2026 21:14:48 -0400 Subject: [PATCH] Add spherical bosses (domes) and seats (sockets): detect a full-revolution spherical cap and rebuild it as editable PartDesign history. A convex cap standing on a face is a spherical BOSS (dome), a concave cap cut into a face is a spherical SEAT (socket). PartDesign has no sphere primitive, so the executor revolve-builds the cap: a circular-arc profile sketched on a vertical plane through the axis, spun 360 deg as a PartDesign::Revolution (additive dome) or PartDesign::Groove (subtractive seat), the apex placed exactly. Smooth domes, truncated (flat-topped) domes, and smooth sockets are supported; full spheres and flat-bottomed sockets are out of scope. The apex is read off the patch's high-elevation end (r_hi ~ 0 => the smooth pole, a real r_hi => a flat truncation). FreeCAD's tessellator peels a boolean-cut socket's pole off as a separate tiny cone cap, so the sphere patch stops just short of the pole and reads a small nonzero r_hi; that pole cap (a cone whose apex sits at the sphere's geometric pole, opening back toward the rim) is recognized so the socket is still detected and rebuilt smooth. A truncated dome's flat top, when the segmentation keeps it as a separate plane, is recorded as provenance and excluded from the base extent (like the cylindrical boss cap), so the base pad is not inflated to the top of the dome. New: the sphere detection rule in features.py, the SphereOp plan op in history.py, the _add_sphere revolve executor branch in build.py, the headless _sphere_cap in solidify.py, 26 test_sphere.py tests (detection/planning/round-trip), and dome + socket smoke cases. Headless suite 551 passed; FreeCAD smoke test green. --- CHANGELOG.md | 15 + README.md | 15 +- ROADMAP.md | 27 +- freecad/meshtofeatures_wb/build.py | 95 +++++ freecad/meshtofeatures_wb/core/features.py | 166 +++++++++ freecad/meshtofeatures_wb/core/history.py | 69 +++- freecad/meshtofeatures_wb/core/solidify.py | 56 +++ .../scripts/freecad_smoke_test.py | 70 ++++ .../tests/test_adversarial.py | 17 + .../meshtofeatures_wb/tests/test_sphere.py | 344 ++++++++++++++++++ 10 files changed, 859 insertions(+), 15 deletions(-) create mode 100644 freecad/meshtofeatures_wb/tests/test_sphere.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 4e33689..0135a98 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,21 @@ footprint at the wrong profile, reported as a clean reconstruction. Headless suite: 23 new `test_cone_boss.py` tests (detection, planning, round-trip); smoke test gains a tapered-boss case. +- **Spherical bosses (domes) and seats (sockets).** A full-revolution + spherical CAP is now a feature: a convex cap standing on a face is a + spherical BOSS (dome), a concave cap cut into a face is a spherical + SEAT (socket). PartDesign has no sphere primitive, so the executor + revolve-builds the cap — a circular-arc profile sketched on a vertical + plane through the axis, spun 360 deg as a `PartDesign::Revolution` + (additive dome) or `PartDesign::Groove` (subtractive seat), the apex + placed exactly. Smooth domes, truncated (flat-topped) domes, and smooth + sockets are supported; full spheres and flat-bottomed sockets are out + of scope. The apex is read off the patch's high-elevation end; when the + tessellator (FreeCAD's, on a boolean-cut socket) peels the pole off as + a separate tiny cone cap, that pole cap is recognized and the cap is + still rebuilt smooth. Headless suite: 26 new `test_sphere.py` tests + (detection, planning, round-trip); smoke test gains a dome and a socket + case. - **FreeCAD executor CI.** A second CI job (`freecad-smoke`) runs the full headless smoke test (`scripts/freecad_smoke_test.py`: 18 parts through reconstruct -> snap -> plan -> feature detection -> PartDesign diff --git a/README.md b/README.md index 43282b3..b8280b7 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,13 @@ Recognized and rebuilt on the current release: - **Tapered bosses** (convex cones): conical studs and draft-angled bosses, truncated or pointed, rebuilt as `PartDesign::AdditiveCone` primitives standing on their base face. +- **Spherical bosses (domes)** and **spherical seats (sockets)**: a + full-revolution spherical cap standing on a face is rebuilt as a + `PartDesign::Revolution` and a concave cap cut into a face as a + `PartDesign::Groove` (PartDesign has no sphere primitive, so the cap + is a revolved circular-arc profile, the apex placed exactly). Smooth + domes, truncated (flat-topped) domes, and smooth sockets are supported; + full spheres and flat-bottomed sockets are out of scope. - **Cross-axis holes** (horizontal holes), both through and blind (a blind side hole is rebuilt as a depth-limited pocket). - **Vertical bosses** and **lateral pads** — flanges, rails, and gusseted @@ -65,10 +72,10 @@ Recognized and rebuilt on the current release: - **Prismatic parts only.** The reconstruction targets parts made of planes, cylinders, and cones (plates, brackets, housings, fixtures), - plus conical countersinks, conical pockets, and tapered bosses. - Organic / sculpted / scanned shapes will not reconstruct meaningfully. - Spheres and tori are fitted by the core but not yet rebuilt as - features. + plus conical countersinks, conical pockets, tapered bosses, and + spherical caps (domes and sockets). Organic / sculpted / scanned + shapes will not reconstruct meaningfully. Full spheres and tori are + fitted by the core but not yet rebuilt as features. - **Freeform transition geometry is carried by the correction pass.** Some parts blend a wall into a base through a swept, freeform transition band (the Thingiverse corner bracket is the canonical diff --git a/ROADMAP.md b/ROADMAP.md index 29ac8cf..eaba4f1 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -39,7 +39,7 @@ Status: **done** — merged as PR #11 (2026-10-28); ships in the next release. ## Phase 2 — Feature depth: convex cones, spheres, tori -(current slice: `feature/additive-cones`) +(current slice: `feature/spheres`) The README's core limitation is that the core *fits* spheres, tori, and convex cones but the planner/executor do not *rebuild* them. Each item @@ -52,13 +52,21 @@ Order (smallest documented gap first): 1. **Convex cones** (tapered bosses, draft-angled studs) as `PartDesign::AdditiveCone` — the `SubtractiveCone` path (ConeOp) already exists end to end; the convex rule, plan op, and executor - branch are the delta. **Done** on `feature/additive-cones`: the - `cone_boss` feature, the additive `ConeOp`, the `AdditiveCone` - executor branch (base sunk into the face, tip exact), 23 headless - tests, and a smoke case. + branch are the delta. **Done** (merged as PR #12, 2026-10-28): the + `cone_boss` feature, the additive `ConeOp`, the `AdditiveCone` + executor branch (base sunk into the face, tip exact), 23 headless + tests, and a smoke case. 2. **Spheres** (spherical bosses and concave seats) — PartDesign has no - sphere primitive; the executor builds a placed `Part::Sphere` revolve - (circle sketch) fused/cut through the body, or declines loudly. + sphere primitive, so the cap is revolve-built as a + `PartDesign::Revolution` (additive dome) or `PartDesign::Groove` + (subtractive seat) from a circular-arc profile, the apex exact. + **Done** (branch `feature/spheres`): the `sphere_boss` / `sphere_seat` + features, the `SphereOp` plan op, the revolve executor branch, and the + pole-cap tessellation artifact (a boolean-cut socket whose pole the + tessellator peels into a separate tiny cone cap is still detected as a + smooth cap and rebuilt smooth). Smooth domes, truncated (flat-topped) + domes, and smooth sockets; full spheres and flat-bottomed sockets are + out of scope. 26 headless tests and dome + socket smoke cases. 3. **Tori** (round blends on edges the fillet rule cannot claim) — the largest of the three; revolve-based, and only where a full-revolution torus fit is unambiguous. @@ -67,8 +75,9 @@ Exit criteria: corpus parts carrying each new feature class with analytic ground truth; smoke case per executor path; no unplanned/silent drops of newly recognized features. -Status: in progress — item 1 (convex cones) done on -`feature/additive-cones`; items 2-3 (spheres, tori) not started. +Status: in progress — item 1 (convex cones) done, merged as PR #12; +item 2 (spheres) done on branch `feature/spheres` (pending merge); +item 3 (tori) not started. ## Phase 3 — Per-feature deviation report diff --git a/freecad/meshtofeatures_wb/build.py b/freecad/meshtofeatures_wb/build.py index f9a33c4..b6da16b 100644 --- a/freecad/meshtofeatures_wb/build.py +++ b/freecad/meshtofeatures_wb/build.py @@ -166,6 +166,82 @@ def _add_cone(doc, body, plan, name, x, y, z_lo, r_lo, r_hi, height, return op +def _add_sphere(doc, body, plan, name, x, y, face_z, R, r_lo, r_hi, depth, + pad, additive, from_top, label=""): + """Add (Revolution) or cut (Groove) a spherical cap about the frame-z + axis at (x, y), rim on the face at ``face_z``. + + PartDesign has no sphere primitive, so the cap is a REVOLVED + circular-arc profile: a sketch on a vertical plane through the axis + (local x = radial, local y = the axis toward the apex) carries the arc + (rim to apex) plus the closing lines, and a ``PartDesign::Revolution`` + (additive dome) or ``PartDesign::Groove`` (subtractive seat) spins it + 360 deg about the sketch's vertical axis. The rim end is sunk/extended + ``pad`` off the face (the cut/add buffer doctrine -- a coincident-face + boolean is the classic OCC flake); the apex (the outermost point) is + placed EXACTLY. + """ + import numpy as np + if depth <= 0.0 or r_lo <= 0.0: + return None + a_lo = math.sqrt(max(R * R - r_lo * r_lo, 0.0)) + a_hi = math.sqrt(max(R * R - r_hi * r_hi, 0.0)) + # local y runs along the axis toward the apex/bottom: for a from-top + # dome and a from-bottom seat that is +frame_z, otherwise -frame_z + apex_sign = 1.0 if (additive == from_top) else -1.0 + o = (plan.frame_origin + x * plan.frame_x + y * plan.frame_y + + face_z * plan.frame_z) + yd = apex_sign * plan.frame_z + zd = -apex_sign * plan.frame_y # keep the triad right-handed + m = App.Matrix( + float(plan.frame_x[0]), float(yd[0]), float(zd[0]), float(o[0]), + float(plan.frame_x[1]), float(yd[1]), float(zd[1]), float(o[1]), + float(plan.frame_x[2]), float(yd[2]), float(zd[2]), float(o[2]), + 0.0, 0.0, 0.0, 1.0) + # profile in (radial, axial): leg at the rim (sunk/extended off the + # face), the arc to the apex, the closing line on the axis + c = np.array([0.0, -a_lo]) + a0 = math.atan2(a_lo, r_lo) + a1 = math.atan2(a_hi, r_hi) if r_hi > 1e-9 else 0.5 * math.pi + prims = [ + SketchLine(start=np.array([0.0, -pad]), end=np.array([r_lo, -pad])), + SketchLine(start=np.array([r_lo, -pad]), end=np.array([r_lo, 0.0])), + SketchArc(center=c, radius=float(R), + start=np.array([r_lo, 0.0]), + end=np.array([r_hi, depth]), + sweep=float(a1 - a0)), + ] + if r_hi > 1e-9: + prims.append(SketchLine(start=np.array([r_hi, depth]), + end=np.array([0.0, depth]))) + prims.append(SketchLine(start=np.array([0.0, depth]), + end=np.array([0.0, -pad]))) + sk = doc.addObject("Sketcher::SketchObject", name + "Profile") + body.addObject(sk) + sk.Placement = App.Placement(m) + _add_geometry(sk, prims) + sk.Visibility = False + kind = "PartDesign::Revolution" if additive else "PartDesign::Groove" + try: + op = doc.addObject(kind, name) + except Exception as exc: # noqa: BLE001 - old FreeCAD + App.Console.PrintError( + f"[meshtofeatures] {label or name}: this FreeCAD has no " + f"{kind} feature ({exc}); the spherical face is NOT rebuilt\n") + doc.removeObject(sk.Name) + doc.recompute() + return None + body.addObject(op) + op.Profile = sk + op.ReferenceAxis = (sk, ["V_Axis"]) + op.Angle = 360.0 + if label: + op.Label = label + _apply_refine(op) + _rollback_if_broken(doc, body, op, sk) + return op + + def _apply_refine(op): """Turn on Refine so booleans clean up residual sliver faces/edges (documented cause of thin 'sheet' walls rendered at curved cut @@ -815,6 +891,25 @@ def build_body(doc, plan: BuildPlan, name: str = "Rebuilt"): label=c.label or name, deferred=deferred) doc.recompute() + # ---- spherical features: revolved arc caps (Revolution/Groove) -------- + for k, s in enumerate(getattr(plan, "spheres", [])): + try: + diag = float(body.Shape.BoundBox.DiagonalLength) or float(L) + except Exception: # noqa: BLE001 + diag = float(L) + pad = 1.5e-3 * diag # same buffer doctrine as the + # cones: never meet the face the rim opens at on a coincident face + face_z = float(s.surface_z) if s.surface_z is not None \ + else (L if s.from_top else 0.0) + name = f"SphericalBoss{k}" if s.additive else f"SphericalSeat{k}" + for pos in s.positions: + _add_sphere(doc, body, plan, name, float(pos[0]), float(pos[1]), + face_z, float(s.radius), float(s.rim_radius), + float(s.top_radius), float(s.depth), pad, + additive=s.additive, from_top=s.from_top, + label=s.label or name) + doc.recompute() + # ---- cross-axis holes: through = midplane pocket, blind = Length ------- import numpy as np for k, ch in enumerate(getattr(plan, "cross_holes", [])): diff --git a/freecad/meshtofeatures_wb/core/features.py b/freecad/meshtofeatures_wb/core/features.py index 55a1898..9905981 100644 --- a/freecad/meshtofeatures_wb/core/features.py +++ b/freecad/meshtofeatures_wb/core/features.py @@ -157,6 +157,38 @@ def _outer_loop_is_disk_on_cone(surf_plane, cone, tol: float) -> bool: return outer is not None and bool(np.all(cone.distance(outer) < tol)) +def _is_concave_sphere(surf) -> bool: + """Outward face normals of a spherical SOCKET wall point toward the + sphere centre (the material lies outside the cap), of a dome point away + from it (the material lies inside).""" + from .primitives import Sphere + sph: Sphere = surf.fit.primitive + k = len(surf.segment.face_indices) + centroids = surf.segment.samples[:k] # samples start with centroids + v = centroids - sph.center + n = np.linalg.norm(v, axis=1, keepdims=True) + n[n == 0.0] = 1.0 + radial = v / n + return float(np.mean(np.einsum("ij,ij->i", + surf.segment.face_normals, radial))) < 0.0 + + +def _plane_hole_loops_on_sphere(surf_plane, sph, tol: float) -> list: + """This plane's *interior* hole loops whose points lie on ``sph`` (a + spherical cap's rim opening at a face).""" + _, holes = _split_loops(surf_plane.segment) + return [lp for lp in holes + if bool(np.all(sph.distance(lp) < tol))] + + +def _outer_loop_is_disk_on_sphere(surf_plane, sph, tol: float) -> bool: + """True when the plane's *outer* boundary rides the sphere: the flat top + of a truncated spherical dome (the cap's own end disk), as opposed to a + face the cap merely opens through.""" + outer, _ = _split_loops(surf_plane.segment) + return outer is not None and bool(np.all(sph.distance(outer) < tol)) + + # -------------------------------------------------------------------------- # detection # -------------------------------------------------------------------------- @@ -522,6 +554,140 @@ def _ends(i: int) -> dict: f"x {height:g}"), )) + # ---- standalone spheres -> spherical bosses / seats ------------------- + # A full-revolution spherical CAP: a convex cap standing on a face is a + # spherical BOSS (dome), a concave cap cut into a face is a spherical + # SEAT (socket). The cap's rim (its low-elevation end) opens at a face + # whose interior hole loop rides the sphere; the apex (high-elevation + # end) is the cap pole (smooth) or a flat truncation (a boss may carry a + # flat top). The truncation reads straight off the patch's v_hi -- its + # end disk is absorbed into the sphere segment, not a separate surface. + # A seat's bottom is smooth by construction (a flat-bottomed socket is a + # different feature, left unassigned). Without this rule the sphere is + # fitted and then dropped, and the terrace machinery substitutes a + # STRAIGHT-WALLED pocket or pad of the rim radius -- the right footprint + # at the wrong profile, reported as a clean reconstruction (the cone_boss + # gap, for spheres). + from .primitives import Sphere, Cone + spheres = [i for i, s in enumerate(report.surfaces) + if isinstance(s.fit.primitive, Sphere)] + for si in spheres: + if si in consumed: + continue + ssph = report.surfaces[si] + sph = ssph.fit.primitive + if not patches[si].full_u: + continue # a lune, not a full cap + R = float(sph.radius) + v_lo, v_hi = patches[si].v_range # elevations from the cap pole + r_lo = float(R * np.cos(v_lo)) # rim radius + a_lo = float(R * np.sin(v_lo)) # centre -> rim plane, along pole + r_hi = float(R * np.cos(v_hi)) # apex radius (0 at the pole) + a_hi = float(R * np.sin(v_hi)) + if r_lo <= tol or a_hi <= a_lo + tol: + continue # degenerate (point) cap + z_dir = patches[si].z_dir + concave = _is_concave_sphere(ssph) + # A smooth cap tessellation puts a vertex at the pole, so a smooth + # apex reads r_hi = 0 exactly (v_hi = pi/2); a flat truncation reads + # a real r_hi. Tolerate 2% of R to absorb coarse-export apex jitter. + # But some tessellators (FreeCAD's, on a boolean-cut socket) peel the + # pole off as a separate tiny CONE cap, so the sphere patch stops just + # short of the pole and reads a small nonzero r_hi. A cone whose apex + # (tip) sits at the sphere's geometric pole and opens back toward the + # rim closes that apex to a point -- a smooth cap, not a truncation. + smooth_tol = max(tol, 0.02 * R) + pole = sph.center + R * np.asarray(z_dir) + pole_cap_i = None + for j in range(len(report.surfaces)): + if j == si: + continue + cj = report.surfaces[j].fit.primitive + if not isinstance(cj, Cone): + continue + if float(np.linalg.norm( + np.asarray(cj.apex) - pole)) > max(tol, 0.05 * R): + continue + if float(np.dot(np.asarray(cj.axis), z_dir)) >= 0.0: + continue # opens away from the rim + pole_cap_i = j + break + is_smooth = r_hi <= smooth_tol or pole_cap_i is not None + if concave and not is_smooth: + continue # flat-bottomed socket: out of scope + + def _elev(pts): + return float(np.mean(np.arcsin(np.clip( + (np.asarray(pts, dtype=float) - sph.center) / R @ z_dir, + -1.0, 1.0)))) + + # the rim face: a plane whose interior hole loop rides the sphere + # near the cap's low-elevation end + rim_p = None + for p in planes: + if p in consumed: + continue + lps = _plane_hole_loops_on_sphere(report.surfaces[p], sph, tol) + if any(abs(_elev(lp) - v_lo) <= max(1e-2, 0.15 * (v_hi - v_lo)) + for lp in lps): + rim_p = p + break + if rim_p is None: + continue # not open at any face + # The apex is the patch's high-elevation end: the pole (smooth, + # r_hi ~ 0) or a flat truncation at radius r_hi -- read straight off + # v_hi. When the segmentation keeps the truncation's end disk as a + # SEPARATE plane (its rim dihedral above the adaptive threshold, or + # peeled by refinement), record it: it is the feature's own end face + # and must be excluded from the base extent, else it inflates the + # base extrusion to the top of the dome. When the disk is absorbed + # into the sphere segment there is no separate plane to record. + cap_p = None + if not concave and not is_smooth: + for p in planes: + if p == rim_p or p in consumed: + continue + if not _outer_loop_is_disk_on_sphere( + report.surfaces[p], sph, tol): + continue + if abs(_elev(report.surfaces[p].segment.points) - v_hi) <= \ + max(1e-2, 0.15 * (v_hi - v_lo)): + cap_p = p + break + axis = z_dir.copy() # centre -> apex (pole direction) + rim_c = sph.center + a_lo * axis + a_hi_eff = R if is_smooth else a_hi # smooth: the apex is the pole + height = float(a_hi_eff - a_lo) + if height <= tol: + continue + top_radius = 0.0 if is_smooth else r_hi + kind = "sphere_seat" if concave else "sphere_boss" + used = [si, rim_p] + if cap_p is not None: + used.append(cap_p) + consumed.add(cap_p) + if pole_cap_i is not None: + used.append(pole_cap_i) # the pole cap: part of the cap + consumed.add(pole_cap_i) + consumed.add(si) + out.features.append(Feature( + kind=kind, + surface_indices=used, + params={ + "radius": R, + "rim_radius": r_lo, + "top_radius": top_radius, + "height": height, + "position": rim_c.tolist(), + "axis": axis.tolist(), + "base": rim_c.tolist(), + "base_radius": r_lo, + }, + description=( + f"Spherical {'socket' if concave else 'dome'} " + f"r={R:g}, rim d{2 * r_lo:g} x {height:g}"), + )) + # ---- coaxial stacks of concave cylinders -> holes / counterbores ------ stacks: list[list[int]] = [] for i in full_concave: diff --git a/freecad/meshtofeatures_wb/core/history.py b/freecad/meshtofeatures_wb/core/history.py index a7624ee..fdc07a6 100644 --- a/freecad/meshtofeatures_wb/core/history.py +++ b/freecad/meshtofeatures_wb/core/history.py @@ -39,8 +39,8 @@ "hole_op_properties", "FilletOp", "fillet_edge_matches", "ChamferOp", "CrossHoleOp", "blend_corner_profile", "chamfer_corner_profile", - "BasePad", "HoleOp", "PocketOp", "PadOp", "BuildPlan", - "plan_history", "MAX_STEP_LEVELS"] + "BasePad", "HoleOp", "PocketOp", "PadOp", "ConeOp", "SphereOp", + "BuildPlan", "plan_history", "MAX_STEP_LEVELS"] #: Above this many intermediate step levels a part is treated as too #: complex for the single-axis prismatic model and declined (a faceted, @@ -522,6 +522,33 @@ class ConeOp: label: str = "" +@dataclass +class SphereOp: + """A spherical cap revolved about a frame-z axis. + + PartDesign has no sphere primitive, so the executor rebuilds the cap as + a ``PartDesign::Revolution`` (a convex cap, additive -- a spherical + BOSS/dome) or ``PartDesign::Groove`` (a concave cap, subtractive -- a + spherical SEAT/socket) of a circular-arc profile; the headless rebuild + unions/differences a spherical cap solid. + + ``radius`` is the sphere radius R, ``rim_radius`` the radius of the + opening circle where the cap meets the face, ``top_radius`` the radius + at the far end (0 for a smooth apex/bottom), and ``depth`` the axial + extent from the face to the apex (R - the rim offset, exactly as for + ConeOp). ``surface_z`` is the frame-z of the face the rim lies on. + """ + radius: float + rim_radius: float + top_radius: float + depth: float + positions: list # [(x, y), ...] in the plan frame + from_top: bool = True + additive: bool = False + surface_z: float | None = None + label: str = "" + + @dataclass class BuildPlan: frame_origin: np.ndarray @@ -536,6 +563,7 @@ class BuildPlan: chamfers: list[ChamferOp] = field(default_factory=list) cross_holes: list[CrossHoleOp] = field(default_factory=list) cones: list[ConeOp] = field(default_factory=list) + spheres: list[SphereOp] = field(default_factory=list) absorbed_features: int = 0 unplanned: list[str] = field(default_factory=list) #: detected blends with no dressable neighbour pair (degenerate @@ -701,6 +729,11 @@ def plan_history(report: ReconstructionReport, feats: FeatureReport, # story: it is the feature's own end face, not a base extent boss_caps |= {f.surface_indices[2] for f in feats.features if f.kind == "cone_boss" and len(f.surface_indices) >= 3} + # a truncated dome's flat top (provenance [sphere, rim, cap]) likewise: + # it is the dome's own end face, not a base extent (only present when the + # segmentation kept the disk separate from the sphere segment) + boss_caps |= {f.surface_indices[2] for f in feats.features + if f.kind == "sphere_boss" and len(f.surface_indices) >= 3} extent_members = [(i, s) for i, s in members if i not in boss_caps] or members offsets = [float(s.fit.primitive.point @ z) for _, s in extent_members] z0, z1 = min(offsets), max(offsets) @@ -984,6 +1017,38 @@ def _cross_hole_op(f): # the tip cap is this cone's own end face: keep the terrace # pass off it (as for cone_pocket's floor disk) _cone_faces.update(f.surface_indices[2:]) + elif f.kind == "sphere_boss" and _aligned(f): + # spherical dome: the rim (base) sits on the face it stands on + # and the cap grows OUT of the material (the mirror of a seat, + # which is cut INTO it). The base face -- not the cap span -- + # fixes the side, as for cone_boss. + base3d = np.asarray(f.params["base"], dtype=float) + bz = float((base3d - origin) @ z) + plan.spheres.append(SphereOp( + radius=float(f.params["radius"]), + rim_radius=float(f.params["rim_radius"]), + top_radius=float(f.params["top_radius"]), + depth=float(f.params["height"]), + positions=[_pos2d(f)], + from_top=bz > plan.base.length / 2, + additive=True, + surface_z=bz, + label=f.description)) + elif f.kind == "sphere_seat" and _aligned(f): + # spherical socket: cut INTO the face its rim opens at, running + # to a smooth bottom. The rim face fixes the side. + base3d = np.asarray(f.params["base"], dtype=float) + bz = float((base3d - origin) @ z) + plan.spheres.append(SphereOp( + radius=float(f.params["radius"]), + rim_radius=float(f.params["rim_radius"]), + top_radius=0.0, + depth=float(f.params["height"]), + positions=[_pos2d(f)], + from_top=bz > plan.base.length / 2, + additive=False, + surface_z=bz, + label=f.description)) elif f.kind == "slot" and _aligned(f) and f.params.get("open"): # synthesize the closed notch profile: two lines + far arc + # a mouth-closing segment pushed OUTWARD so the cut clears the diff --git a/freecad/meshtofeatures_wb/core/solidify.py b/freecad/meshtofeatures_wb/core/solidify.py index 9badc96..bd49607 100644 --- a/freecad/meshtofeatures_wb/core/solidify.py +++ b/freecad/meshtofeatures_wb/core/solidify.py @@ -152,6 +152,45 @@ def ring(r, z): return m +def _sphere_cap(radius, rim_radius, top_radius, center_xy, face_z, up, + pad, sections: int = 96): + """Watertight spherical cap (or zone) about the z axis at ``center_xy``. + + The part of the radius-``radius`` sphere whose rim (radius + ``rim_radius``) lies on the plane z = ``face_z`` and which runs toward + z > face_z (``up``) or z < face_z. The far end is the pole + (``top_radius`` = 0) or a flat truncation at radius ``top_radius``. + + ``pad`` extends the cap PAST the rim (off the face it meets): into the + material for an additive union (a sunk leg) or into the air for a + subtractive cut (an overhanging lip), keeping the boolean off the + coincident face -- the cone boss/pocket doctrine. The far end (the + apex, the outermost point) is placed EXACTLY. Returns None when the + clip boolean fails. + """ + import math + R = float(radius) + a_lo = math.sqrt(max(R * R - rim_radius * rim_radius, 0.0)) + a_hi = math.sqrt(max(R * R - top_radius * top_radius, 0.0)) + zc = face_z - a_lo if up else face_z + a_lo + z_far = face_z + (a_hi - a_lo) if up else face_z - (a_hi - a_lo) + if up: + z0, z1 = face_z - pad, z_far + else: + z0, z1 = z_far, face_z + pad + sph = trimesh.creation.uv_sphere(radius=R, + count=[sections, max(sections // 2, 8)]) + sph.apply_translation([center_xy[0], center_xy[1], zc]) + box = trimesh.creation.box( + extents=[2.0 * R, 2.0 * R, float(z1 - z0)], + transform=trimesh.transformations.translation_matrix( + [center_xy[0], center_xy[1], 0.5 * (z0 + z1)])) + cap = sph.intersection(box) + if cap is None or not cap.is_watertight: + return None + return cap + + def _frame_matrix(plan) -> np.ndarray: t = np.eye(4) t[:3, 0] = plan.frame_x @@ -392,6 +431,23 @@ def _plan_to_mesh(plan, sections: int) -> trimesh.Trimesh: center=(x, y), sections=sections) solid = solid.union(fr) if c.additive else solid.difference(fr) + # spherical bosses (dome, additive) / seats (socket, subtractive): + # a spherical cap revolved about the frame-z axis. The rim sits on the + # face (surface_z) and the cap runs OUT of the material (dome) or INTO + # it (seat); the rim end is padded off the coincident face, the apex is + # exact (see _sphere_cap). + for s in getattr(plan, "spheres", []): + face_z = (float(s.surface_z) if s.surface_z is not None + else (L if s.from_top else 0.0)) + up = bool(s.additive == s.from_top) + for (x, y) in s.positions: + cap = _sphere_cap(s.radius, s.rim_radius, s.top_radius, + (x, y), face_z, up, 0.5, sections) + if cap is None: + raise ValueError( + f"spherical cap boolean failed for {s.label or 'sphere'}") + solid = solid.union(cap) if s.additive else solid.difference(cap) + # into world coordinates (the plan frame is embedded in mesh space) solid.apply_transform(_frame_matrix(plan)) diff --git a/freecad/meshtofeatures_wb/scripts/freecad_smoke_test.py b/freecad/meshtofeatures_wb/scripts/freecad_smoke_test.py index 10f003c..56f7045 100644 --- a/freecad/meshtofeatures_wb/scripts/freecad_smoke_test.py +++ b/freecad/meshtofeatures_wb/scripts/freecad_smoke_test.py @@ -599,6 +599,76 @@ def check(name, cond, info=""): f"{tbo_body.Shape.Volume:.2f} vs {tbo_solid.Volume:.2f}") check("tapered boss body shape is valid", tbo_body.Shape.isValid()) +# --- spherical dome (Revolution primitive) -------------------------------- +# an r10 sphere whose rim (r8) sits on the top face of a 10 mm plate: a +# convex spherical cap (dome) 4 mm tall (R - a_lo, a_lo = sqrt(R^2 - 8^2) = 6). +# Rebuilt as a PartDesign::Revolution of a circular-arc profile -- PartDesign +# has no sphere primitive. The volume check is what verifies it: a dome built +# the wrong way round (a straight r8 pad, or a subtractive cut) is visibly off. +_dome_sphere = Part.makeSphere(10.0, App.Vector(0, 0, 4.0)) # centre z=4 +_dome_cap = _dome_sphere.common( + Part.makeBox(100, 100, 50, App.Vector(-50, -50, 10.0))) # z >= 10 +dome_solid = Part.makeBox(50, 40, 10, App.Vector(-25, -20, 0)) \ + .fuse(_dome_cap).removeSplitter() +dv, df = dome_solid.tessellate(0.05) +dometm = trimesh.Trimesh(vertices=np.array([[v.x, v.y, v.z] for v in dv]), + faces=np.array(df), process=True) +dorep = snap_report(reconstruct(dometm)).report +dop = plan_patches(dorep) +dofeats = detect_features(dorep, dop) +doplan = plan_history(dorep, dofeats, detect_patterns(dofeats), dop) +dospheres = [s for s in doplan.spheres if s.additive] +check("dome planned as an additive SphereOp", len(dospheres) == 1, + f"{len(doplan.spheres)} spheres, {len(doplan.pads)} pads") +check("dome did not also emit a terrace pad", + doplan.pads == [], f"{len(doplan.pads)} pads") +if dospheres: + _s = dospheres[0] + check("dome radii recovered", + abs(_s.radius - 10.0) < 0.2 and abs(_s.rim_radius - 8.0) < 0.2, + f"R {_s.radius:.3f}, rim {_s.rim_radius:.3f}") +dome_body = build.build_body(doc, doplan, name="RebuiltDome") +check("dome body uses a Revolution feature", + any(o.TypeId == "PartDesign::Revolution" for o in dome_body.Group), + ", ".join(sorted({o.TypeId.split("::")[-1] for o in dome_body.Group}))) +check("dome body volume within 2%", + abs(dome_body.Shape.Volume - dome_solid.Volume) / dome_solid.Volume < 0.02, + f"{dome_body.Shape.Volume:.2f} vs {dome_solid.Volume:.2f}") +check("dome body shape is valid", dome_body.Shape.isValid()) + +# --- spherical socket (Groove primitive) ---------------------------------- +# the concave mirror: an r10 sphere whose rim (r8) opens at the top face, cut +# 4 mm down into the plate to a smooth bottom. Rebuilt as a +# PartDesign::Groove (subtractive revolution) of a circular-arc profile. +_seat_sphere = Part.makeSphere(10.0, App.Vector(0, 0, 16.0)) # centre z=16 +_seat_cap = _seat_sphere.common( + Part.makeBox(100, 100, 50, App.Vector(-50, -50, -40.0))) # z <= 10 +seat_solid = Part.makeBox(50, 40, 10, App.Vector(-25, -20, 0)) \ + .cut(_seat_cap) +sv, sf = seat_solid.tessellate(0.05) +seattm = trimesh.Trimesh(vertices=np.array([[v.x, v.y, v.z] for v in sv]), + faces=np.array(sf), process=True) +seatrep = snap_report(reconstruct(seattm)).report +seatp = plan_patches(seatrep) +seatfeats = detect_features(seatrep, seatp) +seatplan = plan_history(seatrep, seatfeats, detect_patterns(seatfeats), seatp) +seatspheres = [s for s in seatplan.spheres if not s.additive] +check("socket planned as a subtractive SphereOp", len(seatspheres) == 1, + f"{len(seatplan.spheres)} spheres, {len(seatplan.pockets)} pockets") +if seatspheres: + _s = seatspheres[0] + check("socket radii recovered", + abs(_s.radius - 10.0) < 0.2 and abs(_s.rim_radius - 8.0) < 0.2, + f"R {_s.radius:.3f}, rim {_s.rim_radius:.3f}") +seat_body = build.build_body(doc, seatplan, name="RebuiltSocket") +check("socket body uses a Groove feature", + any(o.TypeId == "PartDesign::Groove" for o in seat_body.Group), + ", ".join(sorted({o.TypeId.split("::")[-1] for o in seat_body.Group}))) +check("socket body volume within 2%", + abs(seat_body.Shape.Volume - seat_solid.Volume) / seat_solid.Volume < 0.02, + f"{seat_body.Shape.Volume:.2f} vs {seat_solid.Volume:.2f}") +check("socket body shape is valid", seat_body.Shape.isValid()) + # --- deviation correction: freeform blends the feature tree cannot capture -- # issue #5's corner bracket rebuilds +25% over-volume parametrically (its # diagonal band and base scoops fit no primitive); the correction pass diff --git a/freecad/meshtofeatures_wb/tests/test_adversarial.py b/freecad/meshtofeatures_wb/tests/test_adversarial.py index 98c6597..edd5c44 100644 --- a/freecad/meshtofeatures_wb/tests/test_adversarial.py +++ b/freecad/meshtofeatures_wb/tests/test_adversarial.py @@ -217,6 +217,23 @@ def extrude_lateral(pad): t.apply_translation([x, y, 0.0]) solid = solid.union(t) if c.additive else solid.difference(t) + # spherical caps: mirror _plan_to_mesh's cap boolean (same helper, so + # the proxy and the headless rebuild agree). The rim sits on the face + # (surface_z); the cap runs out of the material (dome) or into it + # (seat), rim end padded off the coincident face, apex exact. + if getattr(plan, "spheres", []): + from freecad.meshtofeatures_wb.core.solidify import _sphere_cap + for s in plan.spheres: + sz = s.surface_z + sz = float(sz) if sz is not None else (L if s.from_top else 0.0) + up = bool(s.additive == s.from_top) + for (x, y) in s.positions: + cap = _sphere_cap(s.radius, s.rim_radius, s.top_radius, + (x, y), sz, up, 0.5, SECTIONS) + assert cap is not None, "spherical cap boolean failed" + solid = (solid.union(cap) if s.additive + else solid.difference(cap)) + # apply fillets (convex, ~perpendicular blends) via corner-tool cuts; # FilletOps live in WORLD coordinates, this solid is in the PLAN # frame -- transform each op's geometry into the plan frame first diff --git a/freecad/meshtofeatures_wb/tests/test_sphere.py b/freecad/meshtofeatures_wb/tests/test_sphere.py new file mode 100644 index 0000000..8fe2993 --- /dev/null +++ b/freecad/meshtofeatures_wb/tests/test_sphere.py @@ -0,0 +1,344 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later +"""Spherical feature (dome / socket) tests, written before the implementation. + +A full-revolution spherical CAP: a convex cap standing on a face is a +spherical BOSS (dome), a concave cap cut into a face is a spherical SEAT +(socket). The cap's rim (its low-elevation end) opens at a face; the apex +(high-elevation end) is the cap pole (a smooth apex / bottom) or a flat +truncation (a dome may carry a flat top). + +Rebuilt as a `PartDesign::Revolution` (dome, additive) or +`PartDesign::Groove` (socket, subtractive) of a circular-arc profile; the +headless rebuild unions / differences a spherical cap solid. The rim leg is +sunk a hair off the coincident face, the apex placed exactly (the cone +boss/pocket doctrine). + +The pre-existing gap this suite pins: the core FITS spheres (coverage 1.0) +but the planner/executor had no spherical path, so a dome or socket was left +unassigned and the terrace machinery substituted a straight-walled pad or +pocket of the rim radius -- the right footprint at the wrong profile, +reported as a clean reconstruction (the cone_boss gap, for spheres). +""" + +import math + +import numpy as np +import pytest +import trimesh + +pytest.importorskip("manifold3d") + +from freecad.meshtofeatures_wb.core.emission import plan_patches +from freecad.meshtofeatures_wb.core.features import detect_features +from freecad.meshtofeatures_wb.core.history import plan_history +from freecad.meshtofeatures_wb.core.patterns import detect_patterns +from freecad.meshtofeatures_wb.core.pipeline import reconstruct +from freecad.meshtofeatures_wb.core.primitives import Sphere +from freecad.meshtofeatures_wb.core.snapping import snap_report + +from .test_adversarial import ROT, assert_geometry_match + +SECTIONS = 64 + + +# --------------------------------------------------------------- mesh builders + +def _plate(ext, t, center=(0.0, 0.0)): + p = trimesh.creation.box(extents=[ext[0], ext[1], t]) + p.apply_translation([center[0], center[1], 0.0]) # z in [-t/2, t/2] + return p + + +def _placed_sphere(R, center): + s = trimesh.creation.uv_sphere(radius=R, count=[SECTIONS, SECTIONS // 2]) + s.apply_translation(center) + return s + + +def dome_plate(radius, rim_radius, top_radius=0.0, t=10.0, + ext=(50.0, 40.0), center=(0.0, 0.0)): + """Plate with a convex spherical cap (dome) standing on the TOP face. + + The rim (radius ``rim_radius``) lies on the top face; the cap runs to a + smooth pole (``top_radius`` = 0) or a flat truncation (``top_radius`` > 0). + The sphere centre sits below the top face, so the cap grows UP out of the + material. + """ + R = float(radius) + a_lo = math.sqrt(max(R * R - rim_radius * rim_radius, 0.0)) + a_hi = math.sqrt(max(R * R - top_radius * top_radius, 0.0)) + top = t / 2.0 + plate = _plate(ext, t, center) + zc = top - a_lo # sphere centre below the top face + sph = _placed_sphere(R, [center[0], center[1], zc]) + z_top = top + (a_hi - a_lo) # apex (smooth) or truncation + box = trimesh.creation.box( + extents=[2 * R, 2 * R, z_top - top + 1e-6]) + box.apply_translation([center[0], center[1], 0.5 * (top + z_top)]) + return plate.union(sph.intersection(box)) + + +def socket_plate(radius, rim_radius, t=10.0, + ext=(50.0, 40.0), center=(0.0, 0.0)): + """Plate with a concave spherical cap (socket) cut into the TOP face, + running to a smooth bottom. The rim (radius ``rim_radius``) lies on the + top face; the sphere centre sits above it, so the cut runs DOWN into the + material.""" + R = float(radius) + a_lo = math.sqrt(max(R * R - rim_radius * rim_radius, 0.0)) + top = t / 2.0 + plate = _plate(ext, t, center) + zc = top + a_lo # sphere centre above the top face + sph = _placed_sphere(R, [center[0], center[1], zc]) + z_bot = top - (R - a_lo) # smooth socket bottom + box = trimesh.creation.box( + extents=[2 * R, 2 * R, top - z_bot + 1e-6]) + box.apply_translation([center[0], center[1], 0.5 * (z_bot + top)]) + return plate.difference(sph.intersection(box)) + + +def flat_socket_plate(radius, rim_radius, top_radius, t=10.0, + ext=(50.0, 40.0), center=(0.0, 0.0)): + """A socket with a FLAT bottom (radius ``top_radius`` > 0) cut into the + TOP face. This is a different feature from a smooth spherical seat (a + flat-bottomed spherical counterbore) and must stay out of scope.""" + R = float(radius) + a_lo = math.sqrt(max(R * R - rim_radius * rim_radius, 0.0)) + a_hi = math.sqrt(max(R * R - top_radius * top_radius, 0.0)) + top = t / 2.0 + plate = _plate(ext, t, center) + zc = top + a_lo # sphere centre above the top face + sph = _placed_sphere(R, [center[0], center[1], zc]) + z_bot = top - (a_hi - a_lo) # flat truncation (above the pole) + box = trimesh.creation.box( + extents=[2 * R, 2 * R, top - z_bot + 1e-6]) + box.apply_translation([center[0], center[1], 0.5 * (z_bot + top)]) + return plate.difference(sph.intersection(box)) + + +def _full(mesh): + report = snap_report(reconstruct(mesh)).report + patches = plan_patches(report) + feats = detect_features(report, patches) + plan = plan_history(report, feats, detect_patterns(feats), patches) + return report, feats, plan + + +def _only_dome(feats): + cs = feats.by_kind("sphere_boss") + assert len(cs) == 1, f"expected 1 dome, got {len(cs)}" + return cs[0] + + +def _only_seat(feats): + cs = feats.by_kind("sphere_seat") + assert len(cs) == 1, f"expected 1 socket, got {len(cs)}" + return cs[0] + + +# ------------------------------------------------------------------ detection + +class TestSphericalDomeDetection: + def test_smooth_dome_recognized(self): + _, feats, _ = _full(dome_plate(radius=10.0, rim_radius=8.0)) + d = _only_dome(feats) + assert np.isclose(d.params["radius"], 10.0, atol=0.15) + assert np.isclose(d.params["rim_radius"], 8.0, atol=0.15) + assert d.params["top_radius"] < 0.3 # runs to a smooth pole + assert np.isclose(d.params["height"], 4.0, atol=0.1) # R - a_lo + + def test_truncated_dome_recognized(self): + _, feats, _ = _full(dome_plate( + radius=10.0, rim_radius=8.0, top_radius=6.0)) + d = _only_dome(feats) + assert np.isclose(d.params["radius"], 10.0, atol=0.15) + assert np.isclose(d.params["rim_radius"], 8.0, atol=0.15) + assert np.isclose(d.params["top_radius"], 6.0, atol=0.15) + assert np.isclose(d.params["height"], 2.0, atol=0.1) # a_hi - a_lo + + def test_not_mistaken_for_a_seat(self): + _, feats, _ = _full(dome_plate(radius=10.0, rim_radius=8.0)) + assert feats.by_kind("sphere_seat") == [] + + def test_sphere_consumed(self): + report, feats, _ = _full(dome_plate(radius=10.0, rim_radius=8.0)) + for i in feats.unassigned: + assert not isinstance(report.surfaces[i].fit.primitive, Sphere), \ + "sphere left unassigned" + + def test_axis_points_to_the_apex(self): + # the feature axis is centre -> apex: for a dome on the top face that + # is straight UP, out of the material + _, feats, _ = _full(dome_plate(radius=10.0, rim_radius=8.0)) + d = _only_dome(feats) + axis = np.asarray(d.params["axis"], dtype=float) + assert np.isclose(np.linalg.norm(axis), 1.0, atol=1e-6) + assert axis[2] > 0.999 + + def test_offcenter_position(self): + _, feats, _ = _full(dome_plate( + radius=10.0, rim_radius=8.0, center=(10.0, -7.0))) + d = _only_dome(feats) + pos = np.asarray(d.params["position"]) + assert np.isclose(pos[0], 10.0, atol=0.15) + assert np.isclose(pos[1], -7.0, atol=0.15) + + def test_rotated_part_still_recognized(self): + mesh = dome_plate(radius=10.0, rim_radius=8.0).copy() + mesh.apply_transform(ROT) + _, feats, _ = _full(mesh) + d = _only_dome(feats) + assert np.isclose(d.params["radius"], 10.0, atol=0.25) + + @pytest.mark.parametrize("radius,rim_radius,top_radius", [ + (12.0, 9.0, 0.0), (8.0, 6.0, 0.0), (10.0, 7.0, 4.0)]) + def test_dimension_variants(self, radius, rim_radius, top_radius): + a_lo = math.sqrt(radius * radius - rim_radius * rim_radius) + a_hi = math.sqrt(radius * radius - top_radius * top_radius) + _, feats, _ = _full(dome_plate( + radius=radius, rim_radius=rim_radius, top_radius=top_radius, + t=a_hi - a_lo + 8.0)) + d = _only_dome(feats) + assert np.isclose(d.params["radius"], radius, atol=0.2) + assert np.isclose(d.params["rim_radius"], rim_radius, atol=0.2) + assert np.isclose(d.params["top_radius"], top_radius, atol=0.2) + assert np.isclose(d.params["height"], a_hi - a_lo, atol=0.15) + + +class TestSphericalSocketDetection: + def test_socket_recognized(self): + _, feats, _ = _full(socket_plate(radius=10.0, rim_radius=8.0)) + s = _only_seat(feats) + assert np.isclose(s.params["radius"], 10.0, atol=0.15) + assert np.isclose(s.params["rim_radius"], 8.0, atol=0.15) + assert s.params["top_radius"] < 0.3 # smooth bottom + assert np.isclose(s.params["height"], 4.0, atol=0.1) # depth R - a_lo + + def test_not_mistaken_for_a_dome(self): + _, feats, _ = _full(socket_plate(radius=10.0, rim_radius=8.0)) + assert feats.by_kind("sphere_boss") == [] + + def test_socket_axis_points_into_the_cut(self): + # a socket's centre is above the face; centre -> apex (the bottom) + # runs DOWN, into the material + _, feats, _ = _full(socket_plate(radius=10.0, rim_radius=8.0)) + s = _only_seat(feats) + axis = np.asarray(s.params["axis"], dtype=float) + assert np.isclose(np.linalg.norm(axis), 1.0, atol=1e-6) + assert axis[2] < -0.999 + + +class TestSphericalNegatives: + def test_cylindrical_boss_is_not_a_dome(self): + # a constant-radius boss is a plain (cylindrical) boss, not spherical + plate = _plate((50.0, 40.0), 10.0) + boss = trimesh.creation.cylinder(radius=6.0, height=8.0, + sections=SECTIONS) + boss.apply_translation([0.0, 0.0, 9.0]) # z in [5, 13] + _, feats, _ = _full(plate.union(boss)) + assert feats.by_kind("sphere_boss") == [] + assert feats.by_kind("sphere_seat") == [] + assert len(feats.by_kind("boss")) == 1 + + def test_flat_bottomed_socket_out_of_scope(self): + # a socket with a flat bottom is a different feature, not a smooth + # spherical seat: it must not be reported as a sphere_seat + _, feats, _ = _full(flat_socket_plate( + radius=10.0, rim_radius=8.0, top_radius=6.0)) + assert feats.by_kind("sphere_seat") == [] + assert feats.by_kind("sphere_boss") == [] + + def test_full_ball_is_not_a_cap(self): + # a closed sphere has no rim opening at a face: not a cap + ball = _placed_sphere(8.0, [0.0, 0.0, 0.0]) + report = snap_report(reconstruct(ball)).report + patches = plan_patches(report) + feats = detect_features(report, patches) + assert feats.by_kind("sphere_boss") == [] + assert feats.by_kind("sphere_seat") == [] + + +# -------------------------------------------------------------------- planning + +class TestSphericalPlanning: + def test_dome_planned_as_an_additive_sphere_op(self): + _, _, plan = _full(dome_plate(radius=10.0, rim_radius=8.0)) + assert len(plan.spheres) == 1 + assert plan.unplanned == [] + op = plan.spheres[0] + assert np.isclose(op.radius, 10.0, atol=0.15) + assert np.isclose(op.rim_radius, 8.0, atol=0.15) + assert op.top_radius < 0.3 + assert np.isclose(op.depth, 4.0, atol=0.1) + assert op.from_top is True + assert op.additive is True + + def test_truncated_dome_planned(self): + _, _, plan = _full(dome_plate( + radius=10.0, rim_radius=8.0, top_radius=6.0)) + assert len(plan.spheres) == 1 + op = plan.spheres[0] + assert np.isclose(op.top_radius, 6.0, atol=0.15) + assert np.isclose(op.depth, 2.0, atol=0.1) + assert op.additive is True + + def test_socket_planned_as_a_subtractive_sphere_op(self): + _, _, plan = _full(socket_plate(radius=10.0, rim_radius=8.0)) + assert len(plan.spheres) == 1 + op = plan.spheres[0] + assert np.isclose(op.radius, 10.0, atol=0.15) + assert np.isclose(op.rim_radius, 8.0, atol=0.15) + assert op.top_radius < 0.3 + assert np.isclose(op.depth, 4.0, atol=0.1) + assert op.from_top is True + assert op.additive is False + + def test_no_spurious_terrace_pad(self): + # the cap (and a truncated dome's flat top) must not also become a + # straight-walled terrace pad + _, _, plan = _full(dome_plate( + radius=10.0, rim_radius=8.0, top_radius=6.0)) + assert plan.pads == [] + + def test_bottom_face_dome(self): + mesh = dome_plate(radius=10.0, rim_radius=8.0).copy() + mesh.apply_transform( + trimesh.transformations.rotation_matrix(np.pi, [1, 0, 0])) + _, _, plan = _full(mesh) + assert len(plan.spheres) == 1 + op = plan.spheres[0] + assert op.from_top is False + assert op.additive is True + assert np.isclose(op.rim_radius, 8.0, atol=0.2) + + +# ------------------------------------------------------------------ round-trip + +class TestSphericalRoundtrip: + def test_smooth_dome_roundtrip(self): + mesh = dome_plate(radius=10.0, rim_radius=8.0) + _, _, plan = _full(mesh) + assert_geometry_match(mesh, plan) + + def test_truncated_dome_roundtrip(self): + mesh = dome_plate(radius=10.0, rim_radius=8.0, top_radius=6.0) + _, _, plan = _full(mesh) + assert_geometry_match(mesh, plan) + + def test_socket_roundtrip(self): + mesh = socket_plate(radius=10.0, rim_radius=8.0) + _, _, plan = _full(mesh) + assert_geometry_match(mesh, plan) + + def test_rotated_roundtrip(self): + mesh = dome_plate(radius=10.0, rim_radius=8.0).copy() + mesh.apply_transform(ROT) + _, _, plan = _full(mesh) + assert_geometry_match(mesh, plan) + + def test_bottom_face_roundtrip(self): + mesh = dome_plate(radius=10.0, rim_radius=8.0).copy() + mesh.apply_transform( + trimesh.transformations.rotation_matrix(np.pi, [1, 0, 0])) + _, _, plan = _full(mesh) + assert_geometry_match(mesh, plan)