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
17 changes: 17 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 13 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
19 changes: 14 additions & 5 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/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
Expand Down Expand Up @@ -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

Expand Down
96 changes: 96 additions & 0 deletions freecad/meshtofeatures_wb/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 -------
Expand Down
32 changes: 29 additions & 3 deletions freecad/meshtofeatures_wb/core/emission.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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"]

Expand All @@ -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
Expand Down Expand Up @@ -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] = []
Expand All @@ -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
105 changes: 105 additions & 0 deletions freecad/meshtofeatures_wb/core/features.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
# --------------------------------------------------------------------------
Expand Down Expand Up @@ -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:
Expand Down
Loading
Loading