Skip to main content

arc_flow/
motion.rs

1//! F6 Arc 动效(方案 `docs/flow/arc-flow-plan.md` 第 7 节)。本地设计。
2//!
3//! 画布直接用 canvas 绘制边与端口,没法挂 GPUI 的 `with_transition`,所以这里把每个场景
4//! 做成以时间为输入的纯状态机:画布每帧用 `motion_now` 取样,有动画在跑就请求下一帧。
5//! 时长、缓动、弹簧全部取自 `arc-tokens`,求解器来自 `arc-motion`。
6//!
7//! | 场景 | 实现 |
8//! |---|---|
9//! | 拖拽松手落位 | 拖拽中节点跟手(偏移 = 指针位置 − 吸附位置,不做动画),松手后偏移以 `spring.responsive` 归零 |
10//! | 新增 / 删除节点 | 缩放 0.96→1 + 透明度,`ease.enter` / `duration.standard`;删除留残影,`ease.exit` / `duration.exit` |
11//! | 新建连线 | 按弧长绘入 0→1,`ease.standard` / `duration.standard` |
12//! | 连线吸附 | 目标端口以 `spring.snappy` 放大,并有一圈光晕在 `duration.considered` 内淡出 |
13//! | 非法连接 | 目标端口水平抖动,`duration.fast` 关键帧 |
14//! | 运行中边 | 虚线沿边流动(自行切段,见 `core::dash_polyline`) |
15//! | 执行高亮 | Running 节点边框呼吸(`NodeRenderCtx::pulse`) |
16//! | 适配视图 / 键盘与按钮缩放 | 视口以 `spring.smooth` 过渡:中心线性插值、缩放按对数插值 |
17//!
18//! reduced motion:位移、视口、绘入、抖动、放大全部瞬时;进出场只保留 `duration.instant` 的透明度;
19//! 虚线不流动,边框不呼吸。
20
21use std::collections::HashMap;
22use std::f64::consts::TAU;
23
24use arc_flow_core::{EdgeId, Node, NodeId, PortId, Rect, Vec2, Viewport};
25use arc_motion::{CubicBezier, SpringSolver};
26use arc_tokens::{ArcMotionTokens, SpringSpec};
27
28use crate::metrics::*;
29
30const T: ArcMotionTokens = ArcMotionTokens::DEFAULT;
31
32/// 节点进场起始缩放、退场结束缩放。
33pub const NODE_ENTER_SCALE: f32 = 0.96;
34
35#[derive(Clone, Copy, Debug)]
36struct Tween {
37    start: f64,
38    dur: f64,
39    ease: CubicBezier,
40}
41
42impl Tween {
43    fn new(start: f64, dur: std::time::Duration, ease: arc_tokens::CubicBezierSpec) -> Self {
44        Self {
45            start,
46            dur: dur.as_secs_f64(),
47            ease: ease.into(),
48        }
49    }
50
51    fn linear_t(&self, now: f64) -> f32 {
52        if self.dur <= 0.0 {
53            return 1.0;
54        }
55        ((now - self.start) / self.dur).clamp(0.0, 1.0) as f32
56    }
57
58    fn progress(&self, now: f64) -> f32 {
59        self.ease.sample(self.linear_t(now))
60    }
61
62    fn done(&self, now: f64) -> bool {
63        now - self.start >= self.dur
64    }
65}
66
67#[derive(Clone, Copy, Debug)]
68struct Spring {
69    solver: SpringSolver,
70    start: f64,
71}
72
73impl Spring {
74    fn new(spec: SpringSpec, from: f32, to: f32, now: f64) -> Self {
75        Self {
76            solver: SpringSolver::new(spec, f64::from(from), f64::from(to), 0.0),
77            start: now,
78        }
79    }
80
81    fn sample(&self, now: f64) -> (f32, bool) {
82        let s = self.solver.sample(now - self.start);
83        (s.value, s.settled)
84    }
85}
86
87#[derive(Clone, Copy, Debug)]
88struct Spring2 {
89    x: Spring,
90    y: Spring,
91}
92
93impl Spring2 {
94    fn sample(&self, now: f64) -> (Vec2, bool) {
95        let (x, sx) = self.x.sample(now);
96        let (y, sy) = self.y.sample(now);
97        (Vec2::new(x, y), sx && sy)
98    }
99}
100
101#[derive(Clone, Copy, Debug)]
102struct ViewAnim {
103    from_center: Vec2,
104    from_zoom: f32,
105    to_center: Vec2,
106    to_zoom: f32,
107    spring: Spring,
108}
109
110/// 删除后仍在淡出的节点。
111#[derive(Clone, Debug)]
112pub struct Ghost {
113    pub node: Node,
114    /// 删除时的世界矩形。
115    pub rect: Rect,
116    tween: Tween,
117}
118
119/// 进出场的取样:缩放与不透明度。
120#[derive(Clone, Copy, Debug, PartialEq)]
121pub struct Appear {
122    pub scale: f32,
123    pub opacity: f32,
124}
125
126impl Appear {
127    pub const FULL: Self = Self {
128        scale: 1.0,
129        opacity: 1.0,
130    };
131}
132
133#[derive(Debug, Default)]
134pub struct FlowMotion {
135    reduced: bool,
136    live: HashMap<NodeId, Vec2>,
137    settle: HashMap<NodeId, Spring2>,
138    enter: HashMap<NodeId, Tween>,
139    ghosts: Vec<Ghost>,
140    draw_in: HashMap<EdgeId, Tween>,
141    shake: Option<(PortId, Tween)>,
142    target: Option<(PortId, Spring, Tween)>,
143    view: Option<ViewAnim>,
144}
145
146impl FlowMotion {
147    pub fn set_reduced(&mut self, reduced: bool) {
148        self.reduced = reduced;
149    }
150
151    pub fn reduced(&self) -> bool {
152        self.reduced
153    }
154
155    // ---------- 拖拽落位 ----------
156
157    /// 拖拽中:节点显示位置相对模型位置的偏移(跟手,无动画)。
158    pub fn set_live_offset(&mut self, id: NodeId, offset: Vec2) {
159        if offset == Vec2::ZERO {
160            self.live.remove(&id);
161        } else {
162            self.live.insert(id, offset);
163            self.settle.remove(&id);
164        }
165    }
166
167    /// 松手:把拖拽中的偏移交给弹簧归零。
168    pub fn release(&mut self, now: f64) {
169        let live = std::mem::take(&mut self.live);
170        if self.reduced {
171            return;
172        }
173        let spec = T.spring.responsive;
174        for (id, off) in live {
175            self.settle.insert(
176                id,
177                Spring2 {
178                    x: Spring::new(spec, off.x, 0.0, now),
179                    y: Spring::new(spec, off.y, 0.0, now),
180                },
181            );
182        }
183    }
184
185    /// 取消拖拽:偏移立即清零。
186    pub fn cancel_live(&mut self) {
187        self.live.clear();
188    }
189
190    /// 节点自身(不含祖先)的显示偏移。
191    pub fn own_offset(&self, id: NodeId, now: f64) -> Vec2 {
192        if let Some(v) = self.live.get(&id) {
193            return *v;
194        }
195        self.settle.get(&id).map_or(Vec2::ZERO, |s| s.sample(now).0)
196    }
197
198    pub fn has_offsets(&self) -> bool {
199        !self.live.is_empty() || !self.settle.is_empty()
200    }
201
202    // ---------- 进出场 ----------
203
204    pub fn node_entered(&mut self, id: NodeId, now: f64) {
205        let tw = if self.reduced {
206            Tween::new(now, T.duration.instant, T.ease.standard)
207        } else {
208            Tween::new(now, T.duration.standard, T.ease.enter)
209        };
210        self.enter.insert(id, tw);
211    }
212
213    pub fn enter_sample(&self, id: NodeId, now: f64) -> Appear {
214        let Some(tw) = self.enter.get(&id) else {
215            return Appear::FULL;
216        };
217        let p = tw.progress(now);
218        Appear {
219            scale: if self.reduced {
220                1.0
221            } else {
222                NODE_ENTER_SCALE + (1.0 - NODE_ENTER_SCALE) * p
223            },
224            opacity: p,
225        }
226    }
227
228    pub fn node_removed(&mut self, node: Node, rect: Rect, now: f64) {
229        self.enter.remove(&node.id);
230        self.settle.remove(&node.id);
231        let tween = if self.reduced {
232            Tween::new(now, T.duration.instant, T.ease.standard)
233        } else {
234            Tween::new(now, T.duration.exit, T.ease.exit)
235        };
236        self.ghosts.push(Ghost { node, rect, tween });
237    }
238
239    /// 正在淡出的节点及其取样。
240    pub fn ghosts(&self, now: f64) -> impl Iterator<Item = (&Ghost, Appear)> {
241        let reduced = self.reduced;
242        self.ghosts.iter().map(move |g| {
243            let p = g.tween.progress(now);
244            let a = Appear {
245                scale: if reduced {
246                    1.0
247                } else {
248                    1.0 - (1.0 - NODE_ENTER_SCALE) * p
249                },
250                opacity: 1.0 - p,
251            };
252            (g, a)
253        })
254    }
255
256    /// 撤销删除时,节点回来就不再画它的残影。
257    pub fn drop_ghost(&mut self, id: NodeId) {
258        self.ghosts.retain(|g| g.node.id != id);
259    }
260
261    // ---------- 连线 ----------
262
263    pub fn edge_added(&mut self, id: EdgeId, now: f64) {
264        if !self.reduced {
265            self.draw_in
266                .insert(id, Tween::new(now, T.duration.standard, T.ease.standard));
267        }
268    }
269
270    /// 绘入比例 0..=1。
271    pub fn draw_progress(&self, id: EdgeId, now: f64) -> f32 {
272        self.draw_in.get(&id).map_or(1.0, |tw| tw.progress(now))
273    }
274
275    pub fn reject(&mut self, port: PortId, now: f64) {
276        if !self.reduced {
277            self.shake = Some((port, Tween::new(now, T.duration.fast, T.ease.standard)));
278        }
279    }
280
281    /// 非法目标端口的水平抖动(屏幕 px):0 → −A → A → −A/2 → A/2 → 0 的线性关键帧。
282    pub fn shake(&self, now: f64) -> Option<(PortId, f32)> {
283        const KEYS: [f32; 6] = [0.0, -1.0, 1.0, -0.5, 0.5, 0.0];
284        let (port, tw) = self.shake?;
285        if tw.done(now) {
286            return None;
287        }
288        let t = tw.linear_t(now) * (KEYS.len() - 1) as f32;
289        let i = (t.floor() as usize).min(KEYS.len() - 2);
290        let f = t - i as f32;
291        let k = KEYS[i] + (KEYS[i + 1] - KEYS[i]) * f;
292        Some((port, k * SHAKE_AMPLITUDE))
293    }
294
295    /// 连线草稿吸附到了新的目标端口。
296    pub fn target_changed(&mut self, port: Option<PortId>, now: f64) {
297        if port == self.target.as_ref().map(|t| t.0) {
298            return;
299        }
300        self.target = port.map(|p| {
301            (
302                p,
303                Spring::new(T.spring.snappy, 1.0, PORT_TARGET_SCALE, now),
304                Tween::new(now, T.duration.considered, T.ease.standard),
305            )
306        });
307    }
308
309    /// 目标端口的放大倍数与光晕进度(0 → 1 淡出)。
310    pub fn target_sample(&self, port: PortId, now: f64) -> (f32, Option<f32>) {
311        match &self.target {
312            Some((p, spring, glow)) if *p == port && !self.reduced => {
313                let g = (!glow.done(now)).then(|| glow.progress(now));
314                (spring.sample(now).0, g)
315            }
316            _ => (PORT_TARGET_SCALE, None),
317        }
318    }
319
320    // ---------- 视口 ----------
321
322    /// 从 `from` 平滑过渡到 `to`;`center` 为视图中心(屏幕坐标)。返回 false 表示应立即跳转。
323    pub fn animate_view(&mut self, from: &Viewport, to: &Viewport, center: Vec2, now: f64) -> bool {
324        if self.reduced {
325            self.view = None;
326            return false;
327        }
328        self.view = Some(ViewAnim {
329            from_center: from.screen_to_world(center),
330            from_zoom: from.zoom,
331            to_center: to.screen_to_world(center),
332            to_zoom: to.zoom,
333            spring: Spring::new(T.spring.smooth, 0.0, 1.0, now),
334        });
335        true
336    }
337
338    pub fn cancel_view(&mut self) {
339        self.view = None;
340    }
341
342    pub fn view_animating(&self) -> bool {
343        self.view.is_some()
344    }
345
346    /// 视口取样,结束时返回 `(终点, true)`。
347    pub fn view_sample(&self, base: &Viewport, center: Vec2, now: f64) -> Option<(Viewport, bool)> {
348        let a = self.view?;
349        let (p, settled) = a.spring.sample(now);
350        let p = if settled { 1.0 } else { p };
351        let zoom = (a.from_zoom.ln() + (a.to_zoom.ln() - a.from_zoom.ln()) * p).exp();
352        let world = a.from_center.lerp(a.to_center, p);
353        let mut vp = *base;
354        vp.zoom = zoom;
355        vp.offset = center.minus(world.scale(zoom));
356        Some((vp, settled))
357    }
358
359    // ---------- 持续动画 ----------
360
361    /// 运行中边的虚线相位(屏幕 px)。
362    pub fn dash_phase(&self, now: f64) -> f32 {
363        if self.reduced {
364            0.0
365        } else {
366            let period = f64::from(ACTIVE_DASH[0] + ACTIVE_DASH[1]);
367            (now * f64::from(DASH_FLOW_SPEED)).rem_euclid(period) as f32
368        }
369    }
370
371    /// Running 节点的边框呼吸 0..=1;reduced motion 下恒为 1(不呼吸)。
372    pub fn pulse(&self, now: f64) -> f32 {
373        if self.reduced {
374            1.0
375        } else {
376            (0.5 - 0.5 * (now * TAU / f64::from(RUNNING_PULSE_PERIOD)).cos()) as f32
377        }
378    }
379
380    // ---------- 帧 ----------
381
382    /// 清理已结束的动画;返回是否仍有一次性动画在跑(需要下一帧)。
383    pub fn tick(&mut self, now: f64) -> bool {
384        self.settle.retain(|_, s| !s.sample(now).1);
385        self.enter.retain(|_, tw| !tw.done(now));
386        self.ghosts.retain(|g| !g.tween.done(now));
387        self.draw_in.retain(|_, tw| !tw.done(now));
388        if self.shake.is_some_and(|(_, tw)| tw.done(now)) {
389            self.shake = None;
390        }
391        let target_live = self
392            .target
393            .as_ref()
394            .is_some_and(|(_, s, g)| !s.sample(now).1 || !g.done(now));
395        !self.settle.is_empty()
396            || !self.enter.is_empty()
397            || !self.ghosts.is_empty()
398            || !self.draw_in.is_empty()
399            || self.shake.is_some()
400            || self.view.is_some()
401            || (target_live && !self.reduced)
402    }
403
404    pub fn finish_view(&mut self) {
405        self.view = None;
406    }
407}
408
409#[cfg(test)]
410mod tests {
411    use super::*;
412    use arc_flow_core::Size2;
413
414    const N: NodeId = NodeId(1);
415
416    #[test]
417    fn release_springs_offset_back_to_zero() {
418        let mut m = FlowMotion::default();
419        m.set_live_offset(N, Vec2::new(4.0, -3.0));
420        assert_eq!(m.own_offset(N, 0.0), Vec2::new(4.0, -3.0));
421        m.release(10.0);
422        assert_eq!(m.own_offset(N, 10.0), Vec2::new(4.0, -3.0));
423        let mid = m.own_offset(N, 10.05);
424        assert!(mid.x.abs() < 4.0 && mid.x.abs() > 0.0, "{mid:?}");
425        assert!(m.tick(10.05));
426        assert!(!m.tick(12.0));
427        assert_eq!(m.own_offset(N, 12.0), Vec2::ZERO);
428    }
429
430    #[test]
431    fn reduced_motion_makes_moves_instant_and_keeps_fades_short() {
432        let mut m = FlowMotion::default();
433        m.set_reduced(true);
434        m.set_live_offset(N, Vec2::new(4.0, 0.0));
435        m.release(0.0);
436        assert_eq!(m.own_offset(N, 0.0), Vec2::ZERO);
437        m.node_entered(N, 0.0);
438        let a = m.enter_sample(N, 0.06);
439        assert_eq!(a.scale, 1.0);
440        assert!(a.opacity > 0.0 && a.opacity < 1.0);
441        assert_eq!(m.enter_sample(N, 0.13), Appear::FULL);
442        m.edge_added(EdgeId(1), 0.0);
443        assert_eq!(m.draw_progress(EdgeId(1), 0.0), 1.0);
444        m.reject(PortId(1), 0.0);
445        assert!(m.shake(0.05).is_none());
446        assert_eq!(m.dash_phase(3.0), 0.0);
447        assert_eq!(m.pulse(0.3), 1.0);
448        let vp = Viewport::default();
449        let mut to = vp;
450        to.zoom = 2.0;
451        assert!(!m.animate_view(&vp, &to, Vec2::new(400.0, 300.0), 0.0));
452    }
453
454    #[test]
455    fn enter_exit_draw_and_shake_follow_tokens() {
456        let mut m = FlowMotion::default();
457        m.node_entered(N, 0.0);
458        let start = m.enter_sample(N, 0.0);
459        assert_eq!(start.scale, NODE_ENTER_SCALE);
460        assert_eq!(start.opacity, 0.0);
461        assert_eq!(m.enter_sample(N, 0.24), Appear::FULL);
462
463        let node = Node::new(NodeId(2), "x", Vec2::ZERO, Size2::new(10.0, 10.0));
464        m.node_removed(node, Rect::default(), 0.0);
465        let (_, a) = m.ghosts(0.18).next().unwrap();
466        assert_eq!(a.opacity, 0.0);
467        assert!(m.tick(0.1));
468        m.tick(0.2);
469        assert_eq!(m.ghosts(0.2).count(), 0);
470
471        m.edge_added(EdgeId(3), 1.0);
472        assert_eq!(m.draw_progress(EdgeId(3), 1.0), 0.0);
473        let half = m.draw_progress(EdgeId(3), 1.12);
474        assert!(half > 0.5 && half < 1.0, "standard 缓动前快后慢:{half}");
475        assert_eq!(m.draw_progress(EdgeId(3), 1.24), 1.0);
476
477        m.reject(PortId(9), 2.0);
478        let (p, dx) = m.shake(2.0 + 0.16 * 0.2).unwrap();
479        assert_eq!(p, PortId(9));
480        assert!(
481            (dx + SHAKE_AMPLITUDE).abs() < 1e-3,
482            "第一帧关键帧在 −A:{dx}"
483        );
484        assert!(m.shake(2.2).is_none());
485    }
486
487    #[test]
488    fn view_transition_interpolates_centre_and_log_zoom() {
489        let mut m = FlowMotion::default();
490        let center = Vec2::new(400.0, 300.0);
491        let from = Viewport::default();
492        let mut to = from;
493        to.zoom = 4.0;
494        to.offset = center.minus(Vec2::new(1000.0, 0.0).scale(4.0));
495        assert!(m.animate_view(&from, &to, center, 0.0));
496        let (start, _) = m.view_sample(&from, center, 0.0).unwrap();
497        assert!((start.zoom - 1.0).abs() < 1e-4);
498        let (mid, done) = m.view_sample(&from, center, 0.1).unwrap();
499        assert!(!done && mid.zoom > 1.0 && mid.zoom < 4.0);
500        let (end, done) = m.view_sample(&from, center, 2.0).unwrap();
501        assert!(done);
502        assert!((end.zoom - 4.0).abs() < 1e-4);
503        assert!(end.screen_to_world(center).distance(Vec2::new(1000.0, 0.0)) < 1e-2);
504    }
505
506    #[test]
507    fn dash_phase_advances_and_wraps() {
508        let m = FlowMotion::default();
509        let period = ACTIVE_DASH[0] + ACTIVE_DASH[1];
510        let a = m.dash_phase(0.1);
511        assert!((a - DASH_FLOW_SPEED * 0.1).abs() < 1e-3);
512        let b = m.dash_phase(f64::from(period / DASH_FLOW_SPEED) + 0.1);
513        assert!((a - b).abs() < 1e-3);
514        assert!(m.pulse(0.0) < 1e-6);
515        assert!((m.pulse(f64::from(RUNNING_PULSE_PERIOD) / 2.0) - 1.0).abs() < 1e-6);
516    }
517}