Skip to main content

rayengine_core/tween/
shake.rs

1//! Trauma-based screen shake for 2D and 3D cameras.
2
3use crate::camera::{Camera2D, Camera3D};
4use glam::{Mat2, Quat, Vec2};
5use std::{fmt, time::Duration};
6
7/// Shake limits at full trauma. Offsets are in camera-aligned world units, so
8/// scale them to the camera's visible height or distance.
9#[derive(Clone, Copy, Debug, PartialEq)]
10pub struct ShakeConfig {
11    /// Maximum horizontal/vertical offset at full trauma, in world units.
12    pub max_offset: Vec2,
13    /// Maximum roll at full trauma, in radians.
14    pub max_roll: f32,
15    /// Noise samples per second; higher values shake faster.
16    pub frequency: f32,
17    /// Trauma removed per second (`1.0` fades full trauma in one second).
18    pub decay: f32,
19    /// Seed selecting a reproducible shake pattern.
20    pub seed: u32,
21}
22
23impl Default for ShakeConfig {
24    fn default() -> Self {
25        Self {
26            max_offset: Vec2::splat(8.0),
27            max_roll: 0.05,
28            frequency: 18.0,
29            decay: 1.5,
30            seed: 0,
31        }
32    }
33}
34
35/// A shake configuration with a nonfinite or out-of-range field.
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub struct ShakeError(pub &'static str);
38
39impl fmt::Display for ShakeError {
40    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41        f.write_str(self.0)
42    }
43}
44impl std::error::Error for ShakeError {}
45
46/// Displacement to apply to a camera this frame.
47#[derive(Clone, Copy, Debug, Default, PartialEq)]
48pub struct ShakeSample {
49    /// Camera-aligned offset: +X right and +Y screen-down in 2D, +Y up in 3D.
50    pub offset: Vec2,
51    /// Roll in radians.
52    pub roll: f32,
53}
54
55/// Trauma-driven camera shake with smooth, seeded, deterministic noise.
56///
57/// Add trauma (`0..=1`) on impacts. Shake strength is trauma squared, so small
58/// hits stay subtle, and trauma decays linearly with explicitly supplied time.
59/// Apply the shake to a copy of the camera when drawing; the game keeps its
60/// unshaken camera. With zero trauma the camera is returned unchanged.
61///
62/// ```
63/// use rayengine_core::{camera::Camera2D, tween::{Shake, ShakeConfig}};
64/// use std::time::Duration;
65/// let mut shake = Shake::new(ShakeConfig::default()).unwrap();
66/// let camera = Camera2D::default();
67/// shake.add_trauma(0.6);
68/// shake.advance(Duration::from_millis(16));
69/// let shaken = shake.apply_2d(camera);
70/// assert_ne!(shaken.target, camera.target);
71/// shake.advance(Duration::from_secs(1)); // fully decayed
72/// assert_eq!(shake.apply_2d(camera).target, camera.target);
73/// ```
74#[derive(Clone, Debug)]
75pub struct Shake {
76    config: ShakeConfig,
77    trauma: f32,
78    // Noise position kept as an integer lattice index plus a fraction, so
79    // running for hours never loses precision.
80    lattice: u32,
81    phase: f64,
82}
83
84impl Shake {
85    /// Validates finite, nonnegative limits, decay and a positive frequency.
86    pub fn new(config: ShakeConfig) -> Result<Self, ShakeError> {
87        Self::validate(&config)?;
88        Ok(Self {
89            config,
90            trauma: 0.0,
91            lattice: 0,
92            phase: 0.0,
93        })
94    }
95
96    fn validate(config: &ShakeConfig) -> Result<(), ShakeError> {
97        if !config.max_offset.is_finite() || config.max_offset.min_element() < 0.0 {
98            return Err(ShakeError("shake offset must be finite and nonnegative"));
99        }
100        if !config.max_roll.is_finite() || config.max_roll < 0.0 {
101            return Err(ShakeError("shake roll must be finite and nonnegative"));
102        }
103        if !config.frequency.is_finite() || config.frequency <= 0.0 {
104            return Err(ShakeError("shake frequency must be finite and positive"));
105        }
106        if !config.decay.is_finite() || config.decay < 0.0 {
107            return Err(ShakeError("shake decay must be finite and nonnegative"));
108        }
109        Ok(())
110    }
111
112    /// Current limits.
113    pub fn config(&self) -> &ShakeConfig {
114        &self.config
115    }
116    /// Replaces limits, keeping trauma and noise position.
117    pub fn set_config(&mut self, config: ShakeConfig) -> Result<(), ShakeError> {
118        Self::validate(&config)?;
119        self.config = config;
120        Ok(())
121    }
122
123    /// Adds trauma, saturating at one. Nonfinite amounts are ignored; negative
124    /// amounts reduce trauma.
125    pub fn add_trauma(&mut self, amount: f32) {
126        if amount.is_finite() {
127            self.trauma = (self.trauma + amount).clamp(0.0, 1.0);
128        }
129    }
130    /// Sets trauma, clamped to `0..=1`. Nonfinite values are ignored.
131    pub fn set_trauma(&mut self, trauma: f32) {
132        if trauma.is_finite() {
133            self.trauma = trauma.clamp(0.0, 1.0);
134        }
135    }
136    /// Current trauma in `0..=1`.
137    pub fn trauma(&self) -> f32 {
138        self.trauma
139    }
140    /// Shake strength, `trauma²`.
141    pub fn intensity(&self) -> f32 {
142        self.trauma * self.trauma
143    }
144
145    /// Decays trauma and moves along the noise by explicitly supplied time.
146    pub fn advance(&mut self, dt: Duration) {
147        let seconds = dt.as_secs_f64();
148        self.trauma =
149            (f64::from(self.trauma) - f64::from(self.config.decay) * seconds).max(0.0) as f32;
150        let phase = self.phase + seconds * f64::from(self.config.frequency);
151        let whole = phase.floor();
152        self.phase = phase - whole;
153        // Lattice indices wrap; hashed noise stays continuous across the wrap.
154        self.lattice = self
155            .lattice
156            .wrapping_add(whole.rem_euclid(4_294_967_296.0) as u32);
157    }
158
159    /// Current displacement; exactly zero without trauma.
160    pub fn sample(&self) -> ShakeSample {
161        let intensity = self.intensity();
162        if intensity == 0.0 {
163            return ShakeSample::default();
164        }
165        ShakeSample {
166            offset: Vec2::new(self.noise(0), self.noise(1)) * self.config.max_offset * intensity,
167            roll: self.noise(2) * self.config.max_roll * intensity,
168        }
169    }
170
171    /// Shaken copy of a 2D camera. The offset follows the camera's screen axes.
172    pub fn apply_2d(&self, camera: Camera2D) -> Camera2D {
173        let sample = self.sample();
174        if sample == ShakeSample::default() {
175            return camera;
176        }
177        Camera2D {
178            target: camera.target + Mat2::from_angle(-camera.rotation) * sample.offset,
179            rotation: camera.rotation + sample.roll,
180            ..camera
181        }
182    }
183
184    /// Shaken copy of a 3D camera: the eye and target move together along the
185    /// view's right/up axes and `up` rolls around the view direction.
186    /// A degenerate camera (eye at target, or `up` parallel to the view) is returned unchanged.
187    pub fn apply_3d(&self, camera: Camera3D) -> Camera3D {
188        let sample = self.sample();
189        let forward = (camera.target - camera.position).normalize_or_zero();
190        let right = forward.cross(camera.up).normalize_or_zero();
191        if sample == ShakeSample::default() || right == glam::Vec3::ZERO {
192            return camera;
193        }
194        let up = right.cross(forward);
195        let offset = right * sample.offset.x + up * sample.offset.y;
196        Camera3D {
197            position: camera.position + offset,
198            target: camera.target + offset,
199            up: Quat::from_axis_angle(forward, sample.roll) * camera.up,
200            ..camera
201        }
202    }
203
204    /// Smooth value noise in `[-1, 1]` for one independent channel.
205    fn noise(&self, channel: u32) -> f32 {
206        let a = self.hash(self.lattice, channel);
207        let b = self.hash(self.lattice.wrapping_add(1), channel);
208        let t = self.phase as f32;
209        let t = t * t * (3.0 - 2.0 * t);
210        a + (b - a) * t
211    }
212
213    fn hash(&self, index: u32, channel: u32) -> f32 {
214        // lowbias32 integer hash mixed with seed and channel.
215        let mut x = index ^ self.config.seed.rotate_left(16) ^ channel.wrapping_mul(0x9E37_79B9);
216        x ^= x >> 16;
217        x = x.wrapping_mul(0x7FEB_352D);
218        x ^= x >> 15;
219        x = x.wrapping_mul(0x846C_A68B);
220        x ^= x >> 16;
221        (x as f32 / u32::MAX as f32) * 2.0 - 1.0
222    }
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228
229    #[test]
230    fn lattice_wraps_without_a_discontinuity() {
231        let mut shake = Shake::new(ShakeConfig {
232            frequency: 1.0,
233            decay: 0.0,
234            ..ShakeConfig::default()
235        })
236        .unwrap();
237        shake.set_trauma(1.0);
238        shake.lattice = u32::MAX;
239        shake.phase = 0.999_999;
240        let before = shake.sample();
241        shake.advance(Duration::from_micros(2));
242        assert_eq!(shake.lattice, 0);
243        assert!((shake.sample().offset - before.offset).length() < 1e-3);
244        shake.advance(Duration::MAX);
245        assert!(shake.phase >= 0.0 && shake.phase < 1.0);
246        assert!(shake.sample().offset.is_finite());
247    }
248}