Skip to main content

xpict_core/doc/
layout_constraints.rs

1//! Hierarchical constraint layout (document tree, not a mol-only mode).
2//!
3//! **Fixed vs movable.** Kits freeze obstacles (chem ink, scheme mol boxes) and
4//! expose translation DOF on the rest. Mol chrome: chem is frozen after depict;
5//! annotations are the free variables. Reaction schemes: mols stay fixed; edge
6//! control points and edge labels move.
7//!
8//! **Clearance is baseline and hard.** Kits emit [`HardConstraint::Outside`] vs
9//! primitive leaves (bonds, disks, shafts) via [`push_clear_leaves`]. An
10//! augmented-Lagrangian outer loop around Nelder–Mead enforces them. Soft
11//! hinges alone leave residual ink overlap; do not special-case a weaker gap.
12//!
13//! Nested node paths (`mol/chem/…`, `scheme/edges/e0/…`), edge-aware shapes,
14//! per-type kits, and a Nelder–Mead minimizer that stops on **pose motion in
15//! CSS-px** (not ΔE). `energy` / `hard_g` / `solve` / `apply_params` never
16//! branch on [`ObjectType`] or path prefixes.
17
18use std::cell::RefCell;
19use std::collections::HashMap;
20
21use crate::doc::clash_grid::{ClashGrid, InkStamp};
22use crate::doc::layout_items::{Aabb, Side, ATOM_DISK_R_PX, CONTAIN_MARGIN_PX};
23use crate::metrics::{BOND_PX, STROKE_PX};
24
25/// Stable path id (`mol/chem/atoms/a3/shade`, `mol/annotations/captions/name`).
26pub type NodeId = String;
27
28/// Geometry used for contain / clash / opt_dist (edge-based, not center-to-center).
29#[derive(Debug, Clone, PartialEq)]
30pub enum Shape {
31    Point {
32        x: f64,
33        y: f64,
34    },
35    Circle {
36        cx: f64,
37        cy: f64,
38        r: f64,
39    },
40    Line {
41        x0: f64,
42        y0: f64,
43        x1: f64,
44        y1: f64,
45    },
46    Aabb(Aabb),
47    /// Closed polyline / hull proxy (last→first implied if not equal).
48    PointSet(Vec<(f64, f64)>),
49    /// Open polyline (no last→first edge). Empty is a group marker: the live
50    /// geometry is the child [`Shape::Point`]s in `children` order
51    /// ([`LayoutWorld::eval_shape`]).
52    Polyline(Vec<(f64, f64)>),
53}
54
55impl Shape {
56    pub fn aabb(&self) -> Aabb {
57        match self {
58            Shape::Point { x, y } => Aabb::new(*x, *y, *x, *y),
59            Shape::Circle { cx, cy, r } => Aabb::new(cx - r, cy - r, cx + r, cy + r),
60            Shape::Line { x0, y0, x1, y1 } => Aabb::new(*x0, *y0, *x1, *y1),
61            Shape::Aabb(a) => *a,
62            Shape::PointSet(pts) | Shape::Polyline(pts) => {
63                if pts.is_empty() {
64                    return Aabb::new(0.0, 0.0, 0.0, 0.0);
65                }
66                let mut x0 = f64::INFINITY;
67                let mut y0 = f64::INFINITY;
68                let mut x1 = f64::NEG_INFINITY;
69                let mut y1 = f64::NEG_INFINITY;
70                for &(x, y) in pts {
71                    x0 = x0.min(x);
72                    y0 = y0.min(y);
73                    x1 = x1.max(x);
74                    y1 = y1.max(y);
75                }
76                Aabb::new(x0, y0, x1, y1)
77            }
78        }
79    }
80
81    /// Translate by `(dx, dy)` (movable pose apply).
82    pub fn translated(&self, dx: f64, dy: f64) -> Shape {
83        match self {
84            Shape::Point { x, y } => Shape::Point {
85                x: x + dx,
86                y: y + dy,
87            },
88            Shape::Circle { cx, cy, r } => Shape::Circle {
89                cx: cx + dx,
90                cy: cy + dy,
91                r: *r,
92            },
93            Shape::Line { x0, y0, x1, y1 } => Shape::Line {
94                x0: x0 + dx,
95                y0: y0 + dy,
96                x1: x1 + dx,
97                y1: y1 + dy,
98            },
99            Shape::Aabb(a) => Shape::Aabb(Aabb::new(a.x0 + dx, a.y0 + dy, a.x1 + dx, a.y1 + dy)),
100            Shape::PointSet(pts) => {
101                Shape::PointSet(pts.iter().map(|&(x, y)| (x + dx, y + dy)).collect())
102            }
103            Shape::Polyline(pts) => {
104                Shape::Polyline(pts.iter().map(|&(x, y)| (x + dx, y + dy)).collect())
105            }
106        }
107    }
108
109    /// Control points used for solver termination (CSS-px).
110    pub fn control_points(&self) -> Vec<(f64, f64)> {
111        match self {
112            Shape::Point { x, y } => vec![(*x, *y)],
113            Shape::Circle { cx, cy, r } => vec![
114                (*cx, *cy),
115                (cx + r, *cy),
116                (cx - r, *cy),
117                (*cx, cy + r),
118                (*cx, cy - r),
119            ],
120            Shape::Line { x0, y0, x1, y1 } => vec![(*x0, *y0), (*x1, *y1)],
121            Shape::Aabb(a) => vec![
122                (a.x0, a.y0),
123                (a.x1, a.y0),
124                (a.x1, a.y1),
125                (a.x0, a.y1),
126                a.center(),
127            ],
128            Shape::PointSet(pts) | Shape::Polyline(pts) => pts.clone(),
129        }
130    }
131}
132
133/// Signed edge distance: positive = separated, negative = penetration depth.
134///
135/// For AABB↔AABB / Circle↔Circle / Point↔* this is exact enough for soft
136/// clash. PointSet uses distance to closest boundary segment (negative inside).
137pub fn edge_signed_distance(a: &Shape, b: &Shape) -> f64 {
138    match (a, b) {
139        (Shape::Point { x: ax, y: ay }, Shape::Point { x: bx, y: by }) => (ax - bx).hypot(ay - by),
140        (Shape::Point { x, y }, other) => point_to_shape_signed(*x, *y, other),
141        (other, Shape::Point { x, y }) => point_to_shape_signed(*x, *y, other),
142        (
143            Shape::Circle {
144                cx: ax,
145                cy: ay,
146                r: ar,
147            },
148            Shape::Circle {
149                cx: bx,
150                cy: by,
151                r: br,
152            },
153        ) => (ax - bx).hypot(ay - by) - ar - br,
154        (Shape::Aabb(aa), Shape::Aabb(bb)) => aabb_aabb_signed(*aa, *bb),
155        (Shape::Circle { cx, cy, r }, Shape::Aabb(box_))
156        | (Shape::Aabb(box_), Shape::Circle { cx, cy, r }) => {
157            aabb_circle_signed(*box_, *cx, *cy, *r)
158        }
159        (Shape::Line { .. }, _) | (_, Shape::Line { .. }) => {
160            // Approximate thick segment via AABB inflate of half stroke later;
161            // here use point-pair distance between closest points on edges.
162            line_shape_signed(a, b)
163        }
164        (Shape::Polyline(_), _) | (_, Shape::Polyline(_)) => polyline_shape_signed(a, b),
165        (Shape::PointSet(pts), other) | (other, Shape::PointSet(pts)) => {
166            let aa = a.aabb();
167            let bb = b.aabb();
168            let d = aabb_aabb_signed(aa, bb);
169            let (acx, acy) = aa.center();
170            let (bcx, bcy) = bb.center();
171            let da = if matches!(a, Shape::PointSet(_)) {
172                point_to_polyline_signed(acx, acy, pts)
173            } else {
174                point_to_shape_signed(acx, acy, other)
175            };
176            let db = if matches!(b, Shape::PointSet(_)) {
177                point_to_polyline_signed(bcx, bcy, pts)
178            } else {
179                point_to_shape_signed(bcx, bcy, other)
180            };
181            da.max(db).min(d)
182        }
183    }
184}
185
186fn aabb_aabb_signed(a: Aabb, b: Aabb) -> f64 {
187    let ox = (a.x0.max(b.x0))..(a.x1.min(b.x1));
188    let oy = (a.y0.max(b.y0))..(a.y1.min(b.y1));
189    let overlap_x = ox.end - ox.start;
190    let overlap_y = oy.end - oy.start;
191    if overlap_x > 0.0 && overlap_y > 0.0 {
192        return -overlap_x.min(overlap_y);
193    }
194    let dx = if a.x1 < b.x0 {
195        b.x0 - a.x1
196    } else if b.x1 < a.x0 {
197        a.x0 - b.x1
198    } else {
199        0.0
200    };
201    let dy = if a.y1 < b.y0 {
202        b.y0 - a.y1
203    } else if b.y1 < a.y0 {
204        a.y0 - b.y1
205    } else {
206        0.0
207    };
208    if dx > 0.0 && dy > 0.0 {
209        (dx * dx + dy * dy).sqrt()
210    } else {
211        dx.max(dy)
212    }
213}
214
215fn aabb_circle_signed(a: Aabb, cx: f64, cy: f64, r: f64) -> f64 {
216    let qx = cx.clamp(a.x0, a.x1);
217    let qy = cy.clamp(a.y0, a.y1);
218    let outside = (cx - qx).hypot(cy - qy);
219    if outside > 1e-12 {
220        return outside - r;
221    }
222    // Center inside AABB: penetration = r + dist to nearest edge (negative).
223    let to_edge = (cx - a.x0).min(a.x1 - cx).min(cy - a.y0).min(a.y1 - cy);
224    -(r + to_edge)
225}
226
227fn point_to_shape_signed(px: f64, py: f64, s: &Shape) -> f64 {
228    match s {
229        Shape::Point { x, y } => (px - x).hypot(py - y),
230        Shape::Circle { cx, cy, r } => (px - cx).hypot(py - cy) - r,
231        Shape::Aabb(a) => {
232            let qx = px.clamp(a.x0, a.x1);
233            let qy = py.clamp(a.y0, a.y1);
234            let outside = (px - qx).hypot(py - qy);
235            if outside > 1e-12 {
236                outside
237            } else {
238                let to_edge = (px - a.x0).min(a.x1 - px).min(py - a.y0).min(a.y1 - py);
239                -to_edge
240            }
241        }
242        Shape::Line { x0, y0, x1, y1 } => point_to_seg(px, py, *x0, *y0, *x1, *y1),
243        Shape::PointSet(pts) => point_to_polyline_signed(px, py, pts),
244        Shape::Polyline(pts) => point_to_open_polyline(px, py, pts),
245    }
246}
247
248fn painted_open_pts(pts: &[(f64, f64)]) -> Vec<(f64, f64)> {
249    if pts.len() >= 3 {
250        crate::catmull::sample_open_catmull(pts, 8)
251    } else {
252        pts.to_vec()
253    }
254}
255
256fn paint_open_polyline(s: &Shape) -> Shape {
257    match s {
258        Shape::Polyline(pts) if pts.len() >= 3 => Shape::Polyline(painted_open_pts(pts)),
259        other => other.clone(),
260    }
261}
262
263fn point_to_open_polyline(px: f64, py: f64, pts: &[(f64, f64)]) -> f64 {
264    let pts = painted_open_pts(pts);
265    if pts.len() < 2 {
266        return if let Some(&(x, y)) = pts.first() {
267            (px - x).hypot(py - y)
268        } else {
269            0.0
270        };
271    }
272    let mut best = f64::INFINITY;
273    for w in pts.windows(2) {
274        best = best.min(point_to_seg(px, py, w[0].0, w[0].1, w[1].0, w[1].1));
275    }
276    best
277}
278
279fn shape_segments(s: &Shape) -> Vec<(f64, f64, f64, f64)> {
280    match s {
281        Shape::Line { x0, y0, x1, y1 } => vec![(*x0, *y0, *x1, *y1)],
282        Shape::Polyline(pts) if pts.len() >= 2 => pts
283            .windows(2)
284            .map(|w| (w[0].0, w[0].1, w[1].0, w[1].1))
285            .collect(),
286        _ => Vec::new(),
287    }
288}
289
290fn polyline_shape_signed(a: &Shape, b: &Shape) -> f64 {
291    let pa = paint_open_polyline(a);
292    let pb = paint_open_polyline(b);
293    let segs_a = shape_segments(&pa);
294    let segs_b = shape_segments(&pb);
295    if !segs_a.is_empty() && !segs_b.is_empty() {
296        let mut best = f64::INFINITY;
297        for &(ax0, ay0, ax1, ay1) in &segs_a {
298            for &(bx0, by0, bx1, by1) in &segs_b {
299                best = best.min(seg_seg_dist(ax0, ay0, ax1, ay1, bx0, by0, bx1, by1));
300            }
301        }
302        return best;
303    }
304    let (poly, other) = if matches!(pa, Shape::Polyline(_)) {
305        (&pa, &pb)
306    } else {
307        (&pb, &pa)
308    };
309    let mut best = f64::INFINITY;
310    for &(x0, y0, x1, y1) in &shape_segments(poly) {
311        best = best.min(line_shape_signed(&Shape::Line { x0, y0, x1, y1 }, other));
312    }
313    if best.is_finite() {
314        best
315    } else {
316        aabb_aabb_signed(pa.aabb(), pb.aabb())
317    }
318}
319
320/// Cosine of 25° — nearly-parallel segment pair for [`HardConstraint::ParallelClear`].
321const PARALLEL_DOT: f64 = 0.906307787;
322
323fn unit_or_zero(dx: f64, dy: f64) -> (f64, f64) {
324    let l = dx.hypot(dy);
325    if l < 1e-12 {
326        (0.0, 0.0)
327    } else {
328        (dx / l, dy / l)
329    }
330}
331
332fn proper_seg_intersect(
333    ax0: f64,
334    ay0: f64,
335    ax1: f64,
336    ay1: f64,
337    bx0: f64,
338    by0: f64,
339    bx1: f64,
340    by1: f64,
341) -> bool {
342    let orient = |px: f64, py: f64, qx: f64, qy: f64, rx: f64, ry: f64| {
343        (qx - px) * (ry - py) - (qy - py) * (rx - px)
344    };
345    let o1 = orient(ax0, ay0, ax1, ay1, bx0, by0);
346    let o2 = orient(ax0, ay0, ax1, ay1, bx1, by1);
347    let o3 = orient(bx0, by0, bx1, by1, ax0, ay0);
348    let o4 = orient(bx0, by0, bx1, by1, ax1, ay1);
349    o1 * o2 < -1e-12 && o3 * o4 < -1e-12
350}
351
352pub(crate) fn shapes_properly_cross(a: &Shape, b: &Shape) -> bool {
353    poly_cross_count(a, b) > 0
354}
355
356fn poly_cross_count(a: &Shape, b: &Shape) -> usize {
357    let mut n = 0usize;
358    for &(ax0, ay0, ax1, ay1) in &shape_segments(a) {
359        for &(bx0, by0, bx1, by1) in &shape_segments(b) {
360            if proper_seg_intersect(ax0, ay0, ax1, ay1, bx0, by0, bx1, by1) {
361                n += 1;
362            }
363        }
364    }
365    n
366}
367
368fn interval_overlap(a0: f64, a1: f64, b0: f64, b1: f64) -> bool {
369    let (alo, ahi) = if a0 <= a1 { (a0, a1) } else { (a1, a0) };
370    let (blo, bhi) = if b0 <= b1 { (b0, b1) } else { (b1, b0) };
371    alo < bhi - 1e-9 && blo < ahi - 1e-9
372}
373
374fn parallel_clear_g(a: &Shape, b: &Shape, clash_dist: f64) -> f64 {
375    let mut worst: f64 = 0.0;
376    let mut any = false;
377    for &(ax0, ay0, ax1, ay1) in &shape_segments(a) {
378        let (ux, uy) = unit_or_zero(ax1 - ax0, ay1 - ay0);
379        if ux == 0.0 && uy == 0.0 {
380            continue;
381        }
382        for &(bx0, by0, bx1, by1) in &shape_segments(b) {
383            let (vx, vy) = unit_or_zero(bx1 - bx0, by1 - by0);
384            if vx == 0.0 && vy == 0.0 {
385                continue;
386            }
387            if (ux * vx + uy * vy).abs() < PARALLEL_DOT {
388                continue;
389            }
390            let pa0 = ax0 * ux + ay0 * uy;
391            let pa1 = ax1 * ux + ay1 * uy;
392            let pb0 = bx0 * ux + by0 * uy;
393            let pb1 = bx1 * ux + by1 * uy;
394            if !interval_overlap(pa0, pa1, pb0, pb1) {
395                continue;
396            }
397            any = true;
398            let d = ((bx0 - ax0) * (-uy) + (by0 - ay0) * ux).abs();
399            worst = worst.max(clash_dist - d);
400        }
401    }
402    if any {
403        worst
404    } else {
405        0.0
406    }
407}
408
409fn point_to_seg(px: f64, py: f64, x0: f64, y0: f64, x1: f64, y1: f64) -> f64 {
410    let dx = x1 - x0;
411    let dy = y1 - y0;
412    let len2 = dx * dx + dy * dy;
413    if len2 < 1e-18 {
414        return (px - x0).hypot(py - y0);
415    }
416    let t = ((px - x0) * dx + (py - y0) * dy) / len2;
417    let t = t.clamp(0.0, 1.0);
418    (px - (x0 + t * dx)).hypot(py - (y0 + t * dy))
419}
420
421/// Signed distance to closed polyline: negative inside (even-odd / winding).
422fn point_to_polyline_signed(px: f64, py: f64, pts: &[(f64, f64)]) -> f64 {
423    if pts.len() < 2 {
424        return if let Some(&(x, y)) = pts.first() {
425            (px - x).hypot(py - y)
426        } else {
427            0.0
428        };
429    }
430    let mut best = f64::INFINITY;
431    let n = pts.len();
432    for i in 0..n {
433        let (x0, y0) = pts[i];
434        let (x1, y1) = pts[(i + 1) % n];
435        best = best.min(point_to_seg(px, py, x0, y0, x1, y1));
436    }
437    if point_in_poly(px, py, pts) {
438        -best
439    } else {
440        best
441    }
442}
443
444fn point_in_poly(px: f64, py: f64, pts: &[(f64, f64)]) -> bool {
445    let mut inside = false;
446    let n = pts.len();
447    if n < 3 {
448        return false;
449    }
450    let mut j = n - 1;
451    for i in 0..n {
452        let (xi, yi) = pts[i];
453        let (xj, yj) = pts[j];
454        if ((yi > py) != (yj > py)) && (px < (xj - xi) * (py - yi) / (yj - yi + 1e-18) + xi) {
455            inside = !inside;
456        }
457        j = i;
458    }
459    inside
460}
461
462fn line_shape_signed(a: &Shape, b: &Shape) -> f64 {
463    match (a, b) {
464        (
465            Shape::Line {
466                x0: ax0,
467                y0: ay0,
468                x1: ax1,
469                y1: ay1,
470            },
471            Shape::Line {
472                x0: bx0,
473                y0: by0,
474                x1: bx1,
475                y1: by1,
476            },
477        ) => seg_seg_dist(*ax0, *ay0, *ax1, *ay1, *bx0, *by0, *bx1, *by1),
478        // AABB vs bond: endpoints alone miss a segment that *crosses* the box.
479        // Subtract half stroke so Outside matches painted bond ink width.
480        (Shape::Line { x0, y0, x1, y1 }, Shape::Aabb(box_))
481        | (Shape::Aabb(box_), Shape::Line { x0, y0, x1, y1 }) => {
482            seg_aabb_signed(*x0, *y0, *x1, *y1, *box_) - bond_half_stroke()
483        }
484        (Shape::Line { x0, y0, x1, y1 }, Shape::Circle { cx, cy, r })
485        | (Shape::Circle { cx, cy, r }, Shape::Line { x0, y0, x1, y1 }) => {
486            point_to_seg(*cx, *cy, *x0, *y0, *x1, *y1) - *r - bond_half_stroke()
487        }
488        (Shape::Line { x0, y0, x1, y1 }, other) | (other, Shape::Line { x0, y0, x1, y1 }) => {
489            // PointSet / residual: sample the segment against the other shape.
490            let n = 12;
491            let mut best = f64::INFINITY;
492            for i in 0..=n {
493                let t = i as f64 / n as f64;
494                let px = x0 + t * (x1 - x0);
495                let py = y0 + t * (y1 - y0);
496                best = best.min(point_to_shape_signed(px, py, other));
497            }
498            best
499        }
500        _ => aabb_aabb_signed(a.aabb(), b.aabb()),
501    }
502}
503
504fn bond_half_stroke() -> f64 {
505    STROKE_PX.max(0.8) * 0.5
506}
507
508/// Signed distance segment ↔ AABB. Negative when the segment crosses the box
509/// (endpoint-only distance would falsely stay positive).
510fn seg_aabb_signed(x0: f64, y0: f64, x1: f64, y1: f64, a: Aabb) -> f64 {
511    let n = 16;
512    let mut best_out = f64::INFINITY;
513    let mut best_pen: f64 = 0.0;
514    let mut any_in = false;
515    for i in 0..=n {
516        let t = i as f64 / n as f64;
517        let px = x0 + t * (x1 - x0);
518        let py = y0 + t * (y1 - y0);
519        let d = point_to_shape_signed(px, py, &Shape::Aabb(a));
520        if d < 0.0 {
521            any_in = true;
522            best_pen = best_pen.max(-d);
523        } else {
524            best_out = best_out.min(d);
525        }
526    }
527    // Also AABB corners → segment (tight exterior when parallel to an edge).
528    for &(cx, cy) in &[(a.x0, a.y0), (a.x1, a.y0), (a.x1, a.y1), (a.x0, a.y1)] {
529        let d = point_to_seg(cx, cy, x0, y0, x1, y1);
530        // Corner outside the segment proximity still counts as exterior gap.
531        if !any_in {
532            best_out = best_out.min(d);
533        }
534    }
535    if any_in {
536        -best_pen
537    } else {
538        best_out
539    }
540}
541
542#[allow(clippy::too_many_arguments)]
543fn seg_seg_dist(
544    ax0: f64,
545    ay0: f64,
546    ax1: f64,
547    ay1: f64,
548    bx0: f64,
549    by0: f64,
550    bx1: f64,
551    by1: f64,
552) -> f64 {
553    point_to_seg(ax0, ay0, bx0, by0, bx1, by1)
554        .min(point_to_seg(ax1, ay1, bx0, by0, bx1, by1))
555        .min(point_to_seg(bx0, by0, ax0, ay0, ax1, ay1))
556        .min(point_to_seg(bx1, by1, ax0, ay0, ax1, ay1))
557}
558
559/// Soft constraint forms emitted by type kits.
560#[derive(Debug, Clone)]
561pub enum Constraint {
562    /// `a` should stay outside `b` by at least `clash_dist` (edge gap).
563    Outside {
564        a: NodeId,
565        b: NodeId,
566        clash_dist: f64,
567        strength: f64,
568    },
569    /// `a` should stay inside `b` by at least `pad`. Energy is `strength * g⁺²`
570    /// using the same residual as [`HardConstraint::Inside`].
571    Inside {
572        a: NodeId,
573        b: NodeId,
574        pad: f64,
575        strength: f64,
576    },
577    MinGap {
578        a: NodeId,
579        b: NodeId,
580        dist: f64,
581        strength: f64,
582    },
583    PreferSide {
584        a: NodeId,
585        b: NodeId,
586        side: Side,
587        strength: f64,
588        /// Extra spring along the edge, as a fraction of `strength`
589        /// (Left/Right → match `b`'s y; Above/Below → match x). `0` is hinge
590        /// only — the solver does not infer this from `b`'s shape.
591        align_along: f64,
592    },
593    PointStandoff {
594        tip: NodeId,
595        target: NodeId,
596        dist: f64,
597        strength: f64,
598    },
599    // Glyph / bond Halo is paint-only (shape + buffer after placement) — never
600    // a layout constraint. See `chrome_paint::halo_for_markup`.
601    MinimizeDist {
602        a: NodeId,
603        b: NodeId,
604        opt_dist: f64,
605        strength: f64,
606    },
607    /// Spring the object's center (or point) to a placement `(x, y)`.
608    ///
609    /// This is the preferred paint position (centered caption, side hug, callout
610    /// standoff, atom-label seed). Clash terms can spend this energy to move
611    /// off an obstacle; with a clear field the minimum is this pose.
612    PreferPose {
613        a: NodeId,
614        x: f64,
615        y: f64,
616        strength: f64,
617    },
618    /// Soft energy when two open polylines / lines have a proper (transverse)
619    /// intersection. Kits that should not uncross an existing X simply omit
620    /// this row for that pair.
621    PolyCross { a: NodeId, b: NodeId, strength: f64 },
622    /// `b` should sit on the segment `a → c` (squared perp distance, plus
623    /// hinges if `b` is behind `a` or past `c`). Scheme arrows use this so
624    /// the shaft keeps its seed orientation while the endpoint extends
625    /// toward a mol centroid without crossing to the far side.
626    Collinear {
627        a: NodeId,
628        b: NodeId,
629        c: NodeId,
630        strength: f64,
631    },
632    /// Squared perpendicular distance from `p` to the infinite line `a → b`.
633    /// Unlike [`Constraint::Collinear`], does not hinge on the segment parameter.
634    RayThrough {
635        a: NodeId,
636        b: NodeId,
637        p: NodeId,
638        strength: f64,
639    },
640    /// `a.rot` should match the local tangent of `b` (mod 180°: lines have no
641    /// direction). Extra DOF: [`LayoutNode::rot`] is packed after `(tx, ty)`
642    /// only for nodes that appear as `a` here. Kits flip upside-down text
643    /// 180° after the solve.
644    Parallel { a: NodeId, b: NodeId, strength: f64 },
645    /// Spring `a`'s anchor to the live midpoint of `b` (arc-length mid of a
646    /// painted open polyline; otherwise the shape center).
647    Midpoint { a: NodeId, b: NodeId, strength: f64 },
648}
649
650/// No-overlap (Outside). Strongest hard group.
651pub const LAGRANGIAN_CLEAR: u8 = 0;
652/// Association ceiling (MaxDist). After clearance, before containment.
653pub const LAGRANGIAN_TETHER: u8 = 1;
654/// Stay inside a hull / cover. Weakest of the three — cannot re-introduce overlap.
655pub const LAGRANGIAN_CONTAIN: u8 = 2;
656
657/// Inequality constraints `g(x) ≤ 0` enforced via augmented Lagrangian.
658///
659/// Soft [`Constraint`] hinges can leave residual overlap when PreferPose /
660/// PreferSide fight them. Hard rows here get Powell–Hestenes–Rockafellar
661/// multipliers so clearance, tether, and contain converge to feasibility.
662/// The `lagrangian` field groups rows: lower is stronger —
663/// [`LAGRANGIAN_CLEAR`], then [`LAGRANGIAN_TETHER`], then [`LAGRANGIAN_CONTAIN`].
664#[derive(Debug, Clone)]
665pub enum HardConstraint {
666    /// Require `edge_signed(a,b) ≥ clash_dist` (`g = clash_dist - d`).
667    Outside {
668        a: NodeId,
669        b: NodeId,
670        clash_dist: f64,
671        /// Lower is stronger. Clear (0) then tether (1) then contain (2).
672        lagrangian: u8,
673    },
674    /// Require `a` inside `b` by at least `pad` (`g` = protrusion / shallow depth).
675    ///
676    /// Kits put this on [`LAGRANGIAN_CONTAIN`] so snug / keep-off / tether can
677    /// finish first; a shared PHR with PreferPose used to pin inside labels.
678    Inside {
679        a: NodeId,
680        b: NodeId,
681        pad: f64,
682        lagrangian: u8,
683    },
684    /// Require `edge_signed(a,b) ≤ dist` (`g = d - dist`). Overlap (`d < 0`) is fine.
685    ///
686    /// This is a **closest-point** tether: some part of `a` must lie within
687    /// `dist` of `b` (the far side of a long label may stick out). Atom labels
688    /// use it so bond-clear AL cannot fling the label across the molecule.
689    MaxDist {
690        a: NodeId,
691        b: NodeId,
692        dist: f64,
693        lagrangian: u8,
694    },
695    /// Nearly-parallel overlapping segments must stay `clash_dist` apart
696    /// (`g = clash - d_perp`). Transverse crossings do not activate.
697    ParallelClear {
698        a: NodeId,
699        b: NodeId,
700        clash_dist: f64,
701        lagrangian: u8,
702    },
703}
704
705fn hard_lagrangian(h: &HardConstraint) -> u8 {
706    match h {
707        HardConstraint::Outside { lagrangian, .. }
708        | HardConstraint::Inside { lagrangian, .. }
709        | HardConstraint::MaxDist { lagrangian, .. }
710        | HardConstraint::ParallelClear { lagrangian, .. } => *lagrangian,
711    }
712}
713
714/// How hard the placement well pulls, relative to clash hinges (strength ~3–8).
715const POSE_STRENGTH: f64 = 0.35;
716
717/// Hard MaxDist ceiling for **index / mapno** numbers (~0.3 CC-bond).
718///
719/// Closest-point: some part of the glyph must reach within this gap of home.
720pub const ATOM_NUMBER_TETHER_PX: f64 = 0.3 * BOND_PX;
721
722/// Hard MaxDist ceiling for custom **atom_label** text (~0.5 CC-bond).
723///
724/// Longer than [`ATOM_NUMBER_TETHER_PX`] so words like “ortho” can clear ink
725/// while still staying associated with the atom.
726pub const ATOM_TEXT_TETHER_PX: f64 = 0.5 * BOND_PX;
727
728fn shape_anchor(shape: &Shape) -> (f64, f64) {
729    match shape {
730        Shape::Point { x, y } => (*x, *y),
731        other => other.aabb().center(),
732    }
733}
734
735fn push_placement_pose(constraints: &mut Vec<Constraint>, id: &str, rest: &Shape) {
736    let (x, y) = shape_anchor(rest);
737    constraints.push(Constraint::PreferPose {
738        a: id.to_string(),
739        x,
740        y,
741        strength: POSE_STRENGTH,
742    });
743}
744
745/// Hard [`HardConstraint::Outside`] vs every primitive leaf under `under`.
746///
747/// Kits emit these rows. The solver does not auto-clash all pairs.
748/// Half stroke width is already in edge distance. Never clears `a` vs itself.
749pub fn push_clear_leaves(
750    world: &LayoutWorld,
751    hard: &mut Vec<HardConstraint>,
752    a: &str,
753    under: &str,
754    clash_dist: f64,
755) {
756    push_clear_leaves_where(world, hard, a, under, clash_dist, |_, _| true);
757}
758
759/// Like [`push_clear_leaves`], with a keep filter on each candidate leaf.
760pub fn push_clear_leaves_where(
761    world: &LayoutWorld,
762    hard: &mut Vec<HardConstraint>,
763    a: &str,
764    under: &str,
765    clash_dist: f64,
766    keep: impl Fn(&str, &LayoutNode) -> bool,
767) {
768    let mut stack = vec![under.to_string()];
769    while let Some(id) = stack.pop() {
770        let Some(n) = world.get(&id) else {
771            continue;
772        };
773        stack.extend(n.children.iter().cloned());
774        if id == a {
775            continue;
776        }
777        if n.children.is_empty() && primitive_leaf(&n.world_shape()) && keep(&id, n) {
778            hard.push(HardConstraint::Outside {
779                a: a.to_string(),
780                b: id,
781                clash_dist,
782                lagrangian: LAGRANGIAN_CLEAR,
783            });
784        }
785    }
786}
787
788fn stamps_from_shape(s: &Shape) -> Vec<InkStamp> {
789    match s {
790        Shape::Point { x, y } => vec![InkStamp::Point { x: *x, y: *y }],
791        Shape::Circle { cx, cy, r } => vec![InkStamp::Circle {
792            cx: *cx,
793            cy: *cy,
794            r: *r,
795        }],
796        Shape::Aabb(a) => {
797            if a.width() <= 1e-9 && a.height() <= 1e-9 {
798                Vec::new()
799            } else {
800                vec![InkStamp::Aabb(*a)]
801            }
802        }
803        Shape::Line { x0, y0, x1, y1 } => vec![InkStamp::Line {
804            x0: *x0,
805            y0: *y0,
806            x1: *x1,
807            y1: *y1,
808            r: bond_half_stroke().max(1.0),
809        }],
810        Shape::Polyline(pts) => polyline_stamps(pts, false),
811        Shape::PointSet(pts) => polyline_stamps(pts, true),
812    }
813}
814
815fn polyline_stamps(pts: &[(f64, f64)], closed: bool) -> Vec<InkStamp> {
816    if pts.len() < 2 {
817        return Vec::new();
818    }
819    let r = bond_half_stroke().max(1.0);
820    let mut out = Vec::with_capacity(pts.len());
821    for w in pts.windows(2) {
822        out.push(InkStamp::Line {
823            x0: w[0].0,
824            y0: w[0].1,
825            x1: w[1].0,
826            y1: w[1].1,
827            r,
828        });
829    }
830    if closed && pts.len() >= 3 {
831        let a = pts[pts.len() - 1];
832        let b = pts[0];
833        if (a.0 - b.0).hypot(a.1 - b.1) > 1e-9 {
834            out.push(InkStamp::Line {
835                x0: a.0,
836                y0: a.1,
837                x1: b.0,
838                y1: b.1,
839                r,
840            });
841        }
842    }
843    out
844}
845
846/// True for painted geometry. Empty container AABBs (`0×0` groups) are not
847/// obstacles — `install_chem_under` always creates `bonds` / `atoms` folders.
848fn primitive_leaf(shape: &Shape) -> bool {
849    match shape {
850        Shape::Point { .. } | Shape::Circle { .. } | Shape::Line { .. } => true,
851        Shape::PointSet(pts) | Shape::Polyline(pts) => pts.len() >= 2,
852        Shape::Aabb(a) => a.width() > 1e-9 || a.height() > 1e-9,
853    }
854}
855
856/// Mol-kit wrapper: hard Outside vs every bond line under `mol/chem/bonds`.
857fn push_clear_bonds(world: &LayoutWorld, hard: &mut Vec<HardConstraint>, a: &str, clash_dist: f64) {
858    push_clear_leaves(world, hard, a, "mol/chem/bonds", clash_dist);
859}
860
861/// Object kind → which kit installed it (debug / filtering).
862#[derive(Debug, Clone, Copy, PartialEq, Eq)]
863pub enum ObjectType {
864    Mol,
865    Chem,
866    Bonds,
867    Atom,
868    Coord,
869    AtomText,
870    Shade,
871    Annotations,
872    Captions,
873    Caption,
874    Regions,
875    Region,
876    RegionHull,
877    RegionText,
878    Callouts,
879    CalloutLabel,
880    CalloutTip,
881    CalloutRoute,
882    AtomNumbers,
883    AtomNumber,
884    AtomLabels,
885    AtomLabel,
886    Group,
887    Scheme,
888    Edge,
889    EdgePoint,
890    EdgeLabel,
891}
892
893/// One node in the layout tree.
894#[derive(Debug, Clone)]
895pub struct LayoutNode {
896    pub id: NodeId,
897    pub parent: Option<NodeId>,
898    pub children: Vec<NodeId>,
899    pub object_type: ObjectType,
900    pub shape: Shape,
901    /// When true, shape is an obstacle / target only (not a DOF).
902    pub fixed: bool,
903    /// Translation DOF for movable leaves (origin offset applied to `rest`).
904    pub tx: f64,
905    pub ty: f64,
906    /// Rotation DOF in degrees (labels). Packed only when a [`Constraint::Parallel`]
907    /// targets this node; geometry stays unrotated (disks / points).
908    pub rot: f64,
909    /// Rest pose (before tx/ty). For fixed nodes, this is the world pose.
910    pub rest: Shape,
911    /// Painted ink this object owns (glyphs, regions, annotations) in world space.
912    pub ink: Vec<Shape>,
913    /// Raster of [`Self::ink`] ∪ descendant primitive leaves. Built on demand.
914    clash_grid: RefCell<Option<ClashGrid>>,
915}
916
917impl LayoutNode {
918    pub fn world_shape(&self) -> Shape {
919        if self.fixed {
920            self.rest.clone()
921        } else {
922            self.rest.translated(self.tx, self.ty)
923        }
924    }
925}
926
927/// Layout world rooted at an arbitrary document node.
928#[derive(Debug, Clone)]
929pub struct LayoutWorld {
930    pub nodes: HashMap<NodeId, LayoutNode>,
931    pub root: NodeId,
932}
933
934impl LayoutWorld {
935    pub fn rooted(root_id: impl Into<NodeId>, object_type: ObjectType) -> Self {
936        let root = root_id.into();
937        let mut nodes = HashMap::new();
938        nodes.insert(
939            root.clone(),
940            LayoutNode {
941                id: root.clone(),
942                parent: None,
943                children: Vec::new(),
944                object_type,
945                shape: Shape::Aabb(Aabb::new(0.0, 0.0, 0.0, 0.0)),
946                fixed: true,
947                tx: 0.0,
948                ty: 0.0,
949                rot: 0.0,
950                rest: Shape::Aabb(Aabb::new(0.0, 0.0, 0.0, 0.0)),
951                ink: Vec::new(),
952                clash_grid: RefCell::new(None),
953            },
954        );
955        Self { nodes, root }
956    }
957
958    pub fn new(root_id: impl Into<NodeId>) -> Self {
959        Self::rooted(root_id, ObjectType::Mol)
960    }
961
962    pub fn insert(
963        &mut self,
964        id: impl Into<NodeId>,
965        parent: impl Into<NodeId>,
966        object_type: ObjectType,
967        shape: Shape,
968        fixed: bool,
969    ) -> NodeId {
970        let id = id.into();
971        let parent = parent.into();
972        if let Some(p) = self.nodes.get_mut(&parent) {
973            if !p.children.iter().any(|c| c == &id) {
974                p.children.push(id.clone());
975            }
976        }
977        self.nodes.insert(
978            id.clone(),
979            LayoutNode {
980                id: id.clone(),
981                parent: Some(parent),
982                children: Vec::new(),
983                object_type,
984                shape: shape.clone(),
985                fixed,
986                tx: 0.0,
987                ty: 0.0,
988                rot: 0.0,
989                rest: shape,
990                ink: Vec::new(),
991                clash_grid: RefCell::new(None),
992            },
993        );
994        id
995    }
996
997    pub fn get(&self, id: &str) -> Option<&LayoutNode> {
998        self.nodes.get(id)
999    }
1000
1001    pub fn get_mut(&mut self, id: &str) -> Option<&mut LayoutNode> {
1002        self.nodes.get_mut(id)
1003    }
1004
1005    /// Union AABB of a node and all descendants (world poses).
1006    pub fn subtree_aabb(&self, id: &str) -> Option<Aabb> {
1007        let node = self.nodes.get(id)?;
1008        let mut box_ = node.world_shape().aabb();
1009        let mut stack = node.children.clone();
1010        while let Some(cid) = stack.pop() {
1011            if let Some(c) = self.nodes.get(&cid) {
1012                let a = c.world_shape().aabb();
1013                box_ = Aabb::new(
1014                    box_.x0.min(a.x0),
1015                    box_.y0.min(a.y0),
1016                    box_.x1.max(a.x1),
1017                    box_.y1.max(a.y1),
1018                );
1019                stack.extend(c.children.iter().cloned());
1020            }
1021        }
1022        Some(box_)
1023    }
1024
1025    /// Refresh group `rest`/`shape` AABB unions from children (fixed groups).
1026    pub fn recompute_group_aabbs(&mut self) {
1027        // Post-order: process leaves depth first via stack of (id, visited).
1028        let ids: Vec<_> = self.nodes.keys().cloned().collect();
1029        for id in ids {
1030            let Some(node) = self.nodes.get(&id) else {
1031                continue;
1032            };
1033            if node.children.is_empty() || !node.fixed {
1034                continue;
1035            }
1036            if matches!(node.rest, Shape::Polyline(_)) {
1037                continue;
1038            }
1039            if let Some(a) = self.subtree_aabb(&id) {
1040                if let Some(n) = self.nodes.get_mut(&id) {
1041                    n.rest = Shape::Aabb(a);
1042                    n.shape = Shape::Aabb(a);
1043                }
1044            }
1045        }
1046    }
1047
1048    pub fn set_pose(&mut self, id: &str, tx: f64, ty: f64) {
1049        if let Some(n) = self.nodes.get_mut(id) {
1050            if !n.fixed {
1051                n.tx = tx;
1052                n.ty = ty;
1053            }
1054        }
1055        self.invalidate_clash(id);
1056    }
1057
1058    /// Bake the live pose into `rest` and mark the node immovable.
1059    pub fn freeze(&mut self, id: &str) {
1060        let pose = match self.get(id) {
1061            Some(n) if !n.fixed => n.world_shape(),
1062            _ => return,
1063        };
1064        if let Some(n) = self.nodes.get_mut(id) {
1065            n.rest = pose.clone();
1066            n.shape = pose;
1067            n.tx = 0.0;
1068            n.ty = 0.0;
1069            n.fixed = true;
1070        }
1071        self.invalidate_clash(id);
1072    }
1073
1074    pub fn set_rot(&mut self, id: &str, rot: f64) {
1075        if let Some(n) = self.nodes.get_mut(id) {
1076            if !n.fixed {
1077                n.rot = rot;
1078            }
1079        }
1080    }
1081
1082    /// Extra painted ink on `id` (glyphs, regions, annotations). Invalidates
1083    /// that node's cached clash grid.
1084    pub fn add_ink(&mut self, id: &str, shapes: impl IntoIterator<Item = Shape>) {
1085        if let Some(n) = self.nodes.get_mut(id) {
1086            n.ink.extend(shapes);
1087        }
1088        self.invalidate_clash(id);
1089    }
1090
1091    fn invalidate_clash(&self, id: &str) {
1092        let mut cur = Some(id.to_string());
1093        while let Some(cid) = cur {
1094            let Some(n) = self.nodes.get(&cid) else {
1095                break;
1096            };
1097            n.clash_grid.borrow_mut().take();
1098            cur = n.parent.clone();
1099        }
1100    }
1101
1102    /// Signed distance to the object's ink grid (negative inside). Builds and
1103    /// caches the raster on first call.
1104    pub fn ink_signed(&self, id: &str, x: f64, y: f64) -> Option<f64> {
1105        self.ensure_clash_grid(id)?;
1106        let n = self.nodes.get(id)?;
1107        n.clash_grid.borrow().as_ref().map(|g| g.signed_at(x, y))
1108    }
1109
1110    fn ensure_clash_grid(&self, id: &str) -> Option<()> {
1111        let n = self.nodes.get(id)?;
1112        if n.clash_grid.borrow().is_some() {
1113            return Some(());
1114        }
1115        // Groups without owned ink keep AABB/leaf clash; Chem (and any node
1116        // that called add_ink) rasterizes descendant primitives + owned ink.
1117        if n.ink.is_empty() && n.object_type != ObjectType::Chem {
1118            return None;
1119        }
1120        let stamps = self.collect_ink_stamps(id);
1121        if stamps.is_empty() {
1122            return None;
1123        }
1124        *n.clash_grid.borrow_mut() = ClashGrid::from_stamps(&stamps);
1125        n.clash_grid.borrow().as_ref().map(|_| ())
1126    }
1127
1128    fn collect_ink_stamps(&self, id: &str) -> Vec<InkStamp> {
1129        let Some(n) = self.nodes.get(id) else {
1130            return Vec::new();
1131        };
1132        let mut stamps = Vec::new();
1133        for s in &n.ink {
1134            stamps.extend(stamps_from_shape(s));
1135        }
1136        let mut stack = n.children.clone();
1137        while let Some(cid) = stack.pop() {
1138            let Some(c) = self.nodes.get(&cid) else {
1139                continue;
1140            };
1141            stack.extend(c.children.iter().cloned());
1142            for s in &c.ink {
1143                stamps.extend(stamps_from_shape(s));
1144            }
1145            if c.children.is_empty() {
1146                let s = c.world_shape();
1147                if primitive_leaf(&s) {
1148                    stamps.extend(stamps_from_shape(&s));
1149                }
1150            }
1151        }
1152        stamps
1153    }
1154
1155    pub fn movable_ids(&self) -> Vec<NodeId> {
1156        self.nodes
1157            .iter()
1158            .filter(|(_, n)| !n.fixed)
1159            .map(|(id, _)| id.clone())
1160            .collect()
1161    }
1162
1163    /// Flatten movable (tx, ty) into a parameter vector (stable sorted by id).
1164    pub fn params(&self) -> (Vec<NodeId>, Vec<f64>) {
1165        let mut ids = self.movable_ids();
1166        ids.sort();
1167        let mut p = Vec::with_capacity(ids.len() * 2);
1168        for id in &ids {
1169            let n = &self.nodes[id];
1170            p.push(n.tx);
1171            p.push(n.ty);
1172        }
1173        (ids, p)
1174    }
1175
1176    pub fn apply_params(&mut self, ids: &[NodeId], p: &[f64]) {
1177        for (i, id) in ids.iter().enumerate() {
1178            let tx = p.get(i * 2).copied().unwrap_or(0.0);
1179            let ty = p.get(i * 2 + 1).copied().unwrap_or(0.0);
1180            self.set_pose(id, tx, ty);
1181        }
1182    }
1183
1184    /// Live geometry: polyline groups assemble child [`Shape::Point`]s in order.
1185    ///
1186    /// Those vertices are the ELK endpoints / routing points (the DOF). Paint
1187    /// and clash sample a Catmull–Rom through them; they are not densified here.
1188    pub fn eval_shape(&self, id: &str) -> Option<Shape> {
1189        let n = self.nodes.get(id)?;
1190        if matches!(&n.rest, Shape::Polyline(_)) {
1191            let mut pts = Vec::new();
1192            for cid in &n.children {
1193                let Some(c) = self.nodes.get(cid) else {
1194                    continue;
1195                };
1196                if let Shape::Point { x, y } = c.world_shape() {
1197                    pts.push((x, y));
1198                }
1199            }
1200            if pts.len() >= 2 {
1201                return Some(Shape::Polyline(pts));
1202            }
1203        }
1204        Some(n.world_shape())
1205    }
1206
1207    pub fn control_points_movable(&self) -> Vec<(f64, f64)> {
1208        let mut pts = Vec::new();
1209        for n in self.nodes.values() {
1210            if n.fixed {
1211                continue;
1212            }
1213            pts.extend(n.world_shape().control_points());
1214        }
1215        pts
1216    }
1217}
1218
1219fn pair_eval(world: &LayoutWorld, a: &str, b: &str) -> Option<(Shape, Shape)> {
1220    Some((world.eval_shape(a)?, world.eval_shape(b)?))
1221}
1222
1223fn hinge_below(x: f64, lo: f64) -> f64 {
1224    let v = lo - x;
1225    if v > 0.0 {
1226        v * v
1227    } else {
1228        0.0
1229    }
1230}
1231
1232fn spring(d: f64, d_star: f64) -> f64 {
1233    let e = d - d_star;
1234    e * e
1235}
1236
1237/// `b` on segment `a → c`: perp distance plus behind/`past c` hinges (px²).
1238fn collinear_energy(a: (f64, f64), b: (f64, f64), c: (f64, f64), strength: f64) -> f64 {
1239    let vx = c.0 - a.0;
1240    let vy = c.1 - a.1;
1241    let l2 = vx * vx + vy * vy;
1242    if l2 < 1e-18 {
1243        return 0.0;
1244    }
1245    let l = l2.sqrt();
1246    let perp = ((b.0 - a.0) * vy - (b.1 - a.1) * vx) / l;
1247    let t = ((b.0 - a.0) * vx + (b.1 - a.1) * vy) / l2;
1248    let back = if t < 0.0 { t * l } else { 0.0 };
1249    let past = if t > 1.0 { (t - 1.0) * l } else { 0.0 };
1250    strength * (perp * perp + back * back + past * past)
1251}
1252
1253/// `strength * (signed distance from `p` to infinite line `a → b`)²`.
1254fn ray_through_energy(a: (f64, f64), b: (f64, f64), p: (f64, f64), strength: f64) -> f64 {
1255    let vx = b.0 - a.0;
1256    let vy = b.1 - a.1;
1257    let l = vx.hypot(vy);
1258    if l < 1e-9 {
1259        return 0.0;
1260    }
1261    let perp = ((p.0 - a.0) * vy - (p.1 - a.1) * vx) / l;
1262    strength * perp * perp
1263}
1264
1265/// Evaluate soft energy for the current world poses.
1266pub fn energy(
1267    world: &LayoutWorld,
1268    constraints: &[Constraint],
1269    seed: &[(NodeId, f64, f64)],
1270    w_travel: f64,
1271) -> f64 {
1272    let mut e = 0.0;
1273    for c in constraints {
1274        e += constraint_energy(world, c);
1275    }
1276    if w_travel > 0.0 {
1277        for (id, sx, sy) in seed {
1278            if let Some(n) = world.get(id) {
1279                let dx = n.tx - sx;
1280                let dy = n.ty - sy;
1281                e += w_travel * (dx * dx + dy * dy);
1282            }
1283        }
1284    }
1285    e
1286}
1287
1288fn constraint_energy(world: &LayoutWorld, c: &Constraint) -> f64 {
1289    match c {
1290        Constraint::Outside {
1291            a,
1292            b,
1293            clash_dist,
1294            strength,
1295        } => {
1296            let (sa, sb) = match pair_eval(world, a, b) {
1297                Some(p) => p,
1298                None => return 0.0,
1299            };
1300            let d = edge_signed_distance(&sa, &sb);
1301            strength * hinge_below(d, *clash_dist)
1302        }
1303        Constraint::Inside {
1304            a,
1305            b,
1306            pad,
1307            strength,
1308        } => {
1309            let (sa, sb) = match pair_eval(world, a, b) {
1310                Some(p) => p,
1311                None => return 0.0,
1312            };
1313            let g = inside_g(&sa, &sb, *pad);
1314            strength * g.max(0.0) * g.max(0.0)
1315        }
1316        Constraint::MinGap {
1317            a,
1318            b,
1319            dist,
1320            strength,
1321        } => {
1322            let (sa, sb) = match pair_eval(world, a, b) {
1323                Some(p) => p,
1324                None => return 0.0,
1325            };
1326            let d = edge_signed_distance(&sa, &sb);
1327            strength * hinge_below(d, *dist)
1328        }
1329        Constraint::PreferSide {
1330            a,
1331            b,
1332            side,
1333            strength,
1334            align_along,
1335        } => {
1336            let (sa, sb) = match pair_eval(world, a, b) {
1337                Some(p) => p,
1338                None => return 0.0,
1339            };
1340            let (ax, ay) = sa.aabb().center();
1341            let (bx, by) = sb.aabb().center();
1342            let (dx, dy) = (ax - bx, ay - by);
1343            let good = match side {
1344                Side::Right => dx,
1345                Side::Left => -dx,
1346                Side::Below => dy,
1347                Side::Above => -dy,
1348            };
1349            let ortho = match side {
1350                Side::Left | Side::Right => dy,
1351                Side::Above | Side::Below => dx,
1352            };
1353            let along = align_along.max(0.0);
1354            strength * hinge_below(good, 0.0) + along * strength * ortho * ortho
1355        }
1356        Constraint::PointStandoff {
1357            tip,
1358            target,
1359            dist,
1360            strength,
1361        } => {
1362            let (sa, sb) = match (world.get(tip), world.get(target)) {
1363                (Some(na), Some(nb)) => (na.world_shape(), nb.world_shape()),
1364                _ => return 0.0,
1365            };
1366            let (tx, ty) = shape_anchor(&sa);
1367            let (ax, ay) = shape_anchor(&sb);
1368            let d = (tx - ax).hypot(ty - ay);
1369            strength * spring(d, *dist)
1370        }
1371        Constraint::MinimizeDist {
1372            a,
1373            b,
1374            opt_dist,
1375            strength,
1376        } => {
1377            let (sa, sb) = match pair_eval(world, a, b) {
1378                Some(p) => p,
1379                None => return 0.0,
1380            };
1381            let d = edge_signed_distance(&sa, &sb).max(0.0);
1382            strength * spring(d, *opt_dist)
1383        }
1384        Constraint::PreferPose { a, x, y, strength } => {
1385            let Some(s) = world.eval_shape(a) else {
1386                return 0.0;
1387            };
1388            let (cx, cy) = shape_anchor(&s);
1389            let dx = cx - x;
1390            let dy = cy - y;
1391            strength * (dx * dx + dy * dy)
1392        }
1393        Constraint::PolyCross { a, b, strength } => {
1394            let (sa, sb) = match pair_eval(world, a, b) {
1395                Some(p) => p,
1396                None => return 0.0,
1397            };
1398            let n = poly_cross_count(&sa, &sb) as f64;
1399            strength * n * n
1400        }
1401        Constraint::Collinear { a, b, c, strength } => {
1402            let sa = match world.eval_shape(a) {
1403                Some(s) => s,
1404                None => return 0.0,
1405            };
1406            let sb = match world.eval_shape(b) {
1407                Some(s) => s,
1408                None => return 0.0,
1409            };
1410            let sc = match world.eval_shape(c) {
1411                Some(s) => s,
1412                None => return 0.0,
1413            };
1414            collinear_energy(
1415                shape_anchor(&sa),
1416                shape_anchor(&sb),
1417                shape_anchor(&sc),
1418                *strength,
1419            )
1420        }
1421        Constraint::RayThrough { a, b, p, strength } => {
1422            let sa = match world.eval_shape(a) {
1423                Some(s) => s,
1424                None => return 0.0,
1425            };
1426            let sb = match world.eval_shape(b) {
1427                Some(s) => s,
1428                None => return 0.0,
1429            };
1430            let sp = match world.eval_shape(p) {
1431                Some(s) => s,
1432                None => return 0.0,
1433            };
1434            ray_through_energy(
1435                shape_anchor(&sa),
1436                shape_anchor(&sb),
1437                shape_anchor(&sp),
1438                *strength,
1439            )
1440        }
1441        Constraint::Parallel { a, b, strength } => {
1442            let Some(na) = world.get(a) else {
1443                return 0.0;
1444            };
1445            let Some(sb) = world.eval_shape(b) else {
1446                return 0.0;
1447            };
1448            let (x, y) = shape_anchor(&na.world_shape());
1449            let tang = tangent_deg_at(&sb, x, y);
1450            let err = parallel_angle_err(na.rot, tang);
1451            strength * err * err
1452        }
1453        Constraint::Midpoint { a, b, strength } => {
1454            let (sa, sb) = match pair_eval(world, a, b) {
1455                Some(p) => p,
1456                None => return 0.0,
1457            };
1458            let (ax, ay) = shape_anchor(&sa);
1459            let (mx, my) = shape_midpoint(&sb);
1460            let dx = ax - mx;
1461            let dy = ay - my;
1462            strength * (dx * dx + dy * dy)
1463        }
1464    }
1465}
1466
1467/// Smallest angle between two undirected lines (degrees, (−90, 90]).
1468fn parallel_angle_err(rot: f64, tangent: f64) -> f64 {
1469    wrap_readable_deg(rot - tangent)
1470}
1471
1472fn shape_midpoint(shape: &Shape) -> (f64, f64) {
1473    match shape {
1474        Shape::Point { x, y } => (*x, *y),
1475        Shape::Circle { cx, cy, .. } => (*cx, *cy),
1476        Shape::Line { x0, y0, x1, y1 } => ((*x0 + *x1) * 0.5, (*y0 + *y1) * 0.5),
1477        Shape::Aabb(a) => a.center(),
1478        Shape::Polyline(pts) => arc_length_midpoint(&painted_open_pts(pts)),
1479        Shape::PointSet(pts) => {
1480            if pts.is_empty() {
1481                (0.0, 0.0)
1482            } else {
1483                let n = pts.len() as f64;
1484                let sx: f64 = pts.iter().map(|p| p.0).sum();
1485                let sy: f64 = pts.iter().map(|p| p.1).sum();
1486                (sx / n, sy / n)
1487            }
1488        }
1489    }
1490}
1491
1492fn arc_length_midpoint(pts: &[(f64, f64)]) -> (f64, f64) {
1493    if pts.is_empty() {
1494        return (0.0, 0.0);
1495    }
1496    if pts.len() == 1 {
1497        return pts[0];
1498    }
1499    let mut total = 0.0;
1500    let mut lens = vec![0.0; pts.len()];
1501    for i in 1..pts.len() {
1502        total += (pts[i].0 - pts[i - 1].0).hypot(pts[i].1 - pts[i - 1].1);
1503        lens[i] = total;
1504    }
1505    if total < 1e-12 {
1506        return pts[0];
1507    }
1508    let half = total * 0.5;
1509    for i in 1..pts.len() {
1510        if lens[i] + 1e-15 < half {
1511            continue;
1512        }
1513        let seg = lens[i] - lens[i - 1];
1514        let t = if seg < 1e-12 {
1515            0.0
1516        } else {
1517            (half - lens[i - 1]) / seg
1518        };
1519        return (
1520            pts[i - 1].0 + t * (pts[i].0 - pts[i - 1].0),
1521            pts[i - 1].1 + t * (pts[i].1 - pts[i - 1].1),
1522        );
1523    }
1524    pts[pts.len() - 1]
1525}
1526
1527fn wrap_readable_deg(deg: f64) -> f64 {
1528    let mut a = ((deg + 180.0) % 360.0 + 360.0) % 360.0 - 180.0;
1529    if a > 90.0 {
1530        a -= 180.0;
1531    } else if a < -90.0 {
1532        a += 180.0;
1533    }
1534    a
1535}
1536
1537fn tangent_deg_at(shape: &Shape, x: f64, y: f64) -> f64 {
1538    let pts = match shape {
1539        Shape::Polyline(pts) => painted_open_pts(pts),
1540        Shape::Line { x0, y0, x1, y1 } => vec![(*x0, *y0), (*x1, *y1)],
1541        _ => return 0.0,
1542    };
1543    if pts.len() < 2 {
1544        return 0.0;
1545    }
1546    let mut best_i = 1;
1547    let mut best_d = f64::INFINITY;
1548    for i in 1..pts.len() {
1549        let (x0, y0) = pts[i - 1];
1550        let (x1, y1) = pts[i];
1551        let vx = x1 - x0;
1552        let vy = y1 - y0;
1553        let l2 = vx * vx + vy * vy;
1554        let t = if l2 < 1e-12 {
1555            0.0
1556        } else {
1557            ((x - x0) * vx + (y - y0) * vy) / l2
1558        }
1559        .clamp(0.0, 1.0);
1560        let px = x0 + t * vx;
1561        let py = y0 + t * vy;
1562        let d = (x - px).hypot(y - py);
1563        if d < best_d {
1564            best_d = d;
1565            best_i = i;
1566        }
1567    }
1568    let (x0, y0) = pts[best_i - 1];
1569    let (x1, y1) = pts[best_i];
1570    (y1 - y0).atan2(x1 - x0).to_degrees()
1571}
1572
1573fn parallel_rot_ids(constraints: &[Constraint]) -> Vec<NodeId> {
1574    let mut ids = Vec::new();
1575    for c in constraints {
1576        if let Constraint::Parallel { a, .. } = c {
1577            if !ids.contains(a) {
1578                ids.push(a.clone());
1579            }
1580        }
1581    }
1582    ids.sort();
1583    ids
1584}
1585
1586fn pack_solve_params(world: &LayoutWorld, xy_ids: &[NodeId], rot_ids: &[NodeId]) -> Vec<f64> {
1587    let mut p = Vec::with_capacity(xy_ids.len() * 2 + rot_ids.len());
1588    for id in xy_ids {
1589        let n = &world.nodes[id];
1590        p.push(n.tx);
1591        p.push(n.ty);
1592    }
1593    for id in rot_ids {
1594        p.push(world.get(id).map(|n| n.rot).unwrap_or(0.0));
1595    }
1596    p
1597}
1598
1599fn apply_solve_params(world: &mut LayoutWorld, xy_ids: &[NodeId], rot_ids: &[NodeId], p: &[f64]) {
1600    world.apply_params(xy_ids, p);
1601    let base = xy_ids.len() * 2;
1602    for (i, id) in rot_ids.iter().enumerate() {
1603        world.set_rot(id, p.get(base + i).copied().unwrap_or(0.0));
1604    }
1605}
1606
1607/// Solver options (pose-drift termination + augmented Lagrangian).
1608#[derive(Debug, Clone)]
1609pub struct SolveOpts {
1610    pub max_iters: usize,
1611    /// Ring buffer length for control-point drift.
1612    pub drift_window: usize,
1613    /// Stop when max control-point displacement vs window ago `< epsilon_px`.
1614    pub epsilon_px: f64,
1615    pub w_travel: f64,
1616    pub noise: f64,
1617    pub initial_simplex_scale: f64,
1618    /// Outer AL updates of multipliers / penalty weight.
1619    pub al_outer_max: usize,
1620    /// Initial quadratic penalty weight ρ.
1621    pub al_rho0: f64,
1622    /// Multiply ρ when max hard violation stalls.
1623    pub al_rho_grow: f64,
1624    pub al_rho_max: f64,
1625    /// Stop outer loop when max `g⁺` (px) is below this.
1626    pub al_tol: f64,
1627}
1628
1629impl Default for SolveOpts {
1630    fn default() -> Self {
1631        Self {
1632            max_iters: 200,
1633            drift_window: 4,
1634            epsilon_px: 0.75,
1635            w_travel: 0.02,
1636            noise: 0.5,
1637            initial_simplex_scale: 2.0,
1638            al_outer_max: 6,
1639            al_rho0: 8.0,
1640            al_rho_grow: 2.5,
1641            al_rho_max: 2.0e4,
1642            al_tol: 0.25,
1643        }
1644    }
1645}
1646
1647#[derive(Debug, Clone)]
1648pub struct SolveResult {
1649    pub iters: usize,
1650    pub energy: f64,
1651    pub stopped_on_drift: bool,
1652    /// Max hard violation `max(0, g_i)` after the last outer update (0 if no hard).
1653    pub max_hard_violation: f64,
1654}
1655
1656/// Inside residual `g`. Feasible when `g ≤ 0` (`a` inside `b` by `pad`).
1657///
1658/// Shape dispatch lives here (geometry), not as a second energy formula in
1659/// [`constraint_energy`] / [`hard_g`].
1660fn inside_g(sa: &Shape, sb: &Shape, pad: f64) -> f64 {
1661    match (sa, sb) {
1662        (Shape::Aabb(inner), Shape::Aabb(outer)) => {
1663            let left = outer.x0 + pad - inner.x0;
1664            let right = inner.x1 - (outer.x1 - pad);
1665            let top = outer.y0 + pad - inner.y0;
1666            let bot = inner.y1 - (outer.y1 - pad);
1667            left.max(0.0) + right.max(0.0) + top.max(0.0) + bot.max(0.0)
1668        }
1669        (Shape::Point { x, y }, _) => point_to_shape_signed(*x, *y, sb) + pad,
1670        (Shape::Aabb(box_), Shape::PointSet(pts)) => {
1671            let (cx, cy) = box_.center();
1672            point_to_polyline_signed(cx, cy, pts) + pad
1673        }
1674        (Shape::Aabb(box_), Shape::Circle { cx, cy, r }) => {
1675            let mut g = f64::NEG_INFINITY;
1676            for &(px, py) in &[
1677                (box_.x0, box_.y0),
1678                (box_.x1, box_.y0),
1679                (box_.x0, box_.y1),
1680                (box_.x1, box_.y1),
1681            ] {
1682                let d = (px - cx).hypot(py - cy) - (r - pad);
1683                g = g.max(d);
1684            }
1685            g
1686        }
1687        _ => edge_signed_distance(sa, sb) + pad,
1688    }
1689}
1690
1691/// Signed hard residual `g(x)`. Feasible when `g ≤ 0`.
1692pub fn hard_g(world: &LayoutWorld, h: &HardConstraint) -> f64 {
1693    match h {
1694        HardConstraint::Outside {
1695            a, b, clash_dist, ..
1696        } => {
1697            let (sa, sb) = match pair_eval(world, a, b) {
1698                Some(p) => p,
1699                None => return 0.0,
1700            };
1701            clash_dist - edge_signed_distance(&sa, &sb)
1702        }
1703        HardConstraint::Inside { a, b, pad, .. } => {
1704            let (sa, sb) = match pair_eval(world, a, b) {
1705                Some(p) => p,
1706                None => return 0.0,
1707            };
1708            inside_g(&sa, &sb, *pad)
1709        }
1710        HardConstraint::MaxDist { a, b, dist, .. } => {
1711            let (sa, sb) = match pair_eval(world, a, b) {
1712                Some(p) => p,
1713                None => return 0.0,
1714            };
1715            edge_signed_distance(&sa, &sb) - dist
1716        }
1717        HardConstraint::ParallelClear {
1718            a, b, clash_dist, ..
1719        } => {
1720            let (sa, sb) = match pair_eval(world, a, b) {
1721                Some(p) => p,
1722                None => return 0.0,
1723            };
1724            parallel_clear_g(&sa, &sb, *clash_dist)
1725        }
1726    }
1727}
1728
1729/// Max of `max(0, g_i)` over hard constraints.
1730pub fn max_hard_violation(world: &LayoutWorld, hard: &[HardConstraint]) -> f64 {
1731    hard.iter()
1732        .map(|h| hard_g(world, h).max(0.0))
1733        .fold(0.0_f64, f64::max)
1734}
1735
1736/// Powell–Hestenes–Rockafellar penalty for inequality `g ≤ 0`.
1737fn phr_penalty(g: f64, lambda: f64, rho: f64) -> f64 {
1738    let t = (lambda + rho * g).max(0.0);
1739    (t * t - lambda * lambda) / (2.0 * rho)
1740}
1741
1742fn al_energy(
1743    world: &LayoutWorld,
1744    soft: &[Constraint],
1745    hard: &[HardConstraint],
1746    lambda: &[f64],
1747    rho: &[f64],
1748    active: &[bool],
1749    seed: &[(NodeId, f64, f64)],
1750    w_travel: f64,
1751) -> f64 {
1752    let mut e = energy(world, soft, seed, w_travel);
1753    for (i, h) in hard.iter().enumerate() {
1754        if !active.get(i).copied().unwrap_or(false) {
1755            continue;
1756        }
1757        let lam = lambda.get(i).copied().unwrap_or(0.0);
1758        let r = rho.get(i).copied().unwrap_or(1.0).max(1e-6);
1759        e += phr_penalty(hard_g(world, h), lam, r);
1760    }
1761    e
1762}
1763
1764/// Minimize soft energy (+ AL hard terms) with Nelder–Mead; stop on pose drift.
1765///
1766/// Hard rows are grouped by [`HardConstraint`] `lagrangian` (lower = stronger).
1767/// Each group is its own PHR loop; stronger groups are then held at `al_rho_max`
1768/// so tether / contain cannot undo no-overlap.
1769pub fn solve(
1770    world: &mut LayoutWorld,
1771    constraints: &[Constraint],
1772    hard: &[HardConstraint],
1773    opts: &SolveOpts,
1774) -> SolveResult {
1775    let (ids, _) = world.params();
1776    let rot_ids = parallel_rot_ids(constraints);
1777    let mut params = pack_solve_params(world, &ids, &rot_ids);
1778    if ids.is_empty() && rot_ids.is_empty() {
1779        return SolveResult {
1780            iters: 0,
1781            energy: energy(world, constraints, &[], opts.w_travel),
1782            stopped_on_drift: true,
1783            max_hard_violation: max_hard_violation(world, hard),
1784        };
1785    }
1786
1787    // Seed travel targets = current poses (after greedy).
1788    let seed: Vec<(NodeId, f64, f64)> = ids
1789        .iter()
1790        .enumerate()
1791        .map(|(i, id)| (id.clone(), params[i * 2], params[i * 2 + 1]))
1792        .collect();
1793
1794    // Light noise once up front (not every AL outer).
1795    if opts.noise > 0.0 {
1796        for (i, _) in ids.iter().enumerate() {
1797            let n = opts.noise * pseudo_noise(i as u64 + 1);
1798            params[i * 2] += n;
1799            params[i * 2 + 1] += opts.noise * pseudo_noise(i as u64 + 17);
1800        }
1801        let xy = ids.len() * 2;
1802        for (i, _) in rot_ids.iter().enumerate() {
1803            params[xy + i] += opts.noise * pseudo_noise(i as u64 + 31);
1804        }
1805        apply_solve_params(world, &ids, &rot_ids, &params);
1806    }
1807
1808    let mut groups: Vec<u8> = hard.iter().map(hard_lagrangian).collect();
1809    groups.sort_unstable();
1810    groups.dedup();
1811    if groups.is_empty() {
1812        groups.push(0);
1813    }
1814
1815    let outer_max = if hard.is_empty() {
1816        1
1817    } else {
1818        opts.al_outer_max.max(1)
1819    };
1820    let mut lambda = vec![0.0; hard.len()];
1821    let mut rho = vec![opts.al_rho0.max(1e-6); hard.len()];
1822    // Stronger Lagrangians start at higher ρ so snug cannot sit on a label
1823    // before the outer loop has grown the penalty.
1824    let max_group = *groups.last().unwrap_or(&0);
1825    for (i, h) in hard.iter().enumerate() {
1826        let steps = max_group.saturating_sub(hard_lagrangian(h)) as i32;
1827        rho[i] = (opts.al_rho0.max(1e-6) * opts.al_rho_grow.powi(steps * 5)).min(opts.al_rho_max);
1828    }
1829    let mut active = vec![false; hard.len()];
1830    let mut total_iters = 0usize;
1831    let mut stopped_on_drift = false;
1832    let mut last_energy = 0.0;
1833
1834    for (gi, &group) in groups.iter().enumerate() {
1835        for (i, h) in hard.iter().enumerate() {
1836            if hard_lagrangian(h) <= group {
1837                active[i] = true;
1838            }
1839        }
1840        let mut prev_max_v = f64::INFINITY;
1841        for outer in 0..outer_max {
1842            let nm = nelder_mead(
1843                world,
1844                &ids,
1845                &rot_ids,
1846                constraints,
1847                hard,
1848                &lambda,
1849                &rho,
1850                &active,
1851                &seed,
1852                opts,
1853                outer == 0 && gi == 0,
1854            );
1855            total_iters += nm.iters;
1856            stopped_on_drift = nm.stopped_on_drift;
1857            last_energy = nm.energy;
1858
1859            if hard.is_empty() {
1860                break;
1861            }
1862
1863            let mut max_v = 0.0_f64;
1864            for (i, h) in hard.iter().enumerate() {
1865                if hard_lagrangian(h) != group {
1866                    continue;
1867                }
1868                let g = hard_g(world, h);
1869                max_v = max_v.max(g.max(0.0));
1870                lambda[i] = (lambda[i] + rho[i] * g).max(0.0);
1871            }
1872            if max_v < opts.al_tol {
1873                break;
1874            }
1875            if outer + 1 < outer_max && max_v > prev_max_v * 0.85 {
1876                for (i, h) in hard.iter().enumerate() {
1877                    if hard_lagrangian(h) == group {
1878                        rho[i] = (rho[i] * opts.al_rho_grow).min(opts.al_rho_max);
1879                    }
1880                }
1881            }
1882            prev_max_v = max_v;
1883        }
1884        // Hold this Lagrangian so weaker groups cannot spend it.
1885        for (i, h) in hard.iter().enumerate() {
1886            if hard_lagrangian(h) == group {
1887                rho[i] = opts.al_rho_max;
1888            }
1889        }
1890    }
1891
1892    SolveResult {
1893        iters: total_iters,
1894        energy: last_energy,
1895        stopped_on_drift,
1896        max_hard_violation: max_hard_violation(world, hard),
1897    }
1898}
1899
1900#[allow(clippy::too_many_arguments)]
1901fn nelder_mead(
1902    world: &mut LayoutWorld,
1903    ids: &[NodeId],
1904    rot_ids: &[NodeId],
1905    constraints: &[Constraint],
1906    hard: &[HardConstraint],
1907    lambda: &[f64],
1908    rho: &[f64],
1909    active: &[bool],
1910    seed: &[(NodeId, f64, f64)],
1911    opts: &SolveOpts,
1912    rebuild_simplex: bool,
1913) -> SolveResult {
1914    let params = pack_solve_params(world, ids, rot_ids);
1915
1916    let n = params.len();
1917    if n == 0 {
1918        return SolveResult {
1919            iters: 0,
1920            energy: al_energy(
1921                world,
1922                constraints,
1923                hard,
1924                lambda,
1925                rho,
1926                active,
1927                seed,
1928                opts.w_travel,
1929            ),
1930            stopped_on_drift: true,
1931            max_hard_violation: 0.0,
1932        };
1933    }
1934    let scale = opts.initial_simplex_scale;
1935    let eval = |world: &mut LayoutWorld, v: &[f64]| -> f64 {
1936        apply_solve_params(world, ids, rot_ids, v);
1937        al_energy(
1938            world,
1939            constraints,
1940            hard,
1941            lambda,
1942            rho,
1943            active,
1944            seed,
1945            opts.w_travel,
1946        )
1947    };
1948
1949    let mut simplex: Vec<(Vec<f64>, f64)> = Vec::with_capacity(n + 1);
1950    {
1951        let e0 = eval(world, &params);
1952        simplex.push((params.clone(), e0));
1953    }
1954    if rebuild_simplex || simplex.len() == 1 {
1955        for i in 0..n {
1956            let mut v = params.clone();
1957            v[i] += if v[i].abs() > 1e-6 {
1958                scale * 0.05 * v[i].abs().max(1.0)
1959            } else {
1960                scale
1961            };
1962            let e = eval(world, &v);
1963            simplex.push((v, e));
1964        }
1965    }
1966
1967    let mut history: Vec<Vec<(f64, f64)>> = Vec::new();
1968    apply_solve_params(world, ids, rot_ids, &simplex[0].0);
1969    history.push(world.control_points_movable());
1970
1971    let alpha = 1.0;
1972    let gamma = 2.0;
1973    let rho = 0.5;
1974    let sigma = 0.5;
1975
1976    let mut stopped_on_drift = false;
1977    let mut iters = 0;
1978    for iter in 0..opts.max_iters {
1979        iters = iter + 1;
1980        simplex.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
1981
1982        let mut centroid = vec![0.0; n];
1983        for s in simplex.iter().take(n) {
1984            for (j, x) in s.0.iter().enumerate() {
1985                centroid[j] += x;
1986            }
1987        }
1988        for c in &mut centroid {
1989            *c /= n as f64;
1990        }
1991
1992        let worst = &simplex[n];
1993        let mut xr = vec![0.0; n];
1994        for j in 0..n {
1995            xr[j] = centroid[j] + alpha * (centroid[j] - worst.0[j]);
1996        }
1997        let er = eval(world, &xr);
1998
1999        if er < simplex[0].1 {
2000            let mut xe = vec![0.0; n];
2001            for j in 0..n {
2002                xe[j] = centroid[j] + gamma * (xr[j] - centroid[j]);
2003            }
2004            let ee = eval(world, &xe);
2005            if ee < er {
2006                simplex[n] = (xe, ee);
2007            } else {
2008                simplex[n] = (xr, er);
2009            }
2010        } else if er < simplex[n - 1].1 {
2011            simplex[n] = (xr, er);
2012        } else {
2013            let mut xc = vec![0.0; n];
2014            if er < worst.1 {
2015                for j in 0..n {
2016                    xc[j] = centroid[j] + rho * (xr[j] - centroid[j]);
2017                }
2018            } else {
2019                for j in 0..n {
2020                    xc[j] = centroid[j] + rho * (worst.0[j] - centroid[j]);
2021                }
2022            }
2023            let ec = eval(world, &xc);
2024            if ec < worst.1.min(er) {
2025                simplex[n] = (xc, ec);
2026            } else {
2027                let best_p = simplex[0].0.clone();
2028                for s in simplex.iter_mut().skip(1) {
2029                    for j in 0..n {
2030                        s.0[j] = best_p[j] + sigma * (s.0[j] - best_p[j]);
2031                    }
2032                    s.1 = eval(world, &s.0);
2033                }
2034            }
2035        }
2036
2037        simplex.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
2038        apply_solve_params(world, ids, rot_ids, &simplex[0].0);
2039        let pts = world.control_points_movable();
2040        history.push(pts.clone());
2041        if history.len() > opts.drift_window + 1 {
2042            let drop = history.len() - (opts.drift_window + 1);
2043            history.drain(0..drop);
2044        }
2045        if history.len() > opts.drift_window {
2046            let old = &history[history.len() - 1 - opts.drift_window];
2047            let drift = max_point_drift(old, &pts);
2048            if drift < opts.epsilon_px {
2049                stopped_on_drift = true;
2050                break;
2051            }
2052        }
2053    }
2054
2055    simplex.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
2056    apply_solve_params(world, ids, rot_ids, &simplex[0].0);
2057    SolveResult {
2058        iters,
2059        energy: simplex[0].1,
2060        stopped_on_drift,
2061        max_hard_violation: 0.0,
2062    }
2063}
2064
2065fn max_point_drift(a: &[(f64, f64)], b: &[(f64, f64)]) -> f64 {
2066    let n = a.len().min(b.len());
2067    let mut m: f64 = 0.0;
2068    for i in 0..n {
2069        let d = (a[i].0 - b[i].0).abs().max((a[i].1 - b[i].1).abs());
2070        m = m.max(d);
2071    }
2072    // Length change: treat as large drift.
2073    if a.len() != b.len() {
2074        m = m.max(1e9);
2075    }
2076    m
2077}
2078
2079fn pseudo_noise(seed: u64) -> f64 {
2080    // Deterministic cheap hash → [-1, 1]
2081    let mut x = seed.wrapping_mul(0x9E3779B97F4A7C15);
2082    x ^= x >> 30;
2083    x = x.wrapping_mul(0xBF58476D1CE4E5B9);
2084    x ^= x >> 27;
2085    let u = (x >> 11) as f64 / ((1u64 << 53) as f64);
2086    u * 2.0 - 1.0
2087}
2088
2089// ─── Build helpers / kits ───────────────────────────────────────────────────
2090
2091/// Install fixed chem group: bonds as lines, atoms as **disks** (~0.3 CC-bond),
2092/// optional shade circles.
2093pub fn install_chem(
2094    world: &mut LayoutWorld,
2095    bonds: &[(f64, f64, f64, f64)],
2096    atoms: &[(usize, f64, f64)],
2097    shades: &[(usize, f64, f64, f64)],
2098) {
2099    install_chem_with_texts(world, bonds, atoms, shades, &[]);
2100}
2101
2102/// Like [`install_chem`], plus fixed chem atom-text AABBs (`ObjectType::AtomText`).
2103///
2104/// Chem ink is immovable — annotations MinGap/Outside against these boxes.
2105pub fn install_chem_with_texts(
2106    world: &mut LayoutWorld,
2107    bonds: &[(f64, f64, f64, f64)],
2108    atoms: &[(usize, f64, f64)],
2109    shades: &[(usize, f64, f64, f64)],
2110    atom_texts: &[(usize, Aabb)],
2111) {
2112    let parent = world.root.clone();
2113    install_chem_under(world, &parent, bonds, atoms, shades, atom_texts);
2114}
2115
2116/// Install chem ink under `parent` (`{parent}/chem/…`).
2117pub fn install_chem_under(
2118    world: &mut LayoutWorld,
2119    parent: &str,
2120    bonds: &[(f64, f64, f64, f64)],
2121    atoms: &[(usize, f64, f64)],
2122    shades: &[(usize, f64, f64, f64)],
2123    atom_texts: &[(usize, Aabb)],
2124) -> NodeId {
2125    let chem = world.insert(
2126        format!("{parent}/chem"),
2127        parent,
2128        ObjectType::Chem,
2129        Shape::Aabb(Aabb::new(0.0, 0.0, 0.0, 0.0)),
2130        true,
2131    );
2132    let bonds_id = world.insert(
2133        format!("{parent}/chem/bonds"),
2134        &chem,
2135        ObjectType::Bonds,
2136        Shape::Aabb(Aabb::new(0.0, 0.0, 0.0, 0.0)),
2137        true,
2138    );
2139    for (i, &(x0, y0, x1, y1)) in bonds.iter().enumerate() {
2140        world.insert(
2141            format!("{parent}/chem/bonds/b{i}"),
2142            &bonds_id,
2143            ObjectType::Bonds,
2144            Shape::Line { x0, y0, x1, y1 },
2145            true,
2146        );
2147    }
2148    let atoms_id = world.insert(
2149        format!("{parent}/chem/atoms"),
2150        &chem,
2151        ObjectType::Atom,
2152        Shape::Aabb(Aabb::new(0.0, 0.0, 0.0, 0.0)),
2153        true,
2154    );
2155    for &(idx, x, y) in atoms {
2156        let aid = world.insert(
2157            format!("{parent}/chem/atoms/a{idx}"),
2158            &atoms_id,
2159            ObjectType::Atom,
2160            Shape::Aabb(Aabb::new(0.0, 0.0, 0.0, 0.0)),
2161            true,
2162        );
2163        world.insert(
2164            format!("{parent}/chem/atoms/a{idx}/coord"),
2165            &aid,
2166            ObjectType::Coord,
2167            Shape::Circle {
2168                cx: x,
2169                cy: y,
2170                r: ATOM_DISK_R_PX,
2171            },
2172            true,
2173        );
2174    }
2175    for &(idx, cx, cy, r) in shades {
2176        let aid = format!("{parent}/chem/atoms/a{idx}");
2177        if world.get(&aid).is_none() {
2178            continue;
2179        }
2180        world.insert(
2181            format!("{parent}/chem/atoms/a{idx}/shade"),
2182            &aid,
2183            ObjectType::Shade,
2184            Shape::Circle { cx, cy, r },
2185            true,
2186        );
2187    }
2188    if !atom_texts.is_empty() {
2189        let texts_id = world.insert(
2190            format!("{parent}/chem/atom_texts"),
2191            &chem,
2192            ObjectType::AtomText,
2193            Shape::Aabb(Aabb::new(0.0, 0.0, 0.0, 0.0)),
2194            true,
2195        );
2196        for &(idx, box_) in atom_texts {
2197            world.insert(
2198                format!("{parent}/chem/atom_texts/t{idx}"),
2199                &texts_id,
2200                ObjectType::AtomText,
2201                Shape::Aabb(box_),
2202                true,
2203            );
2204        }
2205    }
2206    world.recompute_group_aabbs();
2207    chem
2208}
2209
2210/// Caption kit (solver bench / unit tests only).
2211///
2212/// Paint places [`crate::doc::caption::apply_mol_captions`] **after** chrome
2213/// constraints — the mol name is not a live layout DOF.
2214pub fn caption_kit(
2215    world: &mut LayoutWorld,
2216    constraints: &mut Vec<Constraint>,
2217    hard: &mut Vec<HardConstraint>,
2218    ink: Aabb,
2219    preferred: Side,
2220    opt_dist: f64,
2221    clash_dist: f64,
2222) -> NodeId {
2223    let _ = world.insert(
2224        "mol/annotations",
2225        "mol",
2226        ObjectType::Annotations,
2227        Shape::Aabb(Aabb::new(0.0, 0.0, 0.0, 0.0)),
2228        true,
2229    );
2230    let caps = world.insert(
2231        "mol/annotations/captions",
2232        "mol/annotations",
2233        ObjectType::Captions,
2234        Shape::Aabb(Aabb::new(0.0, 0.0, 0.0, 0.0)),
2235        true,
2236    );
2237    // Rest at ink; tx/ty move the label.
2238    let id = world.insert(
2239        "mol/annotations/captions/name",
2240        &caps,
2241        ObjectType::Caption,
2242        Shape::Aabb(ink),
2243        false,
2244    );
2245    constraints.push(Constraint::Outside {
2246        a: id.clone(),
2247        b: "mol/chem".into(),
2248        clash_dist,
2249        strength: 8.0,
2250    });
2251    constraints.push(Constraint::PreferSide {
2252        a: id.clone(),
2253        b: "mol/chem".into(),
2254        side: preferred,
2255        strength: 2.0,
2256        align_along: 0.0,
2257    });
2258    constraints.push(Constraint::MinimizeDist {
2259        a: id.clone(),
2260        b: "mol/chem".into(),
2261        opt_dist,
2262        strength: 1.0,
2263    });
2264    push_clear_bonds(world, hard, &id, clash_dist);
2265    push_placement_pose(constraints, &id, &Shape::Aabb(ink));
2266    id
2267}
2268
2269/// Box / hull region text kit.
2270///
2271/// `side_about` is the mean of contained atom positions — [`Constraint::PreferSide`]
2272/// (`pos`) is relative to this point, not the hull or full-mol AABB. Edge-align
2273/// is `align_along` on that constraint (not a solver branch on Point vs AABB).
2274pub fn region_text_kit(
2275    world: &mut LayoutWorld,
2276    constraints: &mut Vec<Constraint>,
2277    hard: &mut Vec<HardConstraint>,
2278    region_idx: usize,
2279    hull: Shape,
2280    text_ink: Aabb,
2281    inside: bool,
2282    preferred: Side,
2283    clash_dist: f64,
2284    side_about: (f64, f64),
2285    other_labels: &[Aabb],
2286) -> NodeId {
2287    let _ = world.insert(
2288        "mol/annotations",
2289        "mol",
2290        ObjectType::Annotations,
2291        Shape::Aabb(Aabb::new(0.0, 0.0, 0.0, 0.0)),
2292        true,
2293    );
2294    let regs = world.insert(
2295        "mol/annotations/regions",
2296        "mol/annotations",
2297        ObjectType::Regions,
2298        Shape::Aabb(Aabb::new(0.0, 0.0, 0.0, 0.0)),
2299        true,
2300    );
2301    let rid = world.insert(
2302        format!("mol/annotations/regions/r{region_idx}"),
2303        &regs,
2304        ObjectType::Region,
2305        Shape::Aabb(hull.aabb()),
2306        true,
2307    );
2308    let hull_id = world.insert(
2309        format!("mol/annotations/regions/r{region_idx}/hull"),
2310        &rid,
2311        ObjectType::RegionHull,
2312        hull,
2313        true,
2314    );
2315    let text_id = world.insert(
2316        format!("mol/annotations/regions/r{region_idx}/text"),
2317        &rid,
2318        ObjectType::RegionText,
2319        Shape::Aabb(text_ink),
2320        false,
2321    );
2322    let side_ref = world.insert(
2323        format!("mol/annotations/regions/r{region_idx}/side_ref"),
2324        &rid,
2325        ObjectType::Group,
2326        Shape::Point {
2327            x: side_about.0,
2328            y: side_about.1,
2329        },
2330        true,
2331    );
2332    if inside {
2333        // Soft Inside is the snug gradient. Hard contain is a *weaker*
2334        // Lagrangian than keep-off and tether, so it cannot pin the seed at
2335        // the far edge the way a shared AL + PreferPose used to.
2336        constraints.push(Constraint::Inside {
2337            a: text_id.clone(),
2338            b: hull_id.clone(),
2339            pad: CONTAIN_MARGIN_PX,
2340            strength: 2.0,
2341        });
2342        hard.push(HardConstraint::Inside {
2343            a: text_id.clone(),
2344            b: hull_id.clone(),
2345            pad: CONTAIN_MARGIN_PX,
2346            lagrangian: LAGRANGIAN_CONTAIN,
2347        });
2348        constraints.push(Constraint::MinimizeDist {
2349            a: text_id.clone(),
2350            b: "mol/chem".into(),
2351            opt_dist: clash_dist,
2352            strength: 16.0,
2353        });
2354    } else {
2355        constraints.push(Constraint::Outside {
2356            a: text_id.clone(),
2357            b: hull_id.clone(),
2358            clash_dist: 1.0,
2359            strength: 6.0,
2360        });
2361        constraints.push(Constraint::MinimizeDist {
2362            a: text_id.clone(),
2363            b: hull_id.clone(),
2364            opt_dist: clash_dist,
2365            strength: 1.5,
2366        });
2367        push_placement_pose(constraints, &text_id, &Shape::Aabb(text_ink));
2368    }
2369    constraints.push(Constraint::PreferSide {
2370        a: text_id.clone(),
2371        b: side_ref,
2372        side: preferred,
2373        strength: if inside { 4.0 } else { 2.0 },
2374        align_along: 0.35,
2375    });
2376    push_clear_bonds(world, hard, &text_id, clash_dist);
2377    // Prior chrome labels / circles (kitchen-sink atom numbers, callouts, …).
2378    for (i, box_) in other_labels.iter().enumerate() {
2379        if box_.width() <= 0.0 && box_.height() <= 0.0 {
2380            continue;
2381        }
2382        let oid = world.insert(
2383            format!("mol/annotations/regions/r{region_idx}/other{i}"),
2384            &rid,
2385            ObjectType::Group,
2386            Shape::Aabb(*box_),
2387            true,
2388        );
2389        hard.push(HardConstraint::Outside {
2390            a: text_id.clone(),
2391            b: oid,
2392            clash_dist,
2393            lagrangian: LAGRANGIAN_CLEAR,
2394        });
2395    }
2396    // Avoid shade disks (labels sit in front, but still clear painted wash).
2397    // Inside snug: mild shade Outside so shade cannot pin the seed far out.
2398    // Walk the chem subtree (not the whole world) so extra mols in a scheme
2399    // world do not leak into this kit.
2400    let mut stack = vec!["mol/chem".to_string()];
2401    let hull_id = format!("mol/annotations/regions/r{region_idx}/hull");
2402    while let Some(nid) = stack.pop() {
2403        let Some(n) = world.get(&nid) else {
2404            continue;
2405        };
2406        stack.extend(n.children.iter().cloned());
2407        match n.object_type {
2408            ObjectType::Shade => {
2409                constraints.push(Constraint::Outside {
2410                    a: text_id.clone(),
2411                    b: nid.clone(),
2412                    clash_dist: 1.0,
2413                    strength: if inside { 1.5 } else { 3.0 },
2414                });
2415                constraints.push(Constraint::Inside {
2416                    a: nid,
2417                    b: hull_id.clone(),
2418                    pad: CONTAIN_MARGIN_PX,
2419                    strength: 2.0,
2420                });
2421            }
2422            ObjectType::Coord => {
2423                constraints.push(Constraint::Inside {
2424                    a: nid,
2425                    b: hull_id.clone(),
2426                    pad: CONTAIN_MARGIN_PX,
2427                    strength: 2.0,
2428                });
2429            }
2430            _ => {}
2431        }
2432    }
2433    text_id
2434}
2435
2436/// Callout two-point kit: movable label AABB + tip point; optional route points.
2437pub fn callout_kit(
2438    world: &mut LayoutWorld,
2439    constraints: &mut Vec<Constraint>,
2440    hard: &mut Vec<HardConstraint>,
2441    callout_idx: usize,
2442    label_ink: Aabb,
2443    tip_xy: (f64, f64),
2444    target: (f64, f64),
2445    tip_standoff: f64,
2446    preferred: Side,
2447    clash_dist: f64,
2448    route_points: &[(f64, f64)],
2449) -> (NodeId, NodeId) {
2450    let _ = world.insert(
2451        "mol/annotations",
2452        "mol",
2453        ObjectType::Annotations,
2454        Shape::Aabb(Aabb::new(0.0, 0.0, 0.0, 0.0)),
2455        true,
2456    );
2457    let calls = world.insert(
2458        "mol/annotations/callouts",
2459        "mol/annotations",
2460        ObjectType::Callouts,
2461        Shape::Aabb(Aabb::new(0.0, 0.0, 0.0, 0.0)),
2462        true,
2463    );
2464    let cid = format!("mol/annotations/callouts/c{callout_idx}");
2465    let _ = world.insert(
2466        &cid,
2467        &calls,
2468        ObjectType::Group,
2469        Shape::Aabb(Aabb::new(0.0, 0.0, 0.0, 0.0)),
2470        true,
2471    );
2472    let label_id = world.insert(
2473        format!("{cid}/label"),
2474        &cid,
2475        ObjectType::CalloutLabel,
2476        Shape::Aabb(label_ink),
2477        false,
2478    );
2479    let tip_id = world.insert(
2480        format!("{cid}/tip"),
2481        &cid,
2482        ObjectType::CalloutTip,
2483        Shape::Point {
2484            x: tip_xy.0,
2485            y: tip_xy.1,
2486        },
2487        false,
2488    );
2489    // Fixed target point for standoff.
2490    let target_id = world.insert(
2491        format!("{cid}/target"),
2492        &cid,
2493        ObjectType::Coord,
2494        Shape::Point {
2495            x: target.0,
2496            y: target.1,
2497        },
2498        true,
2499    );
2500    constraints.push(Constraint::PointStandoff {
2501        tip: tip_id.clone(),
2502        target: target_id.clone(),
2503        dist: tip_standoff,
2504        strength: 5.0,
2505    });
2506    constraints.push(Constraint::Outside {
2507        a: label_id.clone(),
2508        b: "mol/chem".into(),
2509        clash_dist,
2510        strength: 6.0,
2511    });
2512    constraints.push(Constraint::PreferSide {
2513        a: label_id.clone(),
2514        b: "mol/chem".into(),
2515        side: preferred,
2516        strength: 1.5,
2517        align_along: 0.0,
2518    });
2519    // Label box stays one CC-bond from the target (tip standoff is separate).
2520    constraints.push(Constraint::MinGap {
2521        a: label_id.clone(),
2522        b: target_id.clone(),
2523        dist: crate::metrics::BOND_PX,
2524        strength: 8.0,
2525    });
2526    constraints.push(Constraint::MinimizeDist {
2527        a: label_id.clone(),
2528        b: tip_id.clone(),
2529        opt_dist: crate::metrics::BOND_PX * 0.5,
2530        strength: 0.4,
2531    });
2532    push_placement_pose(constraints, &label_id, &Shape::Aabb(label_ink));
2533    push_placement_pose(
2534        constraints,
2535        &tip_id,
2536        &Shape::Point {
2537            x: tip_xy.0,
2538            y: tip_xy.1,
2539        },
2540    );
2541    push_clear_bonds(world, hard, &label_id, clash_dist);
2542    push_clear_bonds(world, hard, &tip_id, clash_dist);
2543    for (k, &(rx, ry)) in route_points.iter().enumerate() {
2544        let rid = world.insert(
2545            format!("{cid}/route{k}"),
2546            &cid,
2547            ObjectType::CalloutRoute,
2548            Shape::Point { x: rx, y: ry },
2549            false,
2550        );
2551        constraints.push(Constraint::MinimizeDist {
2552            a: rid.clone(),
2553            b: tip_id.clone(),
2554            opt_dist: 8.0,
2555            strength: 0.5,
2556        });
2557        constraints.push(Constraint::MinimizeDist {
2558            a: rid.clone(),
2559            b: label_id.clone(),
2560            opt_dist: 8.0,
2561            strength: 0.5,
2562        });
2563        push_placement_pose(constraints, &rid, &Shape::Point { x: rx, y: ry });
2564        push_clear_bonds(world, hard, &rid, clash_dist);
2565    }
2566    (label_id, tip_id)
2567}
2568
2569/// Atom index / mapno numbers **and** custom atom labels.
2570///
2571/// One kit for all three — chrome `LabelRole::Number` (index or mapno) and
2572/// `LabelRole::Text` both call [`refine_atom_number`] → here.
2573///
2574/// Soft energy (NM objective):
2575/// - strong [`Constraint::MinimizeDist`] to the snug gap (`clash_dist`) on chem
2576///   text if present, else the atom point — this is the home magnet;
2577/// - mild soft [`Constraint::Outside`] vs bonds and vs other labels (smooth
2578///   repulsion in addition to hard rows).
2579///
2580/// Hard / AL (two Lagrangians; lower index is stronger):
2581/// - [`LAGRANGIAN_CLEAR`]: Outside vs bonds, chem text, and prior labels;
2582/// - [`LAGRANGIAN_TETHER`]: [`HardConstraint::MaxDist`] ceiling (`tether_px`).
2583///   No-overlap outranks association — a shared PHR let snug+tether cover "2".
2584///
2585/// No PreferPose — a greedy seed is only the NM start; pinning it made numbers
2586/// look randomly parked. Shade is **not** a layout obstacle.
2587const ATOM_SNUG_STRENGTH: f64 = 14.0;
2588const ATOM_MILD_REPEL: f64 = 2.5;
2589
2590pub fn atom_number_kit(
2591    world: &mut LayoutWorld,
2592    constraints: &mut Vec<Constraint>,
2593    hard: &mut Vec<HardConstraint>,
2594    atom_idx: usize,
2595    ink: Aabb,
2596    clash_dist: f64,
2597    tether_px: f64,
2598    _halo_pad: Option<f64>,
2599    _avoid_shade: bool,
2600) -> NodeId {
2601    let _ = world.insert(
2602        "mol/annotations",
2603        "mol",
2604        ObjectType::Annotations,
2605        Shape::Aabb(Aabb::new(0.0, 0.0, 0.0, 0.0)),
2606        true,
2607    );
2608    let nums = world.insert(
2609        "mol/annotations/atom_numbers",
2610        "mol/annotations",
2611        ObjectType::AtomNumbers,
2612        Shape::Aabb(Aabb::new(0.0, 0.0, 0.0, 0.0)),
2613        true,
2614    );
2615    let id = world.insert(
2616        format!("mol/annotations/atom_numbers/n{atom_idx}"),
2617        &nums,
2618        ObjectType::AtomNumber,
2619        Shape::Aabb(ink),
2620        false,
2621    );
2622    // Home: chem atom text when painted; otherwise the atom **center point**
2623    // (not the 0.3-bond Coord disk — snugging to the disk left a ~disk-radius
2624    // air gap that looked randomly far from the nucleus).
2625    let text_anchor = format!("mol/chem/atom_texts/t{atom_idx}");
2626    let anchor = if world.get(&text_anchor).is_some() {
2627        Some(text_anchor)
2628    } else {
2629        let coord = format!("mol/chem/atoms/a{atom_idx}/coord");
2630        let center = world.get(&coord).map(|n| match n.world_shape() {
2631            Shape::Circle { cx, cy, .. } | Shape::Point { x: cx, y: cy } => (cx, cy),
2632            other => other.aabb().center(),
2633        });
2634        center.map(|(cx, cy)| {
2635            let tip = format!("mol/chem/atoms/a{atom_idx}/snug");
2636            let parent = format!("mol/chem/atoms/a{atom_idx}");
2637            world.insert(
2638                &tip,
2639                &parent,
2640                ObjectType::Coord,
2641                Shape::Point { x: cx, y: cy },
2642                true,
2643            );
2644            tip
2645        })
2646    };
2647    if let Some(ref a) = anchor {
2648        constraints.push(Constraint::MinimizeDist {
2649            a: id.clone(),
2650            b: a.clone(),
2651            opt_dist: clash_dist,
2652            strength: ATOM_SNUG_STRENGTH,
2653        });
2654        hard.push(HardConstraint::MaxDist {
2655            a: id.clone(),
2656            b: a.clone(),
2657            dist: tether_px,
2658            lagrangian: LAGRANGIAN_TETHER,
2659        });
2660    }
2661    // Hard feasibility + mild soft repulsion vs every bond.
2662    push_clear_bonds(world, hard, &id, clash_dist);
2663    if let Some(bonds) = world.get("mol/chem/bonds") {
2664        for bid in bonds.children.clone() {
2665            constraints.push(Constraint::Outside {
2666                a: id.clone(),
2667                b: bid,
2668                clash_dist,
2669                strength: ATOM_MILD_REPEL,
2670            });
2671        }
2672    }
2673    // Chem text and prior annotation boxes (`t{10000+}`): hard Outside + mild
2674    // soft twin. Keep-off-labels is AL — a soft hinge loses to snug MinimizeDist
2675    // (kitchen-sink "2" vs "ortho").
2676    if let Some(texts) = world.get("mol/chem/atom_texts") {
2677        for tid in texts.children.clone() {
2678            hard.push(HardConstraint::Outside {
2679                a: id.clone(),
2680                b: tid.clone(),
2681                clash_dist,
2682                lagrangian: LAGRANGIAN_CLEAR,
2683            });
2684            constraints.push(Constraint::Outside {
2685                a: id.clone(),
2686                b: tid,
2687                clash_dist,
2688                strength: ATOM_MILD_REPEL,
2689            });
2690        }
2691    }
2692    // Intentionally no Outside vs shade — wash is not a placement obstacle.
2693    // No PreferPose: snug + mild repel own the soft energy.
2694    let _ = ink;
2695    id
2696}
2697
2698/// Build a **concave** hull proxy through include points, pad for exclude.
2699///
2700/// Not a convex hull: long chords dig **inward** toward interior include
2701/// samples so L-shaped sets keep bays. After outward normal pad, any exclude
2702/// still inside (or within `exclude_pad`) forces an inward **notch** so the
2703/// polygon cannot swallow excluded atoms. Vertex-only push is not enough.
2704pub fn hull_proxy(
2705    include: &[(f64, f64)],
2706    exclude: &[(f64, f64)],
2707    pad: f64,
2708    exclude_pad: f64,
2709) -> Shape {
2710    if include.is_empty() {
2711        return Shape::PointSet(vec![]);
2712    }
2713    let clear = exclude_pad.max(CONTAIN_MARGIN_PX);
2714    // Default: **convex** surround so atoms + an outside label stay enclosed
2715    // (concave dig + a distant label arm pinched through rings). Use concave
2716    // only when an exclude sits inside that convex hull (empty bay).
2717    let convex = convex_hull_pts(include);
2718    let bay = !exclude.is_empty()
2719        && convex.len() >= 3
2720        && exclude.iter().any(|&(x, y)| point_in_poly(x, y, &convex));
2721    let max_edge = (1.25 * BOND_PX).max(pad * 2.0 + 1.0);
2722    let seed = if bay {
2723        concave_hull_pts(include, max_edge)
2724    } else {
2725        convex
2726    };
2727    let mut pts = finish_hull_proxy(seed, include, exclude, pad, clear);
2728    if pts.len() < 3 || !poly_contains_all(&pts, include) {
2729        pts = finish_hull_proxy(convex_hull_pts(include), include, exclude, pad, clear);
2730    }
2731    if pts.len() < 3 {
2732        let a = Shape::PointSet(include.to_vec()).aabb().inflate(pad);
2733        return Shape::Aabb(a);
2734    }
2735    Shape::PointSet(pts)
2736}
2737
2738fn finish_hull_proxy(
2739    mut pts: Vec<(f64, f64)>,
2740    include: &[(f64, f64)],
2741    exclude: &[(f64, f64)],
2742    pad: f64,
2743    clear: f64,
2744) -> Vec<(f64, f64)> {
2745    if pts.len() < 3 {
2746        return pts;
2747    }
2748    let (cx, cy) = centroid_of(include);
2749    for &(ex, ey) in exclude {
2750        clip_away_from_point(&mut pts, include, cx, cy, ex, ey, clear);
2751    }
2752    offset_polygon_outward(&mut pts, pad);
2753    for &(ex, ey) in exclude {
2754        clip_away_from_point(&mut pts, include, cx, cy, ex, ey, clear);
2755    }
2756    pts
2757}
2758
2759fn poly_contains_all(poly: &[(f64, f64)], pts: &[(f64, f64)]) -> bool {
2760    if poly.len() < 3 {
2761        return false;
2762    }
2763    pts.iter()
2764        .all(|&(x, y)| point_in_poly(x, y, poly) || point_to_poly_edge_dist(x, y, poly) < 1.5)
2765}
2766
2767fn point_to_poly_edge_dist(px: f64, py: f64, poly: &[(f64, f64)]) -> f64 {
2768    let n = poly.len();
2769    let mut best = f64::INFINITY;
2770    for i in 0..n {
2771        let (x0, y0) = poly[i];
2772        let (x1, y1) = poly[(i + 1) % n];
2773        best = best.min(point_to_seg_dist(px, py, x0, y0, x1, y1));
2774    }
2775    best
2776}
2777
2778fn centroid_of(pts: &[(f64, f64)]) -> (f64, f64) {
2779    let n = pts.len().max(1) as f64;
2780    let sx: f64 = pts.iter().map(|p| p.0).sum();
2781    let sy: f64 = pts.iter().map(|p| p.1).sum();
2782    (sx / n, sy / n)
2783}
2784
2785/// Sutherland–Hodgman keep the half-plane on the include-centroid side of the
2786/// supporting line facing exclude `E`.
2787///
2788/// Ideal plane is `E - clear·dir`. It is never pushed past the furthest
2789/// **include-cloud** sample toward `E` (`keep_guard`) — that used to shave ring
2790/// atoms when a substituent exclude sat close to the hull. Empty bays still
2791/// clip: includes do not reach into the bay, so the plane sits at the include
2792/// frontier and leaves `E` outside. Guard with the original cloud (not the
2793/// padded polygon) so offset growth cannot disable the post-pad clip.
2794fn clip_away_from_point(
2795    pts: &mut Vec<(f64, f64)>,
2796    keep_guard: &[(f64, f64)],
2797    cx: f64,
2798    cy: f64,
2799    ex: f64,
2800    ey: f64,
2801    clear: f64,
2802) {
2803    if pts.len() < 3 {
2804        return;
2805    }
2806    let mut dx = ex - cx;
2807    let mut dy = ey - cy;
2808    let len = dx.hypot(dy);
2809    if len < 1e-9 {
2810        dx = 1.0;
2811        dy = 0.0;
2812    } else {
2813        dx /= len;
2814        dy /= len;
2815    }
2816    let excl_proj = (ex - cx) * dx + (ey - cy) * dy;
2817    // Floor only from includes *between* the centroid and E. Arms that project
2818    // past E (L-bay) must not block the cut; includes beyond E along dir are
2819    // on the far side of the exclude and are not a "keep" frontier.
2820    let max_keep = keep_guard
2821        .iter()
2822        .map(|&(x, y)| (x - cx) * dx + (y - cy) * dy)
2823        .filter(|&p| p < excl_proj - 1e-6)
2824        .fold(f64::NEG_INFINITY, f64::max);
2825    // Ideal: plane at excl_proj - clear. Floor: just past near-side includes.
2826    let plane_thresh = if max_keep.is_finite() {
2827        (excl_proj - clear).max(max_keep + 1e-3)
2828    } else {
2829        excl_proj - clear
2830    };
2831    if plane_thresh >= excl_proj - 1e-6 {
2832        return;
2833    }
2834    let px0 = cx + dx * plane_thresh;
2835    let py0 = cy + dy * plane_thresh;
2836    let inside = |x: f64, y: f64| (x - px0) * dx + (y - py0) * dy <= 1e-9;
2837    let intersect = |ax: f64, ay: f64, bx: f64, by: f64| {
2838        let da = (ax - px0) * dx + (ay - py0) * dy;
2839        let db = (bx - px0) * dx + (by - py0) * dy;
2840        let t = da / (da - db);
2841        (ax + (bx - ax) * t, ay + (by - ay) * t)
2842    };
2843    let n = pts.len();
2844    let mut out = Vec::with_capacity(n + 2);
2845    for i in 0..n {
2846        let (ax, ay) = pts[i];
2847        let (bx, by) = pts[(i + 1) % n];
2848        let ain = inside(ax, ay);
2849        let bin = inside(bx, by);
2850        if ain && bin {
2851            out.push((bx, by));
2852        } else if ain && !bin {
2853            out.push(intersect(ax, ay, bx, by));
2854        } else if !ain && bin {
2855            out.push(intersect(ax, ay, bx, by));
2856            out.push((bx, by));
2857        }
2858    }
2859    if out.len() >= 3 {
2860        *pts = out;
2861    }
2862}
2863
2864/// Concave hull via convex seed + inward edge digging (Park–Oh style).
2865///
2866/// Long chords dig using **interior** include samples (left of CCW edges),
2867/// pulling the boundary into empty bays instead of spanning them.
2868fn concave_hull_pts(include: &[(f64, f64)], max_edge: f64) -> Vec<(f64, f64)> {
2869    let mut cloud: Vec<(f64, f64)> = include.to_vec();
2870    cloud.sort_by(|a, b| {
2871        a.0.partial_cmp(&b.0)
2872            .unwrap_or(std::cmp::Ordering::Equal)
2873            .then(a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal))
2874    });
2875    cloud.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6);
2876    if cloud.len() < 3 {
2877        return cloud;
2878    }
2879    let mut hull = convex_hull_pts(&cloud);
2880    if hull.len() < 3 {
2881        return hull;
2882    }
2883    let on_hull = |hull: &[(f64, f64)], p: (f64, f64)| {
2884        hull.iter()
2885            .any(|&h| (h.0 - p.0).abs() < 1e-6 && (h.1 - p.1).abs() < 1e-6)
2886    };
2887    for _ in 0..cloud.len().saturating_mul(4).max(8) {
2888        let n = hull.len();
2889        let mut best: Option<(usize, (f64, f64), f64)> = None;
2890        for i in 0..n {
2891            let a = hull[i];
2892            let b = hull[(i + 1) % n];
2893            let edge_len = (a.0 - b.0).hypot(a.1 - b.1);
2894            if edge_len <= max_edge {
2895                continue;
2896            }
2897            for &p in &cloud {
2898                if on_hull(&hull, p) {
2899                    continue;
2900                }
2901                // CCW: interior is left of a→b (positive cross). Dig inward.
2902                let cross = (b.0 - a.0) * (p.1 - a.1) - (b.1 - a.1) * (p.0 - a.0);
2903                if cross < 1e-9 {
2904                    continue; // exterior or colinear
2905                }
2906                let d = point_to_seg_dist(p.0, p.1, a.0, a.1, b.0, b.1);
2907                if d > edge_len * 0.55 {
2908                    continue;
2909                }
2910                let better = match best {
2911                    None => true,
2912                    Some((bi, _, bd)) => {
2913                        let be = {
2914                            let ba = hull[bi];
2915                            let bb = hull[(bi + 1) % n];
2916                            (ba.0 - bb.0).hypot(ba.1 - bb.1)
2917                        };
2918                        edge_len > be + 1e-9 || ((edge_len - be).abs() < 1e-9 && d < bd)
2919                    }
2920                };
2921                if better {
2922                    best = Some((i, p, d));
2923                }
2924            }
2925        }
2926        let Some((i, p, _)) = best else {
2927            break;
2928        };
2929        hull.insert(i + 1, p);
2930    }
2931    hull
2932}
2933
2934fn point_to_seg_dist(px: f64, py: f64, x0: f64, y0: f64, x1: f64, y1: f64) -> f64 {
2935    let dx = x1 - x0;
2936    let dy = y1 - y0;
2937    let len2 = dx * dx + dy * dy;
2938    if len2 < 1e-18 {
2939        return (px - x0).hypot(py - y0);
2940    }
2941    let t = ((px - x0) * dx + (py - y0) * dy) / len2;
2942    let t = t.clamp(0.0, 1.0);
2943    (px - (x0 + t * dx)).hypot(py - (y0 + t * dy))
2944}
2945
2946/// Push each vertex along the average of adjacent outward edge normals.
2947fn offset_polygon_outward(pts: &mut [(f64, f64)], pad: f64) {
2948    if pad.abs() < 1e-12 || pts.len() < 3 {
2949        return;
2950    }
2951    let n = pts.len();
2952    // Outward for CCW: right normal of each directed edge. Ensure CCW.
2953    let area2: f64 = (0..n)
2954        .map(|i| {
2955            let (x0, y0) = pts[i];
2956            let (x1, y1) = pts[(i + 1) % n];
2957            x0 * y1 - x1 * y0
2958        })
2959        .sum();
2960    let sign = if area2 >= 0.0 { 1.0 } else { -1.0 };
2961    let mut out = vec![(0.0, 0.0); n];
2962    for i in 0..n {
2963        let prev = pts[(i + n - 1) % n];
2964        let cur = pts[i];
2965        let next = pts[(i + 1) % n];
2966        let e0 = (cur.0 - prev.0, cur.1 - prev.1);
2967        let e1 = (next.0 - cur.0, next.1 - cur.1);
2968        let n0 = (sign * e0.1, -sign * e0.0);
2969        let n1 = (sign * e1.1, -sign * e1.0);
2970        let mut nx = n0.0 + n1.0;
2971        let mut ny = n0.1 + n1.1;
2972        let len = nx.hypot(ny);
2973        if len < 1e-9 {
2974            // Fallback: from centroid.
2975            let cx: f64 = pts.iter().map(|p| p.0).sum::<f64>() / n as f64;
2976            let cy: f64 = pts.iter().map(|p| p.1).sum::<f64>() / n as f64;
2977            nx = cur.0 - cx;
2978            ny = cur.1 - cy;
2979        }
2980        let len = nx.hypot(ny).max(1e-6);
2981        out[i] = (cur.0 + nx / len * pad, cur.1 + ny / len * pad);
2982    }
2983    pts.copy_from_slice(&out);
2984}
2985
2986/// Closed **centripetal Catmull–Rom** through proxy vertices → SVG cubics.
2987///
2988/// Interpolates the hull points with α = ½ (Yuksel et al.): no cusps/loops for
2989/// distinct samples, G¹ joins, no linear solve (unlike Hobby / κ-curves). The
2990/// old mid-edge quadratic paint could throw controls past reflex notches.
2991///
2992/// `curve` is ignored (kept so call sites stay stable).
2993pub fn bezier_path_from_proxy(proxy: &Shape, _curve: f64) -> String {
2994    let pts = match proxy {
2995        Shape::PointSet(p) => p.clone(),
2996        Shape::Aabb(a) => vec![(a.x0, a.y0), (a.x1, a.y0), (a.x1, a.y1), (a.x0, a.y1)],
2997        _ => return String::new(),
2998    };
2999    centripetal_catmull_rom_closed_path(&pts)
3000}
3001
3002pub use crate::catmull::centripetal_catmull_rom_closed_path;
3003
3004fn convex_hull_pts(pts: &[(f64, f64)]) -> Vec<(f64, f64)> {
3005    if pts.len() < 2 {
3006        return pts.to_vec();
3007    }
3008    let mut sp: Vec<(f64, f64)> = pts.to_vec();
3009    sp.sort_by(|a, b| {
3010        a.0.partial_cmp(&b.0)
3011            .unwrap_or(std::cmp::Ordering::Equal)
3012            .then(a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal))
3013    });
3014    sp.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9);
3015    if sp.len() < 2 {
3016        return sp;
3017    }
3018    fn cross(o: (f64, f64), a: (f64, f64), b: (f64, f64)) -> f64 {
3019        (a.0 - o.0) * (b.1 - o.1) - (a.1 - o.1) * (b.0 - o.0)
3020    }
3021    let mut lower = Vec::new();
3022    for &p in &sp {
3023        while lower.len() >= 2 && cross(lower[lower.len() - 2], lower[lower.len() - 1], p) <= 0.0 {
3024            lower.pop();
3025        }
3026        lower.push(p);
3027    }
3028    let mut upper = Vec::new();
3029    for &p in sp.iter().rev() {
3030        while upper.len() >= 2 && cross(upper[upper.len() - 2], upper[upper.len() - 1], p) <= 0.0 {
3031            upper.pop();
3032        }
3033        upper.push(p);
3034    }
3035    lower.pop();
3036    upper.pop();
3037    lower.extend(upper);
3038    lower
3039}
3040
3041/// Refine a seeded label AABB translation with caption kit + simplex.
3042///
3043/// `rest` is the label ink in world space at the greedy/snug seed (tx=ty=0).
3044/// Returns world-space delta `(dtx, dty)` to add to the seed origin.
3045pub fn refine_caption(
3046    chem_aabb: Aabb,
3047    bonds: &[(f64, f64, f64, f64)],
3048    rest: Aabb,
3049    preferred: Side,
3050    opt_dist: f64,
3051    clash_dist: f64,
3052) -> (f64, f64) {
3053    let mut world = LayoutWorld::new("mol");
3054    // Synthetic chem AABB (group) + bonds.
3055    install_chem(&mut world, bonds, &[], &[]);
3056    if let Some(n) = world.get_mut("mol/chem") {
3057        n.rest = Shape::Aabb(chem_aabb);
3058        n.shape = Shape::Aabb(chem_aabb);
3059    }
3060    let mut cs = Vec::new();
3061    let mut hard = Vec::new();
3062    let id = caption_kit(
3063        &mut world, &mut cs, &mut hard, rest, preferred, opt_dist, clash_dist,
3064    );
3065    let opts = SolveOpts {
3066        max_iters: 60,
3067        noise: 0.0,
3068        epsilon_px: 0.75,
3069        ..SolveOpts::default()
3070    };
3071    let _ = solve(&mut world, &cs, &hard, &opts);
3072    let n = world.get(&id).unwrap();
3073    (n.tx, n.ty)
3074}
3075
3076/// Refine region text after greedy edge place.
3077///
3078/// `atoms` are `(index, x, y)` centers — installed as ~0.3-bond disks so
3079/// contain / clash treat them as area, not points. Inside labels get hard
3080/// [`LAGRANGIAN_CONTAIN`] on the (grown) hull; PreferPose stays off so snug
3081/// can travel inward.
3082pub fn refine_region_text(
3083    bonds: &[(f64, f64, f64, f64)],
3084    atoms: &[(usize, f64, f64)],
3085    shades: &[(usize, f64, f64, f64)],
3086    hull: Shape,
3087    text_rest: Aabb,
3088    inside: bool,
3089    preferred: Side,
3090    clash_dist: f64,
3091    other_labels: &[Aabb],
3092) -> (f64, f64) {
3093    let mut world = LayoutWorld::new("mol");
3094    install_chem(&mut world, bonds, atoms, shades);
3095    let mut cs = Vec::new();
3096    let mut hard = Vec::new();
3097    let side_about = if atoms.is_empty() {
3098        text_rest.center()
3099    } else {
3100        let n = atoms.len() as f64;
3101        let sx: f64 = atoms.iter().map(|(_, x, _)| x).sum();
3102        let sy: f64 = atoms.iter().map(|(_, _, y)| y).sum();
3103        (sx / n, sy / n)
3104    };
3105    let id = region_text_kit(
3106        &mut world,
3107        &mut cs,
3108        &mut hard,
3109        0,
3110        hull,
3111        text_rest,
3112        inside,
3113        preferred,
3114        clash_dist,
3115        side_about,
3116        other_labels,
3117    );
3118    // Inside seeds often start far (clash-free outside, hull grown around them);
3119    // allow a larger simplex so soft snug to chem can travel inward.
3120    let opts = SolveOpts {
3121        max_iters: if inside { 160 } else { 80 },
3122        noise: 0.0,
3123        epsilon_px: 0.75,
3124        initial_simplex_scale: if inside { 14.0 } else { 4.0 },
3125        ..SolveOpts::default()
3126    };
3127    let _ = solve(&mut world, &cs, &hard, &opts);
3128    let n = world.get(&id).unwrap();
3129    (n.tx, n.ty)
3130}
3131
3132/// Refine callout label + tip; returns `(label_dxy, tip_dxy, route_xy_world)`.
3133pub fn refine_callout(
3134    bonds: &[(f64, f64, f64, f64)],
3135    label_rest: Aabb,
3136    tip_xy: (f64, f64),
3137    target: (f64, f64),
3138    tip_standoff: f64,
3139    preferred: Side,
3140    clash_dist: f64,
3141    routes: &[(f64, f64)],
3142) -> ((f64, f64), (f64, f64), Vec<(f64, f64)>) {
3143    let mut world = LayoutWorld::new("mol");
3144    install_chem(&mut world, bonds, &[], &[]);
3145    let mut cs = Vec::new();
3146    let mut hard = Vec::new();
3147    let (label_id, tip_id) = callout_kit(
3148        &mut world,
3149        &mut cs,
3150        &mut hard,
3151        0,
3152        label_rest,
3153        tip_xy,
3154        target,
3155        tip_standoff,
3156        preferred,
3157        clash_dist,
3158        routes,
3159    );
3160    let opts = SolveOpts {
3161        max_iters: 100,
3162        noise: 0.0,
3163        epsilon_px: 0.75,
3164        ..SolveOpts::default()
3165    };
3166    let _ = solve(&mut world, &cs, &hard, &opts);
3167    let label = world.get(&label_id).unwrap();
3168    let tip = world.get(&tip_id).unwrap();
3169    let mut route_out = Vec::new();
3170    for k in 0..routes.len() {
3171        let rid = format!("mol/annotations/callouts/c0/route{k}");
3172        if let Some(n) = world.get(&rid) {
3173            if let Shape::Point { x, y } = n.world_shape() {
3174                route_out.push((x, y));
3175            }
3176        }
3177    }
3178    ((label.tx, label.ty), (tip.tx, tip.ty), route_out)
3179}
3180
3181/// Refine atom number / custom atom label after a PreferPose seed.
3182///
3183/// `atom_texts` are fixed chem (and prior annotation) AABBs — the solver moves
3184/// the annotation Outside them. `halo_pad` / `avoid_shade` as in [`atom_number_kit`].
3185pub fn refine_atom_number(
3186    bonds: &[(f64, f64, f64, f64)],
3187    atoms: &[(usize, f64, f64)],
3188    shades: &[(usize, f64, f64, f64)],
3189    atom_texts: &[(usize, Aabb)],
3190    atom_idx: usize,
3191    rest: Aabb,
3192    clash_dist: f64,
3193    tether_px: f64,
3194    halo_pad: Option<f64>,
3195    avoid_shade: bool,
3196) -> (f64, f64) {
3197    let mut world = LayoutWorld::new("mol");
3198    install_chem_with_texts(&mut world, bonds, atoms, shades, atom_texts);
3199    let mut cs = Vec::new();
3200    let mut hard = Vec::new();
3201    let id = atom_number_kit(
3202        &mut world,
3203        &mut cs,
3204        &mut hard,
3205        atom_idx,
3206        rest,
3207        clash_dist,
3208        tether_px,
3209        halo_pad,
3210        avoid_shade,
3211    );
3212    let opts = SolveOpts {
3213        max_iters: 100,
3214        noise: 0.0,
3215        epsilon_px: 0.5,
3216        initial_simplex_scale: 4.0,
3217        ..SolveOpts::default()
3218    };
3219    let _ = solve(&mut world, &cs, &hard, &opts);
3220    let n = world.get(&id).unwrap();
3221    (n.tx, n.ty)
3222}
3223
3224/// Suggest up to `max_k` route points between label center and tip along a
3225/// soft arc away from bond midpoints (adaptive routing seed).
3226pub fn suggest_route_points(
3227    from: (f64, f64),
3228    to: (f64, f64),
3229    bond_mids: &[(f64, f64)],
3230    max_k: usize,
3231) -> Vec<(f64, f64)> {
3232    if max_k == 0 {
3233        return vec![];
3234    }
3235    let dx = to.0 - from.0;
3236    let dy = to.1 - from.1;
3237    let len = dx.hypot(dy).max(1e-6);
3238    let nx = -dy / len;
3239    let ny = dx / len;
3240    // If a bond mid sits near the straight segment, bend away.
3241    let mut bend: f64 = 0.0;
3242    for &(mx, my) in bond_mids {
3243        let t = ((mx - from.0) * dx + (my - from.1) * dy) / (len * len);
3244        if (0.1..0.9).contains(&t) {
3245            let px = from.0 + t * dx;
3246            let py = from.1 + t * dy;
3247            let dist = (mx - px).hypot(my - py);
3248            if dist < 12.0 {
3249                let side = (mx - px) * nx + (my - py) * ny;
3250                bend += if side >= 0.0 { -10.0 } else { 10.0 };
3251            }
3252        }
3253    }
3254    if bend.abs() < 1e-6 {
3255        return vec![];
3256    }
3257    let k = max_k.min(2);
3258    let mut out = Vec::with_capacity(k);
3259    for i in 1..=k {
3260        let t = i as f64 / (k as f64 + 1.0);
3261        let bx = from.0 + t * dx + nx * bend * (1.0 - (2.0 * t - 1.0).abs());
3262        let by = from.1 + t * dy + ny * bend * (1.0 - (2.0 * t - 1.0).abs());
3263        out.push((bx, by));
3264    }
3265    out
3266}
3267
3268#[cfg(test)]
3269mod tests {
3270    use super::*;
3271
3272    #[test]
3273    fn aabb_union_nested_group() {
3274        let mut w = LayoutWorld::new("mol");
3275        install_chem(
3276            &mut w,
3277            &[(0.0, 0.0, 10.0, 0.0)],
3278            &[(0, 0.0, 0.0), (1, 10.0, 0.0)],
3279            &[],
3280        );
3281        let a = w.subtree_aabb("mol/chem").unwrap();
3282        assert!(a.x0 <= 0.0 && a.x1 >= 10.0);
3283        assert!(w.get("mol/chem/atoms/a0/coord").is_some());
3284        assert!(w.get("mol/chem/bonds/b0").is_some());
3285    }
3286
3287    #[test]
3288    fn outside_group_covers_children() {
3289        let mut w = LayoutWorld::new("mol");
3290        install_chem(
3291            &mut w,
3292            &[(0.0, 0.0, 20.0, 0.0)],
3293            &[(0, 0.0, 0.0), (1, 20.0, 0.0)],
3294            &[],
3295        );
3296        let mut cs = Vec::new();
3297        let mut hard = Vec::new();
3298        let ink = Aabb::new(-5.0, 10.0, 5.0, 18.0);
3299        let id = caption_kit(&mut w, &mut cs, &mut hard, ink, Side::Below, 4.0, 2.0);
3300        // Caption overlapping chem should have high Outside energy.
3301        w.set_pose(&id, 10.0, -14.0); // pull onto the bond
3302        let e_bad = energy(&w, &cs, &[], 0.0);
3303        w.set_pose(&id, 0.0, 0.0); // rest below
3304        let e_ok = energy(&w, &cs, &[], 0.0);
3305        assert!(
3306            e_bad > e_ok + 1.0,
3307            "overlap should cost more: bad={e_bad} ok={e_ok}"
3308        );
3309    }
3310
3311    #[test]
3312    fn edge_distance_aabb_circle() {
3313        let a = Shape::Aabb(Aabb::new(0.0, 0.0, 10.0, 10.0));
3314        let c = Shape::Circle {
3315            cx: 20.0,
3316            cy: 5.0,
3317            r: 2.0,
3318        };
3319        let d = edge_signed_distance(&a, &c);
3320        assert!((d - 8.0).abs() < 1e-6, "d={d}");
3321    }
3322
3323    #[test]
3324    fn point_in_hull_negative_distance() {
3325        let hull = Shape::PointSet(vec![(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]);
3326        let d = edge_signed_distance(&Shape::Point { x: 5.0, y: 5.0 }, &hull);
3327        assert!(d < 0.0, "inside should be negative, d={d}");
3328    }
3329
3330    #[test]
3331    fn simplex_moves_caption_off_chem() {
3332        let mut w = LayoutWorld::new("mol");
3333        install_chem(
3334            &mut w,
3335            &[(0.0, 0.0, 30.0, 0.0)],
3336            &[(0, 0.0, 0.0), (1, 30.0, 0.0)],
3337            &[],
3338        );
3339        let mut cs = Vec::new();
3340        let mut hard = Vec::new();
3341        // Rest overlapping chem AABB.
3342        let ink = Aabb::new(5.0, -4.0, 25.0, 4.0);
3343        let id = caption_kit(&mut w, &mut cs, &mut hard, ink, Side::Below, 6.0, 2.0);
3344        w.set_pose(&id, 0.0, 0.0);
3345        let opts = SolveOpts {
3346            max_iters: 80,
3347            noise: 0.0,
3348            epsilon_px: 0.5,
3349            ..SolveOpts::default()
3350        };
3351        let r = solve(&mut w, &cs, &hard, &opts);
3352        let pose = w.get(&id).unwrap();
3353        let box_ = pose.world_shape().aabb();
3354        // Should prefer sitting below the chem band.
3355        assert!(
3356            box_.y0 > 2.0 || r.iters > 0,
3357            "expected move below, box={box_:?} iters={}",
3358            r.iters
3359        );
3360    }
3361
3362    #[test]
3363    fn hull_proxy_and_bezier_path() {
3364        let include = [(0.0, 0.0), (20.0, 0.0), (20.0, 10.0), (0.0, 10.0)];
3365        let exclude = [(25.0, 5.0)];
3366        let proxy = hull_proxy(&include, &exclude, 4.0, 8.0);
3367        match &proxy {
3368            Shape::PointSet(pts) => assert!(pts.len() >= 3),
3369            Shape::Aabb(_) => {}
3370            _ => panic!("unexpected"),
3371        }
3372        let d = bezier_path_from_proxy(&proxy, 0.5);
3373        assert!(
3374            d.contains('C') || d.contains('Q') || d.contains('M'),
3375            "d={d}"
3376        );
3377    }
3378
3379    #[test]
3380    fn centripetal_catmull_rom_interpolates_square() {
3381        let sq = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)];
3382        let d = centripetal_catmull_rom_closed_path(&sq);
3383        assert!(d.starts_with("M 0.00 0.00"), "d={d}");
3384        assert!(d.contains("C "), "expected cubic segments: {d}");
3385        for (x, y) in sq {
3386            let needle = format!("{x:.2} {y:.2}");
3387            assert!(
3388                d.contains(&needle),
3389                "missing interpolating vertex {needle} in {d}"
3390            );
3391        }
3392    }
3393
3394    #[test]
3395    fn hull_proxy_evicts_exclude_inside_bay() {
3396        // L-shaped include: convex chord (60,0)—(0,60) would swallow (20,20).
3397        let include = [
3398            (0.0, 0.0),
3399            (30.0, 0.0),
3400            (60.0, 0.0),
3401            (0.0, 30.0),
3402            (0.0, 60.0),
3403            (15.0, 0.0),
3404            (45.0, 0.0),
3405            (0.0, 15.0),
3406            (0.0, 45.0),
3407        ];
3408        let exclude = [(20.0, 20.0)];
3409        let clear = 8.0;
3410        let proxy = hull_proxy(&include, &exclude, 2.0, clear);
3411        let Shape::PointSet(pts) = proxy else {
3412            panic!("expected PointSet");
3413        };
3414        assert!(
3415            !point_in_poly(20.0, 20.0, &pts),
3416            "exclude must not lie inside proxy"
3417        );
3418        let d = edge_signed_distance(
3419            &Shape::Point { x: 20.0, y: 20.0 },
3420            &Shape::PointSet(pts.clone()),
3421        );
3422        assert!(
3423            d >= clear - 1.5,
3424            "exclude needs ~{clear} clearance from hull (include-guarded plane), signed_dist={d}"
3425        );
3426    }
3427
3428    #[test]
3429    fn route_points_bend_around_bond() {
3430        let mids = [(50.0, 0.0)];
3431        let pts = suggest_route_points((0.0, 0.0), (100.0, 0.0), &mids, 2);
3432        assert!(!pts.is_empty());
3433        assert!(pts[0].1.abs() > 1.0, "should bend off axis: {:?}", pts);
3434    }
3435
3436    #[test]
3437    fn prefer_pose_is_a_well_at_the_placement() {
3438        let mut w = LayoutWorld::new("mol");
3439        install_chem(&mut w, &[], &[], &[]);
3440        if let Some(n) = w.get_mut("mol/chem") {
3441            let chem = Aabb::new(0.0, 0.0, 40.0, 20.0);
3442            n.rest = Shape::Aabb(chem);
3443            n.shape = Shape::Aabb(chem);
3444        }
3445        let mut cs = Vec::new();
3446        let mut hard = Vec::new();
3447        // Placed centered under the chem box, half a bond below.
3448        let ink = Aabb::new(10.0, 35.0, 30.0, 48.0);
3449        let id = caption_kit(&mut w, &mut cs, &mut hard, ink, Side::Below, 15.0, 3.0);
3450        let at_pose = energy(&w, &cs, &[], 0.0);
3451        w.set_pose(&id, 18.0, 0.0);
3452        let shifted = energy(&w, &cs, &[], 0.0);
3453        assert!(
3454            shifted > at_pose + 20.0,
3455            "leaving the placement should cost energy: pose={at_pose} shifted={shifted}"
3456        );
3457        let opts = SolveOpts {
3458            max_iters: 40,
3459            noise: 0.0,
3460            epsilon_px: 0.5,
3461            w_travel: 0.0,
3462            ..SolveOpts::default()
3463        };
3464        let _ = solve(&mut w, &cs, &hard, &opts);
3465        let back = w.get(&id).unwrap();
3466        assert!(
3467            back.tx.abs() < 3.0 && back.ty.abs() < 3.0,
3468            "solver should return to the placement well, got tx={} ty={}",
3469            back.tx,
3470            back.ty
3471        );
3472    }
3473
3474    #[test]
3475    fn prefer_side_align_along_is_constraint_data_not_target_shape() {
3476        let mut w = LayoutWorld::new("mol");
3477        w.insert(
3478            "lab",
3479            "mol",
3480            ObjectType::Group,
3481            Shape::Aabb(Aabb::new(-4.0, -2.0, 4.0, 2.0)),
3482            false,
3483        );
3484        w.insert(
3485            "pt",
3486            "mol",
3487            ObjectType::Group,
3488            Shape::Point { x: 0.0, y: 0.0 },
3489            true,
3490        );
3491        w.insert(
3492            "box",
3493            "mol",
3494            ObjectType::Group,
3495            Shape::Aabb(Aabb::new(-10.0, -10.0, 10.0, 10.0)),
3496            true,
3497        );
3498        w.set_pose("lab", 20.0, 12.0);
3499
3500        let hinge = Constraint::PreferSide {
3501            a: "lab".into(),
3502            b: "pt".into(),
3503            side: Side::Right,
3504            strength: 4.0,
3505            align_along: 0.0,
3506        };
3507        let along = Constraint::PreferSide {
3508            a: "lab".into(),
3509            b: "pt".into(),
3510            side: Side::Right,
3511            strength: 4.0,
3512            align_along: 0.35,
3513        };
3514        let e_hinge = constraint_energy(&w, &hinge);
3515        let e_along = constraint_energy(&w, &along);
3516        assert!(
3517            e_along > e_hinge + 10.0,
3518            "align_along must cost the y offset: hinge={e_hinge} along={e_along}"
3519        );
3520
3521        let along_box = Constraint::PreferSide {
3522            a: "lab".into(),
3523            b: "box".into(),
3524            side: Side::Right,
3525            strength: 4.0,
3526            align_along: 0.35,
3527        };
3528        let e_box = constraint_energy(&w, &along_box);
3529        assert!(
3530            (e_box - e_along).abs() < 1e-9,
3531            "align_along energy must not depend on Point vs AABB: pt={e_along} box={e_box}"
3532        );
3533    }
3534
3535    #[test]
3536    fn kits_put_align_along_on_prefer_side_not_in_the_solver() {
3537        let mut w = LayoutWorld::new("mol");
3538        install_chem(&mut w, &[], &[(0, 0.0, 0.0)], &[]);
3539        if let Some(n) = w.get_mut("mol/chem") {
3540            let chem = Aabb::new(0.0, 0.0, 40.0, 20.0);
3541            n.rest = Shape::Aabb(chem);
3542            n.shape = Shape::Aabb(chem);
3543        }
3544        let ink = Aabb::new(-4.0, -2.0, 4.0, 2.0);
3545        let mut cap_cs = Vec::new();
3546        let mut cap_h = Vec::new();
3547        caption_kit(&mut w, &mut cap_cs, &mut cap_h, ink, Side::Below, 8.0, 3.0);
3548        let cap_along: Vec<f64> = cap_cs
3549            .iter()
3550            .filter_map(|c| match c {
3551                Constraint::PreferSide { align_along, .. } => Some(*align_along),
3552                _ => None,
3553            })
3554            .collect();
3555        assert_eq!(cap_along, vec![0.0], "caption vs chem AABB is hinge-only");
3556
3557        let mut reg_cs = Vec::new();
3558        let mut reg_h = Vec::new();
3559        region_text_kit(
3560            &mut w,
3561            &mut reg_cs,
3562            &mut reg_h,
3563            0,
3564            Shape::Aabb(Aabb::new(0.0, 0.0, 40.0, 40.0)),
3565            ink,
3566            true,
3567            Side::Left,
3568            3.0,
3569            (20.0, 20.0),
3570            &[],
3571        );
3572        let reg_along: Vec<f64> = reg_cs
3573            .iter()
3574            .filter_map(|c| match c {
3575                Constraint::PreferSide { align_along, .. } => Some(*align_along),
3576                _ => None,
3577            })
3578            .collect();
3579        assert_eq!(
3580            reg_along,
3581            vec![0.35],
3582            "region pos vs atom-mean Point requests edge-align on the constraint"
3583        );
3584        let contain: Vec<u8> = reg_h
3585            .iter()
3586            .filter_map(|h| match h {
3587                HardConstraint::Inside { lagrangian, .. } => Some(*lagrangian),
3588                _ => None,
3589            })
3590            .collect();
3591        assert_eq!(
3592            contain,
3593            vec![LAGRANGIAN_CONTAIN],
3594            "inside region contain is the third Lagrangian, after clear and tether"
3595        );
3596    }
3597
3598    #[test]
3599    fn lagrangian_order_is_clear_then_tether_then_contain() {
3600        assert!(LAGRANGIAN_CLEAR < LAGRANGIAN_TETHER);
3601        assert!(LAGRANGIAN_TETHER < LAGRANGIAN_CONTAIN);
3602    }
3603
3604    #[test]
3605    fn keep_off_outranks_containment() {
3606        let mut w = LayoutWorld::new("mol");
3607        w.insert(
3608            "hull",
3609            "mol",
3610            ObjectType::Group,
3611            Shape::Aabb(Aabb::new(0.0, 0.0, 40.0, 40.0)),
3612            true,
3613        );
3614        w.insert(
3615            "obs",
3616            "mol",
3617            ObjectType::Group,
3618            Shape::Aabb(Aabb::new(12.0, 16.0, 28.0, 24.0)),
3619            true,
3620        );
3621        w.insert(
3622            "lab",
3623            "mol",
3624            ObjectType::Group,
3625            Shape::Aabb(Aabb::new(-6.0, -3.0, 6.0, 3.0)),
3626            false,
3627        );
3628        w.set_pose("lab", 20.0, 20.0);
3629        let hard = vec![
3630            HardConstraint::Outside {
3631                a: "lab".into(),
3632                b: "obs".into(),
3633                clash_dist: 2.0,
3634                lagrangian: LAGRANGIAN_CLEAR,
3635            },
3636            HardConstraint::Inside {
3637                a: "lab".into(),
3638                b: "hull".into(),
3639                pad: 1.0,
3640                lagrangian: LAGRANGIAN_CONTAIN,
3641            },
3642        ];
3643        let opts = SolveOpts {
3644            max_iters: 80,
3645            noise: 0.0,
3646            epsilon_px: 0.5,
3647            w_travel: 0.0,
3648            initial_simplex_scale: 8.0,
3649            al_outer_max: 8,
3650            ..SolveOpts::default()
3651        };
3652        let _ = solve(&mut w, &[], &hard, &opts);
3653        let lab = w.get("lab").unwrap().world_shape();
3654        let obs = w.get("obs").unwrap().world_shape();
3655        let d = edge_signed_distance(&lab, &obs);
3656        assert!(
3657            d + 1e-6 >= 2.0 - opts.al_tol,
3658            "no-overlap must outrank contain: d={d} lab={lab:?}"
3659        );
3660    }
3661
3662    #[test]
3663    fn inside_energy_is_g_plus_squared_for_every_shape_pair() {
3664        let mut w = LayoutWorld::new("mol");
3665        w.insert(
3666            "lab",
3667            "mol",
3668            ObjectType::Group,
3669            Shape::Aabb(Aabb::new(-4.0, -2.0, 4.0, 2.0)),
3670            false,
3671        );
3672        w.insert(
3673            "box",
3674            "mol",
3675            ObjectType::Group,
3676            Shape::Aabb(Aabb::new(-10.0, -10.0, 10.0, 10.0)),
3677            true,
3678        );
3679        w.insert(
3680            "circ",
3681            "mol",
3682            ObjectType::Group,
3683            Shape::Circle {
3684                cx: 0.0,
3685                cy: 0.0,
3686                r: 12.0,
3687            },
3688            true,
3689        );
3690        w.set_pose("lab", 9.0, 0.0);
3691
3692        for b in ["box", "circ"] {
3693            let soft = Constraint::Inside {
3694                a: "lab".into(),
3695                b: b.into(),
3696                pad: 1.0,
3697                strength: 3.0,
3698            };
3699            let hard = HardConstraint::Inside {
3700                a: "lab".into(),
3701                b: b.into(),
3702                pad: 1.0,
3703                lagrangian: LAGRANGIAN_CONTAIN,
3704            };
3705            let e = constraint_energy(&w, &soft);
3706            let g = hard_g(&w, &hard).max(0.0);
3707            assert!(
3708                (e - 3.0 * g * g).abs() < 1e-9,
3709                "Inside energy must be strength·g⁺² ({b}): e={e} g={g}"
3710            );
3711            assert!(g > 0.5, "fixture should protrude ({b}): g={g}");
3712        }
3713    }
3714
3715    #[test]
3716    fn atom_number_kit_ignores_shade() {
3717        let mut w = LayoutWorld::new("mol");
3718        install_chem(&mut w, &[], &[(0, 0.0, 0.0)], &[(0, 0.0, 0.0, 8.0)]);
3719        let mut cs = Vec::new();
3720        let mut hard = Vec::new();
3721        let ink = Aabb::new(-2.0, -2.0, 2.0, 2.0);
3722        let id = atom_number_kit(
3723            &mut w,
3724            &mut cs,
3725            &mut hard,
3726            0,
3727            ink,
3728            4.0,
3729            ATOM_NUMBER_TETHER_PX,
3730            Some(2.0),
3731            true,
3732        );
3733        let e = energy(&w, &cs, &[], 0.0);
3734        assert!(e.is_finite());
3735        assert!(w.get(&id).is_some());
3736        // No layout constraint vs shade — wash/halo are paint-only for numbers.
3737        let shade_soft = cs.iter().any(|c| match c {
3738            Constraint::Outside { b, .. } => b.ends_with("/shade"),
3739            _ => false,
3740        });
3741        let shade_hard = hard.iter().any(|h| match h {
3742            HardConstraint::Outside { b, .. } => b.ends_with("/shade"),
3743            _ => false,
3744        });
3745        assert!(
3746            !shade_soft && !shade_hard,
3747            "atom_number_kit must not constrain vs shade"
3748        );
3749    }
3750
3751    #[test]
3752    fn atom_number_kit_clears_bonds_hard() {
3753        let mut w = LayoutWorld::new("mol");
3754        install_chem(
3755            &mut w,
3756            &[(0.0, 0.0, 30.0, 0.0)],
3757            &[(0, 0.0, 0.0), (1, 30.0, 0.0)],
3758            &[],
3759        );
3760        let mut cs = Vec::new();
3761        let mut hard = Vec::new();
3762        let ink = Aabb::new(10.0, -2.0, 14.0, 2.0); // sits on the bond
3763        let _ = atom_number_kit(
3764            &mut w,
3765            &mut cs,
3766            &mut hard,
3767            0,
3768            ink,
3769            3.0,
3770            ATOM_NUMBER_TETHER_PX,
3771            None,
3772            false,
3773        );
3774        let bond_h: Vec<_> = hard
3775            .iter()
3776            .filter_map(|h| match h {
3777                HardConstraint::Outside { b, clash_dist, .. } if b.contains("/bonds/") => {
3778                    Some(*clash_dist)
3779                }
3780                _ => None,
3781            })
3782            .collect();
3783        assert!(
3784            !bond_h.is_empty(),
3785            "atom numbers must hard-Outside every bond line"
3786        );
3787        assert!(
3788            bond_h.iter().all(|&d| d >= 3.0 - 1e-9),
3789            "bond clear must use full clash_dist; got {bond_h:?}"
3790        );
3791        let bond_soft: Vec<_> = cs
3792            .iter()
3793            .filter_map(|c| match c {
3794                Constraint::Outside {
3795                    b,
3796                    clash_dist,
3797                    strength,
3798                    ..
3799                } if b.contains("/bonds/") => Some((*clash_dist, *strength)),
3800                _ => None,
3801            })
3802            .collect();
3803        assert!(
3804            !bond_soft.is_empty()
3805                && bond_soft
3806                    .iter()
3807                    .all(|&(d, s)| d >= 3.0 - 1e-9 && (s - ATOM_MILD_REPEL).abs() < 1e-9),
3808            "bonds also get mild soft Outside repulsion; got {bond_soft:?}"
3809        );
3810        assert!(
3811            !cs.iter()
3812                .any(|c| matches!(c, Constraint::MinGap { b, .. } if b.contains("/bonds/"))),
3813            "bond clearance is Outside, not MinGap"
3814        );
3815    }
3816
3817    #[test]
3818    fn atom_text_tether_longer_than_number() {
3819        assert!(
3820            ATOM_TEXT_TETHER_PX > ATOM_NUMBER_TETHER_PX,
3821            "custom atom text should allow a longer MaxDist than index/mapno"
3822        );
3823    }
3824
3825    #[test]
3826    fn atom_number_kit_tethers_to_atom() {
3827        let mut w = LayoutWorld::new("mol");
3828        install_chem(&mut w, &[], &[(0, 0.0, 0.0)], &[]);
3829        let mut cs = Vec::new();
3830        let mut hard = Vec::new();
3831        let ink = Aabb::new(-2.0, -2.0, 2.0, 2.0);
3832        let _ = atom_number_kit(
3833            &mut w,
3834            &mut cs,
3835            &mut hard,
3836            0,
3837            ink,
3838            3.0,
3839            ATOM_NUMBER_TETHER_PX,
3840            None,
3841            false,
3842        );
3843        let tether: Vec<_> = hard
3844            .iter()
3845            .filter_map(|h| match h {
3846                HardConstraint::MaxDist { b, dist, .. } => Some((b.clone(), *dist)),
3847                _ => None,
3848            })
3849            .collect();
3850        assert_eq!(tether.len(), 1, "atom label must MaxDist-tether");
3851        assert!(
3852            tether[0].0.ends_with("/snug"),
3853            "without chem text, tether to atom center point (/snug); got {}",
3854            tether[0].0
3855        );
3856        assert!(
3857            (tether[0].1 - ATOM_NUMBER_TETHER_PX).abs() < 1e-9,
3858            "tether dist must be ATOM_NUMBER_TETHER_PX; got {}",
3859            tether[0].1
3860        );
3861        // Custom atom text may request the longer ceiling.
3862        let mut w2 = LayoutWorld::new("mol");
3863        install_chem(&mut w2, &[], &[(0, 0.0, 0.0)], &[]);
3864        let mut cs2 = Vec::new();
3865        let mut hard_text = Vec::new();
3866        let _ = atom_number_kit(
3867            &mut w2,
3868            &mut cs2,
3869            &mut hard_text,
3870            0,
3871            ink,
3872            3.0,
3873            ATOM_TEXT_TETHER_PX,
3874            None,
3875            false,
3876        );
3877        let text_tether: Vec<_> = hard_text
3878            .iter()
3879            .filter_map(|h| match h {
3880                HardConstraint::MaxDist { dist, .. } => Some(*dist),
3881                _ => None,
3882            })
3883            .collect();
3884        assert_eq!(text_tether.len(), 1);
3885        assert!(
3886            (text_tether[0] - ATOM_TEXT_TETHER_PX).abs() < 1e-9,
3887            "kit must honor caller tether_px; got {}",
3888            text_tether[0]
3889        );
3890    }
3891
3892    #[test]
3893    fn atom_number_kit_tethers_to_chem_text_when_present() {
3894        let mut w = LayoutWorld::new("mol");
3895        install_chem_with_texts(
3896            &mut w,
3897            &[],
3898            &[(0, 0.0, 0.0)],
3899            &[],
3900            &[(0, Aabb::new(4.0, -3.0, 14.0, 3.0))], // chem "OH" beside atom
3901        );
3902        let mut cs = Vec::new();
3903        let mut hard = Vec::new();
3904        let ink = Aabb::new(16.0, -2.0, 22.0, 2.0);
3905        let _ = atom_number_kit(
3906            &mut w,
3907            &mut cs,
3908            &mut hard,
3909            0,
3910            ink,
3911            3.0,
3912            ATOM_NUMBER_TETHER_PX,
3913            None,
3914            false,
3915        );
3916        let tether: Vec<_> = hard
3917            .iter()
3918            .filter_map(|h| match h {
3919                HardConstraint::MaxDist { b, .. } => Some(b.clone()),
3920                _ => None,
3921            })
3922            .collect();
3923        assert_eq!(tether, vec!["mol/chem/atom_texts/t0".to_string()]);
3924        assert!(
3925            !hard.iter().any(|h| matches!(
3926                h,
3927                HardConstraint::MaxDist { b, .. } if b.ends_with("/coord")
3928            )),
3929            "chem text wins over atom point for tether"
3930        );
3931    }
3932
3933    #[test]
3934    fn al_keeps_atom_label_within_tether() {
3935        let mut w = LayoutWorld::new("mol");
3936        install_chem(
3937            &mut w,
3938            &[(0.0, 0.0, 30.0, 0.0)],
3939            &[(0, 0.0, 0.0), (1, 30.0, 0.0)],
3940            &[],
3941        );
3942        let mut cs = Vec::new();
3943        let mut hard = Vec::new();
3944        // Seed far from atom 0 — soft PreferPose would hold it; MaxDist must pull in.
3945        let ink = Aabb::new(200.0, -2.0, 208.0, 2.0);
3946        let id = atom_number_kit(
3947            &mut w,
3948            &mut cs,
3949            &mut hard,
3950            0,
3951            ink,
3952            3.0,
3953            ATOM_NUMBER_TETHER_PX,
3954            None,
3955            false,
3956        );
3957        let g0 = hard
3958            .iter()
3959            .filter_map(|h| match h {
3960                HardConstraint::MaxDist { .. } => Some(hard_g(&w, h).max(0.0)),
3961                _ => None,
3962            })
3963            .fold(0.0_f64, f64::max);
3964        assert!(g0 > 50.0, "far seed must violate tether, g0={g0}");
3965        let opts = SolveOpts {
3966            max_iters: 80,
3967            noise: 0.0,
3968            epsilon_px: 0.5,
3969            initial_simplex_scale: 8.0,
3970            al_outer_max: 8,
3971            al_tol: 0.25,
3972            ..SolveOpts::default()
3973        };
3974        let r = solve(&mut w, &cs, &hard, &opts);
3975        let tether_v = hard
3976            .iter()
3977            .filter_map(|h| match h {
3978                HardConstraint::MaxDist { .. } => Some(hard_g(&w, h).max(0.0)),
3979                _ => None,
3980            })
3981            .fold(0.0_f64, f64::max);
3982        assert!(
3983            tether_v <= opts.al_tol + 1e-6,
3984            "AL must satisfy MaxDist tether: viol={tether_v} iters={}",
3985            r.iters
3986        );
3987        let box_ = w.get(&id).unwrap().world_shape();
3988        let coord = w.get("mol/chem/atoms/a0/coord").unwrap().world_shape();
3989        let d = edge_signed_distance(&box_, &coord);
3990        assert!(
3991            d <= ATOM_NUMBER_TETHER_PX + opts.al_tol + 1e-6,
3992            "label edge gap to atom must be ≤ tether, d={d}"
3993        );
3994    }
3995
3996    #[test]
3997    fn al_moves_atom_label_off_bond() {
3998        let mut w = LayoutWorld::new("mol");
3999        install_chem(
4000            &mut w,
4001            &[(0.0, 0.0, 40.0, 0.0)],
4002            &[(0, 0.0, 0.0), (1, 40.0, 0.0)],
4003            &[],
4004        );
4005        let mut cs = Vec::new();
4006        let mut hard = Vec::new();
4007        let clash = 3.0;
4008        // PreferPose seed sits on the bond — soft alone can leave residual.
4009        let ink = Aabb::new(18.0, -2.0, 22.0, 2.0);
4010        let id = atom_number_kit(
4011            &mut w,
4012            &mut cs,
4013            &mut hard,
4014            0,
4015            ink,
4016            clash,
4017            ATOM_NUMBER_TETHER_PX,
4018            None,
4019            false,
4020        );
4021        let g0 = max_hard_violation(&w, &hard);
4022        assert!(g0 > 1.0, "seed must violate hard bond clear, g0={g0}");
4023        let opts = SolveOpts {
4024            max_iters: 80,
4025            noise: 0.0,
4026            epsilon_px: 0.5,
4027            initial_simplex_scale: 4.0,
4028            al_outer_max: 8,
4029            al_tol: 0.25,
4030            ..SolveOpts::default()
4031        };
4032        let r = solve(&mut w, &cs, &hard, &opts);
4033        assert!(
4034            r.max_hard_violation <= opts.al_tol + 1e-6,
4035            "AL should drive hard residual ≤ tol: viol={} iters={}",
4036            r.max_hard_violation,
4037            r.iters
4038        );
4039        let box_ = w.get(&id).unwrap().world_shape();
4040        // Compare against the installed bond shapes (stroke half-width included).
4041        let bonds = w.get("mol/chem/bonds").unwrap().children.clone();
4042        for bid in bonds {
4043            let sb = w.get(&bid).unwrap().world_shape();
4044            let d = edge_signed_distance(&box_, &sb);
4045            assert!(
4046                d + opts.al_tol + 1e-6 >= clash,
4047                "label must clear bond within al_tol: edge_dist={d} clash={clash}"
4048            );
4049        }
4050        let _ = id;
4051    }
4052
4053    #[test]
4054    fn atom_number_kit_clears_prior_labels_hard() {
4055        let mut w = LayoutWorld::new("mol");
4056        install_chem_with_texts(
4057            &mut w,
4058            &[(0.0, 0.0, 30.0, 0.0)],
4059            &[(0, 0.0, 0.0), (1, 30.0, 0.0)],
4060            &[],
4061            &[(10_000, Aabb::new(6.0, -5.0, 14.0, 5.0))],
4062        );
4063        let mut cs = Vec::new();
4064        let mut hard = Vec::new();
4065        let _ = atom_number_kit(
4066            &mut w,
4067            &mut cs,
4068            &mut hard,
4069            0,
4070            Aabb::new(5.0, -6.0, 25.0, 6.0),
4071            3.0,
4072            ATOM_TEXT_TETHER_PX,
4073            None,
4074            false,
4075        );
4076        let prior_h: Vec<_> = hard
4077            .iter()
4078            .filter_map(|h| match h {
4079                HardConstraint::Outside {
4080                    b,
4081                    clash_dist,
4082                    lagrangian,
4083                    ..
4084                } if b.ends_with("/t10000") => Some((*clash_dist, *lagrangian)),
4085                _ => None,
4086            })
4087            .collect();
4088        assert_eq!(
4089            prior_h,
4090            vec![(3.0, LAGRANGIAN_CLEAR)],
4091            "keep-off-labels must be the clear Lagrangian, not a soft hinge"
4092        );
4093        let tether_g: Vec<_> = hard
4094            .iter()
4095            .filter_map(|h| match h {
4096                HardConstraint::MaxDist { lagrangian, .. } => Some(*lagrangian),
4097                _ => None,
4098            })
4099            .collect();
4100        assert_eq!(
4101            tether_g,
4102            vec![LAGRANGIAN_TETHER],
4103            "tether is a weaker Lagrangian than keep-off"
4104        );
4105    }
4106
4107    #[test]
4108    fn atom_label_hard_clears_prior_near_home() {
4109        // Same-atom number vs custom text: snug used to pull "ortho" onto "2".
4110        let bonds = [(0.0, 0.0, 30.0, 0.0)];
4111        let atoms = [(0usize, 0.0, 0.0), (1, 30.0, 0.0)];
4112        let prior = Aabb::new(6.0, -5.0, 14.0, 5.0);
4113        let seed = Aabb::new(5.0, -6.0, 25.0, 6.0);
4114        let (dtx, dty) = refine_atom_number(
4115            &bonds,
4116            &atoms,
4117            &[],
4118            &[(10_000, prior)],
4119            0,
4120            seed,
4121            3.0,
4122            ATOM_TEXT_TETHER_PX,
4123            None,
4124            false,
4125        );
4126        let placed = seed.translated(dtx, dty);
4127        assert!(
4128            !placed.overlaps(prior),
4129            "custom label {placed:?} must clear prior number {prior:?} (dtx={dtx} dty={dty})"
4130        );
4131        let d = edge_signed_distance(&Shape::Aabb(placed), &Shape::Point { x: 0.0, y: 0.0 });
4132        assert!(
4133            d <= ATOM_TEXT_TETHER_PX + 1.0,
4134            "must stay tethered to the atom: d={d}"
4135        );
4136    }
4137
4138    #[test]
4139    fn install_chem_under_non_mol_parent() {
4140        let mut w = LayoutWorld::rooted("scheme", ObjectType::Scheme);
4141        let mol = w.insert(
4142            "scheme/mols/m0",
4143            "scheme",
4144            ObjectType::Mol,
4145            Shape::Aabb(Aabb::new(0.0, 0.0, 40.0, 20.0)),
4146            true,
4147        );
4148        install_chem_under(
4149            &mut w,
4150            &mol,
4151            &[(2.0, 10.0, 30.0, 10.0)],
4152            &[(0, 2.0, 10.0)],
4153            &[],
4154            &[],
4155        );
4156        assert!(w.get("scheme/mols/m0/chem/bonds/b0").is_some());
4157        let mut hard = Vec::new();
4158        push_clear_leaves(
4159            &w,
4160            &mut hard,
4161            "scheme/mols/m0/chem/bonds/b0",
4162            "scheme/mols/m0/chem",
4163            4.0,
4164        );
4165        assert!(hard
4166            .iter()
4167            .any(|h| matches!(h, HardConstraint::Outside { .. })));
4168    }
4169
4170    #[test]
4171    fn clash_grid_is_opt_in_not_outside() {
4172        let mut w = LayoutWorld::new("mol");
4173        install_chem(
4174            &mut w,
4175            &[(0.0, 0.0, 100.0, 0.0)],
4176            &[(0, 0.0, 0.0), (1, 100.0, 0.0)],
4177            &[],
4178        );
4179        w.recompute_group_aabbs();
4180        let x = 50.0;
4181        let y = ATOM_DISK_R_PX - 1.0;
4182        w.insert("p", "mol", ObjectType::Group, Shape::Point { x, y }, true);
4183        let h = HardConstraint::Outside {
4184            a: "p".into(),
4185            b: "mol/chem".into(),
4186            clash_dist: 4.0,
4187            lagrangian: LAGRANGIAN_CLEAR,
4188        };
4189        let g = hard_g(&w, &h);
4190        let ink = w.ink_signed("mol/chem", x, y).expect("chem raster");
4191        assert!(
4192            g > 0.0,
4193            "Outside vs chem stays the union AABB (point is inside the box): g={g}"
4194        );
4195        assert!(
4196            ink > 2.0,
4197            "ink_signed is the opt-in raster; air beside the bond: {ink}"
4198        );
4199    }
4200
4201    #[test]
4202    fn eval_shape_assembles_child_polyline() {
4203        let mut w = LayoutWorld::rooted("scheme", ObjectType::Scheme);
4204        w.insert(
4205            "e0",
4206            "scheme",
4207            ObjectType::Edge,
4208            Shape::Polyline(vec![]),
4209            true,
4210        );
4211        w.insert(
4212            "e0/p0",
4213            "e0",
4214            ObjectType::EdgePoint,
4215            Shape::Point { x: 0.0, y: 0.0 },
4216            false,
4217        );
4218        w.insert(
4219            "e0/p1",
4220            "e0",
4221            ObjectType::EdgePoint,
4222            Shape::Point { x: 10.0, y: 0.0 },
4223            false,
4224        );
4225        w.set_pose("e0/p1", 0.0, 5.0);
4226        match w.eval_shape("e0").unwrap() {
4227            Shape::Polyline(pts) => {
4228                assert_eq!(pts.len(), 2);
4229                assert!((pts[1].1 - 5.0).abs() < 1e-9);
4230            }
4231            other => panic!("{other:?}"),
4232        }
4233    }
4234
4235    #[test]
4236    fn eval_shape_keeps_elk_routing_vertices() {
4237        let mut w = LayoutWorld::rooted("scheme", ObjectType::Scheme);
4238        w.insert(
4239            "e0",
4240            "scheme",
4241            ObjectType::Edge,
4242            Shape::Polyline(vec![]),
4243            true,
4244        );
4245        let controls = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0)];
4246        for (i, (x, y)) in controls.into_iter().enumerate() {
4247            w.insert(
4248                format!("e0/p{i}"),
4249                "e0",
4250                ObjectType::EdgePoint,
4251                Shape::Point { x, y },
4252                false,
4253            );
4254        }
4255        match w.eval_shape("e0").unwrap() {
4256            Shape::Polyline(pts) => {
4257                assert_eq!(pts, controls, "control polyline, not Catmull samples")
4258            }
4259            other => panic!("{other:?}"),
4260        }
4261    }
4262
4263    #[test]
4264    fn polyline_signed_distance_follows_catmull_not_chords() {
4265        let controls = vec![(0.0, 0.0), (80.0, 0.0), (80.0, 80.0)];
4266        let painted = crate::catmull::sample_open_catmull(&controls, 8);
4267        let on_curve = painted[painted.len() / 4];
4268        let d = edge_signed_distance(
4269            &Shape::Point {
4270                x: on_curve.0,
4271                y: on_curve.1,
4272            },
4273            &Shape::Polyline(controls),
4274        );
4275        assert!(
4276            d < 1.0,
4277            "clash should see the painted Catmull, not the L chords: d={d} pt={on_curve:?}"
4278        );
4279    }
4280
4281    #[test]
4282    fn parallel_constraint_owns_rotation() {
4283        let mut w = LayoutWorld::rooted("scheme", ObjectType::Scheme);
4284        w.insert(
4285            "e0",
4286            "scheme",
4287            ObjectType::Edge,
4288            Shape::Polyline(vec![]),
4289            true,
4290        );
4291        w.insert(
4292            "e0/p0",
4293            "e0",
4294            ObjectType::EdgePoint,
4295            Shape::Point { x: 0.0, y: 0.0 },
4296            true,
4297        );
4298        w.insert(
4299            "e0/p1",
4300            "e0",
4301            ObjectType::EdgePoint,
4302            Shape::Point { x: 80.0, y: 40.0 },
4303            true,
4304        );
4305        w.insert(
4306            "lab",
4307            "scheme",
4308            ObjectType::EdgeLabel,
4309            Shape::Circle {
4310                cx: 40.0,
4311                cy: 28.0,
4312                r: 6.0,
4313            },
4314            false,
4315        );
4316        w.set_rot("lab", 0.0);
4317        let cs = vec![Constraint::Parallel {
4318            a: "lab".into(),
4319            b: "e0".into(),
4320            strength: 1.0,
4321        }];
4322        let _ = solve(
4323            &mut w,
4324            &cs,
4325            &[],
4326            &SolveOpts {
4327                max_iters: 80,
4328                noise: 0.0,
4329                epsilon_px: 0.25,
4330                ..SolveOpts::default()
4331            },
4332        );
4333        let rot = w.get("lab").unwrap().rot;
4334        let want = wrap_readable_deg((40.0f64).atan2(80.0).to_degrees());
4335        assert!(
4336            (wrap_readable_deg(rot) - want).abs() < 8.0,
4337            "solver rot={rot} want={want}"
4338        );
4339    }
4340
4341    #[test]
4342    fn midpoint_constraint_pulls_to_shaft_mid() {
4343        let mut w = LayoutWorld::rooted("scheme", ObjectType::Scheme);
4344        w.insert(
4345            "e0",
4346            "scheme",
4347            ObjectType::Edge,
4348            Shape::Polyline(vec![]),
4349            true,
4350        );
4351        w.insert(
4352            "e0/p0",
4353            "e0",
4354            ObjectType::EdgePoint,
4355            Shape::Point { x: 0.0, y: 0.0 },
4356            true,
4357        );
4358        w.insert(
4359            "e0/p1",
4360            "e0",
4361            ObjectType::EdgePoint,
4362            Shape::Point { x: 80.0, y: 0.0 },
4363            true,
4364        );
4365        w.insert(
4366            "lab",
4367            "scheme",
4368            ObjectType::EdgeLabel,
4369            Shape::Circle {
4370                cx: 10.0,
4371                cy: 30.0,
4372                r: 6.0,
4373            },
4374            false,
4375        );
4376        let cs = vec![Constraint::Midpoint {
4377            a: "lab".into(),
4378            b: "e0".into(),
4379            strength: 1.0,
4380        }];
4381        let _ = solve(
4382            &mut w,
4383            &cs,
4384            &[],
4385            &SolveOpts {
4386                max_iters: 80,
4387                noise: 0.0,
4388                epsilon_px: 0.25,
4389                ..SolveOpts::default()
4390            },
4391        );
4392        let s = w.get("lab").unwrap().world_shape();
4393        let (x, y) = s.aabb().center();
4394        assert!(
4395            (x - 40.0).abs() < 4.0 && y.abs() < 4.0,
4396            "label should sit at the shaft midpoint, got ({x}, {y})"
4397        );
4398    }
4399
4400    #[test]
4401    fn parallel_clear_vs_transverse_cross() {
4402        let stacked = parallel_clear_g(
4403            &Shape::Line {
4404                x0: 0.0,
4405                y0: 0.0,
4406                x1: 40.0,
4407                y1: 0.0,
4408            },
4409            &Shape::Line {
4410                x0: 0.0,
4411                y0: 2.0,
4412                x1: 40.0,
4413                y1: 2.0,
4414            },
4415            10.0,
4416        );
4417        assert!(
4418            stacked > 0.0,
4419            "stacked parallels closer than clearance: {stacked}"
4420        );
4421        let cross = parallel_clear_g(
4422            &Shape::Line {
4423                x0: 0.0,
4424                y0: 0.0,
4425                x1: 40.0,
4426                y1: 0.0,
4427            },
4428            &Shape::Line {
4429                x0: 20.0,
4430                y0: -20.0,
4431                x1: 20.0,
4432                y1: 20.0,
4433            },
4434            10.0,
4435        );
4436        assert!(
4437            cross <= 0.0,
4438            "transverse X must not activate ParallelClear: {cross}"
4439        );
4440        let n = poly_cross_count(
4441            &Shape::Line {
4442                x0: 0.0,
4443                y0: 0.0,
4444                x1: 40.0,
4445                y1: 0.0,
4446            },
4447            &Shape::Line {
4448                x0: 20.0,
4449                y0: -20.0,
4450                x1: 20.0,
4451                y1: 20.0,
4452            },
4453        );
4454        assert_eq!(n, 1);
4455        let miss = poly_cross_count(
4456            &Shape::Line {
4457                x0: 0.0,
4458                y0: 0.0,
4459                x1: 10.0,
4460                y1: 0.0,
4461            },
4462            &Shape::Line {
4463                x0: 0.0,
4464                y0: 10.0,
4465                x1: 10.0,
4466                y1: 10.0,
4467            },
4468        );
4469        assert_eq!(miss, 0);
4470    }
4471
4472    #[test]
4473    fn poly_cross_energy_only_when_attached() {
4474        let mut w = LayoutWorld::rooted("scheme", ObjectType::Scheme);
4475        w.insert(
4476            "e0",
4477            "scheme",
4478            ObjectType::Edge,
4479            Shape::Line {
4480                x0: 0.0,
4481                y0: 0.0,
4482                x1: 40.0,
4483                y1: 40.0,
4484            },
4485            true,
4486        );
4487        w.insert(
4488            "e1",
4489            "scheme",
4490            ObjectType::Edge,
4491            Shape::Line {
4492                x0: 0.0,
4493                y0: 40.0,
4494                x1: 40.0,
4495                y1: 0.0,
4496            },
4497            true,
4498        );
4499        let attached = Constraint::PolyCross {
4500            a: "e0".into(),
4501            b: "e1".into(),
4502            strength: 0.8,
4503        };
4504        assert!(
4505            energy(&w, &[attached], &[], 0.0) > 0.0,
4506            "kit-attached PolyCross must cost a proper X"
4507        );
4508        assert_eq!(
4509            energy(&w, &[], &[], 0.0),
4510            0.0,
4511            "omitting PolyCross must cost nothing (ELK crossings stay)"
4512        );
4513    }
4514
4515    #[test]
4516    fn collinear_energy_zero_on_segment_positive_off() {
4517        let mut w = LayoutWorld::rooted("scheme", ObjectType::Scheme);
4518        w.insert(
4519            "a",
4520            "scheme",
4521            ObjectType::EdgePoint,
4522            Shape::Point { x: 0.0, y: 0.0 },
4523            true,
4524        );
4525        w.insert(
4526            "b",
4527            "scheme",
4528            ObjectType::EdgePoint,
4529            Shape::Point { x: 10.0, y: 0.0 },
4530            false,
4531        );
4532        w.insert(
4533            "c",
4534            "scheme",
4535            ObjectType::Group,
4536            Shape::Point { x: 40.0, y: 0.0 },
4537            true,
4538        );
4539        let row = Constraint::Collinear {
4540            a: "a".into(),
4541            b: "b".into(),
4542            c: "c".into(),
4543            strength: 1.0,
4544        };
4545        assert!(energy(&w, &[row.clone()], &[], 0.0) < 1e-9);
4546        w.set_pose("b", 0.0, 8.0);
4547        assert!(energy(&w, &[row.clone()], &[], 0.0) > 0.0);
4548        w.set_pose("b", -12.0, 0.0);
4549        assert!(
4550            energy(&w, &[row.clone()], &[], 0.0) > 0.0,
4551            "behind the origin of the segment must cost"
4552        );
4553        w.set_pose("b", 55.0, 0.0);
4554        assert!(
4555            energy(&w, &[row], &[], 0.0) > 0.0,
4556            "past the far end of the segment must cost"
4557        );
4558    }
4559
4560    #[test]
4561    fn ray_through_ignores_segment_parameter() {
4562        let mut w = LayoutWorld::rooted("scheme", ObjectType::Scheme);
4563        w.insert(
4564            "a",
4565            "scheme",
4566            ObjectType::EdgePoint,
4567            Shape::Point { x: 0.0, y: 0.0 },
4568            false,
4569        );
4570        w.insert(
4571            "b",
4572            "scheme",
4573            ObjectType::EdgePoint,
4574            Shape::Point { x: 10.0, y: 0.0 },
4575            false,
4576        );
4577        w.insert(
4578            "p",
4579            "scheme",
4580            ObjectType::Group,
4581            Shape::Point { x: 40.0, y: 0.0 },
4582            false,
4583        );
4584        let row = Constraint::RayThrough {
4585            a: "a".into(),
4586            b: "b".into(),
4587            p: "p".into(),
4588            strength: 1.0,
4589        };
4590        assert!(
4591            energy(&w, &[row.clone()], &[], 0.0) < 1e-9,
4592            "centroid past the painted segment still sits on the ray"
4593        );
4594        w.set_pose("p", 40.0, 6.0);
4595        assert!(energy(&w, &[row.clone()], &[], 0.0) > 0.0);
4596        w.set_pose("p", -20.0, 0.0);
4597        assert!(
4598            energy(&w, &[row], &[], 0.0) < 1e-9,
4599            "behind a is still on the infinite ray"
4600        );
4601    }
4602
4603    #[test]
4604    fn push_clear_leaves_skips_empty_container() {
4605        let mut w = LayoutWorld::rooted("scheme", ObjectType::Scheme);
4606        install_chem_under(&mut w, "scheme", &[], &[(0, 10.0, 10.0)], &[], &[]);
4607        let mut hard = Vec::new();
4608        push_clear_leaves(&w, &mut hard, "probe", "scheme/chem", 4.0);
4609        assert!(
4610            hard.iter()
4611                .any(|h| matches!(h, HardConstraint::Outside { b, .. } if b.contains("/coord"))),
4612            "atom disk is a leaf: {hard:?}"
4613        );
4614        assert!(
4615            !hard
4616                .iter()
4617                .any(|h| matches!(h, HardConstraint::Outside { b, .. } if b.ends_with("/bonds"))),
4618            "empty bonds folder is not ink: {hard:?}"
4619        );
4620    }
4621
4622    /// Wall-clock + iteration stats for paint-style refine kits (noise=0).
4623    ///
4624    /// Run: `cargo test -p xpict-core --lib solver_kit_bench --release -- --nocapture`
4625    #[test]
4626    fn solver_kit_bench() {
4627        use std::time::Instant;
4628
4629        let bonds = [
4630            (0.0, 0.0, 30.0, 0.0),
4631            (30.0, 0.0, 45.0, 20.0),
4632            (30.0, 0.0, 45.0, -20.0),
4633        ];
4634        let atoms = [(0usize, 0.0, 0.0), (1, 30.0, 0.0), (2, 45.0, 20.0)];
4635        let shades = [(1usize, 30.0, 0.0, 9.0)];
4636        let trials = 40usize;
4637
4638        fn median(mut v: Vec<f64>) -> f64 {
4639            v.sort_by(|a, b| a.partial_cmp(b).unwrap());
4640            v[v.len() / 2]
4641        }
4642        fn median_usize(mut v: Vec<usize>) -> usize {
4643            v.sort();
4644            v[v.len() / 2]
4645        }
4646
4647        type KitFn = Box<dyn Fn() -> SolveResult>;
4648        let kits: [(&str, usize, KitFn); 5] = [
4649            (
4650                "caption",
4651                60,
4652                Box::new({
4653                    let bonds = bonds;
4654                    let atoms = atoms;
4655                    move || {
4656                        let mut w = LayoutWorld::new("mol");
4657                        install_chem(&mut w, &bonds, &atoms, &[]);
4658                        if let Some(n) = w.get_mut("mol/chem") {
4659                            let chem = Aabb::new(-5.0, -12.0, 50.0, 25.0);
4660                            n.rest = Shape::Aabb(chem);
4661                            n.shape = Shape::Aabb(chem);
4662                        }
4663                        let mut cs = Vec::new();
4664                        let mut hard = Vec::new();
4665                        let _ = caption_kit(
4666                            &mut w,
4667                            &mut cs,
4668                            &mut hard,
4669                            Aabb::new(10.0, 28.0, 40.0, 40.0),
4670                            Side::Below,
4671                            15.0,
4672                            3.0,
4673                        );
4674                        solve(
4675                            &mut w,
4676                            &cs,
4677                            &hard,
4678                            &SolveOpts {
4679                                max_iters: 60,
4680                                noise: 0.0,
4681                                epsilon_px: 0.75,
4682                                ..SolveOpts::default()
4683                            },
4684                        )
4685                    }
4686                }),
4687            ),
4688            (
4689                "region_outside",
4690                80,
4691                Box::new({
4692                    let bonds = bonds;
4693                    let atoms = atoms;
4694                    let shades = shades;
4695                    move || {
4696                        let mut w = LayoutWorld::new("mol");
4697                        install_chem(&mut w, &bonds, &atoms, &shades);
4698                        let mut cs = Vec::new();
4699                        let mut hard = Vec::new();
4700                        let _ = region_text_kit(
4701                            &mut w,
4702                            &mut cs,
4703                            &mut hard,
4704                            0,
4705                            Shape::Aabb(Aabb::new(-8.0, -15.0, 55.0, 28.0)),
4706                            Aabb::new(15.0, -28.0, 35.0, -16.0),
4707                            false,
4708                            Side::Above,
4709                            3.0,
4710                            (20.0, 0.0),
4711                            &[],
4712                        );
4713                        solve(
4714                            &mut w,
4715                            &cs,
4716                            &hard,
4717                            &SolveOpts {
4718                                max_iters: 80,
4719                                noise: 0.0,
4720                                epsilon_px: 0.75,
4721                                ..SolveOpts::default()
4722                            },
4723                        )
4724                    }
4725                }),
4726            ),
4727            (
4728                "region_circle_inside",
4729                80,
4730                Box::new({
4731                    let bonds = bonds;
4732                    let atoms = atoms;
4733                    let shades = shades;
4734                    move || {
4735                        let mut w = LayoutWorld::new("mol");
4736                        install_chem(&mut w, &bonds, &atoms[..2], &shades);
4737                        let mut cs = Vec::new();
4738                        let mut hard = Vec::new();
4739                        let _ = region_text_kit(
4740                            &mut w,
4741                            &mut cs,
4742                            &mut hard,
4743                            0,
4744                            Shape::Circle {
4745                                cx: 15.0,
4746                                cy: 0.0,
4747                                r: 42.0,
4748                            },
4749                            // Outside-style seed (above), circle already grown.
4750                            Aabb::new(5.0, -48.0, 25.0, -36.0),
4751                            true,
4752                            Side::Above,
4753                            3.0,
4754                            (15.0, 0.0),
4755                            &[],
4756                        );
4757                        solve(
4758                            &mut w,
4759                            &cs,
4760                            &hard,
4761                            &SolveOpts {
4762                                max_iters: 80,
4763                                noise: 0.0,
4764                                epsilon_px: 0.75,
4765                                ..SolveOpts::default()
4766                            },
4767                        )
4768                    }
4769                }),
4770            ),
4771            (
4772                "callout_2dof",
4773                100,
4774                Box::new({
4775                    let bonds = bonds;
4776                    let atoms = atoms;
4777                    move || {
4778                        let mut w = LayoutWorld::new("mol");
4779                        install_chem(&mut w, &bonds, &atoms, &[]);
4780                        let mut cs = Vec::new();
4781                        let mut hard = Vec::new();
4782                        let _ = callout_kit(
4783                            &mut w,
4784                            &mut cs,
4785                            &mut hard,
4786                            0,
4787                            Aabb::new(55.0, -8.0, 75.0, 8.0),
4788                            (48.0, 18.0),
4789                            (45.0, 20.0),
4790                            8.0,
4791                            Side::Right,
4792                            3.0,
4793                            &[],
4794                        );
4795                        solve(
4796                            &mut w,
4797                            &cs,
4798                            &hard,
4799                            &SolveOpts {
4800                                max_iters: 100,
4801                                noise: 0.0,
4802                                epsilon_px: 0.75,
4803                                ..SolveOpts::default()
4804                            },
4805                        )
4806                    }
4807                }),
4808            ),
4809            (
4810                "callout_2routes",
4811                100,
4812                Box::new({
4813                    let bonds = bonds;
4814                    let atoms = atoms;
4815                    move || {
4816                        let mut w = LayoutWorld::new("mol");
4817                        install_chem(&mut w, &bonds, &atoms, &[]);
4818                        let mut cs = Vec::new();
4819                        let mut hard = Vec::new();
4820                        let routes = [(60.0, 5.0), (52.0, 12.0)];
4821                        let _ = callout_kit(
4822                            &mut w,
4823                            &mut cs,
4824                            &mut hard,
4825                            0,
4826                            Aabb::new(70.0, -8.0, 95.0, 8.0),
4827                            (48.0, 18.0),
4828                            (45.0, 20.0),
4829                            8.0,
4830                            Side::Right,
4831                            3.0,
4832                            &routes,
4833                        );
4834                        solve(
4835                            &mut w,
4836                            &cs,
4837                            &hard,
4838                            &SolveOpts {
4839                                max_iters: 100,
4840                                noise: 0.0,
4841                                epsilon_px: 0.75,
4842                                ..SolveOpts::default()
4843                            },
4844                        )
4845                    }
4846                }),
4847            ),
4848        ];
4849
4850        eprintln!(
4851            "\nsolver_kit_bench (trials={trials}, release timings if --release):\n\
4852             kit                      med_µs  p95_µs  med_iters  max_iters  drift%"
4853        );
4854        for (name, cap, run) in &kits {
4855            // Warmup
4856            for _ in 0..5 {
4857                let _ = run();
4858            }
4859            let mut us = Vec::with_capacity(trials);
4860            let mut iters = Vec::with_capacity(trials);
4861            let mut drift_n = 0usize;
4862            for _ in 0..trials {
4863                let t0 = Instant::now();
4864                let r = run();
4865                us.push(t0.elapsed().as_secs_f64() * 1e6);
4866                iters.push(r.iters);
4867                if r.stopped_on_drift {
4868                    drift_n += 1;
4869                }
4870            }
4871            let mut us_sorted = us.clone();
4872            us_sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
4873            let p95 = us_sorted[(us_sorted.len() * 95) / 100];
4874            let med_us = median(us);
4875            let med_iters = median_usize(iters);
4876            eprintln!(
4877                "{name:<24} {:>7.1} {:>7.1} {:>9} {:>9} {:>5.0}%",
4878                med_us,
4879                p95,
4880                med_iters,
4881                cap,
4882                100.0 * drift_n as f64 / trials as f64
4883            );
4884            // Sanity: should usually stop before the paint cap.
4885            assert!(
4886                med_iters <= *cap,
4887                "{name}: median iters {med_iters} > cap {cap}"
4888            );
4889        }
4890    }
4891}