Skip to main content

euv_core/game/snapshot/
impl.rs

1use super::*;
2
3/// Construction, commit, discontinuity handling, and interpolation sampling for `DoubleBufferedSnapshot`.
4impl<S> DoubleBufferedSnapshot<S>
5where
6    S: Clone,
7{
8    /// Initializes a double-buffered snapshot pair with `initial` in both `prev_state` and `curr_state`.
9    ///
10    /// # Arguments
11    ///
12    /// - `S` - Initial immutable simulation state snapshot.
13    ///
14    /// # Returns
15    ///
16    /// - `Self` - Initialized snapshot buffer.
17    #[must_use]
18    pub fn new(initial: S) -> Self {
19        Self {
20            prev_state: initial.clone(),
21            curr_state: initial,
22            tick: 0,
23            discontinuity_tick: 0,
24            has_prev: false,
25        }
26    }
27
28    /// Commits a continuous fixed-step snapshot, promoting the prior `curr_state` into `prev_state`.
29    ///
30    /// # Arguments
31    ///
32    /// - `&Self` - Mutable snapshot buffer.
33    /// - `S` - New immutable simulation state snapshot.
34    pub fn commit(&mut self, next: S) {
35        let mut incoming: S = next;
36        swap(self.get_mut_curr_state(), &mut incoming);
37        self.set_prev_state(incoming);
38        let next_tick: u64 = self.get_tick().wrapping_add(1);
39        self.set_tick(next_tick);
40        self.set_has_prev(true);
41    }
42
43    /// Commits a discontinuous snapshot (teleport, scene reset, or hard camera cut), preventing interpolation across the boundary.
44    ///
45    /// # Arguments
46    ///
47    /// - `&Self` - Mutable snapshot buffer.
48    /// - `S` - New immutable simulation state snapshot.
49    pub fn commit_discontinuous(&mut self, next: S) {
50        let next_tick: u64 = self.get_tick().wrapping_add(1);
51        self.set_prev_state(next.clone());
52        self.set_curr_state(next);
53        self.set_tick(next_tick);
54        self.set_discontinuity_tick(next_tick);
55        self.set_has_prev(false);
56    }
57
58    /// Samples the render-time state at normalized `alpha` in `[0.0, 1.0]`.
59    ///
60    /// # Arguments
61    ///
62    /// - `&Self` - Snapshot buffer reference.
63    /// - `f32` - Normalized interpolation factor between previous and current fixed steps.
64    ///
65    /// # Returns
66    ///
67    /// - `S` - Interpolated snapshot or exact `curr_state` on discontinuities.
68    #[must_use]
69    pub fn sample(&self, alpha: f32) -> S
70    where
71        S: InterpolatableState,
72    {
73        let clamped: f32 = if alpha.is_finite() {
74            alpha.clamp(0.0, 1.0)
75        } else {
76            1.0
77        };
78        if !self.get_has_prev()
79            || self.get_discontinuity_tick() == self.get_tick()
80            || clamped >= 1.0
81        {
82            return self.get_curr_state().clone();
83        }
84        if clamped <= 0.0 {
85            return self.get_prev_state().clone();
86        }
87        self.get_prev_state()
88            .interpolate(self.get_curr_state(), clamped)
89    }
90}
91
92/// Snapshot builders and event helpers for `World2DSnapshot`.
93impl World2DSnapshot {
94    /// Captures an immutable `World2DSnapshot` from `world` and `camera`.
95    ///
96    /// # Arguments
97    ///
98    /// - `&GameWorld` - Authoritative 2D ECS world.
99    /// - `Camera2D` - Active 2D camera state.
100    /// - `bool` - Whether a hard camera cut occurred on this tick.
101    /// - `Vec<DiscreteGameEvent>` - Discrete un-interpolated gameplay events emitted on this tick.
102    ///
103    /// # Returns
104    ///
105    /// - `Self` - Captured immutable 2D world snapshot.
106    #[must_use]
107    pub fn capture(
108        world: &GameWorld,
109        camera: Camera2D,
110        camera_cut: bool,
111        discrete_events: Vec<DiscreteGameEvent>,
112    ) -> Self {
113        let records: &[EntityRecord] = world.get_entities().as_slice();
114        let mut entities: Vec<EntityPose2D> = Vec::with_capacity(records.len());
115        for ent in records.iter() {
116            entities.push(EntityPose2D::new(
117                ent.get_id(),
118                ent.get_transform(),
119                ent.get_teleport_epoch(),
120                ent.get_spawn_tick(),
121                ent.get_alive(),
122            ));
123        }
124        Self {
125            tick: world.get_tick(),
126            camera,
127            camera_cut,
128            entities,
129            discrete_events,
130        }
131    }
132}
133
134/// Discontinuity-safe render-time interpolation for `World2DSnapshot`.
135impl InterpolatableState for World2DSnapshot {
136    /// Interpolates camera and continuous entity poses while snapping spawns, despawns, teleports, camera cuts, and discrete events.
137    ///
138    /// # Arguments
139    ///
140    /// - `&Self` - Previous fixed-step 2D snapshot.
141    /// - `&Self` - Current fixed-step 2D snapshot.
142    /// - `f32` - Normalized interpolation factor in `[0.0, 1.0]`.
143    ///
144    /// # Returns
145    ///
146    /// - `Self` - Render-time interpolated 2D world snapshot.
147    fn interpolate(&self, next: &Self, alpha: f32) -> Self {
148        let k: f32 = alpha.clamp(0.0, 1.0);
149        let camera: Camera2D = if next.get_camera_cut() {
150            next.get_camera()
151        } else {
152            self.get_camera().lerp(next.get_camera(), k)
153        };
154        let prev_entities: &[EntityPose2D] = self.get_entities().as_slice();
155        let next_entities: &[EntityPose2D] = next.get_entities().as_slice();
156        let mut out_entities: Vec<EntityPose2D> = Vec::with_capacity(next_entities.len());
157        for (idx, curr) in next_entities.iter().copied().enumerate() {
158            let mut blended: EntityPose2D = curr;
159            if curr.get_alive()
160                && let Some(prev) = prev_entities.get(idx).copied()
161            {
162                let same_entity: bool = prev.get_alive() && prev.get_id() == curr.get_id();
163                let no_teleport: bool = prev.get_teleport_epoch() == curr.get_teleport_epoch();
164                let not_fresh_spawn: bool = curr.get_spawn_tick() <= self.get_tick();
165                if same_entity && no_teleport && not_fresh_spawn {
166                    let interp_tr: EntityTransform =
167                        prev.get_transform().lerp(curr.get_transform(), k);
168                    blended.set_transform(interp_tr);
169                }
170            }
171            out_entities.push(blended);
172        }
173        Self {
174            tick: next.get_tick(),
175            camera,
176            camera_cut: next.get_camera_cut(),
177            entities: out_entities,
178            discrete_events: next.get_discrete_events().clone(),
179        }
180    }
181}
182
183/// Discontinuity-safe skeletal joint interpolation for `SkeletonPoseSnapshot`.
184impl InterpolatableState for SkeletonPoseSnapshot {
185    /// Interpolates joint transforms between `self` and `next` unless `next.cut` is set or joint counts differ.
186    ///
187    /// # Arguments
188    ///
189    /// - `&Self` - Previous skeletal pose snapshot.
190    /// - `&Self` - Current skeletal pose snapshot.
191    /// - `f32` - Normalized interpolation factor in `[0.0, 1.0]`.
192    ///
193    /// # Returns
194    ///
195    /// - `Self` - Interpolated skeletal pose snapshot.
196    fn interpolate(&self, next: &Self, alpha: f32) -> Self {
197        let prev_joints: &[Transform3D] = self.get_joint_transforms().as_slice();
198        let next_joints: &[Transform3D] = next.get_joint_transforms().as_slice();
199        if next.get_cut() || prev_joints.len() != next_joints.len() {
200            return next.clone();
201        }
202        let k: f32 = alpha.clamp(0.0, 1.0);
203        let mut out: Vec<Transform3D> = Vec::with_capacity(next_joints.len());
204        for (a, b) in prev_joints.iter().copied().zip(next_joints.iter().copied()) {
205            out.push(a.lerp_shortest_angle(b, k));
206        }
207        Self {
208            joint_transforms: out,
209            cut: false,
210        }
211    }
212}
213
214/// Snapshot builders for `World3DSnapshot`.
215impl World3DSnapshot {
216    /// Captures an immutable `World3DSnapshot` from `world` with optional skeletal poses and discrete events.
217    ///
218    /// # Arguments
219    ///
220    /// - `&World3D` - Authoritative 3D world state.
221    /// - `u64` - Fixed simulation tick number.
222    /// - `bool` - Whether an instant camera cut occurred on this tick.
223    /// - `Vec<SkeletonPoseSnapshot>` - Skeletal pose snapshots sampled on this tick.
224    /// - `Vec<DiscreteGameEvent>` - Un-interpolated discrete events emitted on this tick.
225    ///
226    /// # Returns
227    ///
228    /// - `Self` - Captured immutable 3D world snapshot.
229    #[must_use]
230    pub fn capture(
231        world: &World3D,
232        tick: u64,
233        camera_cut: bool,
234        skeletons: Vec<SkeletonPoseSnapshot>,
235        discrete_events: Vec<DiscreteGameEvent>,
236    ) -> Self {
237        let objs: &[SceneObject3D] = world.get_objects().as_slice();
238        let mut poses: Vec<ObjectPose3D> = Vec::with_capacity(objs.len());
239        for (idx, obj) in objs.iter().enumerate() {
240            poses.push(ObjectPose3D::new(
241                idx,
242                obj.get_transform(),
243                obj.get_teleport_epoch(),
244                true,
245            ));
246        }
247        Self {
248            tick,
249            camera: world.get_camera(),
250            camera_cut,
251            objects: poses,
252            skeletons,
253            discrete_events,
254        }
255    }
256}
257
258/// Discontinuity-safe render-time interpolation for `World3DSnapshot`.
259impl InterpolatableState for World3DSnapshot {
260    /// Interpolates 3D camera, continuous object transforms, and skeletal poses while snapping cuts, teleports, and discrete events.
261    ///
262    /// # Arguments
263    ///
264    /// - `&Self` - Previous fixed-step 3D snapshot.
265    /// - `&Self` - Current fixed-step 3D snapshot.
266    /// - `f32` - Normalized interpolation factor in `[0.0, 1.0]`.
267    ///
268    /// # Returns
269    ///
270    /// - `Self` - Render-time interpolated 3D world snapshot.
271    fn interpolate(&self, next: &Self, alpha: f32) -> Self {
272        let k: f32 = alpha.clamp(0.0, 1.0);
273        let camera: Camera3D = if next.get_camera_cut() {
274            next.get_camera()
275        } else {
276            self.get_camera().lerp(next.get_camera(), k)
277        };
278        let prev_objs: &[ObjectPose3D] = self.get_objects().as_slice();
279        let next_objs: &[ObjectPose3D] = next.get_objects().as_slice();
280        let mut out_objs: Vec<ObjectPose3D> = Vec::with_capacity(next_objs.len());
281        for (idx, curr) in next_objs.iter().copied().enumerate() {
282            let mut blended: ObjectPose3D = curr;
283            if curr.get_visible()
284                && let Some(prev) = prev_objs.get(idx).copied()
285            {
286                let continuous: bool = prev.get_visible()
287                    && prev.get_object_index() == curr.get_object_index()
288                    && prev.get_teleport_epoch() == curr.get_teleport_epoch();
289                if continuous {
290                    blended.set_transform(
291                        prev.get_transform()
292                            .lerp_shortest_angle(curr.get_transform(), k),
293                    );
294                }
295            }
296            out_objs.push(blended);
297        }
298        let prev_skels: &[SkeletonPoseSnapshot] = self.get_skeletons().as_slice();
299        let next_skels: &[SkeletonPoseSnapshot] = next.get_skeletons().as_slice();
300        let mut out_skels: Vec<SkeletonPoseSnapshot> = Vec::with_capacity(next_skels.len());
301        for (idx, curr_sk) in next_skels.iter().enumerate() {
302            if let Some(prev_sk) = prev_skels.get(idx) {
303                out_skels.push(prev_sk.interpolate(curr_sk, k));
304            } else {
305                out_skels.push(curr_sk.clone());
306            }
307        }
308        Self {
309            tick: next.get_tick(),
310            camera,
311            camera_cut: next.get_camera_cut(),
312            objects: out_objs,
313            skeletons: out_skels,
314            discrete_events: next.get_discrete_events().clone(),
315        }
316    }
317}