Skip to main content

re_core/
motion.rs

1//! Procedural motion so the world does not feel frozen: water ripples,
2//! foliage swaying in the wind, floating crystals.
3//!
4//! Motion is a per-node and per-tile flag evaluated at draw time (viewer) —
5//! no keyframes, no skinning involved. The offset is computed in WORLD space
6//! from the moving vertex position, so it works for meshes, tilemap cells and
7//! skinned rigs alike. The sprite baker (`iso::bake`) bakes at rest per
8//! default; with `anim_frames` > 1 it renders one motion cycle per view
9//! using [`Motion::offset_loop`], which guarantees a seamless loop.
10
11use serde::{Deserialize, Serialize};
12
13/// Loopable wind/water oscillation attached to a node or tile.
14#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, Default)]
15pub enum Motion {
16    /// Static (the default — serialized maps stay compatible).
17    #[default]
18    None,
19    /// Water surface: vertical ripple travelling across XZ.
20    Waves { amp: f32, speed: f32 },
21    /// Foliage: horizontal sway, zero at the base, strongest at the top.
22    Sway { amp: f32, speed: f32 },
23    /// Floating object: whole mesh bobs up and down.
24    Bob { amp: f32, speed: f32 },
25}
26
27impl Motion {
28    /// True when nothing moves (used to skip serialization and per-vertex work).
29    pub fn is_none(&self) -> bool {
30        matches!(self, Motion::None)
31    }
32
33    pub fn label(&self) -> &'static str {
34        match self {
35            Motion::None => "keine",
36            Motion::Waves { .. } => "Wellen",
37            Motion::Sway { .. } => "Schwingen",
38            Motion::Bob { .. } => "Schweben",
39        }
40    }
41
42    pub fn amp(&self) -> f32 {
43        match self {
44            Motion::None => 0.0,
45            Motion::Waves { amp, .. } | Motion::Sway { amp, .. } | Motion::Bob { amp, .. } => *amp,
46        }
47    }
48
49    pub fn speed(&self) -> f32 {
50        match self {
51            Motion::None => 0.0,
52            Motion::Waves { speed, .. }
53            | Motion::Sway { speed, .. }
54            | Motion::Bob { speed, .. } => *speed,
55        }
56    }
57
58    /// World-space displacement of point `p` at time `t`. `y_floor`/`y_ceil`
59    /// bound the object so [`Motion::Sway`] can taper with height; `phase`
60    /// decorrelates neighbours (see [`cell_phase`], [`node_phase`]).
61    pub fn offset(
62        &self,
63        p: glam::Vec3,
64        y_floor: f32,
65        y_ceil: f32,
66        phase: f32,
67        t: f32,
68    ) -> glam::Vec3 {
69        use glam::Vec3;
70        match self {
71            Motion::None => Vec3::ZERO,
72            Motion::Waves { amp, speed } => {
73                let w = speed.max(0.0);
74                let ripple = (p.x * 1.6 + w * t + phase).sin()
75                    + (p.z * 1.2 - w * 0.8 * t + phase * 1.7).sin();
76                Vec3::new(0.0, amp * 0.5 * ripple, 0.0)
77            }
78            Motion::Sway { amp, speed } => {
79                let span = (y_ceil - y_floor).max(1e-4);
80                let hn = ((p.y - y_floor) / span).clamp(0.0, 1.0);
81                let a = *amp * hn * hn;
82                let w = speed.max(0.0);
83                Vec3::new(
84                    a * (w * t + phase).sin(),
85                    0.0,
86                    a * 0.6 * (w * 0.9 * t + phase * 1.3).cos(),
87                )
88            }
89            Motion::Bob { amp, speed } => {
90                Vec3::new(0.0, amp * (speed.max(0.0) * t + phase).sin(), 0.0)
91            }
92        }
93    }
94
95    /// Displacement for sprite-sequence baking: identical shape to
96    /// [`Motion::offset`], but every time term repeats exactly when `t`
97    /// advances by [`std::f32::consts::TAU`]. Baking N frames at
98    /// `t = TAU·k/N` therefore yields a seamless loop.
99    pub fn offset_loop(
100        &self,
101        p: glam::Vec3,
102        y_floor: f32,
103        y_ceil: f32,
104        phase: f32,
105        t: f32,
106    ) -> glam::Vec3 {
107        use glam::Vec3;
108        match self {
109            Motion::None => Vec3::ZERO,
110            Motion::Waves { amp, speed } => {
111                let _ = speed; // loop period is one cycle; amp scales it
112                let ripple = (p.x * 1.6 + t + phase).sin() + (p.z * 1.2 - t + phase * 1.7).sin();
113                Vec3::new(0.0, amp * 0.5 * ripple, 0.0)
114            }
115            Motion::Sway { amp, speed } => {
116                let _ = speed;
117                let span = (y_ceil - y_floor).max(1e-4);
118                let hn = ((p.y - y_floor) / span).clamp(0.0, 1.0);
119                let a = *amp * hn * hn;
120                Vec3::new(
121                    a * (t + phase).sin(),
122                    0.0,
123                    a * 0.6 * (t + phase * 1.3).cos(),
124                )
125            }
126            Motion::Bob { amp, speed } => {
127                let _ = speed;
128                Vec3::new(0.0, amp * (t + phase).sin(), 0.0)
129            }
130        }
131    }
132}
133
134/// Stable phase per tile cell so a lake does not wave in lockstep.
135pub fn cell_phase(x: i32, z: i32) -> f32 {
136    let s = (x as f32 * 12.9898 + z as f32 * 78.233).sin() * 43_758.547;
137    (s - s.floor()) * std::f32::consts::TAU
138}
139
140/// Stable phase per node id.
141pub fn node_phase(id: u32) -> f32 {
142    let s = (id as f32 * 0.618_034) % 1.0;
143    s * std::f32::consts::TAU
144}
145
146/// Does the document contain any moving object (nodes or kit tiles)? The
147/// viewer uses this to decide whether to keep repainting.
148pub fn any_motion(p: &crate::project::Project) -> bool {
149    p.scene
150        .nodes
151        .values()
152        .any(|n| !n.motion.is_none() && n.visible)
153        || p.library
154            .tilesets
155            .values()
156            .any(|ts| ts.tiles.iter().any(|t| !t.motion.is_none()))
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162    use crate::project::Project;
163    use glam::Vec3;
164
165    #[test]
166    fn waves_stay_within_amplitude_and_move() {
167        let m = Motion::Waves {
168            amp: 0.1,
169            speed: 1.5,
170        };
171        let mut saw_peak = 0.0f32;
172        let mut saw_trough = 0.0f32;
173        for k in 0..64 {
174            let t = k as f32 * 0.11;
175            let d = m.offset(Vec3::new(2.0, 0.0, -1.0), -1.0, 1.0, 0.4, t);
176            assert_eq!(d.x, 0.0);
177            assert_eq!(d.z, 0.0);
178            assert!(d.y.abs() <= 0.1 + 1e-5, "wave exceeds amp: {d:?}");
179            saw_peak = saw_peak.max(d.y);
180            saw_trough = saw_trough.min(d.y);
181        }
182        assert!(
183            saw_peak > 0.02 && saw_trough < -0.02,
184            "waves must oscillate"
185        );
186    }
187
188    #[test]
189    fn sway_tapers_with_height() {
190        let m = Motion::Sway {
191            amp: 0.2,
192            speed: 1.0,
193        };
194        let base = m.offset(
195            Vec3::new(0.0, 0.0, 0.0),
196            0.0,
197            2.0,
198            0.0,
199            std::f32::consts::FRAC_PI_4,
200        );
201        assert_eq!(base, Vec3::ZERO, "the trunk foot must not move");
202        let top = m.offset(
203            Vec3::new(0.0, 2.0, 0.0),
204            0.0,
205            2.0,
206            std::f32::consts::FRAC_PI_2,
207            0.0,
208        );
209        assert!(
210            (top.x - 0.2).abs() < 1e-5,
211            "crown sways at full amp: {top:?}"
212        );
213        assert!(top.length() <= 0.2 * 1.2 + 1e-4, "sway bounded by amp");
214    }
215
216    #[test]
217    fn bob_is_pure_vertical_sin() {
218        let m = Motion::Bob {
219            amp: 0.1,
220            speed: 2.0,
221        };
222        assert!(m.offset(Vec3::X * 7.0, 0.0, 1.0, 0.0, 0.0).length() < 1e-6);
223        let up = m.offset(Vec3::X * 7.0, 0.0, 1.0, std::f32::consts::FRAC_PI_2, 0.0);
224        assert!((up.y - 0.1).abs() < 1e-5);
225        assert_eq!(up.x, 0.0);
226    }
227
228    #[test]
229    fn none_never_moves_phases_are_stable() {
230        assert_eq!(
231            Motion::None.offset(Vec3::ONE, 0.0, 1.0, 0.0, 9.9),
232            Vec3::ZERO
233        );
234        assert_eq!(cell_phase(3, -2), cell_phase(3, -2));
235        assert_eq!(node_phase(5), node_phase(5));
236        // neighbouring cells differ
237        assert!((cell_phase(3, -2) - cell_phase(4, -2)).abs() > 1e-6);
238    }
239
240    #[test]
241    fn loop_offset_repeats_after_full_cycle() {
242        use std::f32::consts::TAU;
243        let ms = [
244            Motion::Waves {
245                amp: 0.1,
246                speed: 1.3,
247            },
248            Motion::Sway {
249                amp: 0.2,
250                speed: 0.7,
251            },
252            Motion::Bob {
253                amp: 0.05,
254                speed: 2.5,
255            },
256        ];
257        for m in ms {
258            for &(x, z) in &[(1.5, -2.0), (0.3, 0.9)] {
259                let p = Vec3::new(x, 0.7, z);
260                let a = m.offset_loop(p, 0.0, 2.0, 1.1, 0.0);
261                let b = m.offset_loop(p, 0.0, 2.0, 1.1, TAU);
262                assert!(
263                    (a - b).length() < 1e-5,
264                    "{m:?} must close its loop: {a:?} vs {b:?}"
265                );
266            }
267            // sampling k/N frames hits every extremum at least twice over
268            let mut spread = 0.0f32;
269            for k in 0..8 {
270                let d = m.offset_loop(
271                    Vec3::new(1.0, 1.5, -1.0),
272                    0.0,
273                    2.0,
274                    0.5,
275                    TAU * k as f32 / 8.0,
276                );
277                spread = spread.max(d.length());
278            }
279            assert!(spread > 1e-4, "{m:?} loop must actually move");
280        }
281    }
282
283    #[test]
284    fn any_motion_scans_nodes_and_kits() {
285        let mut p = Project::new("welt");
286        assert!(!any_motion(&p));
287        let id = p.scene.alloc_node_id();
288        let n = crate::scene::Node {
289            motion: Motion::Bob {
290                amp: 0.1,
291                speed: 1.0,
292            },
293            ..Default::default()
294        };
295        p.scene.nodes.insert(id, n);
296        assert!(any_motion(&p));
297    }
298}