1use crate::edge::{Edge, EdgeShape};
8use crate::geometry::{Rect, Vec2, distance_to_segment};
9use crate::graph::Graph;
10use crate::ids::PortId;
11use crate::port::Side;
12
13const BEZIER_SEGMENTS: usize = 24;
15const CORNER_SEGMENTS: usize = 6;
17
18#[derive(Clone, Debug, PartialEq)]
19pub struct EdgeGeometry {
20 pub points: Vec<Vec2>,
22 pub cubic: Option<[Vec2; 4]>,
24 pub label: Vec2,
26 pub end_dir: Vec2,
28 pub bounds: Rect,
29}
30
31impl EdgeGeometry {
32 pub fn length(&self) -> f32 {
33 self.points.windows(2).map(|w| w[0].distance(w[1])).sum()
34 }
35
36 pub fn distance_to(&self, p: Vec2) -> f32 {
37 self.points
38 .windows(2)
39 .map(|w| distance_to_segment(p, w[0], w[1]))
40 .fold(f32::INFINITY, f32::min)
41 }
42}
43
44pub fn port_anchor(graph: &Graph, port: PortId) -> Option<(Vec2, Side)> {
46 let p = graph.port(port)?;
47 let rect = graph.world_rect(p.node)?;
48 let siblings: Vec<PortId> = graph
49 .ports_of(p.node)
50 .filter(|q| q.side == p.side)
51 .map(|q| q.id)
52 .collect();
53 let n = siblings.len().max(1) as f32;
54 let k = siblings.iter().position(|q| *q == port).unwrap_or(0) as f32;
55 let t = (k + 1.0) / (n + 1.0);
56 let pos = match p.side {
57 Side::Left => Vec2::new(rect.min.x, rect.min.y + rect.height() * t),
58 Side::Right => Vec2::new(rect.max.x, rect.min.y + rect.height() * t),
59 Side::Top => Vec2::new(rect.min.x + rect.width() * t, rect.min.y),
60 Side::Bottom => Vec2::new(rect.min.x + rect.width() * t, rect.max.y),
61 };
62 Some((pos, p.side))
63}
64
65pub fn edge_geometry(graph: &Graph, edge: &Edge) -> Option<EdgeGeometry> {
67 let (s, ss) = port_anchor(graph, edge.from)?;
68 let (t, ts) = port_anchor(graph, edge.to)?;
69 Some(path_between(s, ss, t, ts, edge.shape))
70}
71
72pub fn path_between(s: Vec2, ss: Side, t: Vec2, ts: Side, shape: EdgeShape) -> EdgeGeometry {
74 let (points, cubic) = match shape {
75 EdgeShape::Straight => (vec![s, t], None),
76 EdgeShape::Bezier { curvature } => {
77 let c1 = control_with_curvature(ss, s, t, curvature);
78 let c2 = control_with_curvature(ts, t, s, curvature);
79 let pts = (0..=BEZIER_SEGMENTS)
80 .map(|i| cubic_point(s, c1, c2, t, i as f32 / BEZIER_SEGMENTS as f32))
81 .collect();
82 (pts, Some([s, c1, c2, t]))
83 }
84 EdgeShape::SmoothStep { radius, offset } => (
85 round_corners(&step_points(s, ss, t, ts, offset), radius),
86 None,
87 ),
88 EdgeShape::Step { offset } => (step_points(s, ss, t, ts, offset), None),
89 };
90 finish(points, cubic)
91}
92
93pub fn infer_target_side(source: Vec2, source_side: Side, cursor: Vec2) -> Side {
95 match source_side {
96 Side::Left | Side::Right => {
97 if cursor.x >= source.x {
98 Side::Left
99 } else {
100 Side::Right
101 }
102 }
103 Side::Top | Side::Bottom => {
104 if cursor.y >= source.y {
105 Side::Top
106 } else {
107 Side::Bottom
108 }
109 }
110 }
111}
112
113fn finish(mut points: Vec<Vec2>, cubic: Option<[Vec2; 4]>) -> EdgeGeometry {
114 points.dedup_by(|a, b| a.distance(*b) < 1e-3);
115 if points.len() == 1 {
116 points.push(points[0]);
117 }
118 let bounds = Rect::from_points(&points).expect("non-empty");
119 let label = match cubic {
120 Some([a, b, c, d]) => cubic_point(a, b, c, d, 0.5),
121 None => point_at_length(&points, 0.5),
122 };
123 let n = points.len();
124 let dir = points[n - 1].minus(points[n - 2]);
125 let len = dir.length();
126 let end_dir = if len > 1e-6 {
127 dir.scale(1.0 / len)
128 } else {
129 Vec2::new(1.0, 0.0)
130 };
131 EdgeGeometry {
132 points,
133 cubic,
134 label,
135 end_dir,
136 bounds,
137 }
138}
139
140fn control_offset(distance: f32, curvature: f32) -> f32 {
141 if distance >= 0.0 {
142 0.5 * distance
143 } else {
144 curvature * 25.0 * (-distance).sqrt()
145 }
146}
147
148fn control_with_curvature(side: Side, a: Vec2, b: Vec2, c: f32) -> Vec2 {
149 match side {
150 Side::Left => Vec2::new(a.x - control_offset(a.x - b.x, c), a.y),
151 Side::Right => Vec2::new(a.x + control_offset(b.x - a.x, c), a.y),
152 Side::Top => Vec2::new(a.x, a.y - control_offset(a.y - b.y, c)),
153 Side::Bottom => Vec2::new(a.x, a.y + control_offset(b.y - a.y, c)),
154 }
155}
156
157fn cubic_point(a: Vec2, b: Vec2, c: Vec2, d: Vec2, t: f32) -> Vec2 {
158 let u = 1.0 - t;
159 a.scale(u * u * u)
160 .plus(b.scale(3.0 * u * u * t))
161 .plus(c.scale(3.0 * u * t * t))
162 .plus(d.scale(t * t * t))
163}
164
165fn offset_point(p: Vec2, side: Side, offset: f32) -> Vec2 {
166 match side {
167 Side::Left => Vec2::new(p.x - offset, p.y),
168 Side::Right => Vec2::new(p.x + offset, p.y),
169 Side::Top => Vec2::new(p.x, p.y - offset),
170 Side::Bottom => Vec2::new(p.x, p.y + offset),
171 }
172}
173
174fn step_points(s: Vec2, ss: Side, t: Vec2, ts: Side, offset: f32) -> Vec<Vec2> {
175 let a = offset_point(s, ss, offset);
176 let b = offset_point(t, ts, offset);
177 let mut pts = vec![s, a];
178 match (ss.is_horizontal(), ts.is_horizontal()) {
179 (true, true) => {
180 let mx = (a.x + b.x) / 2.0;
181 pts.extend([Vec2::new(mx, a.y), Vec2::new(mx, b.y)]);
182 }
183 (false, false) => {
184 let my = (a.y + b.y) / 2.0;
185 pts.extend([Vec2::new(a.x, my), Vec2::new(b.x, my)]);
186 }
187 (true, false) => pts.push(Vec2::new(b.x, a.y)),
188 (false, true) => pts.push(Vec2::new(a.x, b.y)),
189 }
190 pts.extend([b, t]);
191 pts.dedup_by(|p, q| p.distance(*q) < 1e-3);
192 let mut out: Vec<Vec2> = Vec::with_capacity(pts.len());
194 for p in pts {
195 if out.len() >= 2 {
196 let a = out[out.len() - 2];
197 let b = out[out.len() - 1];
198 let cross = (b.x - a.x) * (p.y - b.y) - (b.y - a.y) * (p.x - b.x);
199 if cross.abs() < 1e-3 {
200 out.pop();
201 }
202 }
203 out.push(p);
204 }
205 out
206}
207
208fn round_corners(pts: &[Vec2], radius: f32) -> Vec<Vec2> {
210 if radius <= 0.0 || pts.len() < 3 {
211 return pts.to_vec();
212 }
213 let mut out = vec![pts[0]];
214 for i in 1..pts.len() - 1 {
215 let (prev, cur, next) = (pts[i - 1], pts[i], pts[i + 1]);
216 let r = radius
217 .min(prev.distance(cur) / 2.0)
218 .min(cur.distance(next) / 2.0);
219 if r < 0.5 {
220 out.push(cur);
221 continue;
222 }
223 let a = cur.plus(prev.minus(cur).scale(r / prev.distance(cur)));
224 let b = cur.plus(next.minus(cur).scale(r / cur.distance(next)));
225 for k in 0..=CORNER_SEGMENTS {
226 let t = k as f32 / CORNER_SEGMENTS as f32;
227 let u = 1.0 - t;
228 out.push(
229 a.scale(u * u)
230 .plus(cur.scale(2.0 * u * t))
231 .plus(b.scale(t * t)),
232 );
233 }
234 }
235 out.push(pts[pts.len() - 1]);
236 out
237}
238
239pub fn point_at_length(points: &[Vec2], fraction: f32) -> Vec2 {
241 let total: f32 = points.windows(2).map(|w| w[0].distance(w[1])).sum();
242 let mut remain = total * fraction.clamp(0.0, 1.0);
243 for w in points.windows(2) {
244 let d = w[0].distance(w[1]);
245 if remain <= d && d > 0.0 {
246 return w[0].lerp(w[1], remain / d);
247 }
248 remain -= d;
249 }
250 *points.last().unwrap_or(&Vec2::ZERO)
251}
252
253#[cfg(test)]
254mod tests {
255 use super::*;
256 use crate::geometry::Size2;
257
258 #[test]
259 fn anchors_spread_on_side() {
260 let mut g = Graph::new();
261 let (_, ins, outs) =
262 g.add_node_with("a", Vec2::new(0.0, 0.0), Size2::new(100.0, 90.0), 2, 1);
263 assert_eq!(port_anchor(&g, ins[0]).unwrap().0, Vec2::new(0.0, 30.0));
264 assert_eq!(port_anchor(&g, ins[1]).unwrap().0, Vec2::new(0.0, 60.0));
265 assert_eq!(
266 port_anchor(&g, outs[0]).unwrap(),
267 (Vec2::new(100.0, 45.0), Side::Right)
268 );
269 }
270
271 #[test]
272 fn bezier_matches_xyflow_controls() {
273 let geo = path_between(
274 Vec2::new(0.0, 0.0),
275 Side::Right,
276 Vec2::new(200.0, 100.0),
277 Side::Left,
278 EdgeShape::Bezier { curvature: 0.25 },
279 );
280 let [_, c1, c2, _] = geo.cubic.unwrap();
281 assert_eq!(c1, Vec2::new(100.0, 0.0));
282 assert_eq!(c2, Vec2::new(100.0, 100.0));
283 assert!(geo.label.distance(Vec2::new(100.0, 50.0)) < 1e-3);
284 assert_eq!(geo.points.first(), Some(&Vec2::new(0.0, 0.0)));
285 assert_eq!(geo.points.last(), Some(&Vec2::new(200.0, 100.0)));
286 }
287
288 #[test]
289 fn backward_bezier_uses_curvature() {
290 let geo = path_between(
291 Vec2::new(100.0, 0.0),
292 Side::Right,
293 Vec2::new(0.0, 0.0),
294 Side::Left,
295 EdgeShape::Bezier { curvature: 0.25 },
296 );
297 let [_, c1, _, _] = geo.cubic.unwrap();
298 assert!((c1.x - (100.0 + 0.25 * 25.0 * 10.0)).abs() < 1e-3);
299 }
300
301 #[test]
302 fn step_is_orthogonal_and_smooth_step_is_rounded() {
303 let s = Vec2::new(0.0, 0.0);
304 let t = Vec2::new(200.0, 100.0);
305 let step = path_between(
306 s,
307 Side::Right,
308 t,
309 Side::Left,
310 EdgeShape::Step { offset: 20.0 },
311 );
312 assert_eq!(
313 step.points,
314 vec![s, Vec2::new(100.0, 0.0), Vec2::new(100.0, 100.0), t]
315 );
316 for w in step.points.windows(2) {
317 assert!(w[0].x == w[1].x || w[0].y == w[1].y);
318 }
319 let smooth = path_between(
320 s,
321 Side::Right,
322 t,
323 Side::Left,
324 EdgeShape::SmoothStep {
325 radius: 8.0,
326 offset: 20.0,
327 },
328 );
329 assert!(smooth.points.len() > step.points.len());
330 assert!(smooth.length() < step.length(), "圆角比直角短");
331 assert!(smooth.distance_to(Vec2::new(100.0, 50.0)) < 1e-3);
332 assert_eq!(smooth.end_dir, Vec2::new(1.0, 0.0));
333 }
334
335 #[test]
336 fn label_at_half_length() {
337 let pts = [Vec2::ZERO, Vec2::new(10.0, 0.0), Vec2::new(10.0, 30.0)];
338 assert_eq!(point_at_length(&pts, 0.5), Vec2::new(10.0, 10.0));
339 }
340}