Skip to main content

arc_graph/
motion.rs

1//! G4 Arc 动效(方案 §6;复用 arc-flow F6 的纯状态机套路,见 `docs/graph/knowledge-graph-plan.md`)。
2//!
3//! 画布用 canvas 批量绘制,挂不了 GPUI 的 `with_transition`,所以每个场景做成以时间为
4//! 输入的纯状态机:视图每帧用 [`arc_motion::motion_now`] 取样,有动画在跑就请求下一帧。
5//! 时长、缓动、弹簧全部取自 `arc-tokens`,求解器来自 `arc-motion`。
6//!
7//! | 场景 | 实现 |
8//! |---|---|
9//! | 搜索定位 / 双击聚焦 | 视口以 `spring.smooth` 过渡:中心线性插值、缩放按对数插值 |
10//! | 悬停高亮 | 非邻居整体淡出:全局透明度渐变(`duration.standard` / `ease.standard`) |
11//! | 双击展开 / 筛选揭示 | 新节点进场:缩放 0.96→1 + 透明度,`ease.enter` / `duration.standard` |
12//! | 类型筛选隐藏 | 节点退场:缩放 1→0.96 + 透明度,`ease.exit` / `duration.standard` |
13//!
14//! reduced motion:相机立即跳转;进退场与高亮只保留 `duration.instant` 的透明度。
15
16use std::collections::HashMap;
17
18use arc_flow_core::Viewport;
19use arc_flow_core::geometry::Vec2;
20use arc_graph_core::NodeId;
21use arc_motion::SpringSolver;
22use arc_tokens::{ArcMotionTokens, SpringSpec};
23
24const T: ArcMotionTokens = ArcMotionTokens::DEFAULT;
25
26/// 节点进场起始缩放(与 arc-flow F6 一致)。
27pub const NODE_ENTER_SCALE: f32 = 0.96;
28/// 悬停时非邻居的淡出强度(1.0 = 全隐;实际用 0.75 保留上下文)。
29pub const DIM_STRENGTH: f32 = 0.75;
30
31#[derive(Clone, Copy, Debug)]
32struct Tween {
33    start: f64,
34    dur: f64,
35    ease: arc_motion::CubicBezier,
36}
37
38impl Tween {
39    fn new(start: f64, dur: std::time::Duration, ease: arc_tokens::CubicBezierSpec) -> Self {
40        Self {
41            start,
42            dur: dur.as_secs_f64(),
43            ease: ease.into(),
44        }
45    }
46
47    fn linear_t(&self, now: f64) -> f32 {
48        if self.dur <= 0.0 {
49            return 1.0;
50        }
51        ((now - self.start) / self.dur).clamp(0.0, 1.0) as f32
52    }
53
54    fn progress(&self, now: f64) -> f32 {
55        self.ease.sample(self.linear_t(now))
56    }
57
58    fn done(&self, now: f64) -> bool {
59        now - self.start >= self.dur
60    }
61}
62
63#[derive(Clone, Copy, Debug)]
64struct Spring {
65    solver: SpringSolver,
66    start: f64,
67}
68
69impl Spring {
70    fn new(spec: SpringSpec, from: f32, to: f32, now: f64) -> Self {
71        Self {
72            solver: SpringSolver::new(spec, f64::from(from), f64::from(to), 0.0),
73            start: now,
74        }
75    }
76
77    fn sample(&self, now: f64) -> (f32, bool) {
78        let s = self.solver.sample(now - self.start);
79        (s.value, s.settled)
80    }
81}
82
83#[derive(Clone, Copy, Debug)]
84struct ViewAnim {
85    from_center: Vec2,
86    from_zoom: f32,
87    to_center: Vec2,
88    to_zoom: f32,
89    spring: Spring,
90}
91
92/// 进场取样:缩放与不透明度。
93#[derive(Clone, Copy, Debug, PartialEq)]
94pub struct Appear {
95    pub scale: f32,
96    pub opacity: f32,
97}
98
99impl Appear {
100    pub const FULL: Self = Self {
101        scale: 1.0,
102        opacity: 1.0,
103    };
104}
105
106/// 图谱画布动效状态机。所有取样都是纯函数:`now` 来自 `motion_now(cx)`。
107#[derive(Debug, Default)]
108pub struct GraphMotion {
109    reduced: bool,
110    enter: HashMap<NodeId, Tween>,
111    exit: HashMap<NodeId, Tween>,
112    view: Option<ViewAnim>,
113    /// 淡出渐变保留中断时的值,避免快速移入移出时跳变。
114    dim: Option<(Tween, f32, bool)>,
115}
116
117impl GraphMotion {
118    pub fn set_reduced(&mut self, reduced: bool) {
119        self.reduced = reduced;
120    }
121
122    pub fn reduced(&self) -> bool {
123        self.reduced
124    }
125
126    // ---------- 进场 ----------
127
128    pub fn node_entered(&mut self, id: NodeId, now: f64) {
129        let tw = if self.reduced {
130            Tween::new(now, T.duration.instant, T.ease.standard)
131        } else {
132            Tween::new(now, T.duration.standard, T.ease.enter)
133        };
134        self.exit.remove(&id);
135        self.enter.insert(id, tw);
136    }
137
138    /// 逻辑上立即隐藏;绘制层保留到退场渐变结束。
139    pub fn node_exited(&mut self, id: NodeId, now: f64) {
140        self.enter.remove(&id);
141        let dur = if self.reduced {
142            T.duration.instant
143        } else {
144            T.duration.standard
145        };
146        self.exit.insert(id, Tween::new(now, dur, T.ease.exit));
147    }
148
149    pub fn is_exiting(&self, id: NodeId, now: f64) -> bool {
150        self.exit.get(&id).is_some_and(|tw| !tw.done(now))
151    }
152
153    pub fn exit_sample(&self, id: NodeId, now: f64) -> Appear {
154        let Some(tw) = self.exit.get(&id) else {
155            return Appear::FULL;
156        };
157        let p = tw.progress(now);
158        Appear {
159            scale: if self.reduced {
160                1.0
161            } else {
162                1.0 - (1.0 - NODE_ENTER_SCALE) * p
163            },
164            opacity: 1.0 - p,
165        }
166    }
167
168    pub fn prune(&mut self, now: f64) {
169        self.enter.retain(|_, tw| !tw.done(now));
170        self.exit.retain(|_, tw| !tw.done(now));
171    }
172
173    pub fn animating(&self, now: f64) -> bool {
174        self.has_entering(now)
175            || self.exit.values().any(|tw| !tw.done(now))
176            || self.dim_animating(now)
177            || self.view_animating()
178    }
179
180    pub fn enter_sample(&self, id: NodeId, now: f64) -> Appear {
181        let Some(tw) = self.enter.get(&id) else {
182            return Appear::FULL;
183        };
184        let p = tw.progress(now);
185        Appear {
186            scale: if self.reduced {
187                1.0
188            } else {
189                NODE_ENTER_SCALE + (1.0 - NODE_ENTER_SCALE) * p
190            },
191            opacity: p,
192        }
193    }
194
195    pub fn has_entering(&self, now: f64) -> bool {
196        self.enter.values().any(|tw| !tw.done(now))
197    }
198
199    pub fn drop_enter(&mut self, id: NodeId) {
200        self.enter.remove(&id);
201    }
202
203    // ---------- 悬停淡出 ----------
204
205    /// 设置淡出目标(`true` = 有悬停,非邻居淡出)。状态不变时不动。
206    pub fn set_dim(&mut self, target: bool, now: f64) {
207        if self.dim.as_ref().is_some_and(|(_, _, t)| *t == target) {
208            return;
209        }
210        let tw = if self.reduced {
211            Tween::new(now, T.duration.instant, T.ease.standard)
212        } else {
213            Tween::new(now, T.duration.standard, T.ease.standard)
214        };
215        self.dim = Some((tw, self.dim_factor(now), target));
216    }
217
218    /// 当前淡出强度 0..=1(0 = 无淡出)。取样结束后收敛为终值。
219    pub fn dim_factor(&self, now: f64) -> f32 {
220        let Some((tw, from, target)) = self.dim else {
221            return 0.0;
222        };
223        let p = tw.progress(now);
224        from + (if target { 1.0 } else { 0.0 } - from) * p
225    }
226
227    pub fn dim_animating(&self, now: f64) -> bool {
228        self.dim.as_ref().is_some_and(|(tw, _, _)| !tw.done(now))
229    }
230
231    // ---------- 视口过渡 ----------
232
233    /// 从 `from` 平滑过渡到 `to`(中心 + 缩放);reduced motion 返回 false 表示立即跳转。
234    pub fn animate_view(&mut self, from: &Viewport, to: &Viewport, center: Vec2, now: f64) -> bool {
235        if self.reduced {
236            self.view = None;
237            return false;
238        }
239        self.view = Some(ViewAnim {
240            from_center: from.screen_to_world(center),
241            from_zoom: from.zoom,
242            to_center: to.screen_to_world(center),
243            to_zoom: to.zoom,
244            spring: Spring::new(T.spring.smooth, 0.0, 1.0, now),
245        });
246        true
247    }
248
249    pub fn cancel_view(&mut self) {
250        self.view = None;
251    }
252
253    pub fn view_animating(&self) -> bool {
254        self.view.is_some()
255    }
256
257    /// 视口取样;结束时返回 `(终点视口, true)`。
258    pub fn view_sample(&self, base: &Viewport, center: Vec2, now: f64) -> Option<(Viewport, bool)> {
259        let a = self.view?;
260        let (p, settled) = a.spring.sample(now);
261        let p = if settled { 1.0 } else { p };
262        let zoom = (a.from_zoom.ln() + (a.to_zoom.ln() - a.from_zoom.ln()) * p).exp();
263        let world = a.from_center.lerp(a.to_center, p);
264        let mut vp = *base;
265        vp.zoom = zoom;
266        vp.offset = center.minus(world.scale(zoom));
267        Some((vp, settled))
268    }
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274
275    #[test]
276    fn highlight_reversal_is_continuous() {
277        let mut motion = GraphMotion::default();
278        motion.set_dim(true, 0.0);
279        let now = T.duration.standard.as_secs_f64() * 0.4;
280        let before = motion.dim_factor(now);
281        motion.set_dim(false, now);
282        assert!((before - motion.dim_factor(now)).abs() < 1e-5);
283        assert_eq!(motion.dim_factor(10.0), 0.0);
284    }
285
286    #[test]
287    fn enter_exit_finish_and_are_pruned() {
288        let mut motion = GraphMotion::default();
289        let id = NodeId(1);
290        motion.node_entered(id, 0.0);
291        assert_eq!(motion.enter_sample(id, 0.0).opacity, 0.0);
292        assert_eq!(motion.enter_sample(id, 10.0), Appear::FULL);
293        motion.node_exited(id, 10.0);
294        assert!(motion.is_exiting(id, 10.0));
295        assert_eq!(motion.exit_sample(id, 20.0).opacity, 0.0);
296        motion.prune(20.0);
297        assert!(motion.enter.is_empty() && motion.exit.is_empty());
298        assert!(!motion.animating(20.0));
299    }
300
301    #[test]
302    fn reduced_motion_never_scales_or_flies() {
303        let mut motion = GraphMotion::default();
304        motion.set_reduced(true);
305        motion.node_entered(NodeId(1), 0.0);
306        motion.node_exited(NodeId(2), 0.0);
307        assert_eq!(motion.enter_sample(NodeId(1), 0.0).scale, 1.0);
308        assert_eq!(motion.exit_sample(NodeId(2), 0.0).scale, 1.0);
309        assert!(!motion.animate_view(&Viewport::default(), &Viewport::default(), Vec2::ZERO, 0.0));
310    }
311
312    #[test]
313    fn spring_reaches_target_and_can_be_cancelled() {
314        let mut motion = GraphMotion::default();
315        let from = Viewport::default();
316        let to = Viewport {
317            zoom: 2.0,
318            offset: Vec2::new(70.0, 90.0),
319            ..from
320        };
321        assert!(motion.animate_view(&from, &to, Vec2::new(400.0, 300.0), 0.0));
322        let (end, done) = motion
323            .view_sample(&from, Vec2::new(400.0, 300.0), 20.0)
324            .unwrap();
325        assert!(done);
326        assert!((end.zoom - to.zoom).abs() < 1e-5);
327        assert!(end.offset.distance(to.offset) < 1e-3);
328        motion.cancel_view();
329        assert!(!motion.view_animating());
330    }
331}