Skip to main content

rayengine_core/
quality.rs

1//! CPU-only render quality validation and allocation planning.
2use crate::viewport::{ScaleMode, Viewport};
3use glam::Vec2;
4use std::fmt;
5
6/// Anti-aliasing applied to the game's offscreen world before UI composition.
7#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
8#[serde(rename_all = "snake_case")]
9pub enum AntiAliasing {
10    /// No edge filter (supersampling can still be selected independently).
11    #[default]
12    None,
13    /// Fast approximate anti-aliasing, a luminance-directed offscreen edge filter.
14    Fxaa,
15}
16
17/// Rendering controls, independent of camera and UI coordinates.
18#[derive(Clone, Copy, Debug, PartialEq)]
19pub struct RenderQuality {
20    /// Internal world pixels per native content pixel in each dimension: exactly 1 or 2.
21    /// 2 means four times the world pixel count, resolved with bilinear filtering.
22    pub render_scale: f32,
23    /// World edge filter. UI is composed afterwards at native resolution.
24    pub anti_aliasing: AntiAliasing,
25}
26impl Default for RenderQuality {
27    fn default() -> Self {
28        Self {
29            render_scale: 1.0,
30            anti_aliasing: AntiAliasing::None,
31        }
32    }
33}
34
35/// Invalid settings or a render allocation exceeding the SDK's bounds.
36#[derive(Clone, Debug, PartialEq, Eq)]
37pub struct QualityError(pub String);
38impl fmt::Display for QualityError {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        f.write_str(&self.0)
41    }
42}
43impl std::error::Error for QualityError {}
44
45/// Checked target dimensions and steady-state color/depth allocation estimate.
46#[derive(Clone, Copy, Debug, PartialEq, Eq)]
47pub struct RenderPlan {
48    /// World target dimensions (reference-sized in IntegerFit).
49    pub world: (u32, u32),
50    /// Native composition target dimensions, or world dimensions for pixel art.
51    pub output: (u32, u32),
52    /// Whether separate native UI and resolved output targets are required.
53    pub separate_ui: bool,
54    /// Conservative allocation estimate: 4-byte RGBA plus 4-byte depth per target pixel.
55    pub target_bytes: u64,
56}
57impl RenderQuality {
58    /// Maximum width or height of any target; the device limit may be lower.
59    pub const MAX_DIMENSION: u32 = 8192;
60    /// Maximum estimated total allocation, 512 MiB; resize drops old targets first.
61    pub const MAX_TARGET_BYTES: u64 = 512 * 1024 * 1024;
62
63    /// Checks supported quality/pixel-art combinations without opening a window.
64    pub fn validate(self, mode: ScaleMode) -> Result<(), QualityError> {
65        if !self.render_scale.is_finite() || ![1.0, 2.0].contains(&self.render_scale) {
66            return Err(QualityError(
67                "render_scale must be 1 (native) or 2 (supersampling)".into(),
68            ));
69        }
70        if mode == ScaleMode::IntegerFit && self != Self::default() {
71            return Err(QualityError(
72                "IntegerFit requires render_scale = 1 and anti_aliasing = none".into(),
73            ));
74        }
75        Ok(())
76    }
77
78    /// Plans targets from current logical viewport and physical framebuffer DPI.
79    /// Oversized requests fail explicitly rather than silently lowering quality.
80    pub fn plan(
81        self,
82        view: &Viewport,
83        dpi: Vec2,
84        mode: ScaleMode,
85    ) -> Result<RenderPlan, QualityError> {
86        self.validate(mode)?;
87        if !dpi.is_finite() || dpi.min_element() <= 0.0 {
88            return Err(QualityError(
89                "framebuffer DPI must be finite and positive".into(),
90            ));
91        }
92        let physical = if mode == ScaleMode::IntegerFit {
93            view.logical_size
94        } else {
95            view.size * dpi
96        };
97        let dimensions = |size: Vec2| -> Result<(u32, u32), QualityError> {
98            if !size.is_finite()
99                || size.min_element() <= 0.0
100                || size.round().max_element() > Self::MAX_DIMENSION as f32
101            {
102                return Err(QualityError(
103                    "render target dimensions exceed 8192 or are invalid".into(),
104                ));
105            }
106            Ok((
107                size.x.round().max(1.0) as u32,
108                size.y.round().max(1.0) as u32,
109            ))
110        };
111        let output = dimensions(physical)?;
112        // Scale the rounded native dimensions so 2x always means exactly twice each dimension.
113        let world = dimensions(Vec2::new(output.0 as f32, output.1 as f32) * self.render_scale)?;
114        let separate_ui = self != Self::default();
115        let pixels = |size: (u32, u32)| u64::from(size.0) * u64::from(size.1);
116        let target_bytes = 8 * (pixels(world) + if separate_ui { 2 * pixels(output) } else { 0 });
117        if target_bytes > Self::MAX_TARGET_BYTES {
118            return Err(QualityError(format!(
119                "render targets need {target_bytes} bytes; limit is {}",
120                Self::MAX_TARGET_BYTES
121            )));
122        }
123        Ok(RenderPlan {
124            world,
125            output,
126            separate_ui,
127            target_bytes,
128        })
129    }
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135    use crate::camera::Camera2D;
136    #[test]
137    fn invalid_and_pixel_art_combinations_fail() {
138        for scale in [0.0, 0.5, 1.5, 2.1, f32::NAN, f32::INFINITY] {
139            assert!(
140                RenderQuality {
141                    render_scale: scale,
142                    ..Default::default()
143                }
144                .validate(ScaleMode::Fit)
145                .is_err()
146            );
147        }
148        for quality in [
149            RenderQuality {
150                render_scale: 2.0,
151                ..Default::default()
152            },
153            RenderQuality {
154                anti_aliasing: AntiAliasing::Fxaa,
155                ..Default::default()
156            },
157        ] {
158            assert!(quality.validate(ScaleMode::IntegerFit).is_err());
159        }
160    }
161    #[test]
162    fn dpi_resize_quality_preserve_layout_camera_and_picking() {
163        for mode in [ScaleMode::Fit, ScaleMode::Expand, ScaleMode::IntegerFit] {
164            for window in [
165                Vec2::new(1280.0, 720.0),
166                Vec2::new(800.0, 1000.0),
167                Vec2::new(160.0, 90.0),
168            ] {
169                let view = Viewport::new(window, Vec2::new(960.0, 540.0), mode).unwrap();
170                let ui = view.logical_size * 0.4;
171                let screen = view.ui_to_screen(ui);
172                let camera = Camera2D::default();
173                let before = camera.screen_to_world(screen, &view).unwrap();
174                for dpi in [Vec2::ONE, Vec2::splat(2.0), Vec2::splat(1.25)] {
175                    let native = RenderQuality::default().plan(&view, dpi, mode).unwrap();
176                    if mode == ScaleMode::IntegerFit {
177                        assert_eq!(native.world, (960, 540));
178                        continue;
179                    }
180                    for aa in [AntiAliasing::None, AntiAliasing::Fxaa] {
181                        let plan = RenderQuality {
182                            render_scale: 2.0,
183                            anti_aliasing: aa,
184                        }
185                        .plan(&view, dpi, mode)
186                        .unwrap();
187                        assert_eq!(plan.output, native.world);
188                        assert_eq!(plan.world, (native.world.0 * 2, native.world.1 * 2));
189                        assert_eq!(plan.target_bytes, native.target_bytes * 6);
190                        assert!(view.screen_to_ui(screen).unwrap().abs_diff_eq(ui, 0.001));
191                        assert_eq!(camera.screen_to_world(screen, &view).unwrap(), before);
192                    }
193                }
194            }
195        }
196    }
197    #[test]
198    fn excessive_allocations_and_bad_dpi_fail_without_clamping() {
199        let large = Viewport::new(Vec2::new(8192.0, 8192.0), Vec2::ONE, ScaleMode::Fit).unwrap();
200        assert_eq!(
201            RenderQuality::default()
202                .plan(&large, Vec2::ONE, ScaleMode::Fit)
203                .unwrap()
204                .target_bytes,
205            RenderQuality::MAX_TARGET_BYTES
206        );
207        let high = RenderQuality {
208            render_scale: 2.0,
209            ..Default::default()
210        };
211        assert!(high.plan(&large, Vec2::ONE, ScaleMode::Fit).is_err());
212        let budget = Viewport::new(Vec2::splat(4096.0), Vec2::ONE, ScaleMode::Fit).unwrap();
213        assert!(
214            high.plan(&budget, Vec2::ONE, ScaleMode::Fit)
215                .unwrap_err()
216                .0
217                .contains("bytes")
218        );
219        for dpi in [Vec2::ZERO, Vec2::splat(f32::NAN), Vec2::splat(3.0)] {
220            assert!(
221                RenderQuality::default()
222                    .plan(&large, dpi, ScaleMode::Fit)
223                    .is_err()
224            );
225        }
226    }
227}