Skip to main content

alpha2_model/
shutter.rs

1//! The project's shutter: the part of each frame over which marked transforms are averaged.
2
3use alpha2_time::{FrameRate, MediaTime, TICKS_PER_SECOND};
4use serde::{Deserialize, Serialize};
5use std::fmt;
6
7/// Most samples a [`Shutter`] averages.
8pub const MAX_SHUTTER_SAMPLES: u32 = 64;
9/// Fewest samples a [`Shutter`] averages.
10pub const MIN_SHUTTER_SAMPLES: u32 = 2;
11/// Largest [`Shutter::angle_degrees`]: two frames.
12pub const MAX_SHUTTER_ANGLE_DEGREES: f32 = 720.0;
13/// Largest magnitude of [`Shutter::phase_degrees`]: one frame.
14pub const MAX_SHUTTER_PHASE_DEGREES: f32 = 360.0;
15
16/// A rotary shutter: the part of each frame during which motion is recorded.
17///
18/// A clip or transform node marked `motion_blur` is drawn as the average of its placements at the
19/// midpoints of equal parts of the open interval; the picture placed is the one at the frame
20/// time.
21#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
22#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
23#[serde(deny_unknown_fields)]
24pub struct Shutter {
25    /// How long the shutter is open, 360 being one whole frame. Above 0, at most
26    /// [`MAX_SHUTTER_ANGLE_DEGREES`].
27    #[serde(default = "Shutter::default_angle")]
28    pub angle_degrees: f32,
29    /// Where the open interval starts relative to the frame time, 360 being one frame. Within
30    /// [`MAX_SHUTTER_PHASE_DEGREES`] either way; -90 with an angle of 180 centres the interval on
31    /// the frame time.
32    #[serde(default = "Shutter::default_phase")]
33    pub phase_degrees: f32,
34    /// Most samples averaged: a power of two from [`MIN_SHUTTER_SAMPLES`] to
35    /// [`MAX_SHUTTER_SAMPLES`]. Slow motion uses fewer.
36    #[serde(default = "Shutter::default_samples")]
37    pub samples: u32,
38}
39
40/// The [`Shutter`] field a [`crate::ModelError::InvalidShutter`] names.
41#[derive(Copy, Clone, Debug, Eq, PartialEq)]
42pub enum ShutterProblem {
43    /// [`Shutter::angle_degrees`] is not above 0 and at most [`MAX_SHUTTER_ANGLE_DEGREES`].
44    Angle,
45    /// [`Shutter::phase_degrees`] is beyond [`MAX_SHUTTER_PHASE_DEGREES`] either way.
46    Phase,
47    /// [`Shutter::samples`] is not a power of two from [`MIN_SHUTTER_SAMPLES`] to
48    /// [`MAX_SHUTTER_SAMPLES`].
49    Samples,
50}
51
52impl fmt::Display for ShutterProblem {
53    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
54        match self {
55            Self::Angle => write!(
56                formatter,
57                "the shutter angle must be above 0 and at most {MAX_SHUTTER_ANGLE_DEGREES} degrees"
58            ),
59            Self::Phase => write!(
60                formatter,
61                "the shutter phase must be within -{MAX_SHUTTER_PHASE_DEGREES}..={MAX_SHUTTER_PHASE_DEGREES} degrees"
62            ),
63            Self::Samples => write!(
64                formatter,
65                "the shutter samples must be a power of two from {MIN_SHUTTER_SAMPLES} to {MAX_SHUTTER_SAMPLES}"
66            ),
67        }
68    }
69}
70
71impl Default for Shutter {
72    fn default() -> Self {
73        Self {
74            angle_degrees: Self::default_angle(),
75            phase_degrees: Self::default_phase(),
76            samples: Self::default_samples(),
77        }
78    }
79}
80
81impl Shutter {
82    const fn default_angle() -> f32 {
83        180.0
84    }
85
86    const fn default_phase() -> f32 {
87        -90.0
88    }
89
90    const fn default_samples() -> u32 {
91        16
92    }
93
94    /// Whether every field has its default, in which case a document leaves the shutter out.
95    #[must_use]
96    pub fn is_default(&self) -> bool {
97        *self == Self::default()
98    }
99
100    /// Checks that every field is finite and in range.
101    ///
102    /// # Errors
103    /// Returns the first field out of range.
104    pub fn validate(&self) -> Result<(), ShutterProblem> {
105        if !(self.angle_degrees > 0.0 && self.angle_degrees <= MAX_SHUTTER_ANGLE_DEGREES) {
106            return Err(ShutterProblem::Angle);
107        }
108        if !(self.phase_degrees >= -MAX_SHUTTER_PHASE_DEGREES
109            && self.phase_degrees <= MAX_SHUTTER_PHASE_DEGREES)
110        {
111            return Err(ShutterProblem::Phase);
112        }
113        if !(self.samples.is_power_of_two()
114            && (MIN_SHUTTER_SAMPLES..=MAX_SHUTTER_SAMPLES).contains(&self.samples))
115        {
116            return Err(ShutterProblem::Samples);
117        }
118        Ok(())
119    }
120
121    /// The instant sample `index` of `count` reads for the frame at `time`: the midpoint of the
122    /// `index`-th of `count` equal parts of the open interval, to the nearest tick (a half rounds
123    /// up). One frame is `frame`'s.
124    #[must_use]
125    pub fn sample_time(
126        &self,
127        time: MediaTime,
128        frame: FrameRate,
129        index: u32,
130        count: u32,
131    ) -> MediaTime {
132        #[expect(
133            clippy::cast_precision_loss,
134            reason = "the tick rate is far below 2^53"
135        )]
136        let frame_ticks =
137            TICKS_PER_SECOND as f64 * f64::from(frame.denominator()) / f64::from(frame.numerator());
138        let open = f64::from(self.phase_degrees) / 360.0;
139        let length = f64::from(self.angle_degrees) / 360.0;
140        let part = (f64::from(index) + 0.5) / f64::from(count.max(1));
141        let shift = (frame_ticks * (open + length * part) + 0.5).floor();
142        #[expect(
143            clippy::cast_possible_truncation,
144            reason = "a float to integer cast saturates"
145        )]
146        MediaTime(time.ticks().saturating_add(shift as i64))
147    }
148}