1use crate::doc::{EdgeArrow, EdgeRouting};
7
8pub const KINK_PX: f64 = 10.0;
10pub const TURN_RADIUS: f64 = 36.0;
12
13const DEFAULT_COLOR: &str = "#222";
14const DEFAULT_WIDTH: f64 = 1.6;
15const HEAD: f64 = 9.0;
17
18pub fn head_px(stroke_width: Option<f64>) -> f64 {
20 let w = stroke_width.unwrap_or(DEFAULT_WIDTH).max(0.5);
21 HEAD * (w / DEFAULT_WIDTH)
22}
23
24pub fn min_shaft_px(stroke_width: Option<f64>) -> f64 {
26 head_px(stroke_width) * 2.5
27}
28const DASH: &str = "6 4";
29const EQ_SEP: f64 = 3.2;
30pub const ANCHOR_GAP: f64 = 6.0;
32
33pub fn clip_box_edge(cx: f64, cy: f64, tx: f64, ty: f64, w: f64, h: f64, pad: f64) -> Pt {
35 let dx = tx - cx;
36 let dy = ty - cy;
37 if dx.abs() < 1e-9 && dy.abs() < 1e-9 {
38 return (cx, cy);
39 }
40 let hw = w * 0.5 + pad;
41 let hh = h * 0.5 + pad;
42 let sx = if dx.abs() > 1e-9 {
43 hw / dx.abs()
44 } else {
45 f64::INFINITY
46 };
47 let sy = if dy.abs() > 1e-9 {
48 hh / dy.abs()
49 } else {
50 f64::INFINITY
51 };
52 let t = sx.min(sy);
53 (cx + dx * t, cy + dy * t)
54}
55
56pub fn edge_anchors(src: (f64, f64, f64, f64), tgt: (f64, f64, f64, f64), pad: f64) -> (Pt, Pt) {
60 let (sx, sy, sw, sh) = src;
61 let (tx, ty, tw, th) = tgt;
62 let scx = sx + sw * 0.5;
63 let scy = sy + sh * 0.5;
64 let tcx = tx + tw * 0.5;
65 let tcy = ty + th * 0.5;
66 let p0 = clip_box_edge(scx, scy, tcx, tcy, sw, sh, pad);
67 let p1 = clip_box_edge(tcx, tcy, scx, scy, tw, th, pad);
68 (p0, p1)
69}
70
71pub type Pt = (f64, f64);
73
74fn hypot(dx: f64, dy: f64) -> f64 {
75 dx.hypot(dy)
76}
77
78fn point_line_distance(px: f64, py: f64, ax: f64, ay: f64, bx: f64, by: f64) -> f64 {
79 let dx = bx - ax;
80 let dy = by - ay;
81 let l2 = dx * dx + dy * dy;
82 if l2 < 1e-12 {
83 return hypot(px - ax, py - ay);
84 }
85 let t = ((px - ax) * dx + (py - ay) * dy) / l2;
86 let qx = ax + t * dx;
87 let qy = ay + t * dy;
88 hypot(px - qx, py - qy)
89}
90
91pub fn simplify_route(pts: &[Pt], kink_px: f64) -> Vec<Pt> {
93 if pts.len() < 2 {
94 return pts.to_vec();
95 }
96 let mut cleaned: Vec<Pt> = Vec::with_capacity(pts.len());
97 for &(x, y) in pts {
98 if cleaned
99 .last()
100 .map(|&(lx, ly)| hypot(x - lx, y - ly) > 1e-6)
101 .unwrap_or(true)
102 {
103 cleaned.push((x, y));
104 }
105 }
106 if cleaned.len() <= 2 {
107 return cleaned;
108 }
109
110 let mut changed = true;
112 while changed && cleaned.len() > 2 {
113 changed = false;
114 let mut out: Vec<Pt> = vec![cleaned[0]];
115 let mut i = 1;
116 while i + 1 < cleaned.len() {
117 let (x0, y0) = *out.last().unwrap();
118 let (x1, y1) = cleaned[i];
119 let (x2, y2) = cleaned[i + 1];
120 let seg = hypot(x1 - x0, y1 - y0);
121 let nxt = hypot(x2 - x1, y2 - y1);
122 if seg < kink_px || nxt < kink_px {
123 i += 1;
124 changed = true;
125 continue;
126 }
127 out.push(cleaned[i]);
128 i += 1;
129 }
130 out.push(*cleaned.last().unwrap());
131 cleaned = out;
132 }
133
134 changed = true;
136 while changed && cleaned.len() > 2 {
137 changed = false;
138 let mut out: Vec<Pt> = vec![cleaned[0]];
139 for i in 1..cleaned.len() - 1 {
140 let (ax, ay) = *out.last().unwrap();
141 let (px, py) = cleaned[i];
142 let (bx, by) = cleaned[i + 1];
143 if point_line_distance(px, py, ax, ay, bx, by) < kink_px {
144 changed = true;
145 continue;
146 }
147 out.push(cleaned[i]);
148 }
149 out.push(*cleaned.last().unwrap());
150 cleaned = out;
151 }
152 cleaned
153}
154
155pub fn axis_aligned(pts: &[Pt], tol: f64) -> bool {
157 if pts.len() < 2 {
158 return true;
159 }
160 for i in 1..pts.len() {
161 let dx = (pts[i].0 - pts[i - 1].0).abs();
162 let dy = (pts[i].1 - pts[i - 1].1).abs();
163 if dx > tol && dy > tol {
164 return false;
165 }
166 }
167 true
168}
169
170pub fn should_fillet(pts: &[Pt], routing: Option<EdgeRouting>) -> bool {
172 match routing {
173 Some(EdgeRouting::Orthogonal) => false,
174 Some(EdgeRouting::Polyline | EdgeRouting::Splines) => !axis_aligned(pts, 1e-3),
175 None => pts.len() > 2 && !axis_aligned(pts, 1e-3),
176 }
177}
178
179fn polyline_d(pts: &[Pt]) -> String {
180 if pts.is_empty() {
181 return String::new();
182 }
183 let mut bits = Vec::with_capacity(pts.len());
184 bits.push(format!("M {:.2} {:.2}", pts[0].0, pts[0].1));
185 for &(x, y) in &pts[1..] {
186 bits.push(format!("L {x:.2} {y:.2}"));
187 }
188 bits.join(" ")
189}
190
191pub fn filleted_path_d(pts: &[Pt], radius: f64) -> String {
193 if pts.len() < 2 {
194 return String::new();
195 }
196 if pts.len() == 2 || radius <= 0.0 {
197 return polyline_d(pts);
198 }
199 let mut bits: Vec<String> = vec![format!("M {:.2} {:.2}", pts[0].0, pts[0].1)];
200 for i in 1..pts.len() - 1 {
201 let (ax, ay) = pts[i - 1];
202 let (bx, by) = pts[i];
203 let (cx, cy) = pts[i + 1];
204 let v1x = ax - bx;
205 let v1y = ay - by;
206 let v2x = cx - bx;
207 let v2y = cy - by;
208 let len1 = hypot(v1x, v1y).max(1e-9);
209 let len2 = hypot(v2x, v2y).max(1e-9);
210 let dot = (v1x * v2x + v1y * v2y) / (len1 * len2);
211 if dot < -0.98 {
212 bits.push(format!("L {bx:.2} {by:.2}"));
213 continue;
214 }
215 let r = radius.min(0.45 * len1).min(0.45 * len2);
216 if r < 1.0 {
217 bits.push(format!("L {bx:.2} {by:.2}"));
218 continue;
219 }
220 let u1x = v1x / len1;
221 let u1y = v1y / len1;
222 let u2x = v2x / len2;
223 let u2y = v2y / len2;
224 let p1x = bx + u1x * r;
225 let p1y = by + u1y * r;
226 let p2x = bx + u2x * r;
227 let p2y = by + u2y * r;
228 bits.push(format!("L {p1x:.2} {p1y:.2}"));
229 bits.push(format!("Q {bx:.2} {by:.2} {p2x:.2} {p2y:.2}"));
230 }
231 let (lx, ly) = *pts.last().unwrap();
232 bits.push(format!("L {lx:.2} {ly:.2}"));
233 bits.join(" ")
234}
235
236pub fn shaft_path_d(pts: &[Pt], routing: Option<EdgeRouting>) -> String {
238 if should_fillet(pts, routing) {
239 filleted_path_d(pts, TURN_RADIUS)
240 } else {
241 polyline_d(pts)
242 }
243}
244
245fn painted_shaft_d(pts: &[Pt], routing: Option<EdgeRouting>, curve_catmull: bool) -> String {
246 if curve_catmull {
247 crate::catmull::centripetal_catmull_rom_open_path(pts)
248 } else {
249 shaft_path_d(pts, routing)
250 }
251}
252
253fn unit(dx: f64, dy: f64) -> (f64, f64) {
254 let l = hypot(dx, dy).max(1e-9);
255 (dx / l, dy / l)
256}
257
258fn perp(ux: f64, uy: f64) -> (f64, f64) {
259 (-uy, ux)
260}
261
262fn polyline_length(pts: &[Pt]) -> f64 {
263 let mut total = 0.0;
264 for i in 1..pts.len() {
265 total += hypot(pts[i].0 - pts[i - 1].0, pts[i].1 - pts[i - 1].1);
266 }
267 total
268}
269
270fn shorten_polyline_end(pts: &[Pt], amount: f64) -> (Vec<Pt>, Pt, (f64, f64)) {
271 if pts.len() < 2 {
272 let p = pts.first().copied().unwrap_or((0.0, 0.0));
273 return (vec![p], p, (1.0, 0.0));
274 }
275 let tip = *pts.last().unwrap();
276 let mut pts = pts.to_vec();
277 let mut remaining = amount;
278 while pts.len() >= 2 && remaining > 0.0 {
279 let (x1, y1) = pts[pts.len() - 2];
280 let (x2, y2) = pts[pts.len() - 1];
281 let seg = hypot(x2 - x1, y2 - y1);
282 if seg <= 1e-9 {
283 pts.pop();
284 continue;
285 }
286 if seg > remaining {
287 let (ux, uy) = unit(x2 - x1, y2 - y1);
288 let nx = x2 - ux * remaining;
289 let ny = y2 - uy * remaining;
290 let last = pts.len() - 1;
291 pts[last] = (nx, ny);
292 return (pts, tip, (ux, uy));
293 }
294 remaining -= seg;
295 pts.pop();
296 }
297 let (ux, uy) = if pts.len() >= 2 {
298 unit(
299 pts[pts.len() - 1].0 - pts[pts.len() - 2].0,
300 pts[pts.len() - 1].1 - pts[pts.len() - 2].1,
301 )
302 } else {
303 (1.0, 0.0)
304 };
305 (pts, tip, (ux, uy))
306}
307
308fn shaft_and_head(
312 pts: &[Pt],
313 head_size: f64,
314 routing: Option<EdgeRouting>,
315 curve_catmull: bool,
316) -> (String, Pt, Pt, (f64, f64)) {
317 if curve_catmull {
318 crate::catmull::open_catmull_with_arrow(pts, head_size)
319 } else {
320 let (shaft, tip, (ux, uy)) = shorten_polyline_end(pts, head_size);
321 let base = *shaft.last().unwrap_or(&tip);
322 (shaft_path_d(&shaft, routing), tip, base, (ux, uy))
323 }
324}
325
326fn filled_arrow_head_d(tip: Pt, base: Pt, size: f64) -> String {
327 let (ux, uy) = unit(tip.0 - base.0, tip.1 - base.1);
328 let (px, py) = perp(ux, uy);
329 let half = size * 0.55;
330 format!(
331 "M {:.2} {:.2} L {:.2} {:.2} L {:.2} {:.2} Z",
332 base.0 + px * half,
333 base.1 + py * half,
334 tip.0,
335 tip.1,
336 base.0 - px * half,
337 base.1 - py * half
338 )
339}
340
341#[derive(Debug, Clone)]
343pub struct EdgePaintIn {
344 pub pts: Vec<Pt>,
345 pub arrow: EdgeArrow,
346 pub routing: Option<EdgeRouting>,
347 pub color: Option<String>,
348 pub stroke_width: Option<f64>,
349 pub dashed: bool,
350 pub label: Option<String>,
351 pub label_pos: Option<String>,
352 pub index: usize,
353 pub curve_catmull: bool,
355 pub label_xy: Option<Pt>,
357 pub label_rotate: Option<f64>,
359}
360
361#[derive(Debug, Clone, PartialEq)]
363pub enum EdgePrim {
364 Path {
365 d: String,
366 stroke: String,
367 fill: String,
368 stroke_width: f64,
369 stroke_dasharray: Option<String>,
370 class: String,
371 },
372 Text {
373 x: f64,
374 y: f64,
375 text: String,
376 fill: String,
377 font_size: f64,
378 anchor: String,
379 class: String,
380 rotate: f64,
382 },
383}
384
385fn path_prim(
386 d: String,
387 stroke: &str,
388 fill: &str,
389 width: f64,
390 dashed: bool,
391 class: &str,
392) -> EdgePrim {
393 EdgePrim::Path {
394 d,
395 stroke: stroke.to_string(),
396 fill: fill.to_string(),
397 stroke_width: width,
398 stroke_dasharray: if dashed { Some(DASH.to_string()) } else { None },
399 class: class.to_string(),
400 }
401}
402
403fn label_point(pts: &[Pt]) -> (f64, f64, f64, f64) {
404 if pts.len() < 2 {
405 let (x, y) = pts.first().copied().unwrap_or((0.0, 0.0));
406 return (x, y, 0.0, -1.0);
407 }
408 let mut best_i = 1;
409 let mut best_len = -1.0;
410 for i in 1..pts.len() {
411 let l = hypot(pts[i].0 - pts[i - 1].0, pts[i].1 - pts[i - 1].1);
412 if l > best_len {
413 best_len = l;
414 best_i = i;
415 }
416 }
417 let (x1, y1) = pts[best_i - 1];
418 let (x2, y2) = pts[best_i];
419 let (ux, uy) = unit(x2 - x1, y2 - y1);
420 let (px, py) = perp(ux, uy);
421 ((x1 + x2) * 0.5, (y1 + y2) * 0.5, px, py)
422}
423
424fn offset_polyline(pts: &[Pt], dist: f64) -> Vec<Pt> {
425 if pts.len() < 2 {
426 return pts.to_vec();
427 }
428 let n = pts.len();
429 let mut out = Vec::with_capacity(n);
430 for (i, &(x, y)) in pts.iter().enumerate() {
431 let (px, py) = if i == 0 {
432 let (ux, uy) = unit(pts[1].0 - x, pts[1].1 - y);
433 perp(ux, uy)
434 } else if i + 1 == n {
435 let (ux, uy) = unit(x - pts[i - 1].0, y - pts[i - 1].1);
436 perp(ux, uy)
437 } else {
438 let (u1x, u1y) = unit(x - pts[i - 1].0, y - pts[i - 1].1);
439 let (u2x, u2y) = unit(pts[i + 1].0 - x, pts[i + 1].1 - y);
440 let (p1x, p1y) = perp(u1x, u1y);
441 let (p2x, p2y) = perp(u2x, u2y);
442 let mut px = p1x + p2x;
443 let mut py = p1y + p2y;
444 let l = hypot(px, py).max(1e-9);
445 px /= l;
446 py /= l;
447 (px, py)
448 };
449 out.push((x + px * dist, y + py * dist));
450 }
451 out
452}
453
454fn harpoon_poly(
455 pts: &[Pt],
456 color: &str,
457 width: f64,
458 dashed: bool,
459 head_size: f64,
460 class: &str,
461 routing: Option<EdgeRouting>,
462 curve_catmull: bool,
463) -> Vec<EdgePrim> {
464 let (shaft_d, tip, base, (ux, uy)) = shaft_and_head(pts, head_size, routing, curve_catmull);
465 let (px, py) = perp(ux, uy);
466 let barb = head_size * 0.55;
467 let mut out = Vec::new();
468 if !shaft_d.is_empty() {
469 out.push(path_prim(shaft_d, color, "none", width, dashed, class));
470 }
471 out.push(path_prim(
472 format!(
473 "M {:.2} {:.2} L {:.2} {:.2}",
474 tip.0,
475 tip.1,
476 base.0 + px * barb,
477 base.1 + py * barb
478 ),
479 color,
480 "none",
481 width,
482 false,
483 &format!("{class} harpoon"),
484 ));
485 out
486}
487
488pub fn edge_primitives(edge: &EdgePaintIn) -> Vec<EdgePrim> {
490 let pts = simplify_route(&edge.pts, KINK_PX);
491 if polyline_length(&pts) < 4.0 {
492 return Vec::new();
493 }
494 let color = edge.color.as_deref().unwrap_or(DEFAULT_COLOR);
495 let width = edge.stroke_width.unwrap_or(DEFAULT_WIDTH);
496 let head = head_px(edge.stroke_width).min((polyline_length(&pts) * 0.45).max(HEAD * 0.5));
497 let dashed = edge.dashed;
498 let routing = edge.routing;
499 let cls = format!("edge edge-{}", edge.index);
500 let mut out: Vec<EdgePrim> = Vec::new();
501
502 match edge.arrow {
503 EdgeArrow::Equilibrium => {
504 let fwd = offset_polyline(&pts, EQ_SEP);
505 let mut rev = offset_polyline(&pts, -EQ_SEP);
506 rev.reverse();
507 out.extend(harpoon_poly(
508 &fwd,
509 color,
510 width,
511 dashed,
512 head * 0.85,
513 &format!("{cls} eq-fwd"),
514 routing,
515 edge.curve_catmull,
516 ));
517 out.extend(harpoon_poly(
518 &rev,
519 color,
520 width,
521 dashed,
522 head * 0.85,
523 &format!("{cls} eq-rev"),
524 routing,
525 edge.curve_catmull,
526 ));
527 }
528 EdgeArrow::Line => {
529 out.push(path_prim(
530 painted_shaft_d(&pts, routing, edge.curve_catmull),
531 color,
532 "none",
533 width,
534 dashed,
535 &cls,
536 ));
537 }
538 EdgeArrow::Open => {
539 let (shaft_d, tip, base, (ux, uy)) =
540 shaft_and_head(&pts, head, routing, edge.curve_catmull);
541 if !shaft_d.is_empty() {
542 out.push(path_prim(shaft_d, color, "none", width, dashed, &cls));
543 }
544 let (px, py) = perp(ux, uy);
545 let half = head * 0.55;
546 out.push(path_prim(
547 format!(
548 "M {:.2} {:.2} L {:.2} {:.2} L {:.2} {:.2}",
549 base.0 + px * half,
550 base.1 + py * half,
551 tip.0,
552 tip.1,
553 base.0 - px * half,
554 base.1 - py * half
555 ),
556 color,
557 "none",
558 width,
559 false,
560 &format!("{cls} head"),
561 ));
562 }
563 EdgeArrow::Forward => {
564 let (shaft_d, tip, base, _) = shaft_and_head(&pts, head, routing, edge.curve_catmull);
565 if !shaft_d.is_empty() {
566 out.push(path_prim(shaft_d, color, "none", width, dashed, &cls));
567 }
568 out.push(path_prim(
569 filled_arrow_head_d(tip, base, head),
570 "none",
571 color,
572 0.0,
573 false,
574 &format!("{cls} head"),
575 ));
576 }
577 }
578
579 if let Some(ref label) = edge.label {
580 let (mx, my, mut px, mut py) = label_point(&pts);
581 let pos = edge
582 .label_pos
583 .as_deref()
584 .unwrap_or("above")
585 .to_ascii_lowercase();
586 if pos == "below" || pos == "right" {
587 px = -px;
588 py = -py;
589 }
590 let (x, y) = edge
591 .label_xy
592 .unwrap_or((mx + px * 10.0, my + py * 10.0 + 4.0));
593 let rotate = edge.label_rotate.unwrap_or(0.0);
594 out.push(EdgePrim::Text {
595 x,
596 y,
597 text: label.clone(),
598 fill: color.to_string(),
599 font_size: 11.0,
600 anchor: "middle".into(),
601 class: format!("{cls} label"),
602 rotate,
603 });
604 }
605 out
606}
607
608#[cfg(test)]
609mod tests {
610 use super::*;
611
612 fn paint(pts: Vec<Pt>, arrow: EdgeArrow, routing: Option<EdgeRouting>) -> EdgePaintIn {
613 EdgePaintIn {
614 pts,
615 arrow,
616 routing,
617 color: Some("#06c".into()),
618 stroke_width: Some(2.0),
619 dashed: true,
620 label: Some("lab".into()),
621 label_pos: Some("below".into()),
622 index: 1,
623 curve_catmull: false,
624 label_xy: None,
625 label_rotate: None,
626 }
627 }
628
629 #[test]
630 fn head_scales_with_stroke() {
631 assert!((head_px(None) - 9.0).abs() < 1e-9);
632 assert!((head_px(Some(1.6)) - 9.0).abs() < 1e-9);
633 assert!((head_px(Some(4.8)) - 27.0).abs() < 1e-9);
634 assert!(min_shaft_px(Some(4.8)) > head_px(Some(4.8)) * 2.0);
635 }
636
637 #[test]
638 fn simplify_snaps_micro_kink() {
639 let jog = vec![(0.0, 0.0), (100.0, 0.0), (100.0, 5.0), (200.0, 5.0)];
640 let flat = simplify_route(&jog, KINK_PX);
641 assert_eq!(flat.len(), 2);
642 assert_eq!(flat[0], (0.0, 0.0));
643 assert_eq!(flat[1], (200.0, 5.0));
644 }
645
646 #[test]
647 fn simplify_handles_short_and_duplicates() {
648 assert!(simplify_route(&[], KINK_PX).is_empty());
649 assert_eq!(simplify_route(&[(1.0, 2.0)], KINK_PX), vec![(1.0, 2.0)]);
650 let dups = vec![(0.0, 0.0), (0.0, 0.0), (10.0, 0.0)];
651 assert_eq!(simplify_route(&dups, KINK_PX).len(), 2);
652 let elbow = vec![(0.0, 0.0), (80.0, 0.0), (80.0, 60.0), (140.0, 60.0)];
654 assert_eq!(simplify_route(&elbow, KINK_PX).len(), 4);
655 }
656
657 #[test]
658 fn orthogonal_keeps_sharp_corners() {
659 let pts = vec![(0.0, 0.0), (80.0, 0.0), (80.0, 60.0), (140.0, 60.0)];
660 assert!(!should_fillet(&pts, Some(EdgeRouting::Orthogonal)));
661 assert!(!should_fillet(&pts, Some(EdgeRouting::Polyline))); assert!(!should_fillet(&pts, None));
663 let d = shaft_path_d(&pts, Some(EdgeRouting::Orthogonal));
664 assert!(!d.contains('Q'));
665 assert!(d.matches('L').count() >= 2);
666 }
667
668 #[test]
669 fn polyline_diagonal_gets_fillet() {
670 let pts = vec![(0.0, 0.0), (80.0, 0.0), (120.0, 60.0), (180.0, 60.0)];
671 assert!(should_fillet(&pts, Some(EdgeRouting::Polyline)));
672 assert!(should_fillet(&pts, Some(EdgeRouting::Splines)));
673 assert!(should_fillet(&pts, None));
674 let d = shaft_path_d(&pts, Some(EdgeRouting::Polyline));
675 assert!(d.contains('Q'));
676 }
677
678 #[test]
679 fn filleted_path_edge_cases() {
680 assert!(filleted_path_d(&[], TURN_RADIUS).is_empty());
681 assert!(!filleted_path_d(&[(0.0, 0.0), (10.0, 0.0)], TURN_RADIUS).contains('Q'));
682 assert!(!filleted_path_d(&[(0.0, 0.0), (10.0, 0.0), (20.0, 0.0)], 0.0).contains('Q'));
683 let almost = vec![(0.0, 0.0), (50.0, 0.0), (100.0, 0.1)];
685 let d = filleted_path_d(&almost, TURN_RADIUS);
686 assert!(d.contains('L'));
687 let tiny = vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1.0)];
689 assert!(!filleted_path_d(&tiny, TURN_RADIUS).contains('Q'));
690 }
691
692 #[test]
693 fn axis_aligned_and_point_line() {
694 assert!(axis_aligned(&[(0.0, 0.0)], 1e-3));
695 assert!(axis_aligned(&[(0.0, 0.0), (1.0, 0.0), (1.0, 2.0)], 1e-3));
696 assert!(!axis_aligned(&[(0.0, 0.0), (1.0, 1.0)], 1e-3));
697 assert!(point_line_distance(0.0, 1.0, 0.0, 0.0, 0.0, 0.0) >= 0.0);
698 assert!((point_line_distance(1.0, 1.0, 0.0, 0.0, 2.0, 0.0) - 1.0).abs() < 1e-9);
699 }
700
701 #[test]
702 fn shorten_polyline_edge_cases() {
703 let (s, tip, _) = shorten_polyline_end(&[], 5.0);
704 assert_eq!(s.len(), 1);
705 assert_eq!(tip, (0.0, 0.0));
706 let (s, tip, dir) = shorten_polyline_end(&[(1.0, 2.0)], 5.0);
707 assert_eq!(tip, (1.0, 2.0));
708 assert_eq!(dir, (1.0, 0.0));
709 assert_eq!(s, vec![(1.0, 2.0)]);
710 let pts = vec![(0.0, 0.0), (0.0, 0.0), (100.0, 0.0)];
712 let (s, _, (ux, _)) = shorten_polyline_end(&pts, 10.0);
713 assert!(s.len() >= 2);
714 assert!(ux > 0.0);
715 let (s, _, _) = shorten_polyline_end(&[(0.0, 0.0), (5.0, 0.0)], 20.0);
717 assert!(s.len() <= 2);
718 }
719
720 fn painted_shaft_and_head(prims: &[EdgePrim]) -> (&str, &str) {
721 let shaft = prims.iter().find_map(|p| match p {
722 EdgePrim::Path { d, class, .. }
723 if class.contains("edge")
724 && !class.contains("head")
725 && !class.contains("harpoon") =>
726 {
727 Some(d.as_str())
728 }
729 _ => None,
730 });
731 let head = prims.iter().find_map(|p| match p {
732 EdgePrim::Path { d, class, .. } if class.contains("head") => Some(d.as_str()),
733 _ => None,
734 });
735 (shaft.expect("shaft"), head.expect("head"))
736 }
737
738 fn assert_forward_head_locked_to_route(pts: Vec<Pt>, curve_catmull: bool) {
739 let mut edge = paint(pts.clone(), EdgeArrow::Forward, None);
740 edge.curve_catmull = curve_catmull;
741 edge.label = None;
742 edge.stroke_width = Some(4.8);
743 let simplified = simplify_route(&pts, KINK_PX);
744 let tip = *simplified.last().expect("route");
745 let prev = simplified[simplified.len() - 2];
746 let head_size =
747 head_px(edge.stroke_width).min((polyline_length(&simplified) * 0.45).max(HEAD * 0.5));
748 let (expected_shaft, base) = if curve_catmull {
749 let chord = (tip.0 - prev.0).hypot(tip.1 - prev.1).max(1e-9);
750 let h = head_size.min(chord * 0.9);
751 let (ux, uy) = ((tip.0 - prev.0) / chord, (tip.1 - prev.1) / chord);
752 let base = (tip.0 - ux * h, tip.1 - uy * h);
753 let mut shaft_pts = simplified.clone();
754 let last = shaft_pts.len() - 1;
755 shaft_pts[last] = base;
756 (
757 crate::catmull::centripetal_catmull_rom_open_path(&shaft_pts),
758 base,
759 )
760 } else {
761 let (shaft, _, _) = shorten_polyline_end(&simplified, head_size);
762 let base = *shaft.last().unwrap_or(&tip);
763 (shaft_path_d(&shaft, None), base)
764 };
765 let prims = edge_primitives(&edge);
766 let (shaft, head) = painted_shaft_and_head(&prims);
767 assert_eq!(
768 shaft, expected_shaft,
769 "shaft must interpolate the last routing points and end at the head base"
770 );
771 assert_eq!(
772 head,
773 filled_arrow_head_d(tip, base, head_size),
774 "head must be the triangle of the last control and that base"
775 );
776 }
777
778 #[test]
779 fn catmull_forward_head_meets_shaft() {
780 assert_forward_head_locked_to_route(vec![(0.0, 0.0), (80.0, 0.0), (80.0, 80.0)], true);
781 assert_forward_head_locked_to_route(
782 vec![(0.0, 0.0), (40.0, 50.0), (90.0, 10.0), (160.0, 80.0)],
783 true,
784 );
785 assert_forward_head_locked_to_route(vec![(0.0, 0.0), (140.0, 20.0)], true);
786 assert_forward_head_locked_to_route(vec![(0.0, 0.0), (80.0, 0.0), (80.0, 80.0)], false);
787 assert_forward_head_locked_to_route(
788 vec![(0.0, 0.0), (40.0, 50.0), (90.0, 10.0), (160.0, 80.0)],
789 false,
790 );
791 }
792
793 #[test]
794 fn open_head_uses_the_same_base_as_the_shaft() {
795 let pts = vec![(0.0, 0.0), (50.0, 40.0), (120.0, 15.0), (180.0, 90.0)];
796 let mut edge = paint(pts.clone(), EdgeArrow::Open, None);
797 edge.curve_catmull = true;
798 edge.label = None;
799 edge.stroke_width = Some(4.8);
800 let simplified = simplify_route(&pts, KINK_PX);
801 let tip = *simplified.last().unwrap();
802 let prev = simplified[simplified.len() - 2];
803 let head_size =
804 head_px(edge.stroke_width).min((polyline_length(&simplified) * 0.45).max(HEAD * 0.5));
805 let chord = (tip.0 - prev.0).hypot(tip.1 - prev.1).max(1e-9);
806 let h = head_size.min(chord * 0.9);
807 let (ux, uy) = ((tip.0 - prev.0) / chord, (tip.1 - prev.1) / chord);
808 let base = (tip.0 - ux * h, tip.1 - uy * h);
809 let mut shaft_pts = simplified.clone();
810 let last = shaft_pts.len() - 1;
811 shaft_pts[last] = base;
812 let expected_shaft = crate::catmull::centripetal_catmull_rom_open_path(&shaft_pts);
813 let (px, py) = perp(ux, uy);
814 let half = head_size * 0.55;
815 let expected_head = format!(
816 "M {:.2} {:.2} L {:.2} {:.2} L {:.2} {:.2}",
817 base.0 + px * half,
818 base.1 + py * half,
819 tip.0,
820 tip.1,
821 base.0 - px * half,
822 base.1 - py * half
823 );
824 let prims = edge_primitives(&edge);
825 let (shaft, head) = painted_shaft_and_head(&prims);
826 assert_eq!(shaft, expected_shaft);
827 assert_eq!(head, expected_head);
828 }
829
830 #[test]
831 fn catmull_shaft_is_shared_open_path() {
832 let pts = vec![(0.0, 0.0), (80.0, 0.0), (80.0, 80.0)];
833 let mut edge = paint(pts.clone(), EdgeArrow::Line, None);
834 edge.curve_catmull = true;
835 edge.label = None;
836 let prims = edge_primitives(&edge);
837 let d = prims.iter().find_map(|p| match p {
838 EdgePrim::Path { d, class, .. }
839 if class.contains("shaft") || class.contains("edge") =>
840 {
841 Some(d.as_str())
842 }
843 _ => None,
844 });
845 let d = d.expect("shaft path");
846 let expected =
847 crate::catmull::centripetal_catmull_rom_open_path(&simplify_route(&pts, KINK_PX));
848 assert_eq!(d, expected);
849 assert!(d.contains('C'), "{d}");
850 assert!(!d.contains('Z'), "{d}");
851 }
852
853 #[test]
854 fn forward_edge_emits_shaft_and_head() {
855 let edge = paint(vec![(0.0, 0.0), (100.0, 0.0)], EdgeArrow::Forward, None);
856 let prims = edge_primitives(&edge);
857 assert!(prims.len() >= 2);
858 assert!(prims.iter().any(|p| matches!(p, EdgePrim::Text { .. })));
859 assert!(prims.iter().any(|p| matches!(
860 p,
861 EdgePrim::Path {
862 stroke_dasharray: Some(_),
863 ..
864 }
865 )));
866 }
867
868 #[test]
869 fn line_open_equilibrium_arrows() {
870 let pts = vec![(0.0, 0.0), (40.0, 0.0), (40.0, 40.0), (80.0, 40.0)];
871 for arrow in [EdgeArrow::Line, EdgeArrow::Open, EdgeArrow::Equilibrium] {
872 let mut edge = paint(pts.clone(), arrow, Some(EdgeRouting::Orthogonal));
873 edge.label_pos = Some("above".into());
874 let prims = edge_primitives(&edge);
875 assert!(!prims.is_empty(), "{arrow:?}");
876 }
877 let short = paint(vec![(0.0, 0.0), (1.0, 0.0)], EdgeArrow::Line, None);
879 assert!(edge_primitives(&short).is_empty());
880 }
881
882 #[test]
883 fn edge_anchors_on_box_boundary() {
884 let (p0, p1) = edge_anchors((0.0, 0.0, 100.0, 80.0), (200.0, 0.0, 100.0, 80.0), 0.0);
885 assert!((p0.0 - 100.0).abs() < 1e-6);
886 assert!((p1.0 - 200.0).abs() < 1e-6);
887 assert!((p0.1 - 40.0).abs() < 1e-6);
888 let same = clip_box_edge(0.0, 0.0, 0.0, 0.0, 10.0, 10.0, 0.0);
889 assert_eq!(same, (0.0, 0.0));
890 }
891
892 #[test]
893 fn offset_and_label_helpers() {
894 assert_eq!(offset_polyline(&[(0.0, 0.0)], 2.0).len(), 1);
895 let off = offset_polyline(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0)], 2.0);
896 assert_eq!(off.len(), 3);
897 let (x, y, _, _) = label_point(&[]);
898 assert_eq!((x, y), (0.0, 0.0));
899 let _ = label_point(&[(5.0, 5.0)]);
900 }
901}