diff --git a/CHANGELOG.md b/CHANGELOG.md index 0135a98..a49b17e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,23 @@ still rebuilt smooth. Headless suite: 26 new `test_sphere.py` tests (detection, planning, round-trip); smoke test gains a dome and a socket case. +- **Rounded ring bands (tori) are now a feature.** A full-revolution ring + band — a donut blend the fillet rule cannot claim (fillets are partial + revolutions; a ring band is a full one) — is detected (`torus_boss` + when it grows out of a face, `torus_recess` when it is cut into one), + planned as a `TorusOp`, and rebuilt by revolve: a circular-arc profile + sketched on a plane through the major axis, spun 360 deg as a + `PartDesign::Revolution` (additive boss) or `PartDesign::Groove` + (subtractive seat). The core gained a `Torus` primitive and a + `fit_torus` fitter (least-variance axis, (rho, h) circle). The fit + carries two impostor gates: a conical one (a cone's normals make a + constant angle with its axis, so the normal sweep is narrow) and a + partial-patch one (a torus is a full ring; a local curved patch such as + a slot's half-cylinder end does not wrap around the major axis), so + truncated cones and slot ends are not mis-fit. Standalone donuts and + partial-revolution bands are out of scope. Headless suite: 29 new + `test_torus.py` tests (detection, planning, round-trip, negatives); + smoke test gains a ring-boss and a ring-groove 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 b8280b7..d68f9b6 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,15 @@ Recognized and rebuilt on the current release: `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. + full spheres and flat-bottomed sockets are out of scope. +- **Rounded ring bands (tori)**: a full-revolution ring band standing on + a face is a rounded ring BOSS (a donut blend the fillet rule cannot + claim), and one cut into a face is a ring SEAT (groove). PartDesign has + no torus primitive, so the band is revolve-built — a circular-arc + profile on a plane through the major axis, spun 360 deg as a + `PartDesign::Revolution` (additive boss) or `PartDesign::Groove` + (subtractive seat). Standalone donuts and partial-revolution bands 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 @@ -72,10 +80,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, 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. + plus conical countersinks, conical pockets, tapered bosses, spherical + caps (domes and sockets), and rounded ring bands (tori). Organic / + sculpted / scanned shapes will not reconstruct meaningfully. Full + spheres 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 eaba4f1..78f6e7f 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/spheres`) +(current slice: `feature/tori`) 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 @@ -67,17 +67,26 @@ Order (smallest documented gap first): 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 +3. **Tori** (rounded ring bands the fillet rule cannot claim) — the largest of the three; revolve-based, and only where a full-revolution - torus fit is unambiguous. + torus fit is unambiguous. **Done** (branch `feature/tori`): the core + gained a `Torus` primitive and a `fit_torus` fitter (least-variance + axis, (rho, h) circle, with conical-impostor and partial-patch + rejection gates so cones and slot half-cylinders are not mis-fit); + the `torus_boss` / `torus_recess` features, the `TorusOp` plan op, and + the revolve executor branch (a circular-arc profile revolved 360° for a + boss, grooved for a seat). Rounded ring bosses (donut blends the + fillet rule cannot claim) and ring seats; standalone donuts and + partial-revolution bands are out of scope. 29 headless tests and ring + boss + ring groove smoke cases. 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, merged as PR #12; -item 2 (spheres) done on branch `feature/spheres` (pending merge); -item 3 (tori) not started. +item 2 (spheres) done, merged as PR #13; item 3 (tori) done on branch +`feature/tori` (pending merge). ## Phase 3 — Per-feature deviation report diff --git a/freecad/meshtofeatures_wb/build.py b/freecad/meshtofeatures_wb/build.py index b6da16b..315aba9 100644 --- a/freecad/meshtofeatures_wb/build.py +++ b/freecad/meshtofeatures_wb/build.py @@ -242,6 +242,85 @@ def _add_sphere(doc, body, plan, name, x, y, face_z, R, r_lo, r_hi, depth, return op +def _add_torus(doc, body, plan, name, x, y, face_z, R, r, a, pad, additive, + from_top, label=""): + """Add (Revolution) or cut (Groove) a rounded ring band about the frame-z + axis at (x, y), rim annulus on the face at ``face_z``. + + PartDesign has no torus primitive, so the band is a REVOLVED circular-arc + profile: a sketch on a vertical plane through the axis (local x = radial, + local y = the axis toward the tube top) carries the tube arc (outer rim + over the top to inner rim) plus the buried legs and the base line, and a + ``PartDesign::Revolution`` (additive boss) 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 tube top (the + outermost point) is placed EXACTLY. + """ + import numpy as np + if r <= 0.0 or a >= r: + return None + s = math.sqrt(max(r * r - a * a, 0.0)) + r_outer = R + s + r_inner = R - s + # local y runs along the axis toward the tube top (the bulge): for a + # from-top boss 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): the tube arc (outer rim -> top -> inner rim), + # the two buried legs (sunk/extended off the face) and the base line. The + # tube centre sits at (R, a) and the rim (h = 0) is the annulus + # [r_inner, r_outer]; the arc is the part of the tube above the rim. + c = np.array([R, a]) + ang_outer = math.atan2(-a, s) # outer-rim point, from the centre + ang_inner = math.atan2(-a, -s) # inner-rim point (third quadrant) + sweep = (ang_inner + 2.0 * math.pi) - ang_outer # over the tube top + prims = [ + SketchLine(start=np.array([r_outer, -pad]), + end=np.array([r_outer, 0.0])), + SketchArc(center=c, radius=float(r), + start=np.array([r_outer, 0.0]), + end=np.array([r_inner, 0.0]), + sweep=float(sweep)), + SketchLine(start=np.array([r_inner, 0.0]), + end=np.array([r_inner, -pad])), + SketchLine(start=np.array([r_inner, -pad]), + end=np.array([r_outer, -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 ring 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 @@ -908,6 +987,23 @@ def build_body(doc, plan: BuildPlan, name: str = "Rebuilt"): float(s.top_radius), float(s.depth), pad, additive=s.additive, from_top=s.from_top, label=s.label or name) + # ---- ring bands: revolved arc tori (Revolution/Groove) ----------------- + for k, t in enumerate(getattr(plan, "tori", [])): + 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 + # spheres: never meet the face the rim opens at on a coincident face + face_z = float(t.surface_z) if t.surface_z is not None \ + else (L if t.from_top else 0.0) + name = f"RingBoss{k}" if t.additive else f"RingSeat{k}" + for pos in t.positions: + _add_torus(doc, body, plan, name, float(pos[0]), float(pos[1]), + face_z, float(t.major_radius), float(t.minor_radius), + float(t.a_center), pad, + additive=t.additive, from_top=t.from_top, + label=t.label or name) doc.recompute() # ---- cross-axis holes: through = midplane pocket, blind = Length ------- diff --git a/freecad/meshtofeatures_wb/core/emission.py b/freecad/meshtofeatures_wb/core/emission.py index b9dad42..631d212 100644 --- a/freecad/meshtofeatures_wb/core/emission.py +++ b/freecad/meshtofeatures_wb/core/emission.py @@ -13,7 +13,10 @@ along the axis (the OCC cone parameter is *slant* distance: divide by cos(half_angle) when realizing) * sphere -> ``Part.Sphere`` face, u = azimuth in ``u_range``, - v = elevation in ``v_range`` (radians, in [-pi/2, pi/2]) + v = elevation in ``v_range`` (radians, in [-pi/2, pi/2]) +* torus -> ``Part.Torus`` face, u = toroidal angle in ``u_range`` + (around the major axis), v = poloidal angle in ``v_range`` + (around the tube, 0 at the tube top, in [-pi, pi]) Frames are right-handed orthonormal triads ``(x_dir, y_dir, z_dir)`` with ``z_dir`` the primitive's natural direction (plane normal, cylinder/cone @@ -30,7 +33,7 @@ from .fitting import _axis_frame from .pipeline import ReconstructionReport -from .primitives import Plane, Sphere, Cylinder, Cone, Primitive +from .primitives import Plane, Sphere, Cylinder, Cone, Torus, Primitive __all__ = ["PatchSpec", "plan_patches"] @@ -42,7 +45,7 @@ @dataclass class PatchSpec: - kind: str # 'plane' | 'cylinder' | 'cone' | 'sphere' + kind: str # 'plane' | 'cylinder' | 'cone' | 'sphere' | 'torus' primitive: Primitive origin: np.ndarray # frame origin (see module docstring) x_dir: np.ndarray @@ -197,6 +200,27 @@ def _sphere_patch(prim: Sphere, pts: np.ndarray) -> PatchSpec: ) +def _torus_patch(prim: Torus, pts: np.ndarray) -> PatchSpec: + x, y, z = _frame(prim.axis) + rel = pts - prim.center + h = rel @ z # axial offset from the tube + rho = np.linalg.norm(rel - np.outer(h, z), axis=1) # radial from axis + # poloidal angle around the tube, 0 at the tube TOP (h = +minor_radius): + # the (rho - major_radius, h) cross-section is a circle of radius + # minor_radius centred at (major_radius, 0) + v = np.arctan2(rho - prim.major_radius, h) + v_range = (float(v.min()), float(v.max())) + u = np.arctan2(rel @ y, rel @ x) # toroidal angle around axis + u_range, full = _angular_range(u) + return PatchSpec( + kind="torus", primitive=prim, origin=prim.center.copy(), + x_dir=x, y_dir=y, z_dir=z, + u_range=u_range, full_u=full, v_range=v_range, + polygon=None, primitive_points=pts, + label=f"Torus R={prim.major_radius:g} r={prim.minor_radius:g}", + ) + + def plan_patches(report: ReconstructionReport) -> list[PatchSpec]: """One bounded :class:`PatchSpec` per recognized surface, same order.""" patches: list[PatchSpec] = [] @@ -214,4 +238,6 @@ def plan_patches(report: ReconstructionReport) -> list[PatchSpec]: patches.append(_cone_patch(prim, pts)) elif isinstance(prim, Sphere): patches.append(_sphere_patch(prim, pts)) + elif isinstance(prim, Torus): + patches.append(_torus_patch(prim, pts)) return patches diff --git a/freecad/meshtofeatures_wb/core/features.py b/freecad/meshtofeatures_wb/core/features.py index 9905981..47faa9c 100644 --- a/freecad/meshtofeatures_wb/core/features.py +++ b/freecad/meshtofeatures_wb/core/features.py @@ -189,6 +189,15 @@ def _outer_loop_is_disk_on_sphere(surf_plane, sph, tol: float) -> bool: return outer is not None and bool(np.all(sph.distance(outer) < tol)) +def _plane_loops_on_torus(surf_plane, tor, tol: float) -> list: + """This plane's boundary loops (inner or outer) whose points lie on + ``tor`` -- a ring band's rim opening at a face. A ring band is cut by + the face along two circles (inner and outer rim), so a rim face usually + carries two such loops; either qualifies the face.""" + return [lp for lp in surf_plane.segment.boundary_loops + if len(lp) >= 3 and bool(np.all(tor.distance(lp) < tol))] + + # -------------------------------------------------------------------------- # detection # -------------------------------------------------------------------------- @@ -688,6 +697,102 @@ def _elev(pts): f"r={R:g}, rim d{2 * r_lo:g} x {height:g}"), )) + # ---- standalone tori -> rounded ring bosses / seats -------------------- + # A full-revolution ring band (a torus) standing on a face is a rounded + # ring BOSS (a donut blend the partial-revolution fillet rule cannot + # claim), a ring groove cut into a face is a ring SEAT. The band's rim + # (where the tube is cut by the face -- an annulus: two concentric circles + # in one or two coplanar faces) opens at a face whose boundary loop rides + # the torus; the tube top (the outermost point) is the far end. Without + # this rule the torus is fitted and then dropped, and the terrace + # machinery substitutes a straight-walled pad of the rim radius -- the + # right footprint at the wrong profile (the cone_boss/sphere gap, for + # tori). The band is claimed only when it is a genuine ring: a real tube + # (r < R) actually cut by the face (the tube centre closer than r). + from .primitives import Torus + toruses = [i for i, s in enumerate(report.surfaces) + if isinstance(s.fit.primitive, Torus)] + for ti in toruses: + if ti in consumed: + continue + s_t = report.surfaces[ti] + tor = s_t.fit.primitive + if not patches[ti].full_u: + continue # a partial ring, not a full band + R = float(tor.major_radius) + r = float(tor.minor_radius) + if r <= tol or r >= R: + continue # degenerate tube + z_dir = patches[ti].z_dir + + # the rim: the face(s) the ring band stands on -- a plane perpendicular + # to the band axis whose boundary loop rides the torus. A fused ring + # splits the face into an inner disk and an outer region, so there are + # usually two coplanar rim faces (inner + outer rim circles). + rim_planes: list[int] = [] + for p in planes: + if p in consumed: + continue + sp = report.surfaces[p] + if abs(float(sp.fit.primitive.normal @ z_dir)) < 0.999: + continue + if _plane_loops_on_torus(sp, tor, tol): + rim_planes.append(p) + if not rim_planes: + continue # not open at any face + + # tube-centre height above the rim plane, along the axis; the band + # bulges on the tube-centre side of the rim + rim_h = float(np.mean([ + (report.surfaces[p].fit.primitive.point - tor.center) @ z_dir + for p in rim_planes])) + a_center = float(abs(rim_h)) + if a_center <= tol or a_center >= r: + continue # tube does not cross the face + s = float(np.sqrt(max(r * r - a_center * a_center, 0.0))) + r_outer = R + s + r_inner = R - s + if r_inner <= tol or r_outer <= tol: + continue + # the band bulges toward the tube centre; a BOSS grows out of the face + # it sits on, a SEAT is cut into it. The rim face's outward normal + # (mean mesh face normal) points away from the material. + outward = s_t.segment.face_normals.mean(axis=0) + on = float(np.linalg.norm(outward)) + outward = outward / on if on > 1e-9 else z_dir + additive = float((s_t.segment.points.mean(axis=0) + - report.surfaces[rim_planes[0]].fit.primitive.point) + @ outward) > 0.0 + height = a_center + r # rim -> tube top (outermost) + # the band bulges toward the tube centre; the axis runs rim -> band + # (the direction the feature grows out of the face) + axis = z_dir if rim_h <= 0.0 else -z_dir + rim_c = tor.center + rim_h * z_dir # the rim centre, on the face + used = [ti] + rim_planes + for p in rim_planes: + consumed.add(p) + consumed.add(ti) + kind = "torus_boss" if additive else "torus_recess" + out.features.append(Feature( + kind=kind, + surface_indices=used, + params={ + "major_radius": R, + "minor_radius": r, + "a_center": a_center, + "rim_inner_radius": r_inner, + "rim_outer_radius": r_outer, + "height": height, + "position": rim_c.tolist(), + "axis": axis.tolist(), + "base": rim_c.tolist(), + "base_radius": r_outer, + }, + description=( + f"Rounded ring {'groove' if not additive else 'boss'} " + f"R={R:g} r={r:g}, rim d{2 * r_outer: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/fitting.py b/freecad/meshtofeatures_wb/core/fitting.py index 2f6f32d..1014db3 100644 --- a/freecad/meshtofeatures_wb/core/fitting.py +++ b/freecad/meshtofeatures_wb/core/fitting.py @@ -25,7 +25,7 @@ import numpy as np from scipy.optimize import least_squares -from .primitives import Plane, Sphere, Cylinder, Cone, Primitive +from .primitives import Plane, Sphere, Cylinder, Cone, Torus, Primitive __all__ = [ "FitResult", @@ -33,6 +33,7 @@ "fit_sphere", "fit_cylinder", "fit_cone", + "fit_torus", "fit_best", ] @@ -318,6 +319,98 @@ def residuals(x): return FitResult.from_primitive(cone, pts) +# -------------------------------------------------------------------------- +# torus: least-variance axis (a ring is thin along its major axis), circle +# in the (rho, h) cross-section, then refinement +# -------------------------------------------------------------------------- + +def fit_torus(points: np.ndarray, normals: np.ndarray | None = None, + trim: bool = True) -> FitResult: + pts = _as_points(points) + if len(pts) < 8: + raise ValueError("torus fit needs at least 8 points") + + # ---- initial axis ---- + # A ring is thin along its major axis: the least-variance direction of + # the point cloud. (A cylinder is the opposite -- elongated along its + # axis, so it takes the LARGEST variance; that contrast is what lets + # model selection tell the two apart.) + cent = pts.mean(axis=0) + cov = (pts - cent).T @ (pts - cent) + eigvals, eigvecs = np.linalg.eigh(cov) + axis0 = eigvecs[:, 0] # smallest eigenvalue + if float(eigvals[0]) <= 0.0: + raise ValueError("degenerate torus: no axial thinness") + + # ---- initial centre / major / minor radius ---- + h0 = (pts - cent) @ axis0 + rho0 = np.linalg.norm(pts - cent - np.outer(h0, axis0), axis=1) + R0 = float(np.mean(rho0)) + r0 = max(float(np.mean(np.sqrt((rho0 - R0) ** 2 + h0 * h0))), 1e-9) + + theta0, phi0 = _spherical(axis0) + + def unpack(x): + cx, cy, cz, theta, phi, R, r = x + return np.array([cx, cy, cz]), _from_spherical(theta, phi), R, r + + def residuals(x): + center, axis, R, r = unpack(x) + v = pts - center + h = v @ axis + rho = np.linalg.norm(v - np.outer(h, axis), axis=1) + return np.sqrt((rho - R) ** 2 + h * h) - r + + x0 = [*cent, theta0, phi0, R0, r0] + res = least_squares(residuals, x0=x0, method="lm") + center, axis, R, r = unpack(res.x) + if R <= 0.0 or r <= 0.0: + raise ValueError("degenerate torus fit (non-positive radii)") + # A conical impostor: every cone surface normal makes the SAME angle with + # the axis, so the normal angles never sweep far from that constant (and + # a short frustum's (rho, h) cross-section is arc-like, so the point + # fit alone cannot tell the two apart). A genuine torus's normals wrap + # around the minor circle, sweeping from ~0 deg (tube top) to ~90 deg + # (tube equator). Reject when the normals stay inside a narrow band about + # the axis -- that band is the cone's half-angle, never the tube's sweep. + if normals is not None: + nrm = np.atleast_2d(np.asarray(normals, dtype=float)) + if len(nrm) == len(pts) and len(nrm) >= 6: + nrm = nrm / np.linalg.norm(nrm, axis=1, keepdims=True) + ax = axis / np.linalg.norm(axis) + ang = np.degrees(np.arccos(np.clip(np.abs(nrm @ ax), -1.0, 1.0))) + if float(np.percentile(ang, 95)) < 60.0: + raise ValueError("torus fit rejected: normals do not sweep " + "around the tube (conical impostor)") + # A torus is a FULL ring: it wraps all the way around its major axis, so + # the toroidal angle spans ~360 deg. A local curved patch -- a half- + # cylinder (a slot's rounded end), a fillet strip, a partial blend -- + # covers only a narrow arc of that angle, yet the flexible 7-dof fit + # grabs it when the cylinder fit fails on a partial circumference. Reject + # when the surface does not wrap around the axis. + if len(pts) >= 8: + ax = axis / np.linalg.norm(axis) + w = pts - center - np.outer((pts - center) @ ax, ax) + ref = np.array([1.0, 0.0, 0.0]) if abs(ax[0]) < 0.9 \ + else np.array([0.0, 1.0, 0.0]) + u0 = ref - ax * (ref @ ax) + u0 /= np.linalg.norm(u0) + u = np.arctan2(w @ np.cross(ax, u0), w @ u0) + us = np.sort(u) + gap = float(np.max(np.diff(np.concatenate([us, [us[0] + 2 * np.pi]])))) + if 2 * np.pi - gap < np.deg2rad(300.0): + raise ValueError("torus fit rejected: surface does not wrap " + "around the major axis (partial patch)") + torus = Torus(center=center, axis=axis, major_radius=R, minor_radius=r) + if trim: + mask = _trim_mask(torus.distance(pts)) + if mask is not None and normals is not None \ + and len(np.atleast_2d(normals)) == len(pts): + return fit_torus(pts[mask], np.atleast_2d(normals)[mask], + trim=False) + return FitResult.from_primitive(torus, pts) + + # -------------------------------------------------------------------------- # model selection # -------------------------------------------------------------------------- @@ -372,6 +465,7 @@ def fit_best( (1, lambda: fit_sphere(fit_pts)), (1, lambda: fit_cylinder(fit_pts, fit_nrm)), (2, lambda: fit_cone(fit_pts, fit_nrm)), + (3, lambda: fit_torus(fit_pts, fit_nrm)), ) prev_complexity = -1 for complexity, fitter in fitters: diff --git a/freecad/meshtofeatures_wb/core/history.py b/freecad/meshtofeatures_wb/core/history.py index fdc07a6..ee9e9a5 100644 --- a/freecad/meshtofeatures_wb/core/history.py +++ b/freecad/meshtofeatures_wb/core/history.py @@ -40,7 +40,7 @@ "ChamferOp", "CrossHoleOp", "blend_corner_profile", "chamfer_corner_profile", "BasePad", "HoleOp", "PocketOp", "PadOp", "ConeOp", "SphereOp", - "BuildPlan", "plan_history", "MAX_STEP_LEVELS"] + "TorusOp", "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, @@ -549,6 +549,34 @@ class SphereOp: label: str = "" +@dataclass +class TorusOp: + """A ring band (torus) revolved about a frame-z axis. + + PartDesign has no torus primitive, so the executor rebuilds the band as a + ``PartDesign::Revolution`` (a rounded ring BOSS, additive -- the tube + grows out of the face it sits on) or ``PartDesign::Groove`` (a ring SEAT, + subtractive -- a groove cut into the face) of a circular-arc profile; the + headless rebuild unions/differences a torus-band solid. + + ``major_radius`` is the major-circle radius R (axis to tube centreline), + ``minor_radius`` the tube radius r, and ``a_center`` the axial offset of + the tube-centre from the rim plane (the face the band opens at). The rim + is an annulus: inner radius ``R - sqrt(r^2 - a_center^2)``, outer + ``R + sqrt(r^2 - a_center^2)``; the band runs ``a_center + r`` from the + face to the tube top. ``surface_z`` is the frame-z of the rim face, as for + ConeOp. + """ + major_radius: float + minor_radius: float + a_center: 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 @@ -564,6 +592,7 @@ class BuildPlan: cross_holes: list[CrossHoleOp] = field(default_factory=list) cones: list[ConeOp] = field(default_factory=list) spheres: list[SphereOp] = field(default_factory=list) + tori: list[TorusOp] = field(default_factory=list) absorbed_features: int = 0 unplanned: list[str] = field(default_factory=list) #: detected blends with no dressable neighbour pair (degenerate @@ -1049,6 +1078,22 @@ def _cross_hole_op(f): additive=False, surface_z=bz, label=f.description)) + elif f.kind in ("torus_boss", "torus_recess") and _aligned(f): + # rounded ring band: the rim (an annulus) sits on the face it + # opens at and the tube grows OUT of it (a boss) or is cut INTO it + # (a seat). The rim face -- not the band span -- fixes the side, + # as for cone_boss/sphere_boss. + base3d = np.asarray(f.params["base"], dtype=float) + bz = float((base3d - origin) @ z) + plan.tori.append(TorusOp( + major_radius=float(f.params["major_radius"]), + minor_radius=float(f.params["minor_radius"]), + a_center=float(f.params["a_center"]), + positions=[_pos2d(f)], + from_top=bz > plan.base.length / 2, + additive=(f.kind == "torus_boss"), + 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/primitives.py b/freecad/meshtofeatures_wb/core/primitives.py index 406775d..539b1ea 100644 --- a/freecad/meshtofeatures_wb/core/primitives.py +++ b/freecad/meshtofeatures_wb/core/primitives.py @@ -20,7 +20,7 @@ import numpy as np -__all__ = ["Plane", "Sphere", "Cylinder", "Cone", "Primitive"] +__all__ = ["Plane", "Sphere", "Cylinder", "Cone", "Torus", "Primitive"] def _unit(v: np.ndarray) -> np.ndarray: @@ -146,4 +146,44 @@ def distance(self, points: np.ndarray) -> np.ndarray: return np.where(t >= 0.0, d_line, d_apex) -Primitive = Plane | Sphere | Cylinder | Cone +@dataclass +class Torus: + """Surface of revolution of a circle about ``axis``. + + ``center`` is the centre of the major circle (a point on the axis); + ``major_radius`` is the major-circle radius (axis to tube centreline) + and ``minor_radius`` the tube radius. ``minor_radius < major_radius`` + gives a ring; the distance is to the tube surface. + """ + + center: np.ndarray + axis: np.ndarray + major_radius: float + minor_radius: float + + complexity: int = field(default=3, init=False, repr=False) + kind: str = field(default="torus", init=False) + #: degrees of freedom of the surface parametrization + dof: int = field(default=7, init=False, repr=False) + + def __post_init__(self) -> None: + self.center = np.asarray(self.center, dtype=float) + self.axis = _unit(self.axis) + self.major_radius = float(self.major_radius) + self.minor_radius = float(self.minor_radius) + if self.major_radius <= 0.0 or self.minor_radius <= 0.0: + raise ValueError("torus radii must be positive") + + def distance(self, points: np.ndarray) -> np.ndarray: + points = np.atleast_2d(np.asarray(points, dtype=float)) + v = points - self.center + h = v @ self.axis + rho = np.linalg.norm(v - np.outer(h, self.axis), axis=1) + # distance to the major circle (tube centreline), minus the tube + # radius: the (rho, h) cross-section is a circle of radius + # minor_radius centred at (major_radius, 0) + return np.abs(np.sqrt((rho - self.major_radius) ** 2 + h * h) + - self.minor_radius) + + +Primitive = Plane | Sphere | Cylinder | Cone | Torus diff --git a/freecad/meshtofeatures_wb/core/solidify.py b/freecad/meshtofeatures_wb/core/solidify.py index bd49607..e705a3e 100644 --- a/freecad/meshtofeatures_wb/core/solidify.py +++ b/freecad/meshtofeatures_wb/core/solidify.py @@ -191,6 +191,49 @@ def _sphere_cap(radius, rim_radius, top_radius, center_xy, face_z, up, return cap +def _torus_band(major_radius, minor_radius, a_center, center_xy, face_z, up, + pad, sections: int = 96): + """Watertight torus band (the tube arc on the ``up`` side of the rim + plane) plus buried annular legs, about the z axis at ``center_xy``. + + The tube is the solid of revolution of the minor circle (radius + ``minor_radius`` centred at (major_radius, a_center) in the (rho, axial) + cross-section); the rim is the annulus where the tube crosses the plane + z = ``face_z``. The band is the part of the tube on the ``up`` side of the + rim, extended ``pad`` past it (off the coincident face -- the cone + boss/pocket doctrine); the tube top (the outermost point) is placed + exactly. Returns None when the clip boolean fails. + """ + R = float(major_radius) + r = float(minor_radius) + a = float(a_center) + theta = np.linspace(0.0, 2.0 * np.pi, sections, endpoint=False) + circ = np.column_stack([R + r * np.cos(theta), r * np.sin(theta)]) + circ = np.vstack([circ, circ[:1]]) # closed loop -> watertight + tor = trimesh.creation.revolve(circ, sections=sections) + tor.process() + h_top = a + r # rim -> tube top + # the tube centre sits ``a`` from the rim toward the bulge: above the rim + # for a boss (up), below it for a seat. The revolve left the centre at + # height 0 (the minor circle is centred on the rim plane), so shift to + # face_z + sign*a. + sign = 1.0 if up else -1.0 + if up: + z0, z1 = face_z - pad, face_z + h_top + else: + z0, z1 = face_z - h_top, face_z + pad + tor.apply_translation([center_xy[0], center_xy[1], face_z + sign * a]) + span = 2.0 * (R + r) + box = trimesh.creation.box( + extents=[span, span, float(z1 - z0)], + transform=trimesh.transformations.translation_matrix( + [center_xy[0], center_xy[1], 0.5 * (z0 + z1)])) + band = tor.intersection(box) + if band is None or not band.is_watertight: + return None + return band + + def _frame_matrix(plan) -> np.ndarray: t = np.eye(4) t[:3, 0] = plan.frame_x @@ -448,6 +491,23 @@ def _plan_to_mesh(plan, sections: int) -> trimesh.Trimesh: f"spherical cap boolean failed for {s.label or 'sphere'}") solid = solid.union(cap) if s.additive else solid.difference(cap) + # rounded ring bands (boss, additive) / seats (groove, subtractive): a + # torus band revolved about the frame-z axis. The rim (an annulus) sits on + # the face (surface_z) and the tube runs OUT of the material (boss) or + # INTO it (seat); the rim end is padded off the coincident face, the tube + # top is exact (see _torus_band). + for t in getattr(plan, "tori", []): + face_z = (float(t.surface_z) if t.surface_z is not None + else (L if t.from_top else 0.0)) + up = bool(t.additive == t.from_top) + for (x, y) in t.positions: + band = _torus_band(t.major_radius, t.minor_radius, t.a_center, + (x, y), face_z, up, 0.5, sections) + if band is None: + raise ValueError( + f"torus band boolean failed for {t.label or 'torus'}") + solid = solid.union(band) if t.additive else solid.difference(band) + # 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 56f7045..2240ac9 100644 --- a/freecad/meshtofeatures_wb/scripts/freecad_smoke_test.py +++ b/freecad/meshtofeatures_wb/scripts/freecad_smoke_test.py @@ -669,6 +669,81 @@ def check(name, cond, info=""): f"{seat_body.Shape.Volume:.2f} vs {seat_solid.Volume:.2f}") check("socket body shape is valid", seat_body.Shape.isValid()) +# --- rounded ring boss (Revolution primitive) ----------------------------- +# a full-revolution ring band (major R=10, minor r=3) standing on the top face +# of a 10 mm plate: the tube centre sits 2 mm above the face and the tube is +# sunk into the plate. Rebuilt as a PartDesign::Revolution of a circular-arc +# profile -- PartDesign has no torus primitive. The volume check verifies it: a +# band built the wrong way round (a straight-walled pad of the rim radius) is +# visibly off. +_ring_torus = Part.makeTorus(10.0, 3.0, App.Vector(0, 0, 12.0)) # tube z[9,15] +_ring_band = _ring_torus.common( + Part.makeBox(100, 100, 50, App.Vector(-50, -50, 10.0))) # z >= 10 +ring_solid = Part.makeBox(50, 40, 10, App.Vector(-25, -20, 0)) \ + .fuse(_ring_band).removeSplitter() +rv, rf = ring_solid.tessellate(0.05) +ringtm = trimesh.Trimesh(vertices=np.array([[v.x, v.y, v.z] for v in rv]), + faces=np.array(rf), process=True) +ringrep = snap_report(reconstruct(ringtm)).report +ringp = plan_patches(ringrep) +ringfeats = detect_features(ringrep, ringp) +ringplan = plan_history(ringrep, ringfeats, detect_patterns(ringfeats), ringp) +ringtori = [t for t in ringplan.tori if t.additive] +check("ring boss planned as an additive TorusOp", len(ringtori) == 1, + f"{len(ringplan.tori)} tori, {len(ringplan.pads)} pads") +check("ring boss did not also emit a terrace pad", + ringplan.pads == [], f"{len(ringplan.pads)} pads") +if ringtori: + _t = ringtori[0] + check("ring boss radii recovered", + abs(_t.major_radius - 10.0) < 0.2 and abs(_t.minor_radius - 3.0) < 0.2, + f"R {_t.major_radius:.3f}, r {_t.minor_radius:.3f}") +ring_body = build.build_body(doc, ringplan, name="RebuiltRingBoss") +check("ring boss body uses a Revolution feature", + any(o.TypeId == "PartDesign::Revolution" for o in ring_body.Group), + ", ".join(sorted({o.TypeId.split("::")[-1] for o in ring_body.Group}))) +check("ring boss body volume within 2%", + abs(ring_body.Shape.Volume - ring_solid.Volume) / ring_solid.Volume < 0.02, + f"{ring_body.Shape.Volume:.2f} vs {ring_solid.Volume:.2f}") +check("ring boss body shape is valid", ring_body.Shape.isValid()) + +# --- ring groove (Groove primitive) --------------------------------------- +# the concave mirror: a full-revolution ring band cut into the top face -- the +# tube centre sits 2 mm below the face, leaving an annular groove. Rebuilt as a +# PartDesign::Groove (subtractive revolution) of a circular-arc profile. +_seat_ring_torus = Part.makeTorus(10.0, 3.0, App.Vector(0, 0, 8.0)) # tube z[5,11] +_seat_ring_band = _seat_ring_torus.common( + Part.makeBox(100, 100, 50, App.Vector(-50, -50, -40.0))) # z <= 10 +seat_ring_solid = Part.makeBox(50, 40, 10, App.Vector(-25, -20, 0)) \ + .cut(_seat_ring_band) +srv, srf = seat_ring_solid.tessellate(0.05) +seat_ring_tm = trimesh.Trimesh( + vertices=np.array([[v.x, v.y, v.z] for v in srv]), + faces=np.array(srf), process=True) +seat_ring_rep = snap_report(reconstruct(seat_ring_tm)).report +seat_ring_p = plan_patches(seat_ring_rep) +seat_ring_feats = detect_features(seat_ring_rep, seat_ring_p) +seat_ring_plan = plan_history(seat_ring_rep, seat_ring_feats, + detect_patterns(seat_ring_feats), seat_ring_p) +seat_ring_tori = [t for t in seat_ring_plan.tori if not t.additive] +check("ring groove planned as a subtractive TorusOp", + len(seat_ring_tori) == 1, + f"{len(seat_ring_plan.tori)} tori, {len(seat_ring_plan.pockets)} pockets") +if seat_ring_tori: + _t = seat_ring_tori[0] + check("ring groove radii recovered", + abs(_t.major_radius - 10.0) < 0.2 and abs(_t.minor_radius - 3.0) < 0.2, + f"R {_t.major_radius:.3f}, r {_t.minor_radius:.3f}") +seat_ring_body = build.build_body(doc, seat_ring_plan, name="RebuiltRingSeat") +check("ring groove body uses a Groove feature", + any(o.TypeId == "PartDesign::Groove" for o in seat_ring_body.Group), + ", ".join(sorted({o.TypeId.split("::")[-1] for o in seat_ring_body.Group}))) +check("ring groove body volume within 2%", + abs(seat_ring_body.Shape.Volume - seat_ring_solid.Volume) + / seat_ring_solid.Volume < 0.02, + f"{seat_ring_body.Shape.Volume:.2f} vs {seat_ring_solid.Volume:.2f}") +check("ring groove body shape is valid", seat_ring_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 edd5c44..4e755aa 100644 --- a/freecad/meshtofeatures_wb/tests/test_adversarial.py +++ b/freecad/meshtofeatures_wb/tests/test_adversarial.py @@ -234,6 +234,23 @@ def extrude_lateral(pad): solid = (solid.union(cap) if s.additive else solid.difference(cap)) + # torus bands: mirror _plan_to_mesh's band boolean (same helper, so the + # proxy and the headless rebuild agree). The rim annulus sits on the face + # (surface_z); the tube runs out of the material (boss) or into it (seat), + # rim end padded off the coincident face, tube top exact. + if getattr(plan, "tori", []): + from freecad.meshtofeatures_wb.core.solidify import _torus_band + for t in plan.tori: + sz = t.surface_z + sz = float(sz) if sz is not None else (L if t.from_top else 0.0) + up = bool(t.additive == t.from_top) + for (x, y) in t.positions: + band = _torus_band(t.major_radius, t.minor_radius, + t.a_center, (x, y), sz, up, 0.5, SECTIONS) + assert band is not None, "torus band boolean failed" + solid = (solid.union(band) if t.additive + else solid.difference(band)) + # 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_torus.py b/freecad/meshtofeatures_wb/tests/test_torus.py new file mode 100644 index 0000000..b12d260 --- /dev/null +++ b/freecad/meshtofeatures_wb/tests/test_torus.py @@ -0,0 +1,310 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later +"""Rounded ring band (torus) tests, written before the implementation. + +A full-revolution ring band is a torus: a tube (major radius R, minor radius +r) of revolution standing on a face. A convex band growing OUT of the face it +sits on is a rounded ring BOSS (a donut blend the partial-revolution fillet +rule cannot claim -- fillets are partial revolutions, a ring band is a full +one); a band cut INTO a face is a ring SEAT (a ring groove). The band's rim +is an annulus (two concentric circles) where the tube is cut by the face; the +tube top (the outermost point) is the far end. + +The core had no torus primitive at all, so a ring band was either left +unassigned or absorbed by a straight-walled terrace pad -- the right +footprint at the wrong profile (the cone_boss/sphere gap, for tori). Rebuilt +as a ``PartDesign::Revolution`` (boss) / ``PartDesign::Groove`` (seat) of a +circular-arc profile; the headless rebuild unions/differences a torus-band +solid. +""" + +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 Torus +from freecad.meshtofeatures_wb.core.snapping import snap_report + +from .test_adversarial import ROT, assert_geometry_match + +# the band is a closed curve of revolution: use more sections than the +# default 64 so the fit and the boolean are both clean +SECTIONS = 96 + + +# --------------------------------------------------------------- mesh builders + +def _torus_solid(R, r, zc, sections=SECTIONS): + """Watertight solid torus about the z axis, tube centred at height ``zc`` + (major R, minor r). A closed minor-circle profile revolved 360 deg.""" + theta = np.linspace(0.0, 2.0 * np.pi, sections, endpoint=False) + circ = np.column_stack([R + r * np.cos(theta), r * np.sin(theta)]) + circ = np.vstack([circ, circ[:1]]) + t = trimesh.creation.revolve(circ, sections=sections) + t.process() + t.apply_translation([0.0, 0.0, zc]) + return t + + +def rounded_ring_boss(R=10.0, r=3.0, a_center=2.0, t=10.0, + ext=(50.0, 40.0), center=(0.0, 0.0)): + """Plate (z in [-t/2, t/2]) with a rounded ring boss on the top face: the + tube centre sits ``a_center`` above the top face and the tube is sunk + into the plate (its bottom is below the face) for a clean union.""" + plate = trimesh.creation.box(extents=[ext[0], ext[1], t]) + tor = _torus_solid(R, r, t / 2.0 + a_center) + tor.apply_translation([center[0], center[1], 0.0]) + return plate.union(tor) + + +def ring_seat(R=10.0, r=3.0, a_center=2.0, t=10.0, + ext=(50.0, 40.0), center=(0.0, 0.0)): + """Plate (z in [-t/2, t/2]) with a ring groove (seat) cut into the top + face: the tube centre sits ``a_center`` below the top face and is + subtracted, leaving an annular depression.""" + plate = trimesh.creation.box(extents=[ext[0], ext[1], t]) + tor = _torus_solid(R, r, t / 2.0 - a_center) + tor.apply_translation([center[0], center[1], 0.0]) + return plate.difference(tor) + + +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(feats, kind): + cs = feats.by_kind(kind) + assert len(cs) == 1, f"expected 1 {kind}, got {len(cs)}" + return cs[0] + + +# ------------------------------------------------------------------ detection + +class TestTorusBossDetection: + def test_boss_recognized(self): + _, feats, _ = _full(rounded_ring_boss()) + b = _only(feats, "torus_boss") + assert np.isclose(b.params["major_radius"], 10.0, atol=0.15) + assert np.isclose(b.params["minor_radius"], 3.0, atol=0.15) + assert np.isclose(b.params["a_center"], 2.0, atol=0.15) + assert np.isclose(b.params["height"], 5.0, atol=0.15) + + def test_rim_radii(self): + # rim annulus: [R - sqrt(r^2 - a^2), R + sqrt(r^2 - a^2)] + s = np.sqrt(3.0 ** 2 - 2.0 ** 2) + _, feats, _ = _full(rounded_ring_boss()) + b = _only(feats, "torus_boss") + assert np.isclose(b.params["rim_inner_radius"], 10.0 - s, atol=0.15) + assert np.isclose(b.params["rim_outer_radius"], 10.0 + s, atol=0.15) + + def test_not_mistaken_for_a_plain_boss(self): + _, feats, _ = _full(rounded_ring_boss()) + assert feats.by_kind("boss") == [] + + def test_torus_consumed(self): + report, feats, _ = _full(rounded_ring_boss()) + for i in feats.unassigned: + assert not isinstance(report.surfaces[i].fit.primitive, Torus), \ + "torus left unassigned" + + def test_axis_points_out_of_the_face(self): + # a boss grows OUT of the face it sits on: the axis (rim -> band) + # points away from the material. Base on top -> up. + _, feats, _ = _full(rounded_ring_boss()) + axis = np.asarray(_only(feats, "torus_boss").params["axis"]) + assert np.isclose(np.linalg.norm(axis), 1.0, atol=1e-6) + assert axis[2] > 0.999 + + def test_offcenter_position(self): + _, feats, _ = _full(rounded_ring_boss(center=(10.0, -7.0))) + pos = np.asarray(_only(feats, "torus_boss").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 = rounded_ring_boss().copy() + mesh.apply_transform(ROT) + _, feats, _ = _full(mesh) + b = _only(feats, "torus_boss") + assert np.isclose(b.params["major_radius"], 10.0, atol=0.25) + assert np.isclose(b.params["minor_radius"], 3.0, atol=0.25) + + @pytest.mark.parametrize("R,r,a_center", [ + (12.0, 2.0, 1.0), (8.0, 4.0, 3.0), (15.0, 3.0, 1.5)]) + def test_dimension_variants(self, R, r, a_center): + _, feats, _ = _full(rounded_ring_boss( + R=R, r=r, a_center=a_center, t=a_center + r + 6.0)) + b = _only(feats, "torus_boss") + assert np.isclose(b.params["major_radius"], R, atol=0.2) + assert np.isclose(b.params["minor_radius"], r, atol=0.2) + assert np.isclose(b.params["a_center"], a_center, atol=0.2) + + +class TestTorusSeatDetection: + def test_seat_recognized(self): + _, feats, _ = _full(ring_seat()) + s = _only(feats, "torus_recess") + assert np.isclose(s.params["major_radius"], 10.0, atol=0.15) + assert np.isclose(s.params["minor_radius"], 3.0, atol=0.15) + assert np.isclose(s.params["a_center"], 2.0, atol=0.15) + + def test_seat_axis_points_into_the_material(self): + # a groove is cut INTO the face: the axis (rim -> band) points away + # from the outward normal. Base on top -> down. + _, feats, _ = _full(ring_seat()) + axis = np.asarray(_only(feats, "torus_recess").params["axis"]) + assert axis[2] < -0.999 + + def test_not_mistaken_for_a_boss(self): + _, feats, _ = _full(ring_seat()) + assert feats.by_kind("torus_boss") == [] + + +# ------------------------------------------------------- negative / robustness + +class TestTorusNegatives: + def test_cylindrical_boss_is_not_a_torus(self): + # a constant-radius boss is a plain (cylindrical) boss, not a ring + plate = trimesh.creation.box(extents=[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("torus_boss") == [] + assert len(feats.by_kind("boss")) == 1 + + def test_standalone_donut_is_not_claimed(self): + # a full donut not fused to a face has no rim (and no planar base): + # the band is fitted but left unassigned rather than guessed as a + # boss. Detection only -- a base-less part has no prismatic plan. + donut = _torus_solid(10.0, 3.0, 15.0) + report = snap_report(reconstruct(donut)).report + feats = detect_features(report, plan_patches(report)) + assert feats.by_kind("torus_boss") == [] + assert feats.by_kind("torus_recess") == [] + + def test_slot_rounded_end_is_not_a_torus(self): + # a stadium (slot) opening's rounded ends are half-cylinders: local + # curved patches that do not wrap around a major axis. The flexible + # 7-dof torus fit grabs one when the cylinder fit fails on the partial + # circumference -- it must be rejected so the slot is still detected. + r, a, h = 4.0, 11.0, 6.0 + tool = trimesh.creation.box(extents=[2 * a, 2 * r, h]) + for sx in (-a, a): + c = trimesh.creation.cylinder(radius=r, height=h, + sections=SECTIONS) + c.apply_translation([sx, 0.0, 0.0]) + tool = tool.union(c) + plate = trimesh.creation.box(extents=[60.0, 40.0, h]) + slot = plate.difference(tool) + _, feats, _ = _full(slot) + assert feats.by_kind("torus_boss") == [] + assert feats.by_kind("torus_recess") == [] + assert len(feats.by_kind("slot")) == 1 + + +# -------------------------------------------------------------------- planning + +class TestTorusPlanning: + def test_planned_as_an_additive_torus_op(self): + _, _, plan = _full(rounded_ring_boss()) + assert len(plan.tori) == 1 + assert plan.unplanned == [] + op = plan.tori[0] + assert np.isclose(op.major_radius, 10.0, atol=0.15) + assert np.isclose(op.minor_radius, 3.0, atol=0.15) + assert np.isclose(op.a_center, 2.0, atol=0.15) + assert op.from_top is True + assert op.additive is True + + def test_seat_planned_as_a_subtractive_torus_op(self): + _, _, plan = _full(ring_seat()) + assert len(plan.tori) == 1 + assert plan.unplanned == [] + op = plan.tori[0] + assert op.additive is False + assert op.from_top is True + + def test_no_spurious_terrace_pad(self): + # the band must not also become a straight-walled terrace pad + _, _, plan = _full(rounded_ring_boss()) + assert plan.pads == [] + + def test_base_face_is_the_sketch_plane(self): + _, _, plan = _full(rounded_ring_boss(t=10.0)) + # the ring sits on the plate top face (plan-frame z = L = 10) + assert np.isclose(plan.tori[0].surface_z, 10.0, atol=0.15) + + def test_bottom_face_boss(self): + mesh = rounded_ring_boss().copy() + mesh.apply_transform( + trimesh.transformations.rotation_matrix(np.pi, [1, 0, 0])) + _, _, plan = _full(mesh) + assert len(plan.tori) == 1 + assert plan.tori[0].from_top is False + assert plan.tori[0].additive is True + assert np.isclose(plan.tori[0].major_radius, 10.0, atol=0.2) + + def test_boss_alongside_a_hole(self): + mesh = rounded_ring_boss(center=(-12.0, 0.0)) + drill = trimesh.creation.cylinder(radius=2.5, height=40.0, + sections=SECTIONS) + drill.apply_translation([14.0, 8.0, 0.0]) + _, _, plan = _full(mesh.difference(drill)) + assert len(plan.tori) == 1 + assert len(plan.holes) == 1 + assert plan.unplanned == [] + + +# ------------------------------------------------------------------ round-trip + +class TestTorusRoundtrip: + def test_boss_roundtrip(self): + mesh = rounded_ring_boss() + _, _, plan = _full(mesh) + assert_geometry_match(mesh, plan) + + def test_seat_roundtrip(self): + mesh = ring_seat() + _, _, plan = _full(mesh) + assert_geometry_match(mesh, plan) + + def test_rotated_roundtrip(self): + mesh = rounded_ring_boss().copy() + mesh.apply_transform(ROT) + _, _, plan = _full(mesh) + assert_geometry_match(mesh, plan) + + def test_bottom_face_roundtrip(self): + mesh = rounded_ring_boss().copy() + mesh.apply_transform( + trimesh.transformations.rotation_matrix(np.pi, [1, 0, 0])) + _, _, plan = _full(mesh) + assert_geometry_match(mesh, plan) + + def test_alongside_hole_roundtrip(self): + mesh = rounded_ring_boss(center=(-12.0, 0.0)) + drill = trimesh.creation.cylinder(radius=2.5, height=40.0, + sections=SECTIONS) + drill.apply_translation([14.0, 8.0, 0.0]) + mesh = mesh.difference(drill) + _, _, plan = _full(mesh) + assert_geometry_match(mesh, plan) + + @pytest.mark.parametrize("R,r,a_center", [ + (12.0, 2.0, 1.0), (8.0, 4.0, 3.0)]) + def test_dimension_variants_roundtrip(self, R, r, a_center): + mesh = rounded_ring_boss(R=R, r=r, a_center=a_center, + t=a_center + r + 6.0) + _, _, plan = _full(mesh) + assert_geometry_match(mesh, plan)