Skip to main content

xpict_core/
bonds.rs

1//! Bond strokes: skeleton centerlines, multi-bond offsets, stereo, joins.
2//!
3//! Python host draw stack removed; this module is SoT.
4
5use std::collections::HashMap;
6
7use crate::metrics::{
8    hash_count, BOND_PX, CHAIN_END_GAP_PX, END_GAP_PX, OFFSET_PX, STROKE_PX, WEDGE_HALF_PX,
9};
10use crate::scene::Primitive;
11
12/// True for aromatic bond encodings: RDKit-style ``1.5`` or CTAB/Chematic ``4``.
13pub fn is_aromatic_order(order: f64) -> bool {
14    order >= 3.5 || (1.4..1.6).contains(&order)
15}
16
17/// Normalize engine bond orders for 2D *stroke multiplicity*.
18///
19/// Aromatic encodings collapse to a single skeleton stroke (never a triple).
20/// Ring aromaticity is drawn separately (circle) via [`is_aromatic_order`].
21pub fn depict_order(order: f64) -> f64 {
22    if is_aromatic_order(order) {
23        1.0
24    } else {
25        order
26    }
27}
28
29/// Parallel spacing for double/triple strokes (RDKit `multipleBondOffset`).
30///
31/// Prefer [`OFFSET_PX`]. Do **not** scale down to the post-label stroke length —
32/// heteroatom insets must not collapse carbonyl spacing. Only shrink for
33/// degenerate stubs shorter than two offset widths.
34pub fn multi_bond_offset(length: f64) -> f64 {
35    if length < 2.0 * OFFSET_PX {
36        OFFSET_PX.min(length * 0.25)
37    } else {
38        OFFSET_PX
39    }
40}
41
42/// Signed offsets of a centered multiple bond along the left normal.
43///
44/// A double is two lines split evenly about the axis (separation `off`).
45/// A triple keeps the axis and one line `off` to each side.
46pub fn centered_displacements(order: f64, off: f64) -> Vec<f64> {
47    if order >= 2.5 {
48        vec![-off, 0.0, off]
49    } else {
50        vec![-off * 0.5, off * 0.5]
51    }
52}
53
54pub fn shorten(x1: f64, y1: f64, x2: f64, y2: f64, gap1: f64, gap2: f64) -> (f64, f64, f64, f64) {
55    let dx = x2 - x1;
56    let dy = y2 - y1;
57    let length = (dx * dx + dy * dy).sqrt().max(1.0);
58    if gap1 + gap2 >= length {
59        let mx = (x1 + x2) * 0.5;
60        let my = (y1 + y2) * 0.5;
61        return (mx, my, mx, my);
62    }
63    let ux = dx / length;
64    let uy = dy / length;
65    (
66        x1 + ux * gap1,
67        y1 + uy * gap1,
68        x2 - ux * gap2,
69        y2 - uy * gap2,
70    )
71}
72
73fn unit(x1: f64, y1: f64, x2: f64, y2: f64) -> (f64, f64, f64, f64, f64) {
74    let dx = x2 - x1;
75    let dy = y2 - y1;
76    let length = (dx * dx + dy * dy).sqrt().max(1.0);
77    (dx / length, dy / length, -dy / length, dx / length, length)
78}
79
80fn fmt2(v: f64) -> String {
81    format!("{v:.2}")
82}
83
84fn line_path(x1: f64, y1: f64, x2: f64, y2: f64, class: &str, width: f64) -> StrokePath {
85    StrokePath {
86        pts: vec![(x1, y1), (x2, y2)],
87        d: format!("M {} {} L {} {}", fmt2(x1), fmt2(y1), fmt2(x2), fmt2(y2)),
88        stroke: "#111".into(),
89        fill: None,
90        stroke_width: width,
91        stroke_linecap: Some("round".into()),
92        class: class.into(),
93    }
94}
95
96/// One SVG stroke before it becomes a [`Primitive`].
97#[derive(Debug, Clone, PartialEq)]
98pub struct StrokePath {
99    /// Interpolating vertices used to build [`Self::d`]. Halo/clash read these,
100    /// not a scrape of the serialized path.
101    pub pts: Vec<(f64, f64)>,
102    pub d: String,
103    pub stroke: String,
104    pub fill: Option<String>,
105    pub stroke_width: f64,
106    pub stroke_linecap: Option<String>,
107    pub class: String,
108}
109
110impl StrokePath {
111    pub fn to_primitive(&self) -> Primitive {
112        Primitive::Path {
113            d: self.d.clone(),
114            stroke: Some(self.stroke.clone()),
115            fill: self.fill.clone().or_else(|| Some("none".into())),
116            stroke_width: self.stroke_width,
117            opacity: 1.0,
118            stroke_dasharray: None,
119            stroke_linecap: self.stroke_linecap.clone(),
120            class: Some(self.class.clone()),
121            data_text: None,
122        }
123    }
124
125    pub fn with_color(mut self, color: &str) -> Self {
126        self.stroke = color.into();
127        if self.fill.as_ref().is_some_and(|f| f != "none") {
128            self.fill = Some(color.into());
129        }
130        self
131    }
132}
133
134/// Strokes for one bond, ordered for painting: skeleton → offsets → stereo.
135#[derive(Debug, Clone, Default, PartialEq)]
136pub struct BondStrokes {
137    pub skeleton: Option<StrokePath>,
138    pub offsets: Vec<StrokePath>,
139    pub stereo: Vec<StrokePath>,
140}
141
142impl BondStrokes {
143    pub fn paint_order(&self) -> Vec<&StrokePath> {
144        let mut out = Vec::new();
145        if let Some(ref s) = self.skeleton {
146            out.push(s);
147        }
148        out.extend(self.offsets.iter());
149        out.extend(self.stereo.iter());
150        out
151    }
152
153    pub fn into_primitives(self, color: &str) -> Vec<Primitive> {
154        let mut out = Vec::new();
155        if let Some(s) = self.skeleton {
156            out.push(s.with_color(color).to_primitive());
157        }
158        for p in self.offsets {
159            out.push(p.with_color(color).to_primitive());
160        }
161        for p in self.stereo {
162            out.push(p.with_color(color).to_primitive());
163        }
164        out
165    }
166}
167
168/// Filled wedge; tip at `(x1,y1)` stereocenter — RDKit BEGINWEDGE.
169pub fn solid_wedge(x1: f64, y1: f64, x2: f64, y2: f64, half: Option<f64>) -> StrokePath {
170    let half = half.unwrap_or(WEDGE_HALF_PX);
171    let (_ux, _uy, nx, ny, _) = unit(x1, y1, x2, y2);
172    let ax = x2 + nx * half;
173    let ay = y2 + ny * half;
174    let bx = x2 - nx * half;
175    let by = y2 - ny * half;
176    StrokePath {
177        pts: vec![(x1, y1), (ax, ay), (bx, by)],
178        d: format!(
179            "M {} {} L {} {} L {} {} Z",
180            fmt2(x1),
181            fmt2(y1),
182            fmt2(ax),
183            fmt2(ay),
184            fmt2(bx),
185            fmt2(by)
186        ),
187        stroke: "#111".into(),
188        fill: Some("#111".into()),
189        stroke_width: 0.6,
190        stroke_linecap: Some("round".into()),
191        class: "bond bond-wedge-up".into(),
192    }
193}
194
195/// Hashed wedge for a bond going away from the viewer.
196///
197/// `(x1, y1)` is the stereocenter. Hashes are wide there and narrow at the
198/// substituent.
199pub fn hashed_wedge(
200    x1: f64,
201    y1: f64,
202    x2: f64,
203    y2: f64,
204    half: Option<f64>,
205    n: Option<usize>,
206) -> Vec<StrokePath> {
207    hashed_wedge_sw(x1, y1, x2, y2, half, n, STROKE_PX)
208}
209
210fn hashed_wedge_sw(
211    x1: f64,
212    y1: f64,
213    x2: f64,
214    y2: f64,
215    half: Option<f64>,
216    n: Option<usize>,
217    stroke_width: f64,
218) -> Vec<StrokePath> {
219    let half = half.unwrap_or(WEDGE_HALF_PX);
220    let (ux, uy, nx, ny, length) = unit(x1, y1, x2, y2);
221    let count = n.unwrap_or_else(|| hash_count(length));
222    let mut paths = Vec::with_capacity(count);
223    for i in 0..count {
224        let t = (i + 1) as f64 / (count + 1) as f64;
225        let w = half * (1.0 - t);
226        let cx = x1 + ux * length * t;
227        let cy = y1 + uy * length * t;
228        paths.push(line_path(
229            cx + nx * w,
230            cy + ny * w,
231            cx - nx * w,
232            cy - ny * w,
233            "bond bond-wedge-down",
234            stroke_width,
235        ));
236    }
237    paths
238}
239
240/// Wiggly single for unspecified stereo (e.g. RDKit UNKNOWN).
241pub fn wavy_bond(x1: f64, y1: f64, x2: f64, y2: f64, amp: Option<f64>, waves: usize) -> StrokePath {
242    wavy_bond_sw(x1, y1, x2, y2, amp, waves, STROKE_PX)
243}
244
245fn wavy_bond_sw(
246    x1: f64,
247    y1: f64,
248    x2: f64,
249    y2: f64,
250    amp: Option<f64>,
251    waves: usize,
252    stroke_width: f64,
253) -> StrokePath {
254    let (ux, uy, nx, ny, length) = unit(x1, y1, x2, y2);
255    let amp = amp.unwrap_or(0.055 * BOND_PX);
256    let mut pts = vec![(x1, y1)];
257    let mut parts = vec![format!("M {} {}", fmt2(x1), fmt2(y1))];
258    let steps = waves * 2;
259    for i in 1..=steps {
260        let t = i as f64 / steps as f64;
261        let side = if i % 2 == 1 { 1.0 } else { -1.0 };
262        let px = x1 + ux * length * t + nx * amp * side;
263        let py = y1 + uy * length * t + ny * amp * side;
264        pts.push((px, py));
265        parts.push(format!("L {} {}", fmt2(px), fmt2(py)));
266    }
267    StrokePath {
268        pts,
269        d: parts.join(" "),
270        stroke: "#111".into(),
271        fill: Some("none".into()),
272        stroke_width,
273        stroke_linecap: Some("round".into()),
274        class: "bond bond-either".into(),
275    }
276}
277
278fn offset_gap(length: f64, chain: bool) -> f64 {
279    let px = if chain { CHAIN_END_GAP_PX } else { END_GAP_PX };
280    px.min(length * 0.22)
281}
282
283/// Crossed double for unspecified E/Z (RDKit EITHERDOUBLE).
284pub fn crossed_double(
285    x1: f64,
286    y1: f64,
287    x2: f64,
288    y2: f64,
289    interior: Option<(f64, f64)>,
290) -> Vec<StrokePath> {
291    crossed_double_sw(x1, y1, x2, y2, interior, STROKE_PX)
292}
293
294fn crossed_double_sw(
295    x1: f64,
296    y1: f64,
297    x2: f64,
298    y2: f64,
299    interior: Option<(f64, f64)>,
300    stroke_width: f64,
301) -> Vec<StrokePath> {
302    let (_ux, _uy, lx, ly, length) = unit(x1, y1, x2, y2);
303    let (nx, ny) = interior.unwrap_or((lx, ly));
304    let off = multi_bond_offset(length);
305    let gap = offset_gap(length, interior.is_none());
306    let (sx1, sy1, sx2, sy2) = shorten(x1, y1, x2, y2, gap, gap);
307    let a1x = sx1 + nx * off;
308    let a1y = sy1 + ny * off;
309    let a2x = sx2 + nx * off;
310    let a2y = sy2 + ny * off;
311    let b1x = sx1 - nx * off;
312    let b1y = sy1 - ny * off;
313    let b2x = sx2 - nx * off;
314    let b2y = sy2 - ny * off;
315    vec![
316        line_path(x1, y1, x2, y2, "bond bond-skeleton", stroke_width),
317        line_path(a1x, a1y, b2x, b2y, "bond bond-either-cross", stroke_width),
318        line_path(b1x, b1y, a2x, a2y, "bond bond-either-cross", stroke_width),
319    ]
320}
321
322/// Parallel lines have `|cross(d0, d1)|` below this (unit directions).
323const JOIN_PARALLEL_EPS: f64 = 1e-9;
324/// Reject mitres that run farther than this fraction of the multi-bond length.
325const JOIN_MAX_T_FRAC: f64 = 0.9;
326
327/// Intersect `p0 + t d0` with `p1 + s d1`.
328///
329/// Returns `(t, s, ix, iy)` or `None` when the directions are parallel.
330#[allow(clippy::too_many_arguments)]
331pub fn line_intersect(
332    p0x: f64,
333    p0y: f64,
334    d0x: f64,
335    d0y: f64,
336    p1x: f64,
337    p1y: f64,
338    d1x: f64,
339    d1y: f64,
340) -> Option<(f64, f64, f64, f64)> {
341    let det = d0x * d1y - d0y * d1x;
342    if det.abs() < JOIN_PARALLEL_EPS {
343        return None;
344    }
345    let dx = p1x - p0x;
346    let dy = p1y - p0y;
347    let t = (dx * d1y - dy * d1x) / det;
348    let s = (dx * d0y - dy * d0x) / det;
349    Some((t, s, p0x + t * d0x, p0y + t * d0y))
350}
351
352/// Trim distance at begin, then end, one entry per centered line.
353pub type EndTrims = (Vec<f64>, Vec<f64>);
354
355/// One bond after label inset, before multiple-bond joins.
356#[derive(Debug, Clone, PartialEq)]
357pub struct DrawnBond {
358    pub index: i32,
359    pub begin: i32,
360    pub end: i32,
361    pub x1: f64,
362    pub y1: f64,
363    pub x2: f64,
364    pub y2: f64,
365    pub order: f64,
366    pub interior: Option<(f64, f64)>,
367    pub stereo: Option<String>,
368    pub begin_labeled: bool,
369    pub end_labeled: bool,
370    /// Trim distance at begin, then end, one entry per centered line.
371    pub trims: Option<EndTrims>,
372}
373
374impl DrawnBond {
375    #[allow(clippy::too_many_arguments)]
376    pub fn new(
377        index: i32,
378        begin: i32,
379        end: i32,
380        x1: f64,
381        y1: f64,
382        x2: f64,
383        y2: f64,
384        order: f64,
385    ) -> Self {
386        Self {
387            index,
388            begin,
389            end,
390            x1,
391            y1,
392            x2,
393            y2,
394            order,
395            interior: None,
396            stereo: None,
397            begin_labeled: false,
398            end_labeled: false,
399            trims: None,
400        }
401    }
402}
403
404fn plain_single(bond: &DrawnBond) -> bool {
405    let order = depict_order(bond.order);
406    let stereo = bond
407        .stereo
408        .as_deref()
409        .unwrap_or("none")
410        .to_ascii_lowercase();
411    order < 1.5 && (stereo.is_empty() || stereo == "none")
412}
413
414fn centered_multi(bond: &DrawnBond) -> bool {
415    let order = depict_order(bond.order);
416    let stereo = bond
417        .stereo
418        .as_deref()
419        .unwrap_or("none")
420        .to_ascii_lowercase();
421    if matches!(stereo.as_str(), "up" | "down" | "either") {
422        return false;
423    }
424    bond.interior.is_none() && order >= 1.5
425}
426
427fn end_frame(bond: &DrawnBond, at_begin: bool) -> (f64, f64, f64, f64, f64, f64) {
428    let (ux, uy, nx, ny, _length) = unit(bond.x1, bond.y1, bond.x2, bond.y2);
429    if at_begin {
430        (bond.x1, bond.y1, ux, uy, nx, ny)
431    } else {
432        (bond.x2, bond.y2, -ux, -uy, -nx, -ny)
433    }
434}
435
436/// Mitre acyclic doubles and triples to their single-bond neighbors.
437///
438/// Each parallel stroke is an infinite line; each neighboring single is another.
439/// Junction ends are **line–line intersections** (no fixed-length stubs), so
440/// acute and obtuse angles both close cleanly.
441///
442/// One single: extend it to the far parallel line; both multiple-bond strokes
443/// stop on that single.
444///
445/// Two singles: leave them meeting at the atom; extend each multiple-bond
446/// stroke past the atom until its end lies on a single (closes the vertex
447/// angle gap).
448pub fn join_centered_multibonds(bonds: &mut [DrawnBond]) {
449    let mut by_atom: HashMap<i32, Vec<usize>> = HashMap::new();
450    for (i, bond) in bonds.iter().enumerate() {
451        by_atom.entry(bond.begin).or_default().push(i);
452        by_atom.entry(bond.end).or_default().push(i);
453    }
454
455    // (single index, 0=begin) -> (x, y, distance past the atom)
456    let mut moves: HashMap<(i32, i32), (f64, f64, f64)> = HashMap::new();
457    // (bond index, (begin trims, end trims))
458    let mut trim_updates: Vec<(usize, EndTrims)> = Vec::new();
459
460    for bi in 0..bonds.len() {
461        if !centered_multi(&bonds[bi]) {
462            continue;
463        }
464        let (_ux, _uy, _nx, _ny, length) =
465            unit(bonds[bi].x1, bonds[bi].y1, bonds[bi].x2, bonds[bi].y2);
466        if length < 1.0 {
467            continue;
468        }
469        let off = multi_bond_offset(length);
470        let disps = centered_displacements(depict_order(bonds[bi].order), off);
471        let end_disps = (disps.clone(), disps.iter().map(|d| -d).collect::<Vec<_>>());
472        let mut trims = (vec![0.0; disps.len()], vec![0.0; disps.len()]);
473        let mut joined = false;
474        let t_lo = -0.5 * length;
475        let t_hi = JOIN_MAX_T_FRAC * length;
476
477        let ends = [
478            (0usize, bonds[bi].begin, bonds[bi].begin_labeled),
479            (1usize, bonds[bi].end, bonds[bi].end_labeled),
480        ];
481        for &(end_i, atom, labeled) in &ends {
482            if labeled {
483                continue;
484            }
485            let singles: Vec<usize> = by_atom
486                .get(&atom)
487                .into_iter()
488                .flatten()
489                .copied()
490                .filter(|&oi| oi != bi && plain_single(&bonds[oi]))
491                .collect();
492            if singles.is_empty() || singles.len() > 2 {
493                continue;
494            }
495            let (ex, ey, ux, uy, nx, ny) = end_frame(&bonds[bi], end_i == 0);
496            let disps_e = if end_i == 0 {
497                &end_disps.0
498            } else {
499                &end_disps.1
500            };
501
502            let mut line_ts: Vec<Vec<f64>> = vec![Vec::new(); disps_e.len()];
503            for &si in &singles {
504                let single = &bonds[si];
505                let (sx, sy, end_flag) = if single.begin == atom {
506                    (single.x2, single.y2, 0i32)
507                } else {
508                    (single.x1, single.y1, 1i32)
509                };
510                let vx = sx - ex;
511                let vy = sy - ey;
512                let vlen = (vx * vx + vy * vy).sqrt();
513                if vlen < 1e-6 {
514                    continue;
515                }
516                let vhx = vx / vlen;
517                let vhy = vy / vlen;
518                for (i, &d) in disps_e.iter().enumerate() {
519                    let Some((ti, _s, _ix, _iy)) =
520                        line_intersect(ex + nx * d, ey + ny * d, ux, uy, ex, ey, vhx, vhy)
521                    else {
522                        continue;
523                    };
524                    if ti > t_lo && ti < t_hi && ti.abs() > 1e-9 {
525                        line_ts[i].push(ti);
526                    }
527                }
528                if singles.len() == 1 {
529                    let side = ux * vhy - uy * vhx;
530                    let d_far = if side > 0.0 {
531                        disps_e.iter().cloned().fold(f64::INFINITY, f64::min)
532                    } else {
533                        disps_e.iter().cloned().fold(f64::NEG_INFINITY, f64::max)
534                    };
535                    if let Some((t_far, _s, px, py)) =
536                        line_intersect(ex + nx * d_far, ey + ny * d_far, ux, uy, ex, ey, vhx, vhy)
537                    {
538                        if t_far > 0.0 && t_far < t_hi {
539                            let dist = ((px - ex).powi(2) + (py - ey).powi(2)).sqrt();
540                            let key = (single.index, end_flag);
541                            let replace = match moves.get(&key) {
542                                None => true,
543                                Some(&(_, _, prev)) => dist > prev,
544                            };
545                            if replace {
546                                moves.insert(key, (px, py, dist));
547                            }
548                        }
549                    }
550                }
551            }
552
553            for (i, ts) in line_ts.iter().enumerate() {
554                if ts.is_empty() {
555                    continue;
556                }
557                if singles.len() == 2 {
558                    let neg: Vec<f64> = ts.iter().copied().filter(|&t| t < 0.0).collect();
559                    let pos: Vec<f64> = ts.iter().copied().filter(|&t| t > 0.0).collect();
560                    if !neg.is_empty() {
561                        let v = neg.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
562                        if end_i == 0 {
563                            trims.0[i] = v;
564                        } else {
565                            trims.1[i] = v;
566                        }
567                    } else if !pos.is_empty() {
568                        let v = pos.iter().cloned().fold(f64::INFINITY, f64::min);
569                        if end_i == 0 {
570                            trims.0[i] = v;
571                        } else {
572                            trims.1[i] = v;
573                        }
574                    }
575                } else {
576                    for &ti in ts {
577                        if ti > 0.0 {
578                            let cur = if end_i == 0 { trims.0[i] } else { trims.1[i] };
579                            if cur <= 0.0 || ti < cur {
580                                if end_i == 0 {
581                                    trims.0[i] = ti;
582                                } else {
583                                    trims.1[i] = ti;
584                                }
585                            }
586                        } else {
587                            let cur = if end_i == 0 { trims.0[i] } else { trims.1[i] };
588                            if cur == 0.0 || (cur < 0.0 && ti > cur) {
589                                if end_i == 0 {
590                                    trims.0[i] = ti;
591                                } else {
592                                    trims.1[i] = ti;
593                                }
594                            }
595                        }
596                    }
597                }
598                joined = true;
599            }
600        }
601        if joined {
602            trim_updates.push((bi, trims));
603        }
604    }
605
606    for (bi, trims) in trim_updates {
607        bonds[bi].trims = Some(trims);
608    }
609    for ((index, end_flag), (px, py, _dist)) in moves {
610        if let Some(single) = bonds.iter_mut().find(|b| b.index == index) {
611            if end_flag == 0 {
612                single.x1 = px;
613                single.y1 = py;
614            } else {
615                single.x2 = px;
616                single.y2 = py;
617            }
618        }
619    }
620}
621
622#[allow(clippy::too_many_arguments)]
623fn centered_strokes(
624    x1: f64,
625    y1: f64,
626    x2: f64,
627    y2: f64,
628    order: f64,
629    off: f64,
630    ux: f64,
631    uy: f64,
632    nx: f64,
633    ny: f64,
634    length: f64,
635    trims: Option<&EndTrims>,
636    stroke_width: f64,
637) -> BondStrokes {
638    let disps = centered_displacements(order, off);
639    let (t1_owned, t2_owned) = match trims {
640        Some((a, b)) => (a.clone(), b.clone()),
641        None => (vec![0.0; disps.len()], vec![0.0; disps.len()]),
642    };
643    let mut skeleton = None;
644    let mut offsets = Vec::new();
645    for (i, &disp) in disps.iter().enumerate() {
646        let mut t1 = t1_owned.get(i).copied().unwrap_or(0.0);
647        let mut t2 = t2_owned.get(i).copied().unwrap_or(0.0);
648        if t1 + t2 > length * 0.9 && t1 + t2 > 0.0 {
649            let scale = (length * 0.9) / (t1 + t2);
650            t1 *= scale;
651            t2 *= scale;
652        }
653        let ax = x1 + nx * disp + ux * t1;
654        let ay = y1 + ny * disp + uy * t1;
655        let bx = x2 + nx * disp - ux * t2;
656        let by = y2 + ny * disp - uy * t2;
657        let class = if disp.abs() < 1e-9 {
658            "bond bond-skeleton"
659        } else {
660            "bond bond-offset"
661        };
662        let line = line_path(ax, ay, bx, by, class, stroke_width);
663        if disp.abs() < 1e-9 {
664            skeleton = Some(line);
665        } else {
666            offsets.push(line);
667        }
668    }
669    BondStrokes {
670        skeleton,
671        offsets,
672        stereo: Vec::new(),
673    }
674}
675
676/// Build skeleton / offset / stereo strokes for one bond.
677///
678/// `stereo`: `up` | `down` | `either` | `none` | `None`.
679/// Thin end of a solid wedge, and the thick end of a hashed wedge, are at
680/// `(x1, y1)`. Callers pass the stereocenter first.
681///
682/// `trims` are per-line inset distances at `(x1, y1)` then `(x2, y2)`
683/// for a centered multiple bond (see [`join_centered_multibonds`]).
684///
685/// `stroke_width` defaults to [`STROKE_PX`] when `None` — pass a weight-scaled
686/// width when mol ``weight`` thickens ink.
687#[allow(clippy::too_many_arguments)]
688pub fn bond_strokes(
689    x1: f64,
690    y1: f64,
691    x2: f64,
692    y2: f64,
693    order: f64,
694    interior: Option<(f64, f64)>,
695    stereo: Option<&str>,
696    trims: Option<&EndTrims>,
697    stroke_width: Option<f64>,
698) -> BondStrokes {
699    let sw = stroke_width.unwrap_or(STROKE_PX);
700    let order = depict_order(order);
701    let mut stereo = stereo.unwrap_or("none").to_ascii_lowercase();
702    if stereo == "none" {
703        stereo.clear();
704    }
705
706    if stereo == "up" && order < 1.5 {
707        return BondStrokes {
708            stereo: vec![solid_wedge(x1, y1, x2, y2, None)],
709            ..Default::default()
710        };
711    }
712    if stereo == "down" && order < 1.5 {
713        return BondStrokes {
714            stereo: hashed_wedge_sw(x1, y1, x2, y2, None, None, sw),
715            ..Default::default()
716        };
717    }
718    if stereo == "either" && order < 1.5 {
719        return BondStrokes {
720            stereo: vec![wavy_bond_sw(x1, y1, x2, y2, None, 5, sw)],
721            ..Default::default()
722        };
723    }
724    if stereo == "either" && order >= 1.5 {
725        return BondStrokes {
726            stereo: crossed_double_sw(x1, y1, x2, y2, interior, sw),
727            ..Default::default()
728        };
729    }
730
731    let (ux, uy, lx, ly, length) = unit(x1, y1, x2, y2);
732    let skeleton = line_path(x1, y1, x2, y2, "bond bond-skeleton", sw);
733    if order < 1.5 {
734        return BondStrokes {
735            skeleton: Some(skeleton),
736            ..Default::default()
737        };
738    }
739
740    let off = multi_bond_offset(length);
741    let Some(interior) = interior else {
742        return centered_strokes(
743            x1, y1, x2, y2, order, off, ux, uy, lx, ly, length, trims, sw,
744        );
745    };
746
747    let gap = offset_gap(length, false);
748    let (sx1, sy1, sx2, sy2) = shorten(x1, y1, x2, y2, gap, gap);
749    let mut offsets = Vec::new();
750    if order >= 2.5 {
751        for side in [-1.0, 1.0] {
752            let ox = lx * off * side;
753            let oy = ly * off * side;
754            offsets.push(line_path(
755                sx1 + ox,
756                sy1 + oy,
757                sx2 + ox,
758                sy2 + oy,
759                "bond bond-offset",
760                sw,
761            ));
762        }
763        return BondStrokes {
764            skeleton: Some(skeleton),
765            offsets,
766            stereo: Vec::new(),
767        };
768    }
769    offsets.push(line_path(
770        sx1 + interior.0 * off,
771        sy1 + interior.1 * off,
772        sx2 + interior.0 * off,
773        sy2 + interior.1 * off,
774        "bond bond-offset",
775        sw,
776    ));
777    BondStrokes {
778        skeleton: Some(skeleton),
779        offsets,
780        stereo: Vec::new(),
781    }
782}
783
784/// Flat list (skeleton then offsets then stereo).
785pub fn bond_paths(
786    x1: f64,
787    y1: f64,
788    x2: f64,
789    y2: f64,
790    order: f64,
791    interior: Option<(f64, f64)>,
792    stereo: Option<&str>,
793) -> Vec<StrokePath> {
794    bond_strokes(x1, y1, x2, y2, order, interior, stereo, None, None)
795        .paint_order()
796        .into_iter()
797        .cloned()
798        .collect()
799}
800
801#[cfg(test)]
802mod tests {
803    use super::*;
804
805    fn path_ys(d: &str) -> f64 {
806        // "M x y L ..." — second number is y of start.
807        let nums: Vec<f64> = d
808            .split(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-' || c == '+'))
809            .filter(|s| !s.is_empty())
810            .filter_map(|s| s.parse().ok())
811            .collect();
812        nums[1]
813    }
814
815    fn path_pts(d: &str) -> Vec<(f64, f64)> {
816        let nums: Vec<f64> = d
817            .split(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-' || c == '+'))
818            .filter(|s| !s.is_empty())
819            .filter_map(|s| s.parse().ok())
820            .collect();
821        nums.chunks(2).map(|c| (c[0], c[1])).collect()
822    }
823
824    fn on_line(px: f64, py: f64, x1: f64, y1: f64, x2: f64, y2: f64) -> bool {
825        let cross = ((x2 - x1) * (py - y1) - (y2 - y1) * (px - x1)).abs();
826        let length = ((x2 - x1).powi(2) + (y2 - y1).powi(2)).sqrt().max(1.0);
827        cross / length < 0.08
828    }
829
830    #[test]
831    fn short_visible_stroke_keeps_full_offset() {
832        let stub = 10.0;
833        assert!(stub * 0.22 < OFFSET_PX);
834        assert!(stub >= 2.0 * OFFSET_PX);
835        assert!((multi_bond_offset(stub) - OFFSET_PX).abs() < 1e-9);
836        assert!((multi_bond_offset(BOND_PX) - OFFSET_PX).abs() < 1e-9);
837    }
838
839    #[test]
840    fn double_is_symmetric_about_axis() {
841        let d = centered_displacements(2.0, OFFSET_PX);
842        assert_eq!(d.len(), 2);
843        assert!((d[0] + d[1]).abs() < 1e-9);
844        assert!((d[1] - d[0] - OFFSET_PX).abs() < 1e-9);
845    }
846
847    #[test]
848    fn skeleton_then_offset_for_double() {
849        let strokes = bond_strokes(0.0, 0.0, 20.0, 0.0, 2.0, None, None, None, None);
850        assert!(strokes.skeleton.is_none());
851        assert_eq!(strokes.offsets.len(), 2);
852        assert!(strokes
853            .offsets
854            .iter()
855            .all(|p| p.class.contains("bond-offset")));
856        let mut ys: Vec<f64> = strokes.offsets.iter().map(|p| path_ys(&p.d)).collect();
857        ys.sort_by(|a, b| a.partial_cmp(b).unwrap());
858        assert!((ys[0] + ys[1]).abs() < 0.05);
859        assert!((ys[0].abs() - OFFSET_PX / 2.0).abs() < 0.05);
860    }
861
862    #[test]
863    fn triple_has_skeleton_and_two_offsets() {
864        let strokes = bond_strokes(0.0, 0.0, 30.0, 0.0, 3.0, None, None, None, None);
865        assert!(strokes.skeleton.is_some());
866        assert!(strokes
867            .skeleton
868            .as_ref()
869            .unwrap()
870            .class
871            .contains("bond-skeleton"));
872        assert_eq!(strokes.offsets.len(), 2);
873        let skel_y = path_ys(&strokes.skeleton.as_ref().unwrap().d);
874        assert!(skel_y.abs() < 0.05);
875        let mut off_y: Vec<f64> = strokes.offsets.iter().map(|p| path_ys(&p.d)).collect();
876        off_y.sort_by(|a, b| a.partial_cmp(b).unwrap());
877        assert!((off_y[0] + off_y[1]).abs() < 0.05);
878    }
879
880    #[test]
881    fn solid_wedge_tip_at_begin() {
882        let w = solid_wedge(1.0, 2.0, 11.0, 2.0, None);
883        assert!(w.d.starts_with("M 1.00 2.00"));
884        assert_eq!(w.fill.as_deref(), Some("#111"));
885        assert!(w.class.contains("wedge-up"));
886    }
887
888    #[test]
889    fn hashed_wedge_wide_at_stereocenter() {
890        let dashes = hashed_wedge(0.0, 0.0, 40.0, 0.0, None, None);
891        assert!(dashes.len() >= 4);
892        let mut widths = Vec::new();
893        let mut centers = Vec::new();
894        for dash in &dashes {
895            let pts = path_pts(&dash.d);
896            widths.push((pts[0].1 - pts[1].1).abs());
897            centers.push((pts[0].0 + pts[1].0) * 0.5);
898        }
899        assert!(centers[0] < *centers.last().unwrap());
900        assert!(widths[0] > widths.last().unwrap() * 2.0);
901    }
902
903    #[test]
904    fn stereo_up_replaces_skeleton() {
905        let strokes = bond_strokes(0.0, 0.0, 10.0, 0.0, 1.0, None, Some("up"), None, None);
906        assert!(strokes.skeleton.is_none());
907        assert_eq!(strokes.stereo.len(), 1);
908        assert!(strokes.stereo[0].class.contains("wedge-up"));
909        let pts = path_pts(&strokes.stereo[0].d);
910        assert_eq!(pts.len(), 3, "filled wedge is a triangle (Z closes)");
911        assert!((pts[0].0 - 0.0).abs() < 1e-6 && (pts[0].1 - 0.0).abs() < 1e-6);
912        assert!(strokes.stereo[0].d.starts_with("M 0.00 0.00"));
913        assert!(strokes.stereo[0].d.contains('Z'));
914    }
915
916    #[test]
917    fn either_single_is_wavy() {
918        let strokes = bond_strokes(0.0, 0.0, 20.0, 0.0, 1.0, None, Some("either"), None, None);
919        assert!(strokes.skeleton.is_none());
920        assert_eq!(strokes.stereo.len(), 1);
921        assert!(strokes.stereo[0].class.contains("bond-either"));
922        // wavy_bond_sw(..., waves=5) → M + (5*2) L segments.
923        let pts = path_pts(&strokes.stereo[0].d);
924        assert_eq!(pts.len(), 1 + 5 * 2);
925        assert!((pts[0].0 - 0.0).abs() < 1e-6 && (pts[0].1 - 0.0).abs() < 1e-6);
926    }
927
928    #[test]
929    fn either_double_is_crossed() {
930        let strokes = bond_strokes(0.0, 0.0, 20.0, 0.0, 2.0, None, Some("either"), None, None);
931        assert!(strokes.skeleton.is_none());
932        let crosses: Vec<_> = strokes
933            .stereo
934            .iter()
935            .filter(|p| p.class.contains("either-cross"))
936            .collect();
937        assert_eq!(crosses.len(), 2, "crossed double has two diagonals");
938        assert!(crosses.iter().all(|p| p.class == "bond bond-either-cross"));
939        for p in &crosses {
940            let pts = path_pts(&p.d);
941            assert_eq!(pts.len(), 2);
942        }
943    }
944
945    #[test]
946    fn one_single_extends_to_the_far_line() {
947        let mut bonds = vec![
948            DrawnBond::new(0, 0, 1, 0.0, 0.0, 20.0, 0.0, 2.0),
949            DrawnBond::new(1, 0, 2, 0.0, 0.0, -10.0, 10.0, 1.0),
950        ];
951        join_centered_multibonds(&mut bonds);
952        assert!(bonds[1].y1 < -0.5);
953        assert!((bonds[1].y1 + OFFSET_PX / 2.0).abs() < 0.05);
954        assert!(on_line(0.0, 0.0, bonds[1].x1, bonds[1].y1, -10.0, 10.0));
955        let strokes = bond_strokes(
956            0.0,
957            0.0,
958            20.0,
959            0.0,
960            2.0,
961            None,
962            None,
963            bonds[0].trims.as_ref(),
964            None,
965        );
966        for path in &strokes.offsets {
967            let end = path_pts(&path.d)[0];
968            assert!(on_line(end.0, end.1, bonds[1].x1, bonds[1].y1, -10.0, 10.0));
969        }
970    }
971
972    #[test]
973    fn two_singles_meet_and_clip_the_double() {
974        let mut bonds = vec![
975            DrawnBond::new(0, 0, 1, 0.0, 0.0, 20.0, 0.0, 2.0),
976            DrawnBond::new(1, 0, 2, 0.0, 0.0, -10.0, 8.0, 1.0),
977            DrawnBond::new(2, 0, 3, 0.0, 0.0, -10.0, -8.0, 1.0),
978        ];
979        join_centered_multibonds(&mut bonds);
980        assert!((bonds[1].x1).abs() < 1e-9);
981        assert!((bonds[1].y1).abs() < 1e-9);
982        assert!((bonds[2].x1).abs() < 1e-9);
983        assert!((bonds[2].y1).abs() < 1e-9);
984        let trims = bonds[0].trims.as_ref().expect("trims");
985        assert!(trims.0.iter().all(|&t| t < 0.0));
986        let strokes = bond_strokes(0.0, 0.0, 20.0, 0.0, 2.0, None, None, Some(trims), None);
987        for path in &strokes.offsets {
988            let (x, y) = path_pts(&path.d)[0];
989            let on_upper = on_line(x, y, 0.0, 0.0, -10.0, 8.0);
990            let on_lower = on_line(x, y, 0.0, 0.0, -10.0, -8.0);
991            assert!(on_upper || on_lower);
992            assert!(x < -0.2);
993        }
994    }
995
996    #[test]
997    fn far_end_single_joins_too() {
998        let mut bonds = vec![
999            DrawnBond::new(0, 0, 1, 0.0, 0.0, 20.0, 0.0, 2.0),
1000            DrawnBond::new(1, 1, 2, 20.0, 0.0, 30.0, -10.0, 1.0),
1001        ];
1002        join_centered_multibonds(&mut bonds);
1003        assert!((bonds[1].y1 - OFFSET_PX / 2.0).abs() < 0.05);
1004        assert!(bonds[1].x1 < 20.0);
1005        let strokes = bond_strokes(
1006            0.0,
1007            0.0,
1008            20.0,
1009            0.0,
1010            2.0,
1011            None,
1012            None,
1013            bonds[0].trims.as_ref(),
1014            None,
1015        );
1016        for path in &strokes.offsets {
1017            let end = path_pts(&path.d)[1];
1018            assert!(on_line(end.0, end.1, bonds[1].x1, bonds[1].y1, 30.0, -10.0));
1019        }
1020    }
1021
1022    #[test]
1023    fn acute_two_singles_still_land_on_lines() {
1024        // ~25° between singles — old JOIN_MIN_SIN (0.34) rejected this angle.
1025        // Coords scale with BOND_PX so OFFSET_PX / bond length stays house-like.
1026        let s = BOND_PX / 20.0;
1027        let mut bonds = vec![
1028            DrawnBond::new(0, 0, 1, 0.0, 0.0, 20.0 * s, 0.0, 2.0),
1029            DrawnBond::new(1, 0, 2, 0.0, 0.0, -18.0 * s, 4.0 * s, 1.0),
1030            DrawnBond::new(2, 0, 3, 0.0, 0.0, -18.0 * s, -4.0 * s, 1.0),
1031        ];
1032        join_centered_multibonds(&mut bonds);
1033        let trims = bonds[0].trims.as_ref().expect("trims at acute junction");
1034        assert!(trims.0.iter().all(|&t| t < 0.0));
1035        let strokes = bond_strokes(0.0, 0.0, 20.0 * s, 0.0, 2.0, None, None, Some(trims), None);
1036        for path in &strokes.offsets {
1037            let (x, y) = path_pts(&path.d)[0];
1038            let on_upper = on_line(x, y, 0.0, 0.0, -18.0 * s, 4.0 * s);
1039            let on_lower = on_line(x, y, 0.0, 0.0, -18.0 * s, -4.0 * s);
1040            assert!(on_upper || on_lower, "end ({x},{y}) not on a single");
1041            assert!(x < -0.2);
1042        }
1043    }
1044
1045    #[test]
1046    fn line_intersect_crosses_unit_axes() {
1047        let (t, s, ix, iy) = line_intersect(0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0).unwrap();
1048        assert!((t - 1.0).abs() < 1e-9);
1049        assert!((s - 1.0).abs() < 1e-9);
1050        assert!((ix - 1.0).abs() < 1e-9);
1051        assert!((iy - 1.0).abs() < 1e-9);
1052        assert!(line_intersect(0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0).is_none());
1053    }
1054
1055    #[test]
1056    fn ring_double_keeps_skeleton_and_interior_offset() {
1057        let strokes = bond_strokes(
1058            0.0,
1059            0.0,
1060            BOND_PX,
1061            0.0,
1062            2.0,
1063            Some((0.0, -1.0)),
1064            None,
1065            None,
1066            None,
1067        );
1068        assert!(strokes.skeleton.is_some());
1069        assert_eq!(strokes.offsets.len(), 1);
1070        let y = path_ys(&strokes.offsets[0].d);
1071        assert!(y < -1.0);
1072    }
1073
1074    /// Parity with Python ``test_multi_bond_offset_matches_python``.
1075    #[test]
1076    fn multi_bond_offset_lengths() {
1077        for length in [3.0, 10.0, 20.0, 100.0] {
1078            let got = multi_bond_offset(length);
1079            let expected = if length < 2.0 * OFFSET_PX {
1080                OFFSET_PX.min(length * 0.25)
1081            } else {
1082                OFFSET_PX
1083            };
1084            assert!((got - expected).abs() < 1e-12, "len={length}");
1085        }
1086        // Degenerate stub shorter than 2×OFFSET.
1087        let short = multi_bond_offset(2.0);
1088        assert!((short - OFFSET_PX.min(0.5)).abs() < 1e-12);
1089    }
1090
1091    #[test]
1092    fn depict_order_maps_aromatic_encodings() {
1093        assert!((depict_order(1.5) - 1.0).abs() < 1e-12);
1094        assert!((depict_order(4.0) - 1.0).abs() < 1e-12);
1095        assert!((depict_order(2.0) - 2.0).abs() < 1e-12);
1096    }
1097
1098    #[test]
1099    fn is_aromatic_order_detects_encodings() {
1100        assert!(is_aromatic_order(1.5));
1101        assert!(is_aromatic_order(4.0));
1102        assert!(!is_aromatic_order(1.0));
1103        assert!(!is_aromatic_order(2.0));
1104        assert!(!is_aromatic_order(3.0));
1105    }
1106
1107    #[test]
1108    fn shorten_collapses_when_gaps_eat_length() {
1109        let (x1, y1, x2, y2) = shorten(0.0, 0.0, 10.0, 0.0, 6.0, 6.0);
1110        assert!((x1 - 5.0).abs() < 1e-9);
1111        assert!((x2 - 5.0).abs() < 1e-9);
1112        assert!((y1 - y2).abs() < 1e-9);
1113    }
1114
1115    #[test]
1116    fn stereo_down_and_public_stereo_helpers() {
1117        let strokes = bond_strokes(0.0, 0.0, 40.0, 0.0, 1.0, None, Some("down"), None, None);
1118        assert!(strokes.skeleton.is_none());
1119        assert!(!strokes.stereo.is_empty());
1120        assert!(strokes.stereo[0].class.contains("wedge-down"));
1121
1122        let wavy = wavy_bond(0.0, 0.0, 20.0, 0.0, None, 5);
1123        assert!(wavy.class.contains("bond-either"));
1124        let crossed = crossed_double(0.0, 0.0, 20.0, 0.0, None);
1125        assert!(crossed.iter().any(|p| p.class.contains("either-cross")));
1126    }
1127
1128    #[test]
1129    fn bond_paths_and_filled_wedge_recolor() {
1130        let paths = bond_paths(0.0, 0.0, 20.0, 0.0, 1.0, None, None);
1131        assert_eq!(paths.len(), 1);
1132        assert!(paths[0].class.contains("skeleton"));
1133
1134        let wedge = solid_wedge(0.0, 0.0, 10.0, 0.0, None).with_color("#c00");
1135        assert_eq!(wedge.stroke, "#c00");
1136        assert_eq!(wedge.fill.as_deref(), Some("#c00"));
1137        let prim = wedge.to_primitive();
1138        match prim {
1139            crate::scene::Primitive::Path {
1140                fill: Some(f),
1141                stroke: Some(s),
1142                ..
1143            } => {
1144                assert_eq!(f, "#c00");
1145                assert_eq!(s, "#c00");
1146            }
1147            _ => panic!("expected path"),
1148        }
1149    }
1150
1151    #[test]
1152    fn interior_triple_emits_two_side_offsets() {
1153        let strokes = bond_strokes(0.0, 0.0, 30.0, 0.0, 3.0, Some((0.0, 1.0)), None, None, None);
1154        assert!(strokes.skeleton.is_some());
1155        assert_eq!(strokes.offsets.len(), 2);
1156    }
1157
1158    #[test]
1159    fn centered_multi_skips_stereo_up() {
1160        let mut b = DrawnBond::new(0, 0, 1, 0.0, 0.0, 20.0, 0.0, 2.0);
1161        b.stereo = Some("up".into());
1162        // join should ignore stereo multi; no trims set.
1163        let mut bonds = vec![b, DrawnBond::new(1, 0, 2, 0.0, 0.0, -10.0, 10.0, 1.0)];
1164        join_centered_multibonds(&mut bonds);
1165        assert!(bonds[0].trims.is_none());
1166    }
1167
1168    #[test]
1169    fn join_moves_single_when_atom_is_bond_end() {
1170        // Single oriented so atom is `end` (end_flag == 1) → updates x2/y2.
1171        let mut bonds = vec![
1172            DrawnBond::new(0, 0, 1, 0.0, 0.0, 20.0, 0.0, 2.0),
1173            DrawnBond::new(1, 2, 0, -10.0, 10.0, 0.0, 0.0, 1.0),
1174        ];
1175        join_centered_multibonds(&mut bonds);
1176        assert!(bonds[1].y2 < -0.5 || bonds[1].y2 > 0.5 || bonds[0].trims.is_some());
1177        // End attached at atom 0 should have moved off the atom along the single.
1178        assert!((bonds[1].x2 - 0.0).abs() > 0.01 || (bonds[1].y2 - 0.0).abs() > 0.01);
1179    }
1180
1181    #[test]
1182    fn large_trims_are_scaled_to_fit() {
1183        let trims = (vec![8.0, 8.0], vec![8.0, 8.0]); // sum 16 > 0.9*20
1184        let strokes = bond_strokes(0.0, 0.0, 20.0, 0.0, 2.0, None, None, Some(&trims), None);
1185        assert_eq!(strokes.offsets.len(), 2);
1186        for p in &strokes.offsets {
1187            let pts = path_pts(&p.d);
1188            let len = ((pts[1].0 - pts[0].0).powi(2) + (pts[1].1 - pts[0].1).powi(2)).sqrt();
1189            assert!(len < 20.0 * 0.95, "scaled trim length {len}");
1190        }
1191    }
1192}