BREP_blend 0.33.0

Rust B-rep CAD kernel (next.BREP.io): fillets, chamfers and blends.
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
//! Two support faces that are extrusions along one direction and meet
//! tangent-continuously (G1) along a ruling are one support to the rolling
//! ball: where a selected chain flush-joins across that ruling a corner close
//! to the join seats its ball on the far side of it (benchy
//! outer rail: an r 0.2 corner 0.032 mm from the plane | r 2 cylinder join,
//! whose ball the network solved on the cylinder's fictitious extension and
//! refused). Behind `BREP_FILLET_G1_SUPPORT_MERGE` (default off), such a pair
//! is given ONE carrier, the extrusion of the two profiles joined at the
//! ruling (exact: the pieces are the faces' own profiles, joined C1 in
//! parameter), and merged into one face before the round; the body is
//! otherwise unchanged.
use super::*;
use super::edges::resolve_edge_by_point;

/// `BREP_FILLET_G1_SUPPORT_MERGE` (default off).
pub(super) fn g1_support_merge_on() -> bool {
    switch!(live "BREP_FILLET_G1_SUPPORT_MERGE", false)
}

fn faces_of_edge(solid: &BrepSolid, edge_id: u64) -> Vec<&FaceRecord> {
    solid
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .filter(|face| face.loops.iter().flat_map(|lp| &lp.coedges).any(|coedge| coedge.edge_id == edge_id))
        .collect()
}

fn oriented_normal(face: &FaceRecord, point: Vec3) -> Option<Vec3> {
    let uv = crate::project_point_to_surface(&face.surface, point).ok()?;
    let normal = face.surface.normal(uv.u, uv.v).ok()?;
    Some(if face.same_sense { normal } else { normal.scale(-1.0) })
}

/// The profile of `extrusion` carried along its direction to the plane
/// through `origin` normal to `axis` (homogeneous: each control moves with
/// its weight).
fn profile_on_plane(profile: &NurbsCurve, axis: Vec3, origin: Vec3) -> Option<NurbsCurve> {
    let controls = profile
        .control_points
        .iter()
        .map(|c| {
            let p = c.point().ok()?;
            let q = p.sub(axis.scale(p.sub(origin).dot(axis)));
            Some(crate::Vec4::from_point(q, c.w))
        })
        .collect::<Option<Vec<_>>>()?;
    NurbsCurve::new(profile.degree, profile.knots.clone(), controls).ok()
}

/// `curve` raised from degree 1 to 2 (a straight piece with unit weights).
fn elevated_line(curve: &NurbsCurve) -> Option<NurbsCurve> {
    if curve.degree != 1 || curve.control_points.len() != 2 || curve.control_points.iter().any(|c| (c.w - 1.0).abs() > 1e-14) {
        return None;
    }
    let [t0, t1] = curve.domain().ok()?;
    let (a, b) = (curve.control_points[0], curve.control_points[1]);
    let middle = crate::Vec4 { x: 0.5 * (a.x + b.x), y: 0.5 * (a.y + b.y), z: 0.5 * (a.z + b.z), w: 1.0 };
    NurbsCurve::new(2, vec![t0, t0, t0, t1, t1, t1], vec![a, middle, b]).ok()
}

/// The piece of `curve` on `side` of parameter `at` (`true`: above it),
/// oriented to END at `at` when `ends_at_join`, else to START there.
fn piece(curve: &NurbsCurve, at: f64, above: bool, ends_at_join: bool) -> Option<NurbsCurve> {
    let [t0, t1] = curve.domain().ok()?;
    let span = t1 - t0;
    let inner = |t: f64| t > t0 + 1e-9 * span && t < t1 - 1e-9 * span;
    let part = if above {
        if inner(at) { curve.split(at).ok()?.1 } else if at <= t0 + 1e-9 * span { curve.clone() } else { return None }
    } else if inner(at) {
        curve.split(at).ok()?.0
    } else if at >= t1 - 1e-9 * span {
        curve.clone()
    } else {
        return None;
    };
    // `above` starts at the join; `!above` ends there.
    if above == ends_at_join { part.reversed().ok() } else { Some(part) }
}

/// `curve` with its parameter mapped affinely onto [`start`, `start + length`].
fn rescaled(curve: &NurbsCurve, start: f64, length: f64) -> Option<NurbsCurve> {
    let [t0, t1] = curve.domain().ok()?;
    let knots = curve.knots.iter().map(|t| start + (t - t0) / (t1 - t0) * length).collect();
    NurbsCurve::new(curve.degree, knots, curve.control_points.clone()).ok()
}

/// Join `first` (ending at the join) and `second` (starting there), equal
/// degree, with C1 parameter speed across the join.
fn joined(first: &NurbsCurve, second: &NurbsCurve) -> Option<NurbsCurve> {
    if first.degree != second.degree {
        return None;
    }
    let [a0, a1] = first.domain().ok()?;
    let [b0, b1] = second.domain().ok()?;
    let speed_a = first.derivatives(a1, 1).ok()?[1].length() * (a1 - a0);
    let speed_b = second.derivatives(b0, 1).ok()?[1].length() * (b1 - b0);
    if !(speed_a > 0.0 && speed_b > 0.0) {
        return None;
    }
    // First on [0, la], second on [la, la + 1], matching d/dt at the join.
    let la = speed_a / speed_b;
    let first = rescaled(first, 0.0, la)?;
    let second = rescaled(second, la, 1.0)?;
    let degree = first.degree;
    let mut knots: Vec<f64> = first.knots[..first.knots.len() - 1].to_vec();
    knots.extend_from_slice(&second.knots[degree + 1..]);
    let ja = first.control_points.last()?.point().ok()?;
    let jb = second.control_points.first()?.point().ok()?;
    if ja.sub(jb).length() > 1e-9 * (1.0 + ja.length()) {
        return None;
    }
    // The shared control: weights are made to agree by scaling the second
    // piece's homogeneous controls.
    let scale = first.control_points.last()?.w / second.control_points.first()?.w;
    let mut controls = first.control_points.clone();
    controls.extend(second.control_points[1..].iter().map(|c| crate::Vec4 { x: c.x * scale, y: c.y * scale, z: c.z * scale, w: c.w * scale }));
    NurbsCurve::new(degree, knots, controls).ok()
}

/// `curve`, a single rational Bezier span, raised to `degree` exactly
/// (homogeneous degree elevation).
fn elevated(curve: &NurbsCurve, degree: usize) -> Option<NurbsCurve> {
    let p = curve.degree;
    if degree < p || curve.control_points.len() != p + 1 {
        return None;
    }
    if degree == p {
        return Some(curve.clone());
    }
    let t = degree - p;
    let binomial = |n: usize, k: usize| -> f64 { (0..k).fold(1.0, |acc, i| acc * (n - i) as f64 / (i + 1) as f64) };
    let q = &curve.control_points;
    let controls = (0..=degree)
        .map(|i| {
            let mut sum = crate::Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 };
            for j in i.saturating_sub(t)..=p.min(i) {
                let c = binomial(p, j) * binomial(t, i - j) / binomial(degree, i);
                sum = crate::Vec4 { x: sum.x + c * q[j].x, y: sum.y + c * q[j].y, z: sum.z + c * q[j].z, w: sum.w + c * q[j].w };
            }
            sum
        })
        .collect();
    let [a, b] = curve.domain().ok()?;
    let mut knots = vec![a; degree + 1];
    knots.extend(std::iter::repeat(b).take(degree + 1));
    NurbsCurve::new(degree, knots, controls).ok()
}

/// The edge's curve over [t0, t1], oriented to run from `from`.
fn edge_curve_from(edge: &EdgeRecord, from: u64) -> Option<NurbsCurve> {
    let [c0, c1] = edge.curve.domain().ok()?;
    let mut curve = edge.curve.clone();
    if edge.t1 < c1 - 1e-12 * (c1 - c0).abs().max(1.0) {
        curve = curve.split(edge.t1).ok()?.0;
    }
    if edge.t0 > c0 + 1e-12 * (c1 - c0).abs().max(1.0) {
        curve = curve.split(edge.t0).ok()?.1;
    }
    if edge.start_vertex_id == from { Some(curve) } else { curve.reversed().ok() }
}

/// The two edges at the two-valent `vertex` joined into one (they border the
/// same two faces and continue each other G1), or `None`.
fn join_edges_at(solid: &BrepSolid, vertex: u64) -> Option<BrepSolid> {
    let at: Vec<&EdgeRecord> = solid.edges.iter().filter(|e| !e.degenerate && (e.start_vertex_id == vertex || e.end_vertex_id == vertex)).collect();
    let [a, b] = at.as_slice() else { return None };
    let mut faces_a: Vec<u64> = faces_of_edge(solid, a.id).iter().map(|f| f.id).collect();
    let mut faces_b: Vec<u64> = faces_of_edge(solid, b.id).iter().map(|f| f.id).collect();
    faces_a.sort_unstable();
    faces_b.sort_unstable();
    if faces_a.len() != 2 || faces_a != faces_b {
        return None;
    }
    let far = |e: &EdgeRecord| if e.start_vertex_id == vertex { e.end_vertex_id } else { e.start_vertex_id };
    let (start, end) = (far(a), far(b));
    if start == end {
        return None;
    }
    let first = edge_curve_from(a, start)?;
    let second = edge_curve_from(b, vertex)?;
    let degree = first.degree.max(second.degree);
    let first = if first.degree < degree { elevated(&first, degree)? } else { first };
    let second = if second.degree < degree { elevated(&second, degree)? } else { second };
    let curve = joined(&first, &second)?;
    // G1 at the join.
    let [_, end_first] = first.domain().ok()?;
    let [start_second, _] = second.domain().ok()?;
    let ta = first.derivatives(end_first, 1).ok()?[1].normalized().ok()?;
    let tb = second.derivatives(start_second, 1).ok()?[1].normalized().ok()?;
    if ta.dot(tb) < 1.0 - 1e-9 {
        return None;
    }
    let [d0, d1] = curve.domain().ok()?;
    let mut body = solid.clone();
    let id = a.id;
    body.edges.retain(|e| e.id != a.id && e.id != b.id);
    body.edges.push(EdgeRecord { id, curve: curve.clone(), t0: d0, t1: d1, start_vertex_id: start, end_vertex_id: end, degenerate: false, name: a.name.clone() });
    body.vertices.retain(|v| v.id != vertex);
    for face in body.shells.iter_mut().flat_map(|shell| &mut shell.faces).filter(|f| faces_a.contains(&f.id)) {
        let surface = face.surface.clone();
        for lp in &mut face.loops {
            let n = lp.coedges.len();
            let Some(i) = (0..n).find(|&i| {
                let (x, y) = (&lp.coedges[i], &lp.coedges[(i + 1) % n]);
                (x.edge_id == a.id && y.edge_id == b.id) || (x.edge_id == b.id && y.edge_id == a.id)
            }) else { continue };
            // Traversal runs start -> end when the loop visits `a` first.
            let forward = lp.coedges[i].edge_id == a.id;
            let traversal = if forward { curve.clone() } else { curve.reversed().ok()? };
            let pcurve = crate::build_pcurve_on_surface(&surface, &traversal).ok()?;
            let coedge = crate::topology::CoedgeRecord { id: lp.coedges[i].id, edge_id: id, forward, pcurve };
            let j = (i + 1) % n;
            if j == 0 {
                lp.coedges.remove(0);
                lp.coedges[n - 2] = coedge;
            } else {
                lp.coedges[i] = coedge;
                lp.coedges.remove(j);
            }
        }
    }
    body.validate().is_empty().then_some(body)
}

/// The merged carrier of faces `f` and `g` across their G1 ruling `edge`.
fn merged_carrier(solid: &BrepSolid, f: &FaceRecord, g: &FaceRecord, edge: &EdgeRecord) -> Option<crate::NurbsSurface> {
    let ef = f.surface.linear_extrusion()?;
    let eg = g.surface.linear_extrusion()?;
    let axis = ef.direction.normalized().ok()?;
    if axis.cross(eg.direction.normalized().ok()?).length() > 1e-9 {
        return None;
    }
    // The ruling runs along the axis.
    let (p0, p1) = (edge.curve.evaluate(edge.t0).ok()?, edge.curve.evaluate(edge.t1).ok()?);
    let chord = p1.sub(p0);
    if chord.length() < 1e-9 || chord.normalized().ok()?.cross(axis).length() > 1e-9 {
        return None;
    }
    // Both carriers' sweep extents along the axis, from their bases.
    let extent = |e: &crate::analytic_surface::ExtrusionStructure| -> Option<(f64, f64, Vec3)> {
        let points = e.profile.control_points.iter().map(|c| c.point().ok()).collect::<Option<Vec<_>>>()?;
        let along = e.direction.length() * (e.sweep_domain[1] - e.sweep_domain[0]);
        let low = points.iter().map(|p| p.dot(axis)).fold(f64::INFINITY, f64::min);
        let high = points.iter().map(|p| p.dot(axis)).fold(f64::NEG_INFINITY, f64::max);
        // The sweep runs along +axis or -axis.
        let sign = e.direction.dot(axis).signum();
        let (start, end) = if sign > 0.0 { (low, high + along) } else { (low - along, high) };
        Some((start, end, points[0]))
    };
    let (fs, fe, base) = extent(ef)?;
    let (gs, ge, _) = extent(eg)?;
    let (low, high) = (fs.min(gs), fe.max(ge));
    let origin = base.sub(axis.scale(base.dot(axis) - low));
    let cf = profile_on_plane(&ef.profile, axis, origin)?;
    let cg = profile_on_plane(&eg.profile, axis, origin)?;
    let join = p0.sub(axis.scale(p0.sub(origin).dot(axis)));
    let tf = crate::project_point_to_curve(&cf, join).ok()?;
    let tg = crate::project_point_to_curve(&cg, join).ok()?;
    if tf.distance > 1e-9 * (1.0 + join.length()) || tg.distance > 1e-9 * (1.0 + join.length()) {
        return None;
    }
    // Which side of the join each face lies on: a vertex of the face off the
    // ruling, carried to the plane.
    let side = |face: &FaceRecord, curve: &NurbsCurve, at: f64| -> Option<bool> {
        let vertex = face.loops.iter().flat_map(|lp| &lp.coedges).find_map(|coedge| {
            let e = solid.edges.iter().find(|e| e.id == coedge.edge_id)?;
            [e.start_vertex_id, e.end_vertex_id].into_iter().find(|id| *id != edge.start_vertex_id && *id != edge.end_vertex_id)
        })?;
        let point = solid.vertices.iter().find(|v| v.id == vertex)?.point;
        let point = point.sub(axis.scale(point.sub(origin).dot(axis)));
        Some(crate::project_point_to_curve(curve, point).ok()?.u > at)
    };
    let pf = piece(&cf, tf.u, side(f, &cf, tf.u)?, true)?;
    let pg = piece(&cg, tg.u, side(g, &cg, tg.u)?, false)?;
    let (pf, pg) = match (pf.degree, pg.degree) {
        (1, 2) => (elevated_line(&pf)?, pg),
        (2, 1) => (pf, elevated_line(&pg)?),
        _ => (pf, pg),
    };
    let profile = joined(&pf, &pg)?;
    // Exact: the joined profile traces each piece it was built from (the
    // pieces are the faces' own profiles, split at the join), compared at the
    // affinely mapped parameter, with no projection in the reading.
    let [u0, u1] = profile.domain().ok()?;
    let la = profile.knots.iter().copied().find(|t| *t > u0 && *t < u1).unwrap_or(u0);
    let bar = 1e-12 * (1.0 + join.length());
    let mut worst = [0.0_f64; 2];
    for (slot, (piece, start, end)) in [(&pf, u0, la), (&pg, la, u1)].into_iter().enumerate() {
        let [t0, t1] = piece.domain().ok()?;
        for k in 0..=32 {
            let s = k as f64 / 32.0;
            let on_piece = piece.evaluate(t0 + s * (t1 - t0)).ok()?;
            let on_profile = profile.evaluate(start + s * (end - start)).ok()?;
            worst[slot] = worst[slot].max(on_piece.sub(on_profile).length());
        }
    }
    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
        eprintln!("g1 support merge: faces {} and {}: the joined profile stands {:.3e} / {:.3e} off its pieces (join at u {la:.6} of [{u0}, {u1}])", f.id, g.id, worst[0], worst[1]);
    }
    if worst[0].max(worst[1]) > bar {
        return None;
    }
    let sweep = axis.scale(high - low);
    let rows = profile
        .control_points
        .iter()
        .map(|c| vec![*c, crate::Vec4 { x: c.x + c.w * sweep.x, y: c.y + c.w * sweep.y, z: c.z + c.w * sweep.z, w: c.w }])
        .collect();
    crate::NurbsSurface::new(profile.degree, 1, profile.knots.clone(), vec![0.0, 0.0, 1.0, 1.0], rows).ok()
}

/// Whether the radius-`radius` ball at the convex `corner` (three faces), seated
/// on the merged `carrier` in place of the pair member the short edge borders,
/// touches the carrier on the OTHER member's piece: the case the merge is for.
fn ball_crosses(body: &BrepSolid, carrier: &crate::NurbsSurface, pair: [u64; 2], short_edge: u64, corner: u64, corner_point: Vec3, radius: f64) -> bool {
    let around: Vec<&FaceRecord> = body
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .filter(|face| face.loops.iter().flat_map(|lp| &lp.coedges).any(|coedge| {
            body.edges.iter().find(|e| e.id == coedge.edge_id).is_some_and(|e| e.start_vertex_id == corner || e.end_vertex_id == corner)
        }))
        .collect();
    let Some(own) = faces_of_edge(body, short_edge).into_iter().find(|face| pair.contains(&face.id)) else { return false };
    if around.len() != 3 || !around.iter().any(|face| face.id == own.id) {
        return false;
    }
    let mut seated = own.clone();
    seated.surface = carrier.clone();
    let faces: Vec<&FaceRecord> = around.iter().map(|face| if face.id == own.id { &seated } else { *face }).collect();
    let [u0, u1] = match carrier.domain_u() { Ok(domain) => domain, Err(_) => return false };
    let join = carrier.knots_u.iter().copied().find(|t| *t > u0 && *t < u1).unwrap_or(u0);
    // The first piece of the joined profile is `pair[0]`'s.
    let own_first = own.id == pair[0];
    let scale = crate::solid_scale(body);
    for sign in [1.0, -1.0] {
        let rho_of = |id: u64| faces.iter().find(|face| face.id == id).map(|face| sign * if face.same_sense { -radius } else { radius });
        let Ok(prepared) = crate::blend::corner::corner_faces(&faces, &rho_of, corner_point) else { continue };
        let Ok(ball) = crate::blend::corner::solve_corner_ball(&prepared, scale) else { continue };
        // Contacts come back in the order of the faces.
        let Some(index) = faces.iter().position(|face| face.id == own.id) else { continue };
        let Some(contact) = ball.contacts.get(index) else { continue };
        let on_first = contact.uv[0] < join;
        return on_first != own_first;
    }
    false
}

/// The body with every G1 extrusion support pair at a flush join of the
/// selection merged into one face, or `None` when there is none (or a merge
/// does not validate).
pub(super) fn merge_g1_supports(solid: &BrepSolid, edge_points: &[Vec3], radius: f64) -> Option<BrepSolid> {
    if !g1_support_merge_on() {
        return None;
    }
    let selected: Vec<u64> = edge_points.iter().filter_map(|p| resolve_edge_by_point(solid, *p).ok()).collect();
    let edge_of = |id: u64| solid.edges.iter().find(|e| e.id == id);
    let mut body = solid.clone();
    let mut merged_any = false;
    for edge in &solid.edges {
        if edge.degenerate || selected.contains(&edge.id) {
            continue;
        }
        // A flush join of two selected edges at one end of the ruling, one of
        // them SHORT (under 2r) and ending at a corner on its far side: the
        // corner's ball then reaches back across the join. Every other G1
        // pair is left as it came.
        let valence = |vertex: u64| solid.edges.iter().filter(|e| !e.degenerate && (e.start_vertex_id == vertex || e.end_vertex_id == vertex)).count();
        let short_to_corner = [edge.start_vertex_id, edge.end_vertex_id].into_iter().find_map(|vertex| {
            let at: Vec<&EdgeRecord> = selected.iter().filter_map(|id| edge_of(*id)).filter(|e| e.start_vertex_id == vertex || e.end_vertex_id == vertex).collect();
            if at.len() != 2 {
                return None;
            }
            at.into_iter().find_map(|e| {
                let far = if e.start_vertex_id == vertex { e.end_vertex_id } else { e.start_vertex_id };
                let a = solid.vertices.iter().find(|v| v.id == vertex)?;
                let b = solid.vertices.iter().find(|v| v.id == far)?;
                (a.point.sub(b.point).length() < 2.0 * radius && valence(far) == 3).then_some((e.id, far, b.point))
            })
        });
        let Some((short_edge, corner, corner_point)) = short_to_corner else { continue };
        let mates = faces_of_edge(&body, edge.id);
        let [f, g] = mates.as_slice() else { continue };
        let Ok(middle) = edge.curve.evaluate(0.5 * (edge.t0 + edge.t1)) else { continue };
        let (Some(nf), Some(ng)) = (oriented_normal(f, middle), oriented_normal(g, middle)) else { continue };
        if nf.dot(ng) < 1.0 - 1e-12 {
            continue;
        }
        let Some(carrier) = merged_carrier(&body, f, g, edge) else { continue };
        if !ball_crosses(&body, &carrier, [f.id, g.id], short_edge, corner, corner_point, radius) {
            if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
                eprintln!("g1 support merge: faces {} and {}: the corner ball at vertex {corner} stays on its own face; left as they came", f.id, g.id);
            }
            continue;
        }
        let ids = [f.id, g.id];
        let mut candidate = body.clone();
        let edges = candidate.edges.clone();
        let mut ok = true;
        for face in candidate.shells.iter_mut().flat_map(|shell| &mut shell.faces).filter(|face| ids.contains(&face.id)) {
            let Some(before) = oriented_normal(face, middle) else { ok = false; break };
            face.surface = carrier.clone();
            let Some(raw) = crate::project_point_to_surface(&face.surface, middle).ok().and_then(|uv| face.surface.normal(uv.u, uv.v).ok()) else { ok = false; break };
            face.same_sense = raw.dot(before) > 0.0;
            for coedge in face.loops.iter_mut().flat_map(|lp| &mut lp.coedges) {
                let Some(e) = edges.iter().find(|e| e.id == coedge.edge_id) else { ok = false; break };
                let trimmed = || -> Option<NurbsCurve> {
                    let [c0, c1] = e.curve.domain().ok()?;
                    let mut curve = e.curve.clone();
                    if e.t1 < c1 - 1e-12 * (c1 - c0).abs().max(1.0) {
                        curve = curve.split(e.t1).ok()?.0;
                    }
                    if e.t0 > c0 + 1e-12 * (c1 - c0).abs().max(1.0) {
                        curve = curve.split(e.t0).ok()?.1;
                    }
                    if coedge.forward { Some(curve) } else { curve.reversed().ok() }
                };
                let Some(traversal) = trimmed() else { ok = false; break };
                match crate::build_pcurve_on_surface(&face.surface, &traversal) {
                    Ok(pcurve) => coedge.pcurve = pcurve,
                    Err(_) => {
                        ok = false;
                        break;
                    }
                }
            }
        }
        if !ok {
            continue;
        }
        let Ok((merged, _)) = crate::merge_faces_within(&candidate, 1e-9, &ids) else { continue };
        // The two selected edges at the join now border the same two faces:
        // one chain, joined into one edge so the corner's station is read on
        // the whole run (a short piece alone does not reach the corner ball's
        // tangency, 5.9e-2 short on the rail).
        let ends: rustc_hash::FxHashSet<u64> = [edge.start_vertex_id, edge.end_vertex_id].into_iter().collect();
        let mut merged = merged;
        for vertex in [edge.start_vertex_id, edge.end_vertex_id] {
            if let Some(joined) = join_edges_at(&merged, vertex) {
                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
                    eprintln!("g1 support merge: the two edges at vertex {vertex} joined into one");
                }
                merged = joined;
            }
        }
        if !merged.validate().is_empty() || merged.shells.iter().map(|s| s.faces.len()).sum::<usize>() + 1 != body.shells.iter().map(|s| s.faces.len()).sum::<usize>() {
            continue;
        }
        if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
            eprintln!("g1 support merge: faces {} and {} across ruling {} are one extrusion", ids[0], ids[1], edge.id);
        }
        body = merged;
        merged_any = true;
    }
    merged_any.then_some(body)
}

/// `edge_points` (and their names) with one pick per edge of `body`.
pub(super) fn dedup_picks(body: &BrepSolid, edge_points: &[Vec3], edge_names: Option<&[String]>) -> (Vec<Vec3>, Option<Vec<String>>) {
    let mut seen = Vec::new();
    let mut points = Vec::new();
    let mut names = edge_names.map(|_| Vec::new());
    for (index, point) in edge_points.iter().enumerate() {
        let id = resolve_edge_by_point(body, *point).ok();
        if id.is_some_and(|id| seen.contains(&id)) {
            continue;
        }
        seen.extend(id);
        points.push(*point);
        if let (Some(names), Some(all)) = (names.as_mut(), edge_names) {
            names.push(all[index].clone());
        }
    }
    (points, names)
}