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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 11 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
27 changes: 18 additions & 9 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand All @@ -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

Expand Down
95 changes: 95 additions & 0 deletions freecad/meshtofeatures_wb/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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", [])):
Expand Down
166 changes: 166 additions & 0 deletions freecad/meshtofeatures_wb/core/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
# --------------------------------------------------------------------------
Expand Down Expand Up @@ -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:
Expand Down
Loading
Loading