Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

saveMeshAsStep: convert a mesh into STEP with fitted surfaces - #7581

Draft
Fedr wants to merge 21 commits into
masterfrom
mesh-to-step
Draft

Fedr wants to merge 21 commits into
masterfrom
mesh-to-step

Conversation

@Fedr

@Fedr Fedr commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Adds MR::saveMeshAsStep( mesh, stream or path, MeshToStepSettings ) to MRMesh. It turns a mesh that is a tessellation of a CAD model back into a boundary representation and writes it as STEP (AP214). The STEP text is written directly, so nothing new is linked.

struct MeshToStepSettings
{
    const UndirectedEdgeBitSet* faceBoundaries = nullptr; // optional edges that must separate faces
    float tolerance = 0;        // <= 0: 2.5e-6 of the bounding box diagonal, or more for imprecise coordinates
    std::string name = "mesh";
    ProgressCallback progress;
};
Expected<MeshToStepStats> saveMeshAsStep( const Mesh&, std::ostream&, const MeshToStepSettings& = {} );
Expected<MeshToStepStats> saveMeshAsStep( const Mesh&, const std::filesystem::path&, const MeshToStepSettings& = {} );

How it works

  1. The mesh is split into segments by faceBoundaries (one segment if none are given).
  2. Regions lying on planes, cylinders, cones, spheres and tori are grown from seed triangles. A second pass reuses the surfaces and axes found in the first one.
  3. The regions are cleaned up: strong regions take adjacent leftover triangles, pieces explained by one surface are united, and groups of smoothly adjacent unreliable regions are approximated by bicubic B-spline surfaces (conformal parametrization, least squares).
  4. Borders between regions become lines, circles or interpolating B-spline curves; faces with their loops are written as one shell per connected component (MANIFOLD_SOLID_BREP if everything is closed).

Code

  • MRMeshToStep.h/.cpp: the public function only.
  • MRMeshToStepSurf, MRMeshToStepData: the surface type with its fits, the shared mesh data.
  • MRMeshToStepGrower.cpp, MRMeshToStepCleaner.cpp, MRMeshToStepBRep.cpp: steps 2, 3 and 4.

The internal headers are .hpp in namespace MR::MeshToStep, so the bindings generator does not see them.

Spheres, circles, cylinders, cones, tori and revolution axes are fitted by the public functions of MRBestFit.h (#7589, #7595). B-spline surfaces and curves are public too: FittedBSplineSurface with fitBSplineSurfaceToMesh (#7598) for the surfaces of freeform regions and interpolateBSplineCurve (#7590) for their borders; the converter adds only the (0,0,1) normal where a surface has none. Cylinders and cones are refined by refineCylinder and refineCone (#7600), tori by refineTorus. Own fitting code is only the plane fit on PointAccumulator, and Eigen is not used here at all.

Testing

MRMesh.MeshToStep in MRTest: cube -> 6 planes, cylinder -> 2 planes + 1 cylinder, UV sphere -> 1 sphere, torus -> 1 torus.

Beyond that, 11 NIST PMI test parts were meshed from their STEP files, converted, read back through OpenCASCADE and compared with the mesh (no faceBoundaries):

Part CAD faces Result faces Time Outcome
ctc_01 117 113 0.8 s clean, 0.009 mm
ctc_03 120 105 1.0 s clean, 0.005 mm
ctc_05 156 335 10 s clean, 0.08 mm
ftc_11 42 184 10 s clean, 0.09 mm
ftc_08 247 247 5 s clean, 0.003 mm
ftc_06 187 156 10 s clean, 0.09 mm
ftc_09 163 130 1.7 s 0.003 mm; 5 holes, all present in the source mesh
ctc_04 484 499 15 s 0.03 mm; 1 hole (the source mesh has one)
ftc_10 282 701 34 s 0.05 mm; 28 holes (the source mesh has 28)
ftc_07 306 440 33 s 2 bad faces (0.26 mm), 7 holes (the source mesh has 2)
ctc_02 637 3087 39 s 20 bad faces (up to 1.3 mm), 3 holes; freeform areas left as small planes

"Clean" means watertight, with the deviation at the level of the two tessellations. A bad face deviates by more than 0.1 mm. Times are on Ryzen 9 3900X.

Known limitations (why it is a draft)

🤖 Generated with Claude Code

Fedr and others added 5 commits November 25, 2026 10:09
Regions of the mesh lying on planes, cylinders, cones, spheres and tori are
found by region growing, the remaining smooth regions are approximated by
B-spline surfaces, and all of them are written as trimmed faces of a shell
in STEP AP214. Optional edges can be given that must separate the faces.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
GCC 12 reports an impossible memcpy bound inside the inlined
"(" + std::string + ")"; build the string with fmt::format instead.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A mesh loaded from a text file with few decimal digits (e.g. 6 significant
digits in OBJ) has vertices shifted from their surfaces by more than
2.5e-6 of the diagonal, and mostly came out as tiny planes. The default
tolerance is now at least 7 maximum rounding errors of the coordinates,
found from the number of digits in their shortest exact notation.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A closed chain of 3-4 points on mesh boundary always lies on a circle,
so isolated triangles and rectangles were written as discs. Circles on
mesh boundary now need at most 35 degrees between consecutive points.

A fillet made of long needle triangles has vertices only at its two
ends, and a torus with a very large tube radius passing through them
could win over the true cylinder by taking a few more small triangles.
With areas within 3%, the simpler surface now wins if it is much closer
to the centers of the triangles.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2x2 and 3x3 fits accumulate SymMatrix2d/SymMatrix3d and use their eigens()
and pseudoinverse(). The circle fit keeps Eigen's rank-revealing solver
(pseudoinverse gave more fragmented faces on short arcs), and the two 4x4
fits stay in Eigen until SymMatrix4 gets an eigen-solver.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

@Grantim Grantim left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: reuse of existing MeshLib code

Most of the new code has no counterpart in MeshLib yet (torus, B-spline surfaces and curves, LSCM, normals-based axis fits, the STEP text writer). Several helpers, though, duplicate existing functions.

Drop-in replacements

  • Segments by faceBoundaries (flood fill in makeData) and Cleaner::splitOnComponents_ -> MeshComponents::getAllComponentsMap( mesh, FaceIncidence::PerEdge, faceBoundaries ) (its isCompBd parameter).
  • numBoundaryLoops (std::set/std::map of directed edges) -> findLeftBoundary( topology, &region ).size().
  • Union-find in Cleaner (parent[] / find) -> MRUnionFind.h.
  • frame() -> Vector3d::perpendicular().
  • centroid + fitPlane -> PointAccumulator::getBestPlane().
  • Data::tris / Data::nbr and the BRepWriter::bnd_ / edgeOf_ maps -> MeshTopology (edgeWithLeft, left / right); region borders -> findLeftBoundaryInsideMesh.
  • Grower::patch_ (k-ring) -> expand( topology, FaceId, hops ), limited to available faces.

Fitters: better promoted to the library than replaced

  • Cylinder3Approximation::solveSpecificAxis needs at least 6 points and logs a warning below that, and solveGeneral is a 180x90 hemisphere search, so neither suits per-seed use. The normals-based axes (fitCyl, fitConeByNormals, revolutionAxis) could become public functions or extra fitter types of Cylinder3Approximation / Cone3Approximation, so other callers get them too.
  • Sphere and circle fits exist only inside the SphereObject / CircleObject constructors (float, uncentered). The centered fitSphere / fitCircle2 could become free functions in MRBestFit.h, used by both objects.
  • Surf could hold Plane3d / Cylinder3d / Cone3d / Sphere3d plus a new Torus3d.
  • Optional, a redesign rather than a drop-in: the merge steps of Cleaner could be a MeshSegmenter<Policy> policy with the residual of the union fit as the merge penalty.

Keep as is

  • The OCCT-free STEP writer: MRIOExtras disables STEP under Emscripten, so writing STEP text from MRMesh is the only way to have this on the web.

Suggested split

  1. Public primitives and fits: Torus3 and its fit, sphere / circle free fits, normals-based axes.
  2. B-spline surface and curve, LSCM parametrization.
  3. saveMeshAsStep on top of them, using the topology helpers above.

I'm drafting (1) and (2) as a separate PR, so this one could build on it.

Generated with Claude Code

- segments and components of regions: MeshComponents::getAllComponentsMap
- disk check of a B-spline patch: findLeftBoundary (plus no vertex passed twice)
- union of same-surface regions: UnionFind
- plane fit: PointAccumulator
- orthogonal basis: Vector3d::perpendicular, except the reference direction
  of surface placements, where the previous choice leaves fewer cracks
  after reading the file back

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@Fedr

Fedr commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Thanks. Pushed the drop-in part in cc7a154.

Applied

  • Segments by faceBoundaries and Cleaner::splitOnComponents_ -> MeshComponents::getAllComponentsMap with isCompBd.
  • numBoundaryLoops -> findLeftBoundary( topology, &region ).size(). One addition was needed: the old counter also rejected a patch whose boundary passes a vertex twice, and without that ftc_07 went from 10 bad faces to about 40 (such a patch is not a disk, and its parametrization folds). So the check is now one loop with no repeated vertex.
  • Union-find in Cleaner::mergeSameSurface_ -> UnionFind<RegionId>.
  • centroid + fitPlane -> PointAccumulator::getCenteredCovarianceEigen (the centroid is needed as the plane origin, so not getBestPlane).
  • frame() -> Vector3d::perpendicular() in the fits. In axis2_ the previous choice of the reference direction is kept inline: it sets the seam of cylinders, cones and tori, and with the direction of perpendicular() the file read back through OpenCASCADE had more small cracks at seams (ctc_04: 5 holes instead of 1).

Face counts and deviations on the 11 NIST parts are the same as before the change. Holes after reading back: ftc_06 got one 3-vertex crack, ctc_04 lost one.

Not in this commit

  • Data::tris / Data::nbr, BRepWriter::bnd_ / edgeOf_ -> MeshTopology, and Grower::patch_ -> expand. These index most of the file, and patch_ returns faces in ring order, which the candidate sampling depends on. I would rather do it together with the rebase onto your PR than twice.
  • Fitters, Surf on Plane3d / Cylinder3d / Cone3d / Sphere3d / Torus3d, B-spline and LSCM: agreed with the split, this PR will build on (1) and (2) once they are up.

Generated with Claude Code

Fedr and others added 5 commits November 25, 2026 15:20
The sphere fit solves with SymMatrix4d::pseudoinverse, and the cone fit takes
the eigenvector of the smallest eigenvalue from SymMatrix4d::eigens.
The only fixed-size Eigen call left is the rank-revealing solve of the circle fit.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
MRMeshToStep.cpp had more than 3000 lines. The code is only moved:
B-spline surface and its fit, analytic surfaces and their fits, mesh data,
region growing, region clean-up and B-rep writing get a file each.
Internal headers are .hpp, so the bindings do not see them.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The sphere, circle, cylinder, cone and torus fits and the torus refinement
now call findBestSphere, findBestCircle, findBestCylinderByNormals,
findRevolutionAxis, findBestConeWithAxis, findBestConeByTangentPlanes,
findBestTorusWithAxis and refineTorus; only the Levenberg-Marquardt
refinement of cylinders and cones stays here.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Grantim added a commit that referenced this pull request Nov 26, 2026
BSplineSurface::project clamps the initial parameters to the domain: from
outside it, the steps were halved toward the start, and the result could stay
outside (on the skewed plane of the tests, (1.5, 0.65) instead of (1, 0.8)).
The step is halved without a limit, and the iterations stop when the predicted
decrease of the squared distance is below its rounding error,
8 eps |r| (|p| + |r|): once converged, a step that raised the computed distance
by an ulp was rejected after 5 evaluations. In a simulation of the loop of #7581
(6x4 and 10x5 fits to 2000 points, 8 rounds of project( p, uv, 4 ) from the
previous parameters, also translated by 1e3 and 1e5), the evaluations per call
drop from 7.3-8.5 to 2.1-3.2 with the same final fits. Test: a projection from
outside the domain.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Grantim added a commit that referenced this pull request Nov 26, 2026
A rejected step of BSplineSurface::project is shortened to the minimum of the
parabola through the squared distances at both ends with the slope at the
start, but 2 to 10 times, instead of halved. Halving scales u and v together,
so far from the convex side, where the steps are 1 + distance / curvature
radius times too long, the other parameter lagged: above an arch of curvature
radius 1, the parameters were 0.019, 0.058 and 0.105 off after 12 iterations
at distances 10, 25 and 100. Now distances 1 to 50 converge within 3 to 10
iterations (8.7e-9 at 10, 1.1e-8 at 25); 100 is still 0.006 off. The
evaluations per projection in the simulation of the loop of #7581 stay at
2.1-3.2, at most 11 instead of 18. Test: a point at distance 25 above the arch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
refineTorus from master keeps the major radius non-negative, so a refined
torus without major radius is taken as a sphere, and a sphere region with
several weak sphere pieces around it joins them in a B-spline surface.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Fedr pushed a commit that referenced this pull request Nov 26, 2026
MRBSpline.h: BSplineCurve and BSplineSurface (evaluation, normal, projection of a point),
interpolateBSplineCurve through given points, fitBSplineSurface by least squares with smoothing.
MRConformalMap.h: leastSquaresConformalMap of a mesh part.
All of them come from the private helpers of saveMeshAsStep (#7581), which can use them instead.
Fedr and others added 2 commits November 26, 2026 12:29
BSplineSurface, fitBSplineSurface, interpolateBSplineCurve and
leastSquaresConformalMap from master replace the private basis, dense
fits and parametrization. Left here: the grid of surface points to start
projections from, the fit error, scaling of the parameters into the
margin square, and the loop over the numbers of control points.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The best fits take MR::Vector since #7599, which broke the build here;
all arrays of the converter are MR::Vector now. The output STEP files
of 11 NIST parts are the same as before.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Fedr added a commit that referenced this pull request Nov 26, 2026
MRFittedBSplineSurface.h: FittedBSplineSurface is a BSplineSurface with its fit error and a grid of surface points
to project on it without initial parameters; fitBSplineSurfaceToMesh fits it to a mesh part with disk topology
(conformal parametrization, then least squares fits and projections with more and more control points until given tolerance).
It comes from the private helpers of saveMeshAsStep (#7581), which can use it instead.
Fedr and others added 2 commits November 26, 2026 15:36
fitBSplineSurfaceToMesh from master replaces the private fit of a
B-spline surface to a mesh region; MRMeshToStepBSpline files are gone.
The faces, bad faces and holes of 11 NIST parts are the same.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The own Levenberg-Marquardt refinement of cylinders and cones (numeric
derivatives, on Eigen) is replaced by the public ones. With them one part
got 1500 bad faces: a B-spline surface replacing a group of regions was
taken with any error. Now it must be within 50 tolerances of the vertices.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Fedr added a commit that referenced this pull request Nov 26, 2026
…efinement

As in #7581 now: the own Levenberg-Marquardt with numeric derivatives on
Eigen is gone.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants