ferravex_play/camera/
transition.rs

1//! Opt-in, checked camera presentation blends. No clock, simulation, collision
2//! queries, input, or authoritative pose history is owned here.
3//!
4//! Blend eye position, positive eye-to-target distance and vertical FOV linearly;
5//! blend the orthonormal view orientation along the shortest quaternion arc.
6//! The look target is reconstructed from the blended eye, direction and distance,
7//! not interpolated independently through a possible coincident eye/target.
8//! Up scale and its component parallel to forward do not affect the view: interior
9//! samples use unit perpendicular up. Exact endpoints retain the supplied `Pose3`
10//! verbatim, including its up vector. No Euler-angle or swing/twist stack is added.
11//!
12//! Only symmetric, finite-far perspective lenses are described by [`Perspective3`].
13//! Positive-duration blends require exactly matching lens descriptors, including
14//! aspect, clipping planes, handedness and depth convention; only FOV blends.
15//! Orthographic, infinite-far, asymmetric and custom projections need a host-owned
16//! cut/adapter. Descriptors declare intent; the host must use the same conventions
17//! in its renderer. Internally orientation uses local -Z forward/+Y up as in
18//! `Mat4::try_look_to_rh`; the resulting world-space forward/up also work with the
19//! host's LH view builder. Handedness never changes within a blend.
20//!
21//! Retargeting starts at the last **displayed** pose and resets segment time. It
22//! preserves a hold; `resume` continues the new segment without consuming paused
23//! time. A cut (including a zero-duration retarget or a `Frame3::cut`) immediately
24//! replaces all endpoints and releases hold. `reset` forgets the pose entirely.
25//! The next valid target initializes directly. Host-owned teleport/restart and
26//! renderer history must also be reset; a camera transition cannot repair stale
27//! simulation interpolation. Input frames are borrowed: their obstruction,
28//! recovery and query diagnostics remain observations of the host's original
29//! query, never observations of the blended path. Output is a `Pose3`, not a
30//! fabricated `Frame3`. A blended path can cross obstacles even with safe endpoints.
31//!
32//! # Pause, continuous retarget, accepted teleport and restart
33//!
34//! Runnable headless recipe using actual `Pose3`, `Frame3` and `Rig3`. The host
35//! decides when simulation/network/replay updates execute, even during a local
36//! menu. These injected presentation deltas never schedule simulation ticks.
37//!
38//! ```rust
39//! use ferravex_math::{Vec3, projection::NdcDepth};
40//! use ferravex_play::camera::{Input3, Mode3, NoObstructions, Pose3, Rig3, Target3};
41//! use ferravex_play::camera::transition::{Perspective3, Transition3, ViewHandedness};
42//!
43//! fn main() -> Result<(), Box<dyn std::error::Error>> {
44//!     let lens = Perspective3 { aspect: 16. / 9., near: 0.1, far: 1000.,
45//!         handedness: ViewHandedness::Right, depth: NdcDepth::NegativeOneToOne };
46//!     let mut view = Transition3::new();
47//!     assert_eq!(view.pose(), None);
48//!     view.cut(Pose3::default(), lens)?;
49//!     view.retarget(Pose3 { position: Vec3::X * 8.,
50//!         target: Vec3::X * 8. - Vec3::Z, ..Pose3::default() }, lens, 1.)?;
51//!     let visible = view.advance(0.25)?.unwrap();
52//!     assert_eq!(visible.position.x, 2.);
53//!     assert!(view.is_blending());
54//!     assert_eq!(view.projection(), Some(lens));
55//!     assert!(view.hold());
56//!     assert!(view.is_held());
57//!     assert_eq!(view.advance(0.25)?, Some(visible));
58//!     // A local menu does not block authoritative updates. A newly selected
59//!     // presentation target may replace the pending segment while held.
60//!     view.retarget(Pose3::default(), lens, 0.5)?;
61//!     assert_eq!(view.pose(), Some(visible));
62//!     assert!(view.resume());
63//!     assert_eq!(view.advance(0.)?, Some(visible));
64//!     assert_eq!(view.advance(0.25)?.unwrap().position.x, 1.);
65//!
66//!     let mut rig = Rig3::default();
67//!     // Simulation has accepted this teleport; do not pass a pending request
68//!     // or an old interpolated subject. The host already reset subject history.
69//!     let accepted = Target3::at(Vec3::X * 100.);
70//!     let frame = rig.snap(Input3 { target: accepted, mode: Mode3::Follow {
71//!         eye_offset: Vec3::Z * 5., look_offset: Vec3::ZERO }, fov_y: 1. },
72//!         &NoObstructions)?;
73//!     assert!(frame.cut);
74//!     let generation = view.generation();
75//!     view.retarget_frame(&frame, lens, 1.)?; // Cut overrides blend and hold.
76//!     assert_eq!(view.generation(), generation + 1);
77//!     assert_eq!(view.advance(0.)?, Some(frame.pose));
78//!     assert!(!view.is_blending());
79//!     view.reset(); // Also reset host simulation/rig/history for a real restart.
80//!     assert_eq!(view.advance(0.25)?, None);
81//!     view.retarget(Pose3::default(), lens, 1.)?;
82//!     assert_eq!(view.pose(), Some(Pose3::default()));
83//!     Ok(())
84//! }
85//! ```
86//!
87//! # Numerical and storage limits
88//!
89//! Eye coordinates have absolute components <= 1e6; view distance is in
90//! `0.001..=1e6`; FOV is in `0.05..=3.1` radians (the rig's existing FOV range).
91//! Up must be finite/nonzero, with sine of its angle to forward >= 1e-4. Near
92//! parallel up is rejected, not replaced with an arbitrary roll. Subtraction,
93//! distance and scalar interpolation use f64 intermediates. Rotations use existing
94//! checked quaternion normalization, angular distance and rotate-towards helpers.
95//! Extracted endpoint quaternions are canonicalized to positive w, or, at w == 0,
96//! first nonzero x/y/z positive. A negative endpoint dot flips the destination;
97//! exact zero-dot half-turn ties retain these signs, as in the math helpers.
98//! Small perturbations near half turns may choose the opposite equally short arc.
99//!
100//! Durations are finite seconds in `0..=3600`; per-call presentation deltas are
101//! finite in `0..=0.25`, including during hold/idle. Long suspension time must be
102//! discarded/rebased by the host or handled with a cut. Elapsed segment time uses
103//! f64, capped at duration. Interior outputs round to f32; at large coordinates a
104//! short reconstructed target may round onto the eye. Such samples return
105//! [`TransitionError::NumericalLimit`] atomically. Valid endpoints do not guarantee
106//! every intermediate target is representable. Endpoint completion bypasses
107//! reconstruction and is exact; no cross-platform bitwise determinism is promised.
108//! All methods use fixed-size inline state and bounded work, without heap storage.
109
110use super::{Frame3, Pose3};
111use ferravex_math::{Mat4, Quat, Vec3, Vec4, projection::NdcDepth};
112
113/// Host view-matrix convention. See the module recipe for lens construction.
114#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115pub enum ViewHandedness {
116    /// Host uses a right-handed view, looking along local -Z.
117    Right,
118    /// Host uses a left-handed view, looking along local +Z.
119    Left,
120}
121
122/// Explicit symmetric finite-far perspective intent; FOV comes from `Pose3`.
123///
124/// `aspect` must be finite/positive, and finite planes satisfy `0 < near < far`.
125/// The host owns projection construction and its representability. Exact equality
126/// is required for nonzero blends. To change these values, cut explicitly (or use
127/// zero duration). See the module recipe; no lens is silently inferred/defaulted.
128#[derive(Clone, Copy, Debug, PartialEq)]
129pub struct Perspective3 {
130    /// Width divided by height, in the host's actual viewport.
131    pub aspect: f32,
132    /// Positive near-plane distance.
133    pub near: f32,
134    /// Finite far-plane distance, strictly greater than near.
135    pub far: f32,
136    /// View-matrix convention, independent of the world-space pose.
137    pub handedness: ViewHandedness,
138    /// Explicit clip-space depth convention, reusing the math projector's type.
139    pub depth: NdcDepth,
140}
141
142/// Rejected input leaves the complete transition unchanged, even during hold.
143/// See [`Transition3::retarget`] for an executable error example.
144#[derive(Clone, Copy, Debug, PartialEq, Eq)]
145pub enum TransitionError {
146    /// Invalid/nonfinite/degenerate pose or documented pose bound exceeded.
147    InvalidPose,
148    /// Invalid finite-far perspective descriptor.
149    InvalidProjection,
150    /// Duration is nonfinite or outside `0..=3600` seconds.
151    InvalidDuration,
152    /// Delta is nonfinite or outside `0..=0.25` seconds.
153    InvalidDelta,
154    /// A positive-duration blend would change projection conventions/parameters.
155    IncompatibleProjection,
156    /// A reconstructed interior pose is not representable within the pose limits.
157    NumericalLimit,
158}
159impl std::fmt::Display for TransitionError {
160    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
161        write!(f, "camera transition: {self:?}")
162    }
163}
164impl std::error::Error for TransitionError {}
165
166#[derive(Clone, Copy, Debug, PartialEq)]
167struct PreparedPose {
168    pose: Pose3,
169    rotation: Quat,
170    distance: f64,
171}
172impl PreparedPose {
173    fn new(pose: Pose3) -> Result<Self, TransitionError> {
174        if !pose.position.is_finite()
175            || pose.position.abs().max_element() > 1e6
176            || !pose.target.is_finite()
177            || !pose.fov_y.is_finite()
178            || !(0.05..=3.1).contains(&pose.fov_y)
179        {
180            return Err(TransitionError::InvalidPose);
181        }
182        let delta: [f64; 3] =
183            std::array::from_fn(|i| f64::from(pose.target[i]) - f64::from(pose.position[i]));
184        let distance = delta.iter().map(|v| v * v).sum::<f64>().sqrt();
185        if !(0.001..=1e6).contains(&distance) {
186            return Err(TransitionError::InvalidPose);
187        }
188        let forward = Vec3::from_array(delta.map(|v| (v / distance) as f32));
189        let up = pose
190            .up
191            .try_normalize()
192            .ok_or(TransitionError::InvalidPose)?;
193        if forward.cross(up).length() < 1e-4 {
194            return Err(TransitionError::InvalidPose);
195        }
196        // Existing checked view construction and matrix decomposition own basis
197        // and quaternion conversion. Remove translation before transposing.
198        let view = Mat4::try_look_to_rh(Vec3::ZERO, forward, up)
199            .map_err(|_| TransitionError::InvalidPose)?;
200        let rotation_matrix =
201            Mat4::from_cols(view.x_axis, view.y_axis, view.z_axis, Vec4::W).transpose();
202        let (_, rotation, _) = rotation_matrix
203            .try_to_scale_rotation_translation()
204            .ok_or(TransitionError::InvalidPose)?;
205        let mut rotation = rotation
206            .try_normalize()
207            .ok_or(TransitionError::InvalidPose)?;
208        if [rotation.w, rotation.x, rotation.y, rotation.z]
209            .into_iter()
210            .find(|v| *v != 0.)
211            .is_some_and(|v| v < 0.)
212        {
213            rotation = -rotation;
214        }
215        Ok(Self {
216            pose,
217            rotation,
218            distance,
219        })
220    }
221}
222
223#[derive(Clone, Copy, Debug, PartialEq)]
224struct Segment {
225    start: PreparedPose,
226    end: PreparedPose,
227    displayed: PreparedPose,
228    projection: Perspective3,
229    elapsed: f64,
230    duration: f64,
231}
232
233/// Bounded presentation segment, initially empty. See the module's runnable recipe.
234///
235/// This is a timed camera blend, not a second tick interpolation/history system.
236/// Task202's engine `InterpolationPair` remains the host's optional authoritative
237/// tick-to-presentation adapter; this lower-level crate does not depend on engine.
238#[derive(Clone, Copy, Debug, Default, PartialEq)]
239pub struct Transition3 {
240    segment: Option<Segment>,
241    held: bool,
242    generation: u64,
243}
244impl Transition3 {
245    /// Empty, unheld, generation zero; equivalent to `Default`. See module recipe.
246    pub fn new() -> Self {
247        Self::default()
248    }
249
250    /// Last displayed pose, or `None` before initialization/after reset.
251    pub fn pose(&self) -> Option<Pose3> {
252        self.segment.map(|s| s.displayed.pose)
253    }
254
255    /// Lens of the displayed pose, or `None` when empty. See module recipe.
256    pub fn projection(&self) -> Option<Perspective3> {
257        self.segment.map(|s| s.projection)
258    }
259
260    /// Whether a positive-duration segment has unfinished work, even while held.
261    pub fn is_blending(&self) -> bool {
262        self.segment.is_some_and(|s| s.elapsed < s.duration)
263    }
264
265    /// Whether valid advances retain the displayed pose and segment time.
266    pub fn is_held(&self) -> bool {
267        self.held
268    }
269
270    /// Local discontinuity counter: initializations, cuts and resets increment it.
271    /// Wraps at `u64::MAX`; clones copy it. Not a tick ID or globally unique token.
272    /// Ordinary blends, retargets, holds and resumes do not increment it.
273    pub fn generation(&self) -> u64 {
274        self.generation
275    }
276
277    /// Freeze presentation time; returns true only on entering hold. Empty holds
278    /// are allowed; initialization/cut releases them. See the module recipe.
279    pub fn hold(&mut self) -> bool {
280        let changed = !self.held;
281        self.held = true;
282        changed
283    }
284
285    /// Release a hold without consuming elapsed time or changing the pose.
286    /// Returns true only on leaving hold. See the module recipe.
287    pub fn resume(&mut self) -> bool {
288        let changed = self.held;
289        self.held = false;
290        changed
291    }
292
293    /// Forget all pose/segment/lens state, release hold, advance generation.
294    /// The next valid retarget initializes exactly. See the module recipe.
295    pub fn reset(&mut self) {
296        self.segment = None;
297        self.held = false;
298        self.generation = self.generation.wrapping_add(1);
299    }
300
301    /// Immediately replace endpoints and lens, release hold, advance generation.
302    /// Validation is atomic. Lens changes are allowed. See the module recipe.
303    pub fn cut(&mut self, pose: Pose3, projection: Perspective3) -> Result<(), TransitionError> {
304        let prepared = prepare(pose, projection)?;
305        self.install_cut(prepared, projection);
306        Ok(())
307    }
308
309    fn install_cut(&mut self, pose: PreparedPose, projection: Perspective3) {
310        self.segment = Some(Segment {
311            start: pose,
312            end: pose,
313            displayed: pose,
314            projection,
315            elapsed: 0.,
316            duration: 0.,
317        });
318        self.held = false;
319        self.generation = self.generation.wrapping_add(1);
320    }
321
322    /// Start from the last displayed pose, retaining any hold. No time advances.
323    /// Empty state or zero duration initializes/cuts directly, allowing lens change.
324    /// Duration is checked even for an empty state or a cut frame.
325    ///
326    /// ```
327    /// use ferravex_math::projection::NdcDepth;
328    /// use ferravex_play::camera::{Pose3, transition::*};
329    /// let lens = Perspective3 { aspect: 1., near: 0.1, far: 100.,
330    ///     handedness: ViewHandedness::Right, depth: NdcDepth::ZeroToOne };
331    /// let mut view = Transition3::new();
332    /// view.retarget(Pose3::default(), lens, 0.).unwrap();
333    /// let before = view;
334    /// assert_eq!(view.retarget(Pose3::default(), lens, f32::NAN),
335    ///     Err(TransitionError::InvalidDuration));
336    /// assert_eq!(view, before);
337    /// assert_eq!(view.advance(f32::INFINITY), Err(TransitionError::InvalidDelta));
338    /// assert_eq!(view, before);
339    /// ```
340    pub fn retarget(
341        &mut self,
342        pose: Pose3,
343        projection: Perspective3,
344        duration: f32,
345    ) -> Result<(), TransitionError> {
346        check_duration(duration)?;
347        let prepared = prepare(pose, projection)?;
348        self.install_target(prepared, projection, duration)
349    }
350
351    /// Honor the host's cut flag, borrowing only pose/cut. Other flags/queries are
352    /// neither interpolated nor returned. All inputs, including duration, are
353    /// validated before mutation. See the actual `Rig3` frame in the module recipe.
354    pub fn retarget_frame(
355        &mut self,
356        frame: &Frame3,
357        projection: Perspective3,
358        duration: f32,
359    ) -> Result<(), TransitionError> {
360        check_duration(duration)?;
361        let prepared = prepare(frame.pose, projection)?;
362        if frame.cut {
363            self.install_cut(prepared, projection);
364            Ok(())
365        } else {
366            self.install_target(prepared, projection, duration)
367        }
368    }
369
370    fn install_target(
371        &mut self,
372        end: PreparedPose,
373        projection: Perspective3,
374        duration: f32,
375    ) -> Result<(), TransitionError> {
376        let Some(segment) = self.segment.as_mut().filter(|_| duration > 0.) else {
377            self.install_cut(end, projection);
378            return Ok(());
379        };
380        if segment.projection != projection {
381            return Err(TransitionError::IncompatibleProjection);
382        }
383        segment.start = segment.displayed;
384        segment.end = end;
385        segment.elapsed = 0.;
386        segment.duration = f64::from(duration);
387        Ok(())
388    }
389
390    /// Advance caller-owned presentation seconds in `0..=0.25`. Valid zero time,
391    /// hold, completion or empty state returns the last pose unchanged. Reaching
392    /// duration returns the exact supplied endpoint; overshoot is discarded.
393    /// Errors leave time and every other field unchanged. See the module recipe.
394    pub fn advance(&mut self, delta: f32) -> Result<Option<Pose3>, TransitionError> {
395        if !delta.is_finite() || !(0. ..=0.25).contains(&delta) {
396            return Err(TransitionError::InvalidDelta);
397        }
398        if self.held || delta == 0. || !self.is_blending() {
399            return Ok(self.pose());
400        }
401        // Calculate on a copy: numerical reconstruction failure also rolls back time.
402        let mut segment = self.segment.unwrap();
403        segment.elapsed = (segment.elapsed + f64::from(delta)).min(segment.duration);
404        segment.displayed = if segment.elapsed == segment.duration {
405            segment.end
406        } else {
407            blend(
408                segment.start,
409                segment.end,
410                segment.elapsed / segment.duration,
411            )?
412        };
413        self.segment = Some(segment);
414        Ok(self.pose())
415    }
416}
417
418fn check_duration(duration: f32) -> Result<(), TransitionError> {
419    if duration.is_finite() && (0. ..=3600.).contains(&duration) {
420        Ok(())
421    } else {
422        Err(TransitionError::InvalidDuration)
423    }
424}
425
426fn prepare(pose: Pose3, projection: Perspective3) -> Result<PreparedPose, TransitionError> {
427    if !projection.aspect.is_finite()
428        || projection.aspect <= 0.
429        || !projection.near.is_finite()
430        || projection.near <= 0.
431        || !projection.far.is_finite()
432        || projection.far <= projection.near
433    {
434        return Err(TransitionError::InvalidProjection);
435    }
436    PreparedPose::new(pose)
437}
438
439fn blend(a: PreparedPose, b: PreparedPose, alpha: f64) -> Result<PreparedPose, TransitionError> {
440    let lerp = |a: f64, b: f64| a * (1. - alpha) + b * alpha;
441    let angle = a
442        .rotation
443        .try_angle_between(b.rotation)
444        .ok_or(TransitionError::NumericalLimit)?;
445    let rotation = a
446        .rotation
447        .try_rotate_towards(b.rotation, (f64::from(angle) * alpha) as f32)
448        .ok_or(TransitionError::NumericalLimit)?;
449    let position = Vec3::from_array(std::array::from_fn(|i| {
450        lerp(f64::from(a.pose.position[i]), f64::from(b.pose.position[i])) as f32
451    }));
452    let distance = lerp(a.distance, b.distance);
453    let forward = rotation * Vec3::NEG_Z;
454    let pose = Pose3 {
455        position,
456        target: Vec3::from_array(std::array::from_fn(|i| {
457            (f64::from(position[i]) + f64::from(forward[i]) * distance) as f32
458        })),
459        up: rotation * Vec3::Y,
460        fov_y: lerp(f64::from(a.pose.fov_y), f64::from(b.pose.fov_y)) as f32,
461    };
462    // Verify the rounded public pose rather than claiming its ideal target exists.
463    PreparedPose::new(pose).map_err(|_| TransitionError::NumericalLimit)
464}
465
466#[cfg(test)]
467mod tests {
468    use super::*;
469
470    #[test]
471    fn discontinuity_generation_wraps_on_cut_reset_and_initialization() {
472        let lens = Perspective3 {
473            aspect: 1.,
474            near: 0.1,
475            far: 100.,
476            handedness: ViewHandedness::Right,
477            depth: NdcDepth::ZeroToOne,
478        };
479        let mut view = Transition3 {
480            generation: u64::MAX,
481            ..Default::default()
482        };
483        view.cut(Pose3::default(), lens).unwrap();
484        assert_eq!(view.generation(), 0);
485        view.generation = u64::MAX;
486        view.reset();
487        assert_eq!(view.generation(), 0);
488        view.generation = u64::MAX;
489        view.retarget(Pose3::default(), lens, 1.).unwrap();
490        assert_eq!(view.generation(), 0);
491    }
492}