arc-flow-core 0.4.0

Framework-free graph model for arc-flow: nodes, typed ports, edges, reversible ops, history, validation, edge geometry and spatial index.
Documentation
//! 边几何:端口锚点、四种边形的折线 / 贝塞尔控制点、标签位置、包围盒与命中距离。
//!
//! Bezier 控制点与 SmoothStep 正交路由移植自 gpui-flow `src/edges/*.rs`
//! (MIT) © 2026 Adib,其本身移植自 xyflow `getBezierPath` / `getSmoothStepPath` (MIT)。
//! 圆角、按弧长取标签位置与采样折线为本地设计。

use crate::edge::{Edge, EdgeShape};
use crate::geometry::{Rect, Vec2, distance_to_segment};
use crate::graph::Graph;
use crate::ids::PortId;
use crate::port::Side;

/// 贝塞尔采样段数;命中容差 8 px 下误差远小于 1 px。
const BEZIER_SEGMENTS: usize = 24;
/// 每个圆角的采样段数。
const CORNER_SEGMENTS: usize = 6;

#[derive(Clone, Debug, PartialEq)]
pub struct EdgeGeometry {
    /// 世界坐标折线,首点为源锚点、末点为目标锚点(命中、虚线、绘入截断都基于它)。
    pub points: Vec<Vec2>,
    /// 贝塞尔边的 [起点, 控制点 1, 控制点 2, 终点],视图层可直接用 `cubic_bezier_to` 绘制。
    pub cubic: Option<[Vec2; 4]>,
    /// 标签中心(按弧长取中点)。
    pub label: Vec2,
    /// 终点切线方向(单位向量,画箭头用)。
    pub end_dir: Vec2,
    pub bounds: Rect,
}

impl EdgeGeometry {
    pub fn length(&self) -> f32 {
        self.points.windows(2).map(|w| w[0].distance(w[1])).sum()
    }

    pub fn distance_to(&self, p: Vec2) -> f32 {
        self.points
            .windows(2)
            .map(|w| distance_to_segment(p, w[0], w[1]))
            .fold(f32::INFINITY, f32::min)
    }
}

/// 端口锚点(世界坐标)与所在边。同一边上的多个端口均匀分布。
pub fn port_anchor(graph: &Graph, port: PortId) -> Option<(Vec2, Side)> {
    let p = graph.port(port)?;
    let rect = graph.world_rect(p.node)?;
    let siblings: Vec<PortId> = graph
        .ports_of(p.node)
        .filter(|q| q.side == p.side)
        .map(|q| q.id)
        .collect();
    let n = siblings.len().max(1) as f32;
    let k = siblings.iter().position(|q| *q == port).unwrap_or(0) as f32;
    let t = (k + 1.0) / (n + 1.0);
    let pos = match p.side {
        Side::Left => Vec2::new(rect.min.x, rect.min.y + rect.height() * t),
        Side::Right => Vec2::new(rect.max.x, rect.min.y + rect.height() * t),
        Side::Top => Vec2::new(rect.min.x + rect.width() * t, rect.min.y),
        Side::Bottom => Vec2::new(rect.min.x + rect.width() * t, rect.max.y),
    };
    Some((pos, p.side))
}

/// 计算一条边的几何。
pub fn edge_geometry(graph: &Graph, edge: &Edge) -> Option<EdgeGeometry> {
    let (s, ss) = port_anchor(graph, edge.from)?;
    let (t, ts) = port_anchor(graph, edge.to)?;
    Some(path_between(s, ss, t, ts, edge.shape))
}

/// 由两端锚点计算几何(连线草稿也用它,目标边取自鼠标相对位置)。
pub fn path_between(s: Vec2, ss: Side, t: Vec2, ts: Side, shape: EdgeShape) -> EdgeGeometry {
    let (points, cubic) = match shape {
        EdgeShape::Straight => (vec![s, t], None),
        EdgeShape::Bezier { curvature } => {
            let c1 = control_with_curvature(ss, s, t, curvature);
            let c2 = control_with_curvature(ts, t, s, curvature);
            let pts = (0..=BEZIER_SEGMENTS)
                .map(|i| cubic_point(s, c1, c2, t, i as f32 / BEZIER_SEGMENTS as f32))
                .collect();
            (pts, Some([s, c1, c2, t]))
        }
        EdgeShape::SmoothStep { radius, offset } => (
            round_corners(&step_points(s, ss, t, ts, offset), radius),
            None,
        ),
        EdgeShape::Step { offset } => (step_points(s, ss, t, ts, offset), None),
    };
    finish(points, cubic)
}

/// 目标端未定时(连线草稿),根据相对位置推断目标所在边。
pub fn infer_target_side(source: Vec2, source_side: Side, cursor: Vec2) -> Side {
    match source_side {
        Side::Left | Side::Right => {
            if cursor.x >= source.x {
                Side::Left
            } else {
                Side::Right
            }
        }
        Side::Top | Side::Bottom => {
            if cursor.y >= source.y {
                Side::Top
            } else {
                Side::Bottom
            }
        }
    }
}

fn finish(mut points: Vec<Vec2>, cubic: Option<[Vec2; 4]>) -> EdgeGeometry {
    points.dedup_by(|a, b| a.distance(*b) < 1e-3);
    if points.len() == 1 {
        points.push(points[0]);
    }
    let bounds = Rect::from_points(&points).expect("non-empty");
    let label = match cubic {
        Some([a, b, c, d]) => cubic_point(a, b, c, d, 0.5),
        None => point_at_length(&points, 0.5),
    };
    let n = points.len();
    let dir = points[n - 1].minus(points[n - 2]);
    let len = dir.length();
    let end_dir = if len > 1e-6 {
        dir.scale(1.0 / len)
    } else {
        Vec2::new(1.0, 0.0)
    };
    EdgeGeometry {
        points,
        cubic,
        label,
        end_dir,
        bounds,
    }
}

fn control_offset(distance: f32, curvature: f32) -> f32 {
    if distance >= 0.0 {
        0.5 * distance
    } else {
        curvature * 25.0 * (-distance).sqrt()
    }
}

fn control_with_curvature(side: Side, a: Vec2, b: Vec2, c: f32) -> Vec2 {
    match side {
        Side::Left => Vec2::new(a.x - control_offset(a.x - b.x, c), a.y),
        Side::Right => Vec2::new(a.x + control_offset(b.x - a.x, c), a.y),
        Side::Top => Vec2::new(a.x, a.y - control_offset(a.y - b.y, c)),
        Side::Bottom => Vec2::new(a.x, a.y + control_offset(b.y - a.y, c)),
    }
}

fn cubic_point(a: Vec2, b: Vec2, c: Vec2, d: Vec2, t: f32) -> Vec2 {
    let u = 1.0 - t;
    a.scale(u * u * u)
        .plus(b.scale(3.0 * u * u * t))
        .plus(c.scale(3.0 * u * t * t))
        .plus(d.scale(t * t * t))
}

fn offset_point(p: Vec2, side: Side, offset: f32) -> Vec2 {
    match side {
        Side::Left => Vec2::new(p.x - offset, p.y),
        Side::Right => Vec2::new(p.x + offset, p.y),
        Side::Top => Vec2::new(p.x, p.y - offset),
        Side::Bottom => Vec2::new(p.x, p.y + offset),
    }
}

fn step_points(s: Vec2, ss: Side, t: Vec2, ts: Side, offset: f32) -> Vec<Vec2> {
    let a = offset_point(s, ss, offset);
    let b = offset_point(t, ts, offset);
    let mut pts = vec![s, a];
    match (ss.is_horizontal(), ts.is_horizontal()) {
        (true, true) => {
            let mx = (a.x + b.x) / 2.0;
            pts.extend([Vec2::new(mx, a.y), Vec2::new(mx, b.y)]);
        }
        (false, false) => {
            let my = (a.y + b.y) / 2.0;
            pts.extend([Vec2::new(a.x, my), Vec2::new(b.x, my)]);
        }
        (true, false) => pts.push(Vec2::new(b.x, a.y)),
        (false, true) => pts.push(Vec2::new(a.x, b.y)),
    }
    pts.extend([b, t]);
    pts.dedup_by(|p, q| p.distance(*q) < 1e-3);
    // 去掉共线的中间点,保证圆角只出现在真正的拐角。
    let mut out: Vec<Vec2> = Vec::with_capacity(pts.len());
    for p in pts {
        if out.len() >= 2 {
            let a = out[out.len() - 2];
            let b = out[out.len() - 1];
            let cross = (b.x - a.x) * (p.y - b.y) - (b.y - a.y) * (p.x - b.x);
            if cross.abs() < 1e-3 {
                out.pop();
            }
        }
        out.push(p);
    }
    out
}

/// 用二次贝塞尔把每个拐角替换为半径不超过两侧半段长度的圆角。
fn round_corners(pts: &[Vec2], radius: f32) -> Vec<Vec2> {
    if radius <= 0.0 || pts.len() < 3 {
        return pts.to_vec();
    }
    let mut out = vec![pts[0]];
    for i in 1..pts.len() - 1 {
        let (prev, cur, next) = (pts[i - 1], pts[i], pts[i + 1]);
        let r = radius
            .min(prev.distance(cur) / 2.0)
            .min(cur.distance(next) / 2.0);
        if r < 0.5 {
            out.push(cur);
            continue;
        }
        let a = cur.plus(prev.minus(cur).scale(r / prev.distance(cur)));
        let b = cur.plus(next.minus(cur).scale(r / cur.distance(next)));
        for k in 0..=CORNER_SEGMENTS {
            let t = k as f32 / CORNER_SEGMENTS as f32;
            let u = 1.0 - t;
            out.push(
                a.scale(u * u)
                    .plus(cur.scale(2.0 * u * t))
                    .plus(b.scale(t * t)),
            );
        }
    }
    out.push(pts[pts.len() - 1]);
    out
}

/// 折线上按弧长比例取点(0..=1)。
pub fn point_at_length(points: &[Vec2], fraction: f32) -> Vec2 {
    let total: f32 = points.windows(2).map(|w| w[0].distance(w[1])).sum();
    let mut remain = total * fraction.clamp(0.0, 1.0);
    for w in points.windows(2) {
        let d = w[0].distance(w[1]);
        if remain <= d && d > 0.0 {
            return w[0].lerp(w[1], remain / d);
        }
        remain -= d;
    }
    *points.last().unwrap_or(&Vec2::ZERO)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::geometry::Size2;

    #[test]
    fn anchors_spread_on_side() {
        let mut g = Graph::new();
        let (_, ins, outs) =
            g.add_node_with("a", Vec2::new(0.0, 0.0), Size2::new(100.0, 90.0), 2, 1);
        assert_eq!(port_anchor(&g, ins[0]).unwrap().0, Vec2::new(0.0, 30.0));
        assert_eq!(port_anchor(&g, ins[1]).unwrap().0, Vec2::new(0.0, 60.0));
        assert_eq!(
            port_anchor(&g, outs[0]).unwrap(),
            (Vec2::new(100.0, 45.0), Side::Right)
        );
    }

    #[test]
    fn bezier_matches_xyflow_controls() {
        let geo = path_between(
            Vec2::new(0.0, 0.0),
            Side::Right,
            Vec2::new(200.0, 100.0),
            Side::Left,
            EdgeShape::Bezier { curvature: 0.25 },
        );
        let [_, c1, c2, _] = geo.cubic.unwrap();
        assert_eq!(c1, Vec2::new(100.0, 0.0));
        assert_eq!(c2, Vec2::new(100.0, 100.0));
        assert!(geo.label.distance(Vec2::new(100.0, 50.0)) < 1e-3);
        assert_eq!(geo.points.first(), Some(&Vec2::new(0.0, 0.0)));
        assert_eq!(geo.points.last(), Some(&Vec2::new(200.0, 100.0)));
    }

    #[test]
    fn backward_bezier_uses_curvature() {
        let geo = path_between(
            Vec2::new(100.0, 0.0),
            Side::Right,
            Vec2::new(0.0, 0.0),
            Side::Left,
            EdgeShape::Bezier { curvature: 0.25 },
        );
        let [_, c1, _, _] = geo.cubic.unwrap();
        assert!((c1.x - (100.0 + 0.25 * 25.0 * 10.0)).abs() < 1e-3);
    }

    #[test]
    fn step_is_orthogonal_and_smooth_step_is_rounded() {
        let s = Vec2::new(0.0, 0.0);
        let t = Vec2::new(200.0, 100.0);
        let step = path_between(
            s,
            Side::Right,
            t,
            Side::Left,
            EdgeShape::Step { offset: 20.0 },
        );
        assert_eq!(
            step.points,
            vec![s, Vec2::new(100.0, 0.0), Vec2::new(100.0, 100.0), t]
        );
        for w in step.points.windows(2) {
            assert!(w[0].x == w[1].x || w[0].y == w[1].y);
        }
        let smooth = path_between(
            s,
            Side::Right,
            t,
            Side::Left,
            EdgeShape::SmoothStep {
                radius: 8.0,
                offset: 20.0,
            },
        );
        assert!(smooth.points.len() > step.points.len());
        assert!(smooth.length() < step.length(), "圆角比直角短");
        assert!(smooth.distance_to(Vec2::new(100.0, 50.0)) < 1e-3);
        assert_eq!(smooth.end_dir, Vec2::new(1.0, 0.0));
    }

    #[test]
    fn label_at_half_length() {
        let pts = [Vec2::ZERO, Vec2::new(10.0, 0.0), Vec2::new(10.0, 30.0)];
        assert_eq!(point_at_length(&pts, 0.5), Vec2::new(10.0, 10.0));
    }
}