diff --git a/CHANGELOG.md b/CHANGELOG.md index 644132b..4e33689 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,8 +4,20 @@ ### Added +- **Tapered bosses (convex cones) are now a feature.** A full-revolution + CONVEX cone — a conical stud or draft-angled boss, truncated or + pointed, standing on a face — is detected (`cone_boss`), planned as an + additive `ConeOp`, and rebuilt as a `PartDesign::AdditiveCone` + primitive (base on the face, tip exact). This is the convex mirror + image of the existing conical pocket. The core already *fit* convex + cones (coverage 1.0); previously the planner had no additive path, so + a tapered boss was left unassigned and the terrace machinery + substituted a straight-walled pad of the base radius — the right + 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. - **FreeCAD executor CI.** A second CI job (`freecad-smoke`) runs the - full headless smoke test (`scripts/freecad_smoke_test.py`: 17 parts + full headless smoke test (`scripts/freecad_smoke_test.py`: 18 parts through reconstruct -> snap -> plan -> feature detection -> PartDesign build, including the manifold3d deviation-correction case) inside a sha256-verified FreeCAD 1.1.x AppImage on every push and PR. The diff --git a/README.md b/README.md index b1d793f..43282b3 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,9 @@ Recognized and rebuilt on the current release: `HoleCutType = Counterdrill`. - **Conical pockets**: tapered recesses, conical seats, and tapered through holes, rebuilt as `PartDesign::SubtractiveCone` primitives. +- **Tapered bosses** (convex cones): conical studs and draft-angled + bosses, truncated or pointed, rebuilt as `PartDesign::AdditiveCone` + primitives standing on their base face. - **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 @@ -61,11 +64,11 @@ Recognized and rebuilt on the current release: ## Limitations (please read before filing bugs) - **Prismatic parts only.** The reconstruction targets parts made of - planes and cylinders (plates, brackets, housings, fixtures), plus - conical countersinks and conical pockets. Organic / sculpted / scanned - shapes will not reconstruct meaningfully. Spheres and tori are fitted - by the core but not yet rebuilt as features; CONVEX cones (tapered - bosses, draft-angled studs) are not yet a feature either. + 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. - **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 50223b3..29ac8cf 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -35,9 +35,11 @@ Exit criteria: the job — verified once during development. - Headless suite still green; dependency docs accurate. -Status: **in progress**. +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`) 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 @@ -50,7 +52,10 @@ 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. + 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. 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. @@ -62,7 +67,8 @@ 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: not started. +Status: in progress — item 1 (convex cones) done on +`feature/additive-cones`; items 2-3 (spheres, tori) not started. ## Phase 3 — Per-feature deviation report diff --git a/freecad/meshtofeatures_wb/build.py b/freecad/meshtofeatures_wb/build.py index b56e500..f9a33c4 100644 --- a/freecad/meshtofeatures_wb/build.py +++ b/freecad/meshtofeatures_wb/build.py @@ -769,7 +769,7 @@ def build_body(doc, plan: BuildPlan, name: str = "Rebuilt"): doc.recompute() - # ---- conical pockets: placed Subtractive/AdditiveCone primitives ------- + # ---- conical features: placed Subtractive/AdditiveCone primitives ------ for k, c in enumerate(getattr(plan, "cones", [])): try: diag = float(body.Shape.BoundBox.DiagonalLength) or float(L) @@ -780,19 +780,39 @@ def build_body(doc, plan: BuildPlan, name: str = "Rebuilt"): slope = (c.r_mouth - c.r_far) / max(c.depth, 1e-12) face_z = c.surface_z if c.surface_z is not None \ else (L if c.from_top else 0.0) - far_pad = pad if c.through else 0.0 - r_end = max(c.r_far - slope * far_pad, 0.0) - height = c.depth + far_pad + pad - if c.from_top: - z_lo = float(face_z) - c.depth - far_pad - r_lo, r_hi = r_end, c.r_mouth + slope * pad + if c.additive: + # tapered boss: the base (r_mouth, the wide end) sits on the + # face and the feature grows OUT of the material, along the + # face's outward normal. SINK the base `pad` INTO the face so + # the fuse does not rest on a coincident-face boolean (the cut + # buffer doctrine, applied to an add); the sunk leg keeps the + # cone's exact slope, so the base lands exactly. The TIP is the + # outermost point (in the air, coincident with nothing), so it + # is placed EXACTLY -- extending it would overshoot the source. + if c.from_top: + z_lo = float(face_z) - pad + r_lo, r_hi = c.r_mouth + slope * pad, c.r_far + height = c.depth + pad + else: + z_lo = float(face_z) - c.depth + r_lo, r_hi = c.r_far, c.r_mouth + slope * pad + height = c.depth + pad + name = f"TaperedBoss{k}" else: - z_lo = float(face_z) - pad - r_lo, r_hi = c.r_mouth + slope * pad, r_end + far_pad = pad if c.through else 0.0 + r_end = max(c.r_far - slope * far_pad, 0.0) + height = c.depth + far_pad + pad + if c.from_top: + z_lo = float(face_z) - c.depth - far_pad + r_lo, r_hi = r_end, c.r_mouth + slope * pad + else: + z_lo = float(face_z) - pad + r_lo, r_hi = c.r_mouth + slope * pad, r_end + name = f"ConePocket{k}" for pos in c.positions: - _add_cone(doc, body, plan, f"ConePocket{k}", pos[0], pos[1], + _add_cone(doc, body, plan, name, pos[0], pos[1], z_lo, r_lo, r_hi, height, additive=c.additive, - label=c.label or f"ConePocket{k}", deferred=deferred) + label=c.label or name, deferred=deferred) doc.recompute() # ---- cross-axis holes: through = midplane pocket, blind = Length ------- diff --git a/freecad/meshtofeatures_wb/core/features.py b/freecad/meshtofeatures_wb/core/features.py index e74b721..55a1898 100644 --- a/freecad/meshtofeatures_wb/core/features.py +++ b/freecad/meshtofeatures_wb/core/features.py @@ -445,6 +445,83 @@ def _ends(i: int) -> dict: f"{'through' if through else f'x {depth:g} deep'}"), )) + # ---- standalone convex cones -> tapered bosses ------------------------- + # The convex mirror image of the conical pocket above: a full-revolution + # cone whose WIDE end (the base) opens at a face and whose NARROW end + # (the tip) is either capped by a disk or runs to a point. This is a + # tapered boss / draft-angled stud. Claimed only when both ends are + # explained (base face + capped-or-pointed tip); anything less is left + # unassigned rather than guessed. + for ci in cones: + if ci in consumed: + continue + scone = report.surfaces[ci] + cone = scone.fit.primitive + if not patches[ci].full_u or _is_concave_cone(scone): + continue + ha = cone.half_angle + h_lo, h_hi = patches[ci].v_range # heights above the apex + r_wide = float(h_hi * np.tan(ha)) + r_narrow = float(h_lo * np.tan(ha)) + if r_wide <= tol: + continue + # the base: the WIDE end opening at a face (an interior hole loop + # rides the cone near the wide end) + base_p = None + for p in planes: + lps = _plane_hole_loops_on_cone(report.surfaces[p], cone, tol) + if not lps: + continue + h = max(float(np.mean((lp - cone.apex) @ cone.axis)) + for lp in lps) + if abs(h - h_hi) <= max(tol, 0.1 * (h_hi - h_lo)): + base_p = p + break + if base_p is None: + continue + # the tip: the NARROW end, capped by a disk or running to a point + cap_p = None + if r_narrow > tol: + for p in planes: + if p == base_p or p in consumed: + continue + if _outer_loop_is_disk_on_cone(report.surfaces[p], cone, tol): + h = float(np.mean((report.surfaces[p].segment.points + - cone.apex) @ cone.axis)) + if abs(h - h_lo) <= max(tol, 0.1 * (h_hi - h_lo)): + cap_p = p + break + if cap_p is None: + continue + tip_r = 0.0 if r_narrow <= tol else r_narrow + height = float(h_hi - h_lo) + if height <= tol: + continue + axis = cone.axis.copy() # apex -> wide end (base) + base_pt = cone.apex + h_hi * axis + anchor = base_pt - float(base_pt @ axis) * axis + used = [ci, base_p] + if cap_p is not None: + used.append(cap_p) + consumed.add(cap_p) + consumed.add(ci) + out.features.append(Feature( + kind="cone_boss", + surface_indices=used, + params={ + "base_radius": r_wide, + "tip_radius": tip_r, + "height": height, + "position": anchor.tolist(), + "axis": axis.tolist(), + "base": base_pt.tolist(), + "half_angle": float(np.rad2deg(ha)), + }, + description=( + f"Tapered boss d{2 * r_wide:g} -> d{2 * tip_r:g} " + f"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 62540ee..a7624ee 100644 --- a/freecad/meshtofeatures_wb/core/history.py +++ b/freecad/meshtofeatures_wb/core/history.py @@ -697,6 +697,10 @@ def plan_history(report: ReconstructionReport, feats: FeatureReport, # would inflate the base extrusion to the top of the boss boss_caps = {f.surface_indices[1] for f in feats.features if f.kind == "boss" and len(f.surface_indices) >= 2} + # a tapered boss's tip cap (provenance [cone, base, cap]) is the same + # 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} 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) @@ -960,6 +964,26 @@ def _cross_hole_op(f): # the floor disk is this cone's own end face: keep the terrace # pass off it, or it also emits a straight-walled substitute _cone_faces.update(f.surface_indices[2:]) + elif f.kind == "cone_boss" and _aligned(f): + # tapered boss: r_mouth is the base radius AT the face it + # stands on, r_far the tip. The base face -- not the cone + # span -- fixes the side, since the boss grows OUT of the + # material (the mirror of a cone_pocket, which is cut INTO it) + base3d = np.asarray(f.params["base"], dtype=float) + bz = float((base3d - origin) @ z) + plan.cones.append(ConeOp( + r_mouth=float(f.params["base_radius"]), + r_far=float(f.params["tip_radius"]), + depth=float(f.params["height"]), + positions=[_pos2d(f)], + from_top=bz > plan.base.length / 2, + additive=True, + through=False, + surface_z=bz, + label=f.description)) + # 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 == "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 0d4b4bf..9badc96 100644 --- a/freecad/meshtofeatures_wb/core/solidify.py +++ b/freecad/meshtofeatures_wb/core/solidify.py @@ -360,14 +360,29 @@ def _plan_to_mesh(plan, sections: int) -> trimesh.Trimesh: sections=sections) solid = solid.difference(fr) - # conical pockets / studs + # conical pockets / tapered bosses for c in getattr(plan, "cones", []): face_z = (float(c.surface_z) if c.surface_z is not None else (L if c.from_top else 0.0)) depth = (face_z + 1.0 if c.from_top else L + 1.0 - face_z) \ if getattr(c, "through", False) else float(c.depth) + slope = (c.r_mouth - c.r_far) / max(float(c.depth), 1e-12) for (x, y) in c.positions: - if c.from_top: + if c.additive: + # tapered boss: base (r_mouth, the wide end) on the face, + # growing OUT of the material. The base leg is sunk 0.5 + # INTO the face (inside already-solid ground) along the + # exact slope; the tip is placed EXACTLY (it is the + # outermost point, so extending it would overshoot). + if c.from_top: + fr = _frustum(c.r_mouth + slope * 0.5, c.r_far, + face_z - 0.5, face_z + c.depth, + center=(x, y), sections=sections) + else: + fr = _frustum(c.r_far, c.r_mouth + slope * 0.5, + face_z - c.depth, face_z + 0.5, + center=(x, y), sections=sections) + elif c.from_top: fr = _frustum(c.r_far, c.r_mouth, face_z - depth, face_z + 0.5, center=(x, y), sections=sections) diff --git a/freecad/meshtofeatures_wb/scripts/freecad_smoke_test.py b/freecad/meshtofeatures_wb/scripts/freecad_smoke_test.py index a782f1a..10f003c 100644 --- a/freecad/meshtofeatures_wb/scripts/freecad_smoke_test.py +++ b/freecad/meshtofeatures_wb/scripts/freecad_smoke_test.py @@ -565,6 +565,40 @@ def check(name, cond, info=""): f"{cbbody.Shape.Volume:.2f} vs {cbp.Volume:.2f}") check("cbore body shape is valid", cbbody.Shape.isValid()) +# --- tapered boss (AdditiveCone primitive) -------------------------------- +# an r9 -> r5 truncated tapered boss (a conical stud) 6 mm tall on a 10 mm +# plate: additive material standing on the top face. Rebuilt as a +# PartDesign::AdditiveCone -- base (r9) on the face, tip (r5) exact. The +# volume check is what verifies it: a boss built the wrong way round (a +# straight r5 cylinder, or a subtractive cut into the plate) is visibly off. +tbo_solid = Part.makeBox(50, 40, 10, App.Vector(-25, -20, 0)) \ + .fuse(Part.makeCone(9.0, 5.0, 6.0, App.Vector(0, 0, 10.0))) +tbv, tbf = tbo_solid.tessellate(0.05) +tbotm = trimesh.Trimesh(vertices=np.array([[v.x, v.y, v.z] for v in tbv]), + faces=np.array(tbf), process=True) +tbrep = snap_report(reconstruct(tbotm)).report +tbp = plan_patches(tbrep) +tbfeats = detect_features(tbrep, tbp) +tbplan = plan_history(tbrep, tbfeats, detect_patterns(tbfeats), tbp) +tbocones = [c for c in tbplan.cones if c.additive] +check("tapered boss planned as an additive ConeOp", len(tbocones) == 1, + f"{len(tbplan.cones)} cones, {len(tbplan.pockets)} pockets") +check("tapered boss did not also emit a terrace pocket", + tbplan.pockets == [], f"{len(tbplan.pockets)} pockets") +if tbocones: + _c = tbocones[0] + check("tapered boss radii recovered", + abs(_c.r_mouth - 9.0) < 0.2 and abs(_c.r_far - 5.0) < 0.2, + f"r_mouth {_c.r_mouth:.3f}, r_far {_c.r_far:.3f}") +tbo_body = build.build_body(doc, tbplan, name="RebuiltTaperedBoss") +check("tapered boss body uses an AdditiveCone primitive", + any(o.TypeId == "PartDesign::AdditiveCone" for o in tbo_body.Group), + ", ".join(sorted({o.TypeId.split("::")[-1] for o in tbo_body.Group}))) +check("tapered boss body volume within 2%", + abs(tbo_body.Shape.Volume - tbo_solid.Volume) / tbo_solid.Volume < 0.02, + f"{tbo_body.Shape.Volume:.2f} vs {tbo_solid.Volume:.2f}") +check("tapered boss body shape is valid", tbo_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 30d5702..98c6597 100644 --- a/freecad/meshtofeatures_wb/tests/test_adversarial.py +++ b/freecad/meshtofeatures_wb/tests/test_adversarial.py @@ -163,29 +163,53 @@ def extrude_lateral(pad): _Poly(prof).exterior.coords, sections=SECTIONS) tool.apply_translation([x, y, 0.0]) solid = solid.difference(tool) - # conical pockets: a revolved frustum, r_mouth at the opening face - # tapering to r_far at depth (r_far = 0 runs to a point). A THROUGH cone - # is extrapolated a little past the far face along its own slope so the - # cut is not coincident with it. + # conical features: a revolved frustum. SUBTRACTIVE (pocket): r_mouth at + # the opening face tapering to r_far at depth (r_far = 0 runs to a + # point); a THROUGH cone is extrapolated a little past the far face + # along its own slope so the cut is not coincident with it. ADDITIVE + # (tapered boss): the base (r_mouth, the wide end) sits on the face and + # the frustum grows OUT of the material; the base leg is sunk `ext` INTO + # the material (off the coincident face, inside already-solid ground so + # the union adds nothing there) and the tip is placed EXACTLY -- it is + # the outermost point, so extending it would overshoot the source. for c in getattr(plan, "cones", []): from shapely.geometry import Polygon as _CPoly sz = c.surface_z sz = float(sz) if sz is not None else (L if c.from_top else 0.0) slope = (c.r_mouth - c.r_far) / max(c.depth, 1e-12) ext = 1.0 - r_end = max(c.r_far - slope * ext, 0.0) if c.through else c.r_far - if c.from_top: - z_end = sz - c.depth - (ext if c.through else 0.0) - prof = [(0.0, z_end)] - if r_end > 1e-9: - prof.append((r_end, z_end)) - prof += [(c.r_mouth, sz), (c.r_mouth, sz + ext), (0.0, sz + ext)] + if c.additive: + if c.from_top: + z_tip = sz + c.depth + prof = [(0.0, sz - ext), (c.r_mouth + slope * ext, + sz - ext)] + if c.r_far > 1e-9: + prof.append((c.r_far, z_tip)) + prof.append((0.0, z_tip)) + else: + z_tip = sz - c.depth + prof = [(0.0, z_tip)] + if c.r_far > 1e-9: + prof.append((c.r_far, z_tip)) + prof += [(c.r_mouth, sz), (c.r_mouth + slope * ext, + sz + ext), (0.0, sz + ext)] else: - z_end = sz + c.depth + (ext if c.through else 0.0) - prof = [(0.0, sz - ext), (c.r_mouth, sz - ext), (c.r_mouth, sz)] - if r_end > 1e-9: - prof.append((r_end, z_end)) - prof.append((0.0, z_end)) + r_end = max(c.r_far - slope * ext, 0.0) if c.through \ + else c.r_far + if c.from_top: + z_end = sz - c.depth - (ext if c.through else 0.0) + prof = [(0.0, z_end)] + if r_end > 1e-9: + prof.append((r_end, z_end)) + prof += [(c.r_mouth, sz), (c.r_mouth, sz + ext), + (0.0, sz + ext)] + else: + z_end = sz + c.depth + (ext if c.through else 0.0) + prof = [(0.0, sz - ext), (c.r_mouth, sz - ext), + (c.r_mouth, sz)] + if r_end > 1e-9: + prof.append((r_end, z_end)) + prof.append((0.0, z_end)) tool = trimesh.creation.revolve(_CPoly(prof).exterior.coords, sections=SECTIONS) for (x, y) in c.positions: diff --git a/freecad/meshtofeatures_wb/tests/test_cone_boss.py b/freecad/meshtofeatures_wb/tests/test_cone_boss.py new file mode 100644 index 0000000..e0044c7 --- /dev/null +++ b/freecad/meshtofeatures_wb/tests/test_cone_boss.py @@ -0,0 +1,255 @@ +# SPDX-License-Identifier: LGPL-2.1-or-later +"""Tapered-boss (additive cone) tests, written before the implementation. + +A tapered boss is the convex mirror image of a conical pocket: a +full-revolution CONE whose WIDE end (the base) opens at a face and whose +NARROW end (the tip) is either capped by a disk or runs to a point. It is a +conical stud / draft-angled boss, additive material standing on a face. + +Rebuilt as a `PartDesign::AdditiveCone` primitive: the base (Radius1, the +wide end) sits on the face it stands on and the feature grows OUT of the +material. The base leg is sunk a hair into the face (off the coincident +boolean), the tip is placed exactly (it is the outermost point). + +The pre-existing gap this suite pins: the core FITS convex cones (coverage +1.0) but the planner/executor had no additive path, so a tapered boss was +left unassigned and the terrace machinery either dropped it or substituted +a straight-walled pad of the base radius -- the right footprint at the wrong +profile, reported as a clean reconstruction. +""" + +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 Cone +from freecad.meshtofeatures_wb.core.snapping import snap_report + +from .test_adversarial import ROT, assert_geometry_match + +SECTIONS = 64 + + +# --------------------------------------------------------------- mesh builders + +def tapered_boss_plate(r_base=9.0, r_tip=5.0, height=6.0, t=10.0, + ext=(50.0, 40.0), center=(0.0, 0.0)): + """Plate (z in [-t/2, t/2]) with a truncated tapered boss on the top: + base radius ``r_base`` at the top face, tip radius ``r_tip`` at the top + of the boss. The frustum is sunk 1.0 into the plate for a clean union.""" + from shapely.geometry import Polygon + plate = trimesh.creation.box(extents=[ext[0], ext[1], t]) + top = t / 2.0 + slope = (r_base - r_tip) / height + sink = 1.0 + prof = [(0.0, top - sink), (r_base + slope * sink, top - sink), + (r_tip, top + height), (0.0, top + height)] + boss = trimesh.creation.revolve(Polygon(prof).exterior.coords, + sections=SECTIONS) + boss.apply_translation([center[0], center[1], 0.0]) + return plate.union(boss) + + +def pointed_boss_plate(r_base=8.0, height=7.0, t=10.0, + ext=(50.0, 40.0), center=(0.0, 0.0)): + """Conical stud running to a point (no tip cap).""" + from shapely.geometry import Polygon + plate = trimesh.creation.box(extents=[ext[0], ext[1], t]) + top = t / 2.0 + sink = 1.0 + prof = [(0.0, top - sink), (r_base + (r_base / height) * sink, + top - sink), (0.0, top + height)] + boss = trimesh.creation.revolve(Polygon(prof).exterior.coords, + sections=SECTIONS) + boss.apply_translation([center[0], center[1], 0.0]) + return plate.union(boss) + + +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_boss(feats): + cs = feats.by_kind("cone_boss") + assert len(cs) == 1, f"expected 1 tapered boss, got {len(cs)}" + return cs[0] + + +# ------------------------------------------------------------------ detection + +class TestTaperedBossDetection: + def test_truncated_boss_recognized(self): + _, feats, _ = _full(tapered_boss_plate()) + c = _only_boss(feats) + assert np.isclose(c.params["base_radius"], 9.0, atol=0.15) + assert np.isclose(c.params["tip_radius"], 5.0, atol=0.15) + assert np.isclose(c.params["height"], 6.0, atol=0.1) + + def test_pointed_boss_recognized(self): + _, feats, _ = _full(pointed_boss_plate()) + c = _only_boss(feats) + assert np.isclose(c.params["base_radius"], 8.0, atol=0.15) + assert c.params["tip_radius"] < 0.3 # runs to a point + assert np.isclose(c.params["height"], 7.0, atol=0.15) + + def test_not_mistaken_for_a_pocket(self): + _, feats, _ = _full(tapered_boss_plate()) + assert feats.by_kind("cone_pocket") == [] + + def test_cone_and_cap_consumed(self): + report, feats, _ = _full(tapered_boss_plate()) + for i in feats.unassigned: + assert not isinstance(report.surfaces[i].fit.primitive, Cone), \ + "cone left unassigned" + + def test_axis_points_into_the_material(self): + # like the conical pocket, the feature axis is stored pointing INTO + # the material (the boss grows the other way). Base on top -> down. + _, feats, _ = _full(tapered_boss_plate()) + c = _only_boss(feats) + axis = np.asarray(c.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(tapered_boss_plate(center=(10.0, -7.0))) + c = _only_boss(feats) + pos = np.asarray(c.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 = tapered_boss_plate().copy() + mesh.apply_transform(ROT) + _, feats, _ = _full(mesh) + c = _only_boss(feats) + assert np.isclose(c.params["base_radius"], 9.0, atol=0.25) + + @pytest.mark.parametrize("r_base,r_tip,height", [ + (8.0, 4.0, 5.0), (12.0, 7.0, 4.0), (6.0, 1.0, 8.0)]) + def test_dimension_variants(self, r_base, r_tip, height): + _, feats, _ = _full(tapered_boss_plate( + r_base=r_base, r_tip=r_tip, height=height, t=height + 6.0)) + c = _only_boss(feats) + assert np.isclose(c.params["base_radius"], r_base, atol=0.2) + assert np.isclose(c.params["tip_radius"], r_tip, atol=0.2) + assert np.isclose(c.params["height"], height, atol=0.15) + + +# ------------------------------------------------------- negative / robustness + +class TestTaperedBossNegatives: + def test_cylindrical_boss_is_not_a_cone_boss(self): + # a constant-radius boss is a plain (cylindrical) boss, not tapered + 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("cone_boss") == [] + assert len(feats.by_kind("boss")) == 1 + + def test_conical_pocket_is_not_a_cone_boss(self): + from .test_cone_pocket import conical_pocket_plate + _, feats, _ = _full(conical_pocket_plate()) + assert feats.by_kind("cone_boss") == [] + + +# -------------------------------------------------------------------- planning + +class TestTaperedBossPlanning: + def test_planned_as_an_additive_cone_op(self): + _, _, plan = _full(tapered_boss_plate()) + assert len(plan.cones) == 1 + assert plan.unplanned == [] + op = plan.cones[0] + assert np.isclose(op.r_mouth, 9.0, atol=0.15) # base (wide) + assert np.isclose(op.r_far, 5.0, atol=0.15) # tip (narrow) + assert np.isclose(op.depth, 6.0, atol=0.1) + assert op.from_top is True + assert op.additive is True + assert op.through is False + + def test_pointed_planned_as_an_additive_cone_op(self): + _, _, plan = _full(pointed_boss_plate()) + assert len(plan.cones) == 1 + assert plan.cones[0].additive is True + assert np.isclose(plan.cones[0].r_mouth, 8.0, atol=0.15) + assert plan.cones[0].r_far < 0.3 + + def test_no_spurious_terrace_pad(self): + # the tip cap must not also become a straight-walled terrace pad + _, _, plan = _full(tapered_boss_plate()) + assert plan.pads == [] + + def test_base_face_is_the_sketch_plane(self): + _, _, plan = _full(tapered_boss_plate(t=10.0)) + # the boss stands on the plate top face (plan-frame z = L = 10) + assert np.isclose(plan.cones[0].surface_z, 10.0, atol=0.15) + + def test_bottom_face_boss(self): + mesh = tapered_boss_plate().copy() + mesh.apply_transform( + trimesh.transformations.rotation_matrix(np.pi, [1, 0, 0])) + _, _, plan = _full(mesh) + assert len(plan.cones) == 1 + assert plan.cones[0].from_top is False + assert plan.cones[0].additive is True + assert np.isclose(plan.cones[0].r_mouth, 9.0, atol=0.2) + + def test_boss_alongside_a_hole(self): + mesh = tapered_boss_plate(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.cones) == 1 + assert len(plan.holes) == 1 + assert plan.unplanned == [] + + +# ------------------------------------------------------------------ round-trip + +class TestTaperedBossRoundtrip: + def test_truncated_roundtrip(self): + mesh = tapered_boss_plate() + _, _, plan = _full(mesh) + assert_geometry_match(mesh, plan) + + def test_pointed_roundtrip(self): + mesh = pointed_boss_plate() + _, _, plan = _full(mesh) + assert_geometry_match(mesh, plan) + + def test_rotated_roundtrip(self): + mesh = tapered_boss_plate().copy() + mesh.apply_transform(ROT) + _, _, plan = _full(mesh) + assert_geometry_match(mesh, plan) + + def test_bottom_face_roundtrip(self): + mesh = tapered_boss_plate().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 = tapered_boss_plate(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)