Skip to content
AI-Ready Docs
/llms.txt/llms-mcp.txt

Solving sketch constraints ​

A sketch is drawn by hand, so its points are never exactly where its constraints say: an edge meant to be horizontal leans a little, a length is 36.1 mm instead of 40. The solver moves the points until every constraint holds, then says how much freedom is left. In the studio this runs after every edit of a sketch: the shape on screen is always the solved one, and the status line counts what is still free (2 DOF) until it reads Fully defined.

The method is a damped form of Newton's method on the constraints written as equations. The figures run it in the page on small sketches, with a copy of the kernel's code; on these sketches its iterates are bit-identical to the kernel's.

Three solvers ​

SolverUnknownsMethodUsed by
Kernel line solver, solveXYNumericalSketch, solveXYNumericalSketchPointsx, y of each pointLevenberg–Marquardt, Householder QRthe studio's 2D sketches: every outline, arcs included
Kernel circular solver, solveXYCircularNumericalSketchx, y of each point, and each circle's radiusthe same loopa kernel API; the studio does not call it
Skeleton solver, solveSketch3D (@barocss/cad-model)x, y, z of each pointLevenberg–Marquardt, normal equations, Choleskythe studio's 3D skeleton sketches for frames

Most of this page is the line solver, since the studio's sketches go through it. The other two are at the end.

1. Constraints as residuals ​

The unknowns are the coordinates of the points, in one vector x = (x₀, y₀, x₁, y₁, …). Each constraint becomes one or two equations rᵢ(x) = 0, called residuals: zero when the constraint holds, and as large as the error when it does not. A segment s runs from point a to point b; its vector is s = b − a.

ConstraintRowsResidualTolerance
fixed2x − tₓ, y − ty10⁻⁷ mm
coincident2xb − xa, yb − ya10⁻⁷ mm
horizontal1yb − ya10⁻⁷ mm
vertical1xb − xa10⁻⁷ mm
length1‖s‖ − L, with 0.001 ≤ L ≤ 20000√2 mm10⁻⁷ mm
equal-length1‖sA‖ − ‖sB‖10⁻⁷ mm
signed-angle1wrap(atan2(sB) − atan2(sA) − θ), with −π < θ ≤ π10⁻⁹ rad

wrap brings an angle into (−π, π]. Each row also has its derivatives with respect to every coordinate, written out by hand in the code: together the rows of derivatives are the Jacobian J. The sum of squares Σ rᵢ² that the solver lowers adds millimetres and radians as they are: 1 mm counts as much as 1 rad.

2. The damped Newton step ​

Newton's method replaces r by its straight-line approximation r(x + δ) ≈ r(x) + J δ and solves that for the step δ. J is rarely square and invertible (a sketch has fewer independent equations than unknowns until it is fully defined), so the step is a least-squares one. The kernel adds a penalty λ‖δ‖² that keeps the step short: this is the Levenberg–Marquardt method, and λ is its damping. A large λ gives short, cautious steps; a small λ gives the plain Gauss–Newton step.

Solving a sketch: damped Newton steps on the residuals
iteration 0 · ‖r‖ = 6.69 · λ = 1.0×10⁻³100°H · 40HV · 24p₀p₁p₂p₃‖r‖ per iteration110⁻³10⁻⁶10⁻⁹0123456
1. A rough drawing, seven constraints

Four points p₀ … p₃, joined by segments s₀ … s₃, drawn by hand. The constraints: p₀ fixed where it was drawn (the studio always anchors point 1), s₀ and s₂ horizontal, s₃ vertical, |s₀| = 40 mm, |s₃| = 24 mm, and s₁ turned 100° from the direction of s₀. The unknowns are the eight coordinates of the points.

x = (x₀, y₀, x₁, y₁, x₂, y₂, x₃, y₃)   8 unknowns · 2 + 1 + 1 + 1 + 1 + 1 + 1 = 8 equations
Computed in the page with a line-by-line copy of the kernel's residuals, QR and damped loop; on this sketch its iterates are bit-identical to the kernel's own (checked by running both). The studio would build the same equations for this outline; its own inferences (horizontal and vertical edges as drawn) are left out here.

The loop in the kernel:

  1. λ = 10⁻³. If every residual is already within its tolerance, stop.
  2. Solve [J ; √λ I] δ ≈ [−r ; 0] by Householder QR with column pivoting.
  3. Evaluate r at x + δ from scratch. If Σ rᵢ² fell, keep the step and set λ = max(10⁻¹², λ / 3).
  4. If not (or if x + δ is refused, below), discard it and set λ = min(10¹², 10 λ); try again, up to 12 times.
  5. Repeat from 1, up to 100 iterations and 1200 evaluations of r. If no try succeeds and λ has reached 10¹², stop.

The result is accepted only if every residual is within its tolerance. Otherwise the sketch is refused with NONCONVERGENCE, and the message says this is not an inconsistency proof: a local method that does not converge has not shown that no solution exists. The accepted point is evaluated once more from scratch and must pass the same test before it is returned.

3. Degrees of freedom ​

Each point has two coordinates, so a sketch of n points has 2n degrees of freedom (DOF) before any constraint. Each independent equation takes one away. The number of independent equations is the rank of J at the solution, so

DOF = unknowns − rank J.

The kernel computes the rank with the same QR, on J alone without the damping rows: a diagonal entry of the factor R counts when it is above max(1, the largest |Rkk|) × 10⁻¹⁰. It reports numericalRank, localDegreesOfFreedom and fullyConstrainedLocally (rank = unknowns); locally because the rank is that of J at this solution, not a proof about other solutions.

Counting the freedom left: the rank of the Jacobian
8 unknowns − rank 2 = 6 DOFp₀p₁p₂p₃constraintsfixed p₀6 DOFrows 2 · rank 2
1. Anchored: six freedoms

Eight unknowns, the x and y of four points. The studio fixes point 1 where it was drawn: two equations, rank 2. Every other point can still move both ways. The arrows show, for each point, the moves that keep every constraint so far (to first order).

DOF = unknowns − rank J = 8 − 2 = 6
Each stage solved in the page by the kernel's loop from the stage before, as the studio re-solves after an edit. The arrows are first-order moves: a length keeps its value only along the arrow's tangent, not along the straight arrow itself.

An equation that adds no rank is redundant: it holds, but the others already imply it. The kernel solves such a sketch and reports it (more rows than rank); the studio decides what to do with it. It counts the redundant rows as rows − rank and:

  • refuses an edit that makes more rows redundant than before, with the reason … is already implied by the other constraints — adding it would over-define the sketch, and keeps the previous shape;
  • shows Over-defined · n redundant constraint(s) — remove one on an outline that has some, and otherwise Under-defined · n DOF left or Fully defined.

A constraint that contradicts the others, such as |s₁| = 30 mm on the fully defined quad above, leaves residuals the loop cannot bring within tolerance. The kernel returns NONCONVERGENCE, the studio shows that reason and keeps the previous shape. The studio puts the constraint's label in front, as in Length of edge 3 = 50: XY numerical sketch: Bounded local solve did not meet fixed residual tolerances; this is not an inconsistency proof. It does not say the constraints conflict: a local solve that does not converge has not proved that (CAD review 2215).

One class of contradiction is proved instead (D350): horizontal and vertical edges, their lengths, axis distances (dx, dy) and fixed points, with no arcs or circles. The anchor (point 1 at its drawn position) is one of the fixed points; any other rule kind in the sketch puts it outside the class. There the X and Y equations never mix, and each is a difference of two coordinates (or its absolute value). The studio relaxes every equation to an interval of 4 × the kernel's linear tolerance and does the arithmetic exactly (binary64 inputs as BigInt dyadic rationals). For a choice of sign of every absolute value the system is feasible exactly when its constraint graph has no negative cycle (Bellman–Ford); a search over the signs, pruned as soon as a partial choice is infeasible and capped at 4096 feasibility checks, shows that no choice is feasible. Only then does the studio refuse the edit as Conflict: no shape meets all of these constraints. If the class does not apply, a sign choice is feasible or the budget runs out, the nonconvergence message above stands.

The loop stops as soon as every residual is within its tolerance, a few 10⁻⁸ mm from the exact answer (a width of 60 can come back 59.999999964). The studio then tries the same solution on the 10⁻⁶ mm grid: it solves again from the snapped points and takes them only if that solve accepts them without a single step, that is, if the kernel's own check passes on them as they are. A drawing in whole or short decimal millimetres comes out exact; an off-grid anchor or a driving 10.0000004 mm fails the check when snapped, and the solver's own values are kept (D284).

4. Arcs and circles in the studio ​

The studio stores an outline as points and bulges: segment i runs from point i to point i + 1, and a nonzero bulge b = tan(sweep / 4) makes it an arc, counter-clockwise when b > 0. The kernel's line solver knows only points and straight segments, so the studio rewrites each arc before solving:

  • its centre becomes a point (two more unknowns);
  • two radius segments, centre → start and centre → end, held equal by an equal-length row;
  • a tangent joint is a signed angle between the line and the radius: +90° or −90°, whichever is nearer the drawing (between two arcs' radii, 0° or 180°);
  • a radius dimension is a length on the radius segment centre → start; equal radii is an equal-length row between two arcs' radius segments, concentric arcs a coincident row between their centres.

So each arc brings one degree of freedom of its own: with its ends fixed, its radius can still change.

Arcs in the studio's sketch: centres, radius segments, tangent angles
drawn: b = 1.05, b = 0.95
1. An outline with two arcs

Segment i runs from point i to point i + 1; a nonzero bulge b makes it an arc, b = tan(sweep / 4), positive counter-clockwise (the DXF convention). Drawn here: b = 1.05 and 0.95, radii 6.53 and 6.03 mm. A centre lies on the perpendicular through the chord's midpoint, at a distance set by b.

d = (c / 2) · (1 − b²) / (2b)   centre = midpoint + d · (left normal of the chord),   c = chord length
Computed in the page with the kernel's loop (the copy in the first figure) on the documents the studio builds for this outline; checked against the studio's own run, which gives the same documents and iterates. The tangent and equal-radius rows are the studio's inferences on closing this drawing.

Closing an outline infers what was drawn nearly so, and the solve makes it exact:

Inferred on closingWhenBecomes
Horizontal, verticala straight edge drawn with exactly equal y (or x) on the 1 mm snaphorizontal / vertical row
Tangenta joint next to an arc drawn within 12° of tangentsigned angle ±90° (0° / 180° between arcs)
Equal radiitwo arcs whose radii differ by at most max(0.5 mm, 3 % of the smaller)equal-length row
Concentrictwo arcs whose centres are at most max(1.5 mm, 5 % of the smaller radius) apartcoincident row

All inferred relations are tried together first. If together they fail, or they add redundant rows, they are tried one at a time and each is kept only while the sketch still solves and the redundancy does not grow. A relation an outline already implies is therefore not added a second time.

After the solve, each arc's bulge is rebuilt from the solved ends and centre: the sweep is the angle from start to end about the centre, turned the way the arc was drawn (2π added or taken away when the sign came out wrong), and b = tan(sweep / 4).

The studio's other constraints are written in the same few kinds, sometimes with helper points:

Studio constraintKernel rows
Parallel, perpendicularsigned angle 0° or 180°, ±90°, the one nearest the drawing
Equalequal-length
Fixfixed where the point was when the constraint was added
Coincident (point on an arc's centre)coincident
Distance between two pointsa length on a helper segment between them
Horizontal or vertical distancetwo helper points 10 mm across the axis, tied to the points; the distance measured between the helpers, so it never collapses when the points line up
Angle between two linessigned angle, its sign and half turns taken from the drawing
Symmetric about a linea helper midpoint M: a–M and M–b in line and of one length, M on the line, a–b square to it
Tangent (line and circle)a helper touching point on the line, its radius segment square to the line, of the circle's radius
Concentric circles, circle distancescoincident centres, lengths between centres or to points

A circle placed in an outline (a hole or a boss) is its centre point; its radius is a value, not an unknown.

5. Which solution ​

Constraints usually have more than one solution: a triangle with three given side lengths can be built two ways, one the mirror image of the other. The solver finds the one its seed (the drawing) leads to, with no guarantee it is the nearest; the report says so (seed-dependent-no-global-closest-root-guarantee).

The kernel accepts branch guards to hold a solution on one side:

GuardHolds when
positive-projectiona segment's vector has a positive component along a given direction
oriented-tripletthree points turn counter-clockwise (or clockwise): (b − a) × (c − a) > 0 (or < 0)

They are checked at every evaluation: at the seed (a failing seed refuses the sketch with BRANCH) and at every candidate step (a failing candidate is discarded like a step that did not lower Σ rᵢ²). The studio passes none. It picks its targets nearest the drawing instead (the sign of a tangent's 90°, parallel 0° or 180°, an angle's side) and keeps each arc turning the way it was drawn when it rebuilds the bulge.

6. The circular solver ​

solveXYCircularNumericalSketch takes full circles as well as points and segments. Each circle has a centre point and a radius, and the radius is an unknown of its own, after the coordinates. It adds two constraint kinds to the line solver's (all but equal-length):

ConstraintResidual
radiusr − R
line-circle-tangentσ n · (c − a) − r: the centre's signed distance from the segment's line, on the given side (σ = +1 left, −1 right), minus the radius

Here n is the segment's unit left normal and a its start. A tangency is accepted only where it touches the segment strictly inside it, on the given side: the foot of the centre on the line, at parameter t = (c − a) · s / ‖s‖², must have 0 < t < 1, and σ n · (c − a) > 0. A candidate that breaks this, or a radius outside 0.001–10000 mm, is discarded like any refused step. The damping, tolerances, rank and DOF are the line solver's; DOF counts the radii as unknowns.

The result is built as curves: a degree-1 NURBS per segment and a degree-2 rational NURBS per circle (9 control points, weights alternating 1 and √½, its seam at parameter 0 and 4).

7. The skeleton solver (3D) ​

A frame's skeleton is a 3D sketch: points, straight segments and constraints among them, solved by solveSketch3D in @barocss/cad-model. It is Levenberg–Marquardt as well, written differently:

2D line solver3D skeleton solver
Step[J ; √λ I] δ ≈ [−r ; 0] by QR(JᵀJ + λI) δ = Jᵀr by Cholesky
λfrom 10⁻³; ÷ 3 on a kept step (floor 10⁻¹²), × 10 on a discarded one (ceiling 10¹²)from 10⁻³; ÷ 3 (floor 10⁻¹⁵), × 4
Tries, iterations12, 10030, 200
Stopevery residual within its toleranceΣ rᵢ² ≤ 10⁻²⁰
RankQR of J, relative 10⁻¹⁰Gram–Schmidt (twice) of each row normalised, 10⁻⁸
Diagnosisrank and DOF; the caller counts redundancyper constraint: redundant (adds no rank), unmet (residual > 10⁻⁹), free points; status well, under, over or conflict

Its constraints are coincident, fixed, length, distance, angle (on the cosine), parallel (the cross product over the lengths, three rows), perpendicular, on an axis, on a plane, and along an axis. A sketch with nothing fixed keeps its 6 rigid motions.

Where it is in the code ​

FileResponsibility
packages/barocss-cad/src/sketch/xy-numerical-sketch-solver-internal.tslimits, tolerances, qr, evaluate (residuals, Jacobian, branch guards), solve (the damped loop, final check, rank)
packages/barocss-cad/src/sketch/xy-numerical-sketch-admission-internal.tsthe document checked before solving: kinds, references, value ranges, sizes
packages/barocss-cad/src/sketch/xy-numerical-sketch.tssolveXYNumericalSketch (solve, then native line curves), solveXYNumericalSketchPoints (points and report only), validateXYNumericalSketch
packages/barocss-cad/src/sketch/xy-circular-numerical-sketch-solver-internal.tsthe circular solver: radius and tangent rows, the same loop
packages/barocss-cad/src/sketch/xy-circular-numerical-sketch.ts, …-admission-internal.ts, …-native-internal.tsits API, admission and native circle curves
packages/barocss-cad-model/src/sketch/profile.tssolveOutline: an outline with arcs as the kernel's document; inferredHV, inferTangents, inferArcRelations; bulges rebuilt
packages/barocss-cad-model/src/sketch/terms.tsruleTerms: the studio's explicit constraints and dimensions as kernel rows and helper points
packages/barocss-cad-model/src/sketch/rules.tssolveShape, redundancy, checkEdit (refusing an over-defining edit), applying and committing constraints
packages/barocss-cad-model/src/sketch/settle.tssettleShape: what closing infers, and which inferred relations are kept
apps/cad-studio/src/ui/SketchPanel.tsxthe status line: rank, DOF, over-, under- or fully defined
packages/barocss-cad-model/src/frames/sketch3d.tssolveSketch3D: the 3D skeleton solver and its diagnosis

How it is checked ​

TestWhat it covers
packages/barocss-cad/test/xy-numerical-sketch-equal-length.test.mjsequal-length keeps an arc end on its circle with one DOF left; a slot of lines, centres and radii with ±90° tangency fully defined from a rough seed; the equal-length Jacobian against central differences; refusals and the 16-segment limit; the -v1 profile's larger limits
packages/barocss-cad/test/r7-consumer-dependencies.test.mjsboth the line and the circular solver solve a length and a right angle, rebuild to the same result, and refuse old field names
packages/barocss-cad-model/test/sketch-profile-precision.test.tsoff-grid anchors and driving values kept as solved, not snapped (lengths, arcs, radii, angles); a non-converging edit keeps the previous shape with the kernel's message
packages/barocss-cad-model/test/engine.test.tsa locked rectangle and a tangent semicircle come out on exact values (the grid solution accepted)
apps/cad-studio/test/constraints.test.tsDOF counts as constraints are added and removed; an implied constraint refused as over-defining; a contradicting one refused with the solver's own reason; dimensions; symmetric (two DOF less); tangent to a circle; concentric arcs and circles
packages/barocss-cad-model/test/sketch3d.test.tsthe 3D solver on a tetrahedron and a tilted rectangle; freedoms counted; diagnosis of a conflict and of a redundant length
apps/library-docs/samples/how-ports.test.mjsthe figures' copy of the solver loop against the kernel's on 41 drawings: the same points bit for bit, the same iterations and rank

Limits ​

Line solver -v0Line solver -v1 (the studio's)Circular solver
Points2–162–641–16
Segments1–161–640–8
Circles——1–4
Constraints3212832
Scalar residuals6425664
Unknowns3212832 (radii included)
Branch guards163216
Iterations / evaluations100 / 1200100 / 1200100 / 1200
  • Coordinates must stay within ±10000 mm and every segment at least 0.001 mm long; a step that breaks either is discarded. The studio reports a collapsing edge as These constraints would collapse an edge to a point.
  • The studio refuses an outline of more than 64 points or segments, counting arcs' centres and helper points, before solving (Too many points, arcs and point dimensions for the sketch solver (64 points / 64 segments)); the kernel's LIMIT or BUDGET reads The sketch is too large for the solver (at most 128 constraints).
  • solveXYNumericalSketch also builds native curves, bounded to 16 of them; solveXYNumericalSketchPoints returns the points only, for larger sketches.
  • The solve is local: it finds the solution the drawing leads to, and a failure to converge does not prove the constraints conflict. The rank is numerical, at the solution only.