Skip to main content

euv_core/game/camera/
impl.rs

1use super::*;
2
3/// Default camera centered at `(0, 0)` with `1.0x` zoom.
4impl Default for Camera2D {
5    /// Creates a default `Camera2D`.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default 2D camera.
10    fn default() -> Self {
11        Self {
12            position: Point::new(0.0, 0.0),
13            zoom: 1.0,
14            trauma: 0.0,
15            max_shake: 14.0,
16            shake_time: 0.0,
17            world_bounds: None,
18        }
19    }
20}
21
22/// Camera projection, smooth follow, frustum culling, and trauma shake operations.
23impl Camera2D {
24    /// Creates a `Camera2D` positioned at `center` with `zoom`.
25    ///
26    /// # Arguments
27    ///
28    /// - `Point` - Initial world center.
29    /// - `f32` - Initial zoom multiplier clamped to `[0.25, 4.0]`.
30    ///
31    /// # Returns
32    ///
33    /// - `Self` - Configured 2D camera.
34    #[must_use]
35    pub fn at(center: Point, zoom: f32) -> Self {
36        Self {
37            position: center,
38            zoom: zoom.clamp(0.25, 4.0),
39            ..Self::default()
40        }
41    }
42
43    /// Adds impact trauma in `[0.0, 1.0]` to drive damped screen shake.
44    ///
45    /// # Arguments
46    ///
47    /// - `&Self` - Mutable camera.
48    /// - `f32` - Trauma impulse amount.
49    pub fn add_trauma(&mut self, amount: f32) {
50        let next: f32 = (self.get_trauma() + amount.max(0.0)).clamp(0.0, 1.0);
51        self.set_trauma(next);
52    }
53
54    /// Smoothly follows `target` using frame-rate-independent exponential damping and decays screen shake.
55    ///
56    /// # Arguments
57    ///
58    /// - `&Self` - Mutable camera.
59    /// - `Point` - Desired world target point.
60    /// - `f32` - Responsiveness factor (`6.0..=16.0` recommended).
61    /// - `f32` - Elapsed frame delta in seconds.
62    /// - `Size` - Viewport logical size for optional world-bounds clamping.
63    pub fn follow(&mut self, target: Point, responsiveness: f32, dt_secs: f32, viewport: Size) {
64        let alpha: f32 =
65            (1.0 - (-responsiveness.max(0.1) * dt_secs.max(0.0)).exp()).clamp(0.0, 1.0);
66        let cur: Point = self.get_position();
67        let mut nx: f32 = cur.get_x() + (target.get_x() - cur.get_x()) * alpha;
68        let mut ny: f32 = cur.get_y() + (target.get_y() - cur.get_y()) * alpha;
69        let Self { world_bounds, .. } = *self;
70        if let Some(bounds) = world_bounds {
71            let half_w: f32 = (viewport.get_width() * 0.5) / self.get_zoom().max(0.25);
72            let half_h: f32 = (viewport.get_height() * 0.5) / self.get_zoom().max(0.25);
73            let min_x: f32 = bounds.get_x() + half_w;
74            let max_x: f32 = bounds.right() - half_w;
75            let min_y: f32 = bounds.get_y() + half_h;
76            let max_y: f32 = bounds.bottom() - half_h;
77            nx = if min_x <= max_x {
78                nx.clamp(min_x, max_x)
79            } else {
80                bounds.get_x() + bounds.get_width() * 0.5
81            };
82            ny = if min_y <= max_y {
83                ny.clamp(min_y, max_y)
84            } else {
85                bounds.get_y() + bounds.get_height() * 0.5
86            };
87        }
88        self.set_position(Point::new(nx, ny));
89        let next_trauma: f32 = (self.get_trauma() - dt_secs * 1.8).max(0.0);
90        self.set_trauma(next_trauma);
91        self.set_shake_time(self.get_shake_time() + dt_secs * 38.0);
92    }
93
94    /// Computes the current screen-shake offset in world coordinates.
95    ///
96    /// # Arguments
97    ///
98    /// - `&Self` - Camera reference.
99    ///
100    /// # Returns
101    ///
102    /// - `Point` - Shake offset `(dx, dy)`.
103    #[must_use]
104    pub fn shake_offset(&self) -> Point {
105        let t: f32 = self.get_trauma();
106        if t <= 0.001 {
107            return Point::new(0.0, 0.0);
108        }
109        let mag: f32 = t * t * self.get_max_shake();
110        let phase: f32 = self.get_shake_time();
111        Point::new((phase * 1.7).sin() * mag, (phase * 2.3).cos() * mag)
112    }
113
114    /// Precomputes hoisted camera screen-projection parameters `(effective_cam_x, effective_cam_y, zoom, half_vp_w, half_vp_h)` once per frame so tile/entity/particle loops avoid redundant per-item `sin`/`cos` shake math.
115    ///
116    /// # Arguments
117    ///
118    /// - `&Self` - Camera reference.
119    /// - `Size` - Viewport logical size.
120    ///
121    /// # Returns
122    ///
123    /// - `(f32, f32, f32, f32, f32)` - Hoisted `(cam_x_plus_shake, cam_y_plus_shake, zoom, half_vp_w, half_vp_h)` tuple.
124    #[inline(always)]
125    #[must_use]
126    pub fn projection_params(&self, viewport: Size) -> (f32, f32, f32, f32, f32) {
127        let zoom: f32 = self.get_zoom().max(0.25);
128        let shake: Point = self.shake_offset();
129        let cam: Point = self.get_position();
130        (
131            cam.get_x() + shake.get_x(),
132            cam.get_y() + shake.get_y(),
133            zoom,
134            viewport.get_width() * 0.5,
135            viewport.get_height() * 0.5,
136        )
137    }
138
139    /// Projects a world-space point into viewport-local screen coordinates using a pre-hoisted `shake` offset.
140    ///
141    /// # Arguments
142    ///
143    /// - `&Self` - Camera reference.
144    /// - `Point` - World-space point.
145    /// - `Size` - Viewport logical size.
146    /// - `Point` - Precomputed per-frame `shake_offset()` value.
147    ///
148    /// # Returns
149    ///
150    /// - `Point` - Viewport-local logical pixel coordinates.
151    #[inline(always)]
152    #[must_use]
153    pub fn world_to_screen_with_shake(&self, world: Point, viewport: Size, shake: Point) -> Point {
154        let zoom: f32 = self.get_zoom().max(0.25);
155        let cam: Point = self.get_position();
156        Point::new(
157            (world.get_x() - (cam.get_x() + shake.get_x())) * zoom + viewport.get_width() * 0.5,
158            (world.get_y() - (cam.get_y() + shake.get_y())) * zoom + viewport.get_height() * 0.5,
159        )
160    }
161
162    /// Projects a world-space point into viewport-local screen coordinates.
163    ///
164    /// # Arguments
165    ///
166    /// - `&Self` - Camera reference.
167    /// - `Point` - World-space point.
168    /// - `Size` - Viewport logical size.
169    ///
170    /// # Returns
171    ///
172    /// - `Point` - Viewport-local logical pixel coordinates.
173    #[must_use]
174    pub fn world_to_screen(&self, world: Point, viewport: Size) -> Point {
175        let shake: Point = self.shake_offset();
176        self.world_to_screen_with_shake(world, viewport, shake)
177    }
178
179    /// Unprojects a viewport-local screen point back into world coordinates.
180    ///
181    /// # Arguments
182    ///
183    /// - `&Self` - Camera reference.
184    /// - `Point` - Viewport-local logical pixel point.
185    /// - `Size` - Viewport logical size.
186    ///
187    /// # Returns
188    ///
189    /// - `Point` - Corresponding world-space point.
190    #[must_use]
191    pub fn screen_to_world(&self, screen: Point, viewport: Size) -> Point {
192        let zoom: f32 = self.get_zoom().max(0.25);
193        let cam: Point = self.get_position();
194        Point::new(
195            (screen.get_x() - viewport.get_width() * 0.5) / zoom + cam.get_x(),
196            (screen.get_y() - viewport.get_height() * 0.5) / zoom + cam.get_y(),
197        )
198    }
199
200    /// Linearly interpolates position, zoom, and shake state between `self` and `other` at `alpha` in `[0.0, 1.0]`.
201    ///
202    /// # Arguments
203    ///
204    /// - `Self` - Previous fixed-step camera state.
205    /// - `Self` - Current fixed-step camera state.
206    /// - `f32` - Normalized interpolation factor in `[0.0, 1.0]`.
207    ///
208    /// # Returns
209    ///
210    /// - `Self` - Render-time interpolated 2D camera.
211    #[must_use]
212    pub fn lerp(self, other: Self, alpha: f32) -> Self {
213        let k: f32 = alpha.clamp(0.0, 1.0);
214        let p0: Point = self.get_position();
215        let p1: Point = other.get_position();
216        let Self { world_bounds, .. } = other;
217        Self {
218            position: Point::new(
219                p0.get_x() + (p1.get_x() - p0.get_x()) * k,
220                p0.get_y() + (p1.get_y() - p0.get_y()) * k,
221            ),
222            zoom: self.get_zoom() + (other.get_zoom() - self.get_zoom()) * k,
223            trauma: self.get_trauma() + (other.get_trauma() - self.get_trauma()) * k,
224            max_shake: self.get_max_shake() + (other.get_max_shake() - self.get_max_shake()) * k,
225            shake_time: self.get_shake_time()
226                + (other.get_shake_time() - self.get_shake_time()) * k,
227            world_bounds,
228        }
229    }
230
231    /// Computes the world-space visible frustum rectangle for culling offscreen sprites and tiles.
232    ///
233    /// # Arguments
234    ///
235    /// - `&Self` - Camera reference.
236    /// - `Size` - Viewport logical size.
237    ///
238    /// # Returns
239    ///
240    /// - `Rect` - Visible world-space frustum bounds.
241    #[must_use]
242    pub fn visible_world_rect(&self, viewport: Size) -> Rect {
243        let zoom: f32 = self.get_zoom().max(0.25);
244        let w: f32 = viewport.get_width() / zoom;
245        let h: f32 = viewport.get_height() / zoom;
246        let cam: Point = self.get_position();
247        let pad: f32 = self.get_max_shake();
248        Rect::new(
249            cam.get_x() - w * 0.5 - pad,
250            cam.get_y() - h * 0.5 - pad,
251            w + pad * 2.0,
252            h + pad * 2.0,
253        )
254    }
255}