BREP_solvers 0.33.0

Rust B-rep CAD kernel (next.BREP.io): constraint solvers for 2D and 3D sketches and assemblies.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
//! The least-motion solve one interactive drag frame tries first.
//!
//! Relaxation satisfies constraints one at a time, each by moving whichever of its
//! points it picks, so a drag that re-solves every frame from the last frame's result
//! lets free geometry wander: a point the drag never touches walks a little each
//! frame, and an unconstrained line grows. Here the free coordinates instead take the
//! least motion that meets every constraint row exactly, on the same residual model
//! as the exactness polish, started from where the points stand (the previous
//! frame's solve). "Least" is measured by soft terms: every line the drag does not
//! hold by an end keeps its length, and each coordinate is pulled, weakly, back to
//! where it stood. So a line the drag only turns (a point held on it, a parallel)
//! turns at its length, and a coordinate nothing needs to move stays put. A frame
//! this cannot satisfy (a large jump the linearization cannot follow, or rows past
//! its size limit) leaves the points as they were and falls back to relaxation.

use super::dof_polish::{eval_residuals, finite_diff_jacobian, DofResidual};
use super::*;

/// Outer Gauss-Newton iterations per drag frame.
const DRAG_MAX_ITER: usize = 40;
/// A frame counts as solved when every row is within this of zero, relative to the
/// sketch scale: the exactness polish's own target, so the frame needs no polish.
const DRAG_ACCEPT_REL_TOL: f64 = 1e-11;
/// Above this many free coordinates the dense solve is too slow for a frame.
const DRAG_MAX_FREE_COORDS: usize = 1200;
/// Weight of a kept line's length change: the soft terms only choose among the
/// shapes the constraint rows allow, which the step meets exactly.
const KEEP_LENGTH_WEIGHT: f64 = 1.0;
/// Weight of a freed dragged point's distance from the cursor: above the kept
/// lengths, so the cursor wins where both can be met.
const TARGET_WEIGHT: f64 = 3.0;
/// Weight of every free coordinate's move from where it stood: small, so it only
/// settles what the constraints and soft terms leave open (a point nothing touches
/// stays put).
const MOTION_WEIGHT: f64 = 1e-2;
/// Step halvings a least-motion iteration tries before the frame gives up.
const DRAG_MAX_HALVING: usize = 12;

impl Engine {
    /// Move the free coordinates by the least motion that meets every constraint
    /// row. Returns whether it did; on `false` the coordinates are as they were and
    /// the caller relaxes instead.
    ///
    /// Two tries. First the dragged points are pinned where the caller put them
    /// (the cursor) and every line the drag does not hold by an end keeps its
    /// length, so a line the drag only turns (a point held on it, a parallel) turns
    /// instead of stretching or collapsing. When the cursor position itself
    /// cannot be met (a point held on a fixed line, dragged off it), the dragged
    /// points are freed and only drawn towards the cursor, so they slide to the
    /// nearest place the constraints allow instead of the relaxation pushing other
    /// geometry out of the way.
    pub(super) fn min_change_solve(&mut self) -> Result<bool, String> {
        // The caller's `fixed` flags pin the dragged points for this step only.
        // Relaxation clears every flag and re-fixes grounded points, so the solved
        // sketch (and its freedom diagnostics) carries the same flags either way.
        let pinned: Vec<bool> = self.points.iter().map(|p| p.fixed).collect();
        for point in &mut self.points {
            point.fixed = false;
        }
        // Grounded points take their pinned place first and drop out of the unknowns,
        // as they do at the start of relaxation.
        self.process_constraints_of_type(&Filter::Type(CType::Ground, "⏚"))?;
        let grounded: Vec<bool> = self.points.iter().map(|p| p.fixed).collect();
        let dragged: Vec<usize> = (0..self.points.len()).filter(|&i| pinned[i] && !grounded[i]).collect();
        let before: Vec<(f64, f64)> = self.points.iter().map(|p| (p.x, p.y)).collect();
        let kept = self.lines_to_keep(&self.riding_with(&dragged));
        let restore = |engine: &mut Engine| {
            for (point, &(x, y)) in engine.points.iter_mut().zip(&before) {
                point.x = x;
                point.y = y;
            }
        };

        // 1) dragged points at the cursor.
        for (point, &pin) in self.points.iter_mut().zip(&pinned) {
            point.fixed |= pin;
        }
        let mut solved = self.least_motion_step(&kept, &[]) && {
            self.fix_only(&grounded);
            self.every_row_met()
        };
        // 2) dragged points drawn towards the cursor.
        if !solved && !dragged.is_empty() {
            restore(self);
            self.fix_only(&grounded);
            let targets: Vec<(usize, f64, f64)> = dragged.iter().map(|&i| (i, before[i].0, before[i].1)).collect();
            solved = self.least_motion_step(&kept, &targets) && self.every_row_met();
        }
        self.fix_only(&grounded);
        if !solved {
            restore(self);
        }
        Ok(solved)
    }

    /// Set every point's `fixed` flag to `flags`.
    fn fix_only(&mut self, flags: &[bool]) {
        for (point, &f) in self.points.iter_mut().zip(flags) {
            point.fixed = f;
        }
    }

    /// The dragged points and every point a `≡` holds to one of them (transitively):
    /// a line whose end is coincident with a dragged point is dragged by that end.
    fn riding_with(&self, dragged: &[usize]) -> Vec<usize> {
        let mut riding = dragged.to_vec();
        loop {
            let mut grew = false;
            for c in &self.constraints {
                if c.ctype != CType::Coincident {
                    continue;
                }
                let ends: Vec<usize> = c.point_idx.iter().flatten().copied().collect();
                if ends.iter().any(|i| riding.contains(i)) {
                    for i in ends {
                        if !riding.contains(&i) {
                            riding.push(i);
                            grew = true;
                        }
                    }
                }
            }
            if !grew {
                return riding;
            }
        }
    }

    /// The lines whose length a drag frame keeps, with that length: every line
    /// segment none of whose ends is a dragged point or rides with one (a line
    /// dragged by its end is meant to change).
    fn lines_to_keep(&self, dragged: &[usize]) -> Vec<(usize, usize, f64)> {
        let mut out = Vec::new();
        for geo in &self.geometries {
            let Some(obj) = geo.as_object() else { continue };
            if obj.get("type").and_then(Value::as_str) != Some("line") {
                continue;
            }
            let Some(ids) = obj.get("points").and_then(Value::as_array) else { continue };
            if ids.len() != 2 {
                continue;
            }
            let (Some(&a), Some(&b)) =
                (self.point_index.get(&point_key(&ids[0])), self.point_index.get(&point_key(&ids[1])))
            else {
                continue;
            };
            if a == b || dragged.contains(&a) || dragged.contains(&b) {
                continue;
            }
            let len = (self.points[b].x - self.points[a].x).hypot(self.points[b].y - self.points[a].y);
            if len.is_finite() && len > 0.0 {
                out.push((a, b, len));
            }
        }
        out
    }

    /// The least-motion solve over the free coordinates (points not `fixed`): meet
    /// every constraint row exactly while moving the geometry as little as the soft
    /// terms ask. The soft terms are each kept line's length change, each target's
    /// distance from its point, and a small pull of every free coordinate back to
    /// where it stood. Each iteration takes the step of the linearized problem
    ///
    /// `min ½ δᵀWδ + gᵀδ  subject to  Jδ = −r`,  with `W = JₛᵀJₛ + μI`, `g = Jₛᵀs + μ(x − x₀)`,
    ///
    /// which is `δ = −W⁻¹g − W⁻¹Jᵀy` with `(JW⁻¹Jᵀ) y = r − JW⁻¹g`. The constraint rows
    /// are met by the step itself, not traded against the soft terms, so a parallel
    /// cannot be met by collapsing a line its length row only asks to keep. Steps are
    /// judged by the exact penalty `soft + ρ‖r‖₁` with `ρ` above the multipliers, so a
    /// line can turn along its arc while the rows are briefly off; a closing pass then
    /// takes the rows' own correction until they are met. Returns whether every row
    /// ended within the frame's acceptance; the points are written either way.
    fn least_motion_step(&mut self, kept: &[(usize, usize, f64)], targets: &[(usize, f64, f64)]) -> bool {
        let (point_cols, free_global, mut coords, scale) = self.build_free_layout(true);
        let n = free_global.len();
        if n > DRAG_MAX_FREE_COORDS {
            return false;
        }
        if n == 0 {
            return true;
        }
        let residuals = self.build_dof_residuals(&coords, &point_cols, true);
        let accept = DRAG_ACCEPT_REL_TOL * scale.max(1.0);
        // Driven well inside the acceptance, so the frame's own check (which sees the
        // rows from its own layout) never lands on its edge.
        let tight = 1e-3 * accept;
        let max_abs = |v: &[f64]| v.iter().fold(0.0f64, |acc, &x| acc.max(x.abs()));
        let sum_abs = |v: &[f64]| v.iter().fold(0.0f64, |acc, &x| acc + x.abs());
        let problem = LeastMotion {
            kept,
            targets,
            point_cols: &point_cols,
            free_global: &free_global,
            residuals: &residuals,
            origin: coords.clone(),
            mu: MOTION_WEIGHT * MOTION_WEIGHT,
            scale,
        };
        let mut r = eval_residuals(&residuals, &coords);
        let mut hard = max_abs(&r);
        if !hard.is_finite() {
            return false;
        }
        let mut soft = problem.soft_value(&coords);
        let mut rho = 0.0f64;
        let apply = |coords: &[f64], d: &[f64], t: f64| -> Vec<f64> {
            let mut trial = coords.to_vec();
            for (col, &gcol) in free_global.iter().enumerate() {
                trial[gcol] += t * d[col];
            }
            trial
        };
        // Main pass: the whole step, judged by the penalty.
        for _ in 0..DRAG_MAX_ITER {
            let Some(dir) = problem.directions(&coords, &r) else { break };
            rho = rho.max(2.0 * dir.multiplier + 1e-9);
            let full: Vec<f64> = dir.soft.iter().zip(&dir.restore).map(|(a, b)| a + b).collect();
            let merit = soft + rho * sum_abs(&r);
            let mut t = 1.0f64;
            let mut taken = false;
            for attempt in 0..DRAG_MAX_HALVING {
                let mut trial = apply(&coords, &full, t);
                let mut r_trial = eval_residuals(&residuals, &trial);
                let mut soft_trial = problem.soft_value(&trial);
                let mut merit_trial = soft_trial + rho * sum_abs(&r_trial);
                if attempt == 0 && !(merit_trial < merit) {
                    // The full step turns geometry along a curve the linearization
                    // only follows to first order, so the rows come out a little off
                    // and the penalty refuses a step that is right. Close the rows
                    // from the trial point (a second-order correction) and judge that.
                    if let Some(fix) = problem.directions(&trial, &r_trial) {
                        let corrected = apply(&trial, &fix.restore, 1.0);
                        let r_corr = eval_residuals(&residuals, &corrected);
                        let soft_corr = problem.soft_value(&corrected);
                        let merit_corr = soft_corr + rho * sum_abs(&r_corr);
                        if merit_corr < merit {
                            trial = corrected;
                            r_trial = r_corr;
                            soft_trial = soft_corr;
                            merit_trial = merit_corr;
                        }
                    }
                }
                if merit_trial.is_finite() && merit_trial < merit {
                    coords = trial;
                    hard = max_abs(&r_trial);
                    r = r_trial;
                    soft = soft_trial;
                    taken = true;
                    break;
                }
                t *= 0.5;
            }
            if !taken || t * max_abs(&full) <= 1e-12 * scale.max(1.0) {
                break;
            }
        }
        // Closing pass: the rows' own correction, until they are met.
        for _ in 0..DRAG_MAX_ITER {
            if hard <= tight {
                break;
            }
            let Some(dir) = problem.directions(&coords, &r) else { break };
            let mut t = 1.0f64;
            let mut taken = false;
            for _ in 0..DRAG_MAX_HALVING {
                let trial = apply(&coords, &dir.restore, t);
                let r_trial = eval_residuals(&residuals, &trial);
                let hard_trial = max_abs(&r_trial);
                if hard_trial.is_finite() && hard_trial <= (1.0 - 0.5 * t) * hard {
                    coords = trial;
                    hard = hard_trial;
                    r = r_trial;
                    taken = true;
                    break;
                }
                t *= 0.5;
            }
            if !taken {
                break;
            }
        }
        for &gcol in &free_global {
            let i = gcol / 2;
            if gcol % 2 == 0 {
                self.points[i].x = coords[gcol];
            } else {
                self.points[i].y = coords[gcol];
            }
        }
        hard <= accept
    }

    /// Whether every constraint row (including the engine's implied ones) is within
    /// the drag frame's acceptance at the current coordinates.
    fn every_row_met(&self) -> bool {
        let (point_cols, _free, coords, scale) = self.build_free_layout(true);
        let residuals = self.build_dof_residuals(&coords, &point_cols, true);
        let accept = DRAG_ACCEPT_REL_TOL * scale.max(1.0);
        eval_residuals(&residuals, &coords)
            .iter()
            .all(|r| r.is_finite() && r.abs() <= accept)
    }
}

/// Factor the symmetric positive definite `a` in place into its lower Cholesky
/// factor, reading only the lower triangle. Returns false on a non-positive pivot.
fn cholesky(a: &mut [Vec<f64>]) -> bool {
    let n = a.len();
    for i in 0..n {
        for j in 0..=i {
            let mut sum = a[i][j];
            for k in 0..j {
                sum -= a[i][k] * a[j][k];
            }
            if i == j {
                if !(sum > 0.0) {
                    return false;
                }
                a[i][i] = sum.sqrt();
            } else {
                a[i][j] = sum / a[j][j];
            }
        }
    }
    true
}

/// Solve `L Lᵀ x = b` in place with the factor [`cholesky`] left in `l`.
fn cholesky_solve(l: &[Vec<f64>], b: &mut [f64]) {
    let n = b.len();
    for i in 0..n {
        let mut sum = b[i];
        for k in 0..i {
            sum -= l[i][k] * b[k];
        }
        b[i] = sum / l[i][i];
    }
    for i in (0..n).rev() {
        let mut sum = b[i];
        for k in (i + 1)..n {
            sum -= l[k][i] * b[k];
        }
        b[i] = sum / l[i][i];
    }
}

/// One least-motion problem: the soft terms and the constraint rows over a free layout.
struct LeastMotion<'a> {
    kept: &'a [(usize, usize, f64)],
    targets: &'a [(usize, f64, f64)],
    point_cols: &'a [Option<(usize, usize)>],
    free_global: &'a [usize],
    residuals: &'a [DofResidual],
    origin: Vec<f64>,
    mu: f64,
    scale: f64,
}

/// The two parts of one least-motion step, and the size of its multipliers.
struct Directions {
    /// `−W⁻¹g − W⁻¹Jᵀ S⁻¹(−JW⁻¹g)`: the soft terms' descent, kept on the rows' tangent.
    soft: Vec<f64>,
    /// `−W⁻¹Jᵀ S⁻¹ r`: the correction that closes the rows.
    restore: Vec<f64>,
    /// The largest multiplier magnitude, which the penalty weight must exceed.
    multiplier: f64,
}

impl LeastMotion<'_> {
    fn soft_value(&self, c: &[f64]) -> f64 {
        let mut v = 0.0f64;
        for &(a, b, len) in self.kept {
            let d = (c[2 * b] - c[2 * a]).hypot(c[2 * b + 1] - c[2 * a + 1]);
            v += (KEEP_LENGTH_WEIGHT * (d - len)).powi(2);
        }
        for &(i, tx, ty) in self.targets {
            v += (TARGET_WEIGHT * (c[2 * i] - tx)).powi(2) + (TARGET_WEIGHT * (c[2 * i + 1] - ty)).powi(2);
        }
        for &gcol in self.free_global {
            v += self.mu * (c[gcol] - self.origin[gcol]).powi(2);
        }
        v
    }

    /// The step's parts at `coords` (rows `r` there), or `None` when a factor fails.
    fn directions(&self, coords: &[f64], r: &[f64]) -> Option<Directions> {
        let n = self.free_global.len();
        let m = r.len();
        // W and g from the soft rows.
        let mut w = vec![vec![0.0f64; n]; n];
        let mut g = vec![0.0f64; n];
        let mut add_row = |cols: &[(usize, f64)], value: f64| {
            for &(a, ja) in cols {
                g[a] += ja * value;
                for &(b, jb) in cols {
                    w[a][b] += ja * jb;
                }
            }
        };
        for &(a, b, len) in self.kept {
            let (dx, dy) = (coords[2 * b] - coords[2 * a], coords[2 * b + 1] - coords[2 * a + 1]);
            let d = dx.hypot(dy).max(1e-300);
            let (ux, uy) = (KEEP_LENGTH_WEIGHT * dx / d, KEEP_LENGTH_WEIGHT * dy / d);
            let mut cols = Vec::with_capacity(4);
            if let Some((cx, cy)) = self.point_cols[a] {
                cols.push((cx, -ux));
                cols.push((cy, -uy));
            }
            if let Some((cx, cy)) = self.point_cols[b] {
                cols.push((cx, ux));
                cols.push((cy, uy));
            }
            add_row(&cols, KEEP_LENGTH_WEIGHT * (d - len));
        }
        for &(i, tx, ty) in self.targets {
            if let Some((cx, cy)) = self.point_cols[i] {
                add_row(&[(cx, TARGET_WEIGHT)], TARGET_WEIGHT * (coords[2 * i] - tx));
                add_row(&[(cy, TARGET_WEIGHT)], TARGET_WEIGHT * (coords[2 * i + 1] - ty));
            }
        }
        for (col, &gcol) in self.free_global.iter().enumerate() {
            w[col][col] += self.mu;
            g[col] += self.mu * (coords[gcol] - self.origin[gcol]);
        }
        if !cholesky(&mut w) {
            return None;
        }
        let mut wg = g;
        cholesky_solve(&w, &mut wg);
        let mut soft: Vec<f64> = wg.iter().map(|v| -v).collect();
        let mut restore = vec![0.0f64; n];
        let mut multiplier = 0.0f64;
        if m > 0 {
            let jac = finite_diff_jacobian(self.residuals, coords, self.free_global, self.scale, m);
            // Z = W⁻¹Jᵀ, one column per row.
            let z: Vec<Vec<f64>> = jac
                .iter()
                .map(|row| {
                    let mut col = row.clone();
                    cholesky_solve(&w, &mut col);
                    col
                })
                .collect();
            let mut s_mat = vec![vec![0.0f64; m]; m];
            let mut max_diag = 0.0f64;
            for a in 0..m {
                for b in 0..=a {
                    let v: f64 = jac[a].iter().zip(&z[b]).map(|(x, y)| x * y).sum();
                    s_mat[a][b] = v;
                    s_mat[b][a] = v;
                }
                max_diag = max_diag.max(s_mat[a][a]);
            }
            // Two right-hand sides, solved apart: summed, the soft part's large
            // cancelling terms would bury a small residual's correction in rounding.
            let mut y_soft: Vec<f64> =
                (0..m).map(|a| -jac[a].iter().zip(&wg).map(|(x, y)| x * y).sum::<f64>()).collect();
            let mut y_hard = r.to_vec();
            // Dependent rows (a redundant constraint) leave S singular; a tiny ridge
            // keeps the factor while barely touching the rest.
            let mut ridge = 1e-12 * max_diag.max(1e-300);
            let mut factored = false;
            for _ in 0..6 {
                let mut trial = s_mat.clone();
                for d in 0..m {
                    trial[d][d] += ridge;
                }
                if cholesky(&mut trial) {
                    cholesky_solve(&trial, &mut y_soft);
                    cholesky_solve(&trial, &mut y_hard);
                    factored = true;
                    break;
                }
                ridge *= 100.0;
            }
            if !factored {
                return None;
            }
            for (a, za) in z.iter().enumerate() {
                for col in 0..n {
                    soft[col] -= za[col] * y_soft[a];
                    restore[col] -= za[col] * y_hard[a];
                }
                multiplier = multiplier.max((y_soft[a] + y_hard[a]).abs());
            }
        }
        if !soft.iter().chain(&restore).all(|v| v.is_finite()) {
            return None;
        }
        Some(Directions { soft, restore, multiplier })
    }
}