Repository navigation
B-spline curve and surface, least squares conformal map - #7590
Merged
Merged
Conversation
BSplineCurve and BSplineSurface (evaluation with derivatives, normal, projection by Newton iterations), makeClampedUniformKnots, interpolateBSplineCurve, fitBSplineSurface with BSplineSurfaceFitSettings, and leastSquaresConformalMap of a mesh part with disk topology. The numerics are taken from the private helpers of saveMeshAsStep (#7581). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
BSplineSurface::project solves the Gauss-Newton step with SymMatrix2d::pseudoinverse instead of a determinant clamped at 1e-30, which stalled where a derivative is zero, and minimizes the linearized distance in the domain: when the step leaves the domain, the better of the two border lines through the clamped step is taken, instead of clamping both coordinates, which stopped at wrong points when u and v are not orthogonal. leastSquaresConformalMap returns an error when the LDLT factorization fails, e.g. for a vertex only in degenerate triangles; before, Eigen left the solution uninitialized and returned it as a success. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
leastSquaresConformalMap finds the main direction with PointAccumulator::getBestLine and the pinned vertices with findDirMinMaxBruteForce, numbers the unknowns with makeVectorWithSeqNums, and returns VertUVCoords. makeClampedUniformKnots is internal; the curve interpolation starts from it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
interpolateBSplineCurve solves the banded collocation system by SparseLU instead of a dense LU, O(n) instead of O(n^3) for a chain of n points. fitBSplineSurface sums the normal equations per knot span (all points of a span share 16 basis functions, only the upper triangle is kept) and solves the sparse system by SimplicialLDLT, so the memory no longer grows as (numU * numV)^2 and does not grow with the number of points either. Both keep plain results: their systems are not singular under the preconditions, which are now documented and asserted (increasing curve parameters, i.e. no equal consecutive points; for the fit, smoothing > 0 and 4 points in general position). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The part must be connected via the edges of its non-degenerate triangles; in a component without both pinned vertices the system is singular, which gives an error or meaningless coordinates there. Disk topology is what the map is meant for. Not finite coordinates leave the vertices to pin undefined and now return an error right away, instead of the check of the solution for finite values. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… region Projection with the closest point on the border of the domain of a plane with not orthogonal derivatives, also outside in both u and v, and from a collapsed row of control points; a 3-point curve of degree 2; weights multiplying the squared distances; the conformal map of a region of a larger mesh, not mirrored, and its errors for a vertex only in a degenerate triangle and for a NaN coordinate. The unused MRConstants.h include is removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With violated preconditions (equal consecutive points of a curve, too few or degenerate points of a fit) the factorization fails, and Eigen's solve then reads factors that were not computed (SparseLU, an access violation in Release) or leaves the solution uninitialized (SimplicialLDLT). The control points are NaN instead, and the header says so. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…span interpolateBSplineCurve returns an empty curve for fewer than 2 points, and fitBSplineSurface an empty surface for numU or numV less than 4, instead of reading or writing out of bounds in Release; the asserts stay. The knot span is found by std::upper_bound. Dead guards in the curve parameters and in the smoothing weight are removed, the conformal map takes getBestLinef, and the header says that normal is zero where the derivatives are zero or parallel. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
interpolateBSplineCurve solves the normal equations of its banded collocation system by SimplicialLDLT, like the other sparse solves in MeshLib, instead of the only SparseLU. Equal consecutive points may now give arbitrary control points instead of NaN, which the header says. A test of a curve through unevenly spaced points. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The second differences of the control net are divided by the differences of the Greville abscissae, where the control points of linear functions sit, and scaled to (1, -2, 1) for equal differences. They were by index, which is not zero for a plane with more than 4 clamped control points along u or v, so the smoothing bent exact planes (up to 0.06 of the diagonal outside 10x5 points in an ellipse). Now bilinear functions of (u, v) are not smoothed and are reproduced. The smoothing weight scales with the sum of the weights of the points instead of their number. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
BSplineSurface::project accepts a Gauss-Newton step only if the squared distance decreases by at least 1/4 of the decrease predicted by the linearization, and halves it toward the current parameters up to 4 times otherwise; the iterations stop when no step is left. On the convex side the steps are 1 + distance / curvature radius times too long: plain Gauss-Newton alternated between two wrong points, e.g. at distances 2.54 and 3.08 from a half-cylinder of radius 1 instead of 2.00, and a step exactly 2 times too long, which only keeps the distance, would converge very slowly. The evaluation at an accepted point is reused for the next step, so only the evaluation of the result and rejected steps cost more than before. Since steps below ~1e-9 do not change the computed distance, off-surface parameters are found to about 1e-9. Tests: a point 3 above an arch of curvature radius 1, and the collapsed row starting away from its answer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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>
… fit interpolateBSplineCurve and fitBSplineSurface return std::optional: nullopt for fewer than 2 points, numU or numV less than 4, or a failed factorization, instead of an empty curve or surface and NaN control points. The asserts of these sizes go, since nullopt is now their documented result. One helper solves both systems by SimplicialLDLT on the upper triangle; the control points are bit-identical to before (helices of 40 and 800 points, uneven chains, fits). Tests: a cubic through 4 points without inner knots, and the nullopt results. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ate triangles The third vertex of each triangle in the frame of its first edge comes from unfoldOnPlane instead of an orthonormal frame built here. The right-hand side is one Eigen vector with two rows per face, and degenerate triangles give zero rows; without non-degenerate triangles the matrix is zero and its factorization fails, so the separate error for that case goes (the header says "degenerate system"). MREigenSparseCore.h is included as in the other sparse solves. The coordinates are identical to before on the grid of the test and on a curved strip, also with two degenerate triangles in its middle. Test: a region of only a degenerate triangle. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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>
bsplineBasis takes no number of control points: it always equaled knots.size() - deg - 1, which now bounds the span search. The curve and surface results are bit-identical (control points, values and derivatives also outside the domain, projections). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
interpolateBSplineCurve factorizes the square collocation matrix by SparseLU instead of its normal equations by SimplicialLDLT: those square the condition number, which grows as the chord lengths get uneven. On random chains with 30% of the steps shorter by r, the points were missed by up to 6e-9, 1e-5 and 6e-5 at r = 1e-3, 1e-4 and 1e-5 (and nullopt for some chains at 1e-5 and 1e-6); now by at most 3e-14, 2e-13, 2e-12, and 1e-11 at r = 1e-6. One template solves both systems after checking the factorization. Evenly spaced helices of 40 and 800 points give the same control points up to 2e-15 and 6e-14 (z up to 40). Test: a chain with two consecutive steps of 1e-5, which the normal equations missed by 5e-6. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…n [0, 1]^2 The header says what BSplineSurface::project does (Gauss-Newton with step control from uv clamped to the domain, result in it, stopping at rounding errors), and two lines in the .cpp keep the non-obvious parts: the 1/4 acceptance, the parabola and the scale of the cutoff. fitBSplineSurface expects the parameters in the unit square; outside it the end polynomials are extrapolated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…dMesh, fit failures The conformal map is checked on a fan of 6 triangles around a raised vertex (312 degrees around it) against coordinates computed independently, as the minimum of the Dirichlet energy minus the area of the map (and by Levy's least squares in own frames): the library agrees to 1.2e-8, while unit weights of the triangles are up to 7e-3 off, so on the planar grid alone any weighting passed. The grid comes from makeRegularGridMesh and its region from the vertices with x <= 5 by getInnerFaces. The fit returns nullopt for numV = 3 and for no points, whose zero matrix fails the factorization. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Grantim
marked this pull request as ready for review
November 26, 2026 08:26
…instead of NaN BSplineCurve and BSplineSurface get valid(); eval, normal and project return zero or given values for a degree above 7 or inconsistent sizes instead of writing beyond fixed-size buffers. interpolateBSplineCurve returns nullopt for equal consecutive or not finite points, which were only asserted. leastSquaresConformalMap returns an error for a not finite solution. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Knots, control points, the points, parameters and weights of the fits, and the internal arrays. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Fedr
approved these changes
Nov 26, 2026
This was referenced Nov 26, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Makes the B-spline code and the conformal parametrization from the private helpers of
saveMeshAsStep(#7581) public. #7581 can then call these functions instead of its own. The numerics follow #7581, with the differences listed below. Independent of the analytic fits in #7589.New
MRBSpline.h, in double, with all arrays (knots, control points, the points, parameters and weights of the fits) inMR::Vector:BSplineCurve: degree (1 to 7), knots, control points;valid(),eval( t ).BSplineSurface: degrees, knots along u and v, control points;valid(),eval( uv, du, dv )with optional partial derivatives,normal( uv ),project( p, uv, iterations )by Gauss-Newton iterations with step control, kept in the domain. The number of control points along u and v is derived from the knots.valid()checks the degree and that the numbers of knots and control points agree; for not valid dataevalandnormalreturn zero vectors andprojectreturns the given parameters, without reading beyond the arrays.interpolateBSplineCurve( points ): curve of degree min( 3, n - 1 ) through all points, chord-length parameters in [0, 1], inner knots by averaging.fitBSplineSurface( points, uvs, BSplineSurfaceFitSettings ): bicubic least squares fit to points with known parameters, with smoothing of the second differences of the control net and optional weights of the squared residuals. The differences are divided by the differences of the Greville abscissae, so bilinear functions of (u, v), planes among them, are not smoothed and are reproduced. The solution is unique if smoothing > 0 and no non-zero bilinear function of (u, v) vanishes at all points with positive weights.Both return
std::optional:std::nulloptfor fewer than 2 curve points, two consecutive curve points equal or not finite coordinates of them, fewer than 4 control points along u or v, or a failed factorization (only with violated preconditions). The clamped uniform knots and the sparse solve they share are internal.MRConformalMap.h:leastSquaresConformalMap( MeshPart )returnsExpected<VertUVCoords>, the least squares conformal map of a part, meant for a part with disk topology, with the two vertices most distant along its main direction pinned at (0,0) and (1,0). The part must be connected via the edges of its non-degenerate triangles: in a component without both pinned vertices the system is singular, which gives an error or meaningless coordinates there. Errors are returned for not finite coordinates, a not finite solution and a degenerate system (e.g. a vertex only in degenerate triangles, or no non-degenerate triangles; degenerate triangles give zero rows). It reusesPointAccumulator::getBestLinefandfindDirMinMaxBruteForcefor the pinned vertices andunfoldOnPlanefor the triangles in their planes.Differences from the helpers in #7581:
fitBSplineSurfacemultiplies the squared residual of each point by its weight; saveMeshAsStep: convert a mesh into STEP with fitted surfaces #7581 effectively squares its weights, so it would pass 0.01 where it now passes 0.1.fitBSplineSurfacesmooths by second differences divided by the differences of the Greville abscissae (scaled to (1, -2, 1) for equal differences), with the smoothing weight proportional to the sum of the weights of the points. saveMeshAsStep: convert a mesh into STEP with fitted surfaces #7581 takes the differences by index, which bends exact planes with more than 4 control points along u or v (10x5 control points, points in an ellipse inside [0.06, 0.94]^2: by 1.6e-5 of the diagonal at the points and up to 0.06 outside them); now bilinear functions are reproduced to rounding. Fits of curved surfaces at the default smoothing change accordingly: with weights 1 and 0.1, points in an ellipse and 6x4 to 40x8 control points, by up to 4e-5 of the diagonal inside the ellipse and up to 0.15 outside it, near the corners of the domain.leastSquaresConformalMaptakes aMeshPartinstead of separate point and triangle arrays, returns float coordinates like other UV maps, and does not rescale them into a margin square, which stays in the caller.interpolateBSplineCurvefactorizes its square banded collocation system byEigen::SparseLU(O(n) non-zeros instead of a dense n x n LU), andfitBSplineSurfacesums the normal equations per knot span (memory independent of the number of points) and solves them byEigen::SimplicialLDLT. The curve avoids normal equations, since they square the condition number, which grows with uneven chord lengths: on random chains with 30% of the steps shorter by 1e-4 to 1e-6, they missed the points by up to 6e-5 or failed, while the LU interpolates them to 1.2e-11 or better. For helices of 50 and 800 points the curve control points agree with the dense LU of saveMeshAsStep: convert a mesh into STEP with fitted surfaces #7581 to 5e-16 (relative); on the uneven chains both LUs pass through the points, but their control points (up to 5e5 at 1e-6) differ by up to 1e-5 relative, as the conditioning of the problem allows. The speed was not measured.projectminimizes the linearized distance over the domain (the step bySymMatrix2d::pseudoinverse, then the better of the two border lines through the clamped step) instead of clamping both coordinates of the full step, so it finds closest points on the border when the derivatives are not orthogonal and does not stall on a collapsed row of control points. It starts from the initial parameters clamped to the domain.projectaccepts a step only if the squared distance decreases by at least 1/4 of the decrease predicted by the linearization; otherwise it shortens the step 2 to 10 times, to the minimum of the parabola through the squared distances at both ends and the slope at the start. It stops when the predicted decrease is below the rounding error of the squared distance, 8 eps |r| (|p| + |r|). On the convex side, Gauss-Newton steps are 1 + distance / curvature radius times too long, and plain Gauss-Newton (saveMeshAsStep: convert a mesh into STEP with fitted surfaces #7581) can alternate between two wrong points. Above an arch of curvature radius 1, points at distances 1 to 50 converge within 3 to 10 iterations (to 1e-7 or better in the parameters); at 100 the parameters are 0.006 off after 12 iterations, and at 0.5 the convergence is linear (2e-5 after 12). Halving instead of the interpolation left the parameters 0.019, 0.058 and 0.105 off at distances 10, 25 and 100. In a simulation of the loop of saveMeshAsStep: convert a mesh into STEP with fitted surfaces #7581 (6x4 and 10x5 fits to 2000 points, 8 rounds ofproject( p, uv, 4 )from the previous parameters, also translated by 1e3 and 1e5), a projection costs 2.1-3.2 surface evaluations on average and at most 11 (4 in saveMeshAsStep: convert a mesh into STEP with fitted surfaces #7581). The parameters are found to about sqrt( 8 eps |r| |p| ) / |du|, e.g. 2e-9 for |p| ~ 3 at distance 0.01, and 2e-6 for |p| ~ 1.7e5 at distance 0.1.normal( uv )returns a zero vector where the derivatives are zero or parallel (asnormalized()does in MeshLib); saveMeshAsStep: convert a mesh into STEP with fitted surfaces #7581 used (0,0,1) there, which stays in the caller if it needs a fallback.Tests
MRBSplineTests.cpp:std::nulloptfor one point, equal consecutive points, all points equal, and infinite or NaN coordinates;valid()is false,eval,normalandprojectreturn as described above;std::nulloptfor numU = 3, numV = 3, and no points (a failed factorization);makeRegularGridMesh: a similarity, vertices outside the region untouched, triangles not mirrored; of a non-developable fan of 6 triangles, against coordinates computed independently as the minimum of the Dirichlet energy minus the area of the map (the map agrees to 1.2e-8; unit weights of the triangles would be 7e-3 off); errors for a vertex only in a degenerate triangle, a region of only a degenerate triangle, and a NaN coordinate.Locally (Windows, MSVC): the full MRTest suite passes in Release (770 tests) and Debug (769 tests; one test is Release-only).
MRBSpline.cpp,MRConformalMap.cppand the test compile with GCC 13 at -O2 with MeshLib's GCC warning flags and -Werror, with and without NDEBUG, and the B-spline tests (not the conformal map, which needs all of MRMesh) pass in a standalone GCC build, also with -mfma -ffp-contract=fast. Bindings, Clang and wasm are left to CI. The last commits (MR::Vectorinstead ofstd::vector,valid(), the failures ofinterpolateBSplineCurve, the not finite solution of the conformal map) were checked only by the tests ofMRBSplineTests.cppin a standalone MSVC Release build.Generated with Claude Code