Skip to main content

alpha2_engine/
quality.rs

1use alpha2_model::ProjectSettings;
2use alpha2_render::RenderSize;
3
4use crate::EngineError;
5
6// Must match the model's canvas limit so any accepted canvas renders at full scale.
7const _: () = assert!(
8    alpha2_model::MAX_CANVAS_DIMENSION == RenderSize::MAX_DIMENSION
9        && alpha2_model::MAX_CANVAS_PIXELS == RenderSize::MAX_PIXELS
10);
11
12/// Runtime quality controls shared by real-time playback and export.
13#[derive(Copy, Clone, Debug, PartialEq)]
14#[non_exhaustive]
15pub struct QualityProfile {
16    /// Output scale relative to project dimensions.
17    pub resolution_scale: f32,
18    /// Maximum sampling work available to a filter pass.
19    pub max_filter_samples: u32,
20    /// Soft budget available to reusable GPU textures.
21    pub texture_budget_bytes: u64,
22    /// Most shutter samples a layer marked for motion blur is averaged from: `None` for as many
23    /// as the project's shutter allows, otherwise at most this many, rounded down to a power of
24    /// two. Below two no layer is averaged, and a frame is drawn as if nothing were marked.
25    pub shutter_samples: Option<u32>,
26}
27
28impl Default for QualityProfile {
29    fn default() -> Self {
30        Self::export()
31    }
32}
33
34impl QualityProfile {
35    /// Largest supported multiplier for project dimensions.
36    pub const MAX_RESOLUTION_SCALE: f32 = 8.0;
37    /// Largest per-pass filter sampling budget
38    /// ([`alpha2_render::RenderQualityControls::MAX_FILTER_SAMPLES`]). Tier B applies less.
39    pub const MAX_FILTER_SAMPLES: u32 = alpha2_render::RenderQualityControls::MAX_FILTER_SAMPLES;
40    /// Largest accepted [`Self::shutter_samples`].
41    pub const MAX_SHUTTER_SAMPLES: u32 = alpha2_model::MAX_SHUTTER_SAMPLES;
42    /// The shutter samples of [`Self::preview`].
43    pub const PREVIEW_SHUTTER_SAMPLES: u32 = 8;
44    /// Smallest useful reusable-texture pool budget.
45    pub const MIN_TEXTURE_BUDGET_BYTES: u64 = 1024 * 1024;
46    /// Largest accepted reusable-texture pool budget.
47    pub const MAX_TEXTURE_BUDGET_BYTES: u64 = 64 * 1024 * 1024 * 1024;
48
49    /// Full-resolution deterministic export defaults.
50    #[must_use]
51    pub const fn export() -> Self {
52        Self {
53            resolution_scale: 1.0,
54            max_filter_samples: 64,
55            texture_budget_bytes: 512 * 1024 * 1024,
56            shutter_samples: None,
57        }
58    }
59
60    /// Responsive half-resolution playback defaults.
61    #[must_use]
62    pub const fn preview() -> Self {
63        Self {
64            resolution_scale: 0.5,
65            max_filter_samples: 32,
66            texture_budget_bytes: 256 * 1024 * 1024,
67            shutter_samples: Some(Self::PREVIEW_SHUTTER_SAMPLES),
68        }
69    }
70
71    /// This profile with `scale` as its dimension multiplier (checked by [`Self::validate`]).
72    #[must_use]
73    pub const fn with_resolution_scale(mut self, scale: f32) -> Self {
74        self.resolution_scale = scale;
75        self
76    }
77
78    /// This profile averaging marked layers from at most `samples` shutter samples (checked by
79    /// [`Self::validate`]); `None` leaves the project's.
80    #[must_use]
81    pub const fn with_shutter_samples(mut self, samples: Option<u32>) -> Self {
82        self.shutter_samples = samples;
83        self
84    }
85
86    /// Applies [`Self::shutter_samples`] to an evaluated frame before it is drawn.
87    pub fn cap_shutter(self, frame: &mut alpha2_eval::FrameDesc<'_>) {
88        if let Some(samples) = self.shutter_samples {
89            frame.shutter = frame.shutter.and_then(|shutter| shutter.capped(samples));
90        }
91    }
92
93    /// Checks that all controls are finite and within runtime-safe bounds.
94    ///
95    /// # Errors
96    /// Returns [`EngineError::InvalidQualityProfile`] for out-of-range values.
97    pub fn validate(self) -> Result<(), EngineError> {
98        if self.resolution_scale.is_finite()
99            && self.resolution_scale > 0.0
100            && self.resolution_scale <= Self::MAX_RESOLUTION_SCALE
101            && (1..=Self::MAX_FILTER_SAMPLES).contains(&self.max_filter_samples)
102            && (Self::MIN_TEXTURE_BUDGET_BYTES..=Self::MAX_TEXTURE_BUDGET_BYTES)
103                .contains(&self.texture_budget_bytes)
104            && self
105                .shutter_samples
106                .is_none_or(|samples| samples <= Self::MAX_SHUTTER_SAMPLES)
107        {
108            Ok(())
109        } else {
110            Err(EngineError::InvalidQualityProfile)
111        }
112    }
113
114    /// Resolves scaled project dimensions, rounding to the nearest pixel.
115    ///
116    /// # Errors
117    /// Returns [`EngineError`] for an invalid profile or unrepresentable size.
118    pub fn render_size(self, settings: &ProjectSettings) -> Result<RenderSize, EngineError> {
119        self.validate()?;
120        let width = scaled_dimension(settings.width, self.resolution_scale)?;
121        let height = scaled_dimension(settings.height, self.resolution_scale)?;
122        RenderSize::new(width, height).map_err(EngineError::from)
123    }
124
125    /// The 4:2:0 export size: the [render size](Self::render_size), which must be even. Export
126    /// entry points check this before rendering so the error names the nearest even size.
127    ///
128    /// # Errors
129    /// Returns [`EngineError::OddExportDimensions`], or what
130    /// [`Self::render_size`] returns.
131    pub fn export_size(self, settings: &ProjectSettings) -> Result<RenderSize, EngineError> {
132        let size = self.render_size(settings)?;
133        if size.width % 2 != 0 || size.height % 2 != 0 {
134            let even = |value: u32| match value {
135                1 => 2,
136                odd if odd % 2 != 0 => odd - 1,
137                even => even,
138            };
139            return Err(EngineError::OddExportDimensions {
140                width: size.width,
141                height: size.height,
142                suggested: (even(size.width), even(size.height)),
143            });
144        }
145        Ok(size)
146    }
147
148    /// Captures project, adapter, driver, backend, and quality facts for a benchmark.
149    ///
150    /// # Errors
151    /// Returns [`EngineError`] when the profile cannot resolve output dimensions.
152    pub fn benchmark_metadata(
153        self,
154        project: impl Into<String>,
155        settings: &ProjectSettings,
156        renderer: &alpha2_render::Renderer,
157    ) -> Result<alpha2_render::BenchmarkMetadata, EngineError> {
158        let size = self.render_size(settings)?;
159        Ok(alpha2_render::BenchmarkMetadata {
160            project: project.into(),
161            alpha2_version: env!("CARGO_PKG_VERSION"),
162            adapter: renderer.diagnostics().adapter,
163            dimensions: (size.width, size.height),
164            resolution_scale: self.resolution_scale,
165            max_filter_samples: self.max_filter_samples,
166            texture_budget_bytes: self.texture_budget_bytes,
167        })
168    }
169}
170
171fn scaled_dimension(value: u32, scale: f32) -> Result<u32, EngineError> {
172    let scaled = f64::from(value) * f64::from(scale);
173    if scaled.is_finite() && scaled <= f64::from(u32::MAX) {
174        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
175        Ok((scaled.round() as u32).max(1))
176    } else {
177        Err(EngineError::OutOfRange)
178    }
179}
180
181#[cfg(test)]
182mod tests {
183    use alpha2_time::FrameRate;
184
185    use super::*;
186
187    #[test]
188    fn quality_scales_dimensions_and_rejects_zero() {
189        let settings = ProjectSettings::new(
190            1920,
191            1080,
192            FrameRate::new(30, 1).expect("valid rate"),
193            48_000,
194        )
195        .expect("valid settings");
196        assert_eq!(
197            QualityProfile::preview()
198                .render_size(&settings)
199                .expect("valid size"),
200            RenderSize::new(960, 540).expect("valid size")
201        );
202        assert_eq!(
203            QualityProfile {
204                resolution_scale: 0.0,
205                ..QualityProfile::default()
206            }
207            .validate(),
208            Err(EngineError::InvalidQualityProfile)
209        );
210        assert_eq!(
211            QualityProfile {
212                texture_budget_bytes: 1,
213                ..QualityProfile::default()
214            }
215            .validate(),
216            Err(EngineError::InvalidQualityProfile)
217        );
218    }
219
220    #[test]
221    fn a_preview_scale_sizes_the_render_and_is_validated() {
222        let settings = |width, height| {
223            ProjectSettings::new(
224                width,
225                height,
226                FrameRate::new(30, 1).expect("valid rate"),
227                48_000,
228            )
229            .expect("valid settings")
230        };
231        let size = |scale: f32, width, height| {
232            QualityProfile::preview()
233                .with_resolution_scale(scale)
234                .render_size(&settings(width, height))
235                .map(|size| (size.width, size.height))
236        };
237        assert_eq!(size(0.5, 1280, 720), Ok((640, 360)));
238        assert_eq!(size(1.0, 1280, 720), Ok((1280, 720)));
239        // An odd document rounds to the nearest pixel.
240        assert_eq!(size(0.5, 1281, 721), Ok((641, 361)));
241        assert_eq!(size(0.25, 1282, 722), Ok((321, 181)));
242        for scale in [0.0, -1.0, 8.5, f32::NAN, f32::INFINITY] {
243            assert_eq!(
244                QualityProfile::preview()
245                    .with_resolution_scale(scale)
246                    .validate(),
247                Err(EngineError::InvalidQualityProfile),
248                "{scale}"
249            );
250        }
251        assert_eq!(
252            QualityProfile::preview()
253                .with_resolution_scale(QualityProfile::MAX_RESOLUTION_SCALE)
254                .validate(),
255            Ok(())
256        );
257    }
258}