Skip to main content

sim_logic/rendering/
render.rs

1//! Renderer-independent limits for visual extraction and presentation.
2
3use crate::three_d::ThreeDRenderLimits;
4use bevy_ecs::{
5    prelude::{Res, Resource},
6    system::SystemParam,
7};
8use sim_engine::{LogicalViewport, SceneBudget};
9
10#[path = "feedback.rs"]
11mod feedback;
12pub use feedback::{
13    PresentationBudgetRejection, PresentationBudgetResource, PresentationBudgetStage,
14    PresentationFeedback,
15};
16
17/// Validated logical viewport supplied to the current application frame.
18///
19/// FrameUpdate systems may use this for camera or screen-layout decisions.
20/// Headless callers provide the same value explicitly through `FrameRequest`.
21#[derive(Debug, Clone, Copy, PartialEq, Resource)]
22pub(crate) struct FrameViewportState(LogicalViewport);
23
24impl FrameViewportState {
25    pub const fn new(viewport: LogicalViewport) -> Self {
26        Self(viewport)
27    }
28
29    pub const fn logical(self) -> LogicalViewport {
30        self.0
31    }
32}
33
34/// Read-only validated logical viewport for the current FrameUpdate.
35///
36/// It is intentionally unavailable to FixedUpdate systems so a resize cannot
37/// silently affect fixed simulation rules.
38#[derive(SystemParam)]
39pub struct FrameViewport<'w> {
40    state: Res<'w, FrameViewportState>,
41}
42
43impl FrameViewport<'_> {
44    /// Returns the current logical pixel dimensions.
45    pub fn logical(&self) -> LogicalViewport {
46        self.state.logical()
47    }
48}
49
50/// Maximum world-space circles extracted by the default setup.
51pub const DEFAULT_MAX_WORLD_CIRCLES: usize = 10_000;
52
53/// Maximum world-space rectangles extracted by the default setup.
54pub const DEFAULT_MAX_WORLD_RECTANGLES: usize = 10_000;
55
56/// Maximum world-space line sources extracted by the default setup.
57pub const DEFAULT_MAX_WORLD_LINES: usize = 10_000;
58
59/// Maximum logical-screen rectangles extracted by the default setup.
60pub const DEFAULT_MAX_SCREEN_RECTANGLES: usize = 256;
61
62/// Bounded work accepted by the default world-space scene.
63pub const DEFAULT_WORLD_SCENE_BUDGET: SceneBudget = SceneBudget::new(
64    10_000,
65    0,
66    2_000_000,
67    8 * 1024 * 1024,
68    16 * 1024 * 1024,
69    128 * 1024 * 1024,
70    10_000,
71);
72
73/// Bounded work accepted by the default logical-screen scene.
74pub const DEFAULT_SCREEN_SCENE_BUDGET: SceneBudget =
75    SceneBudget::new(256, 65_536, 3_072, 256 * 1024, 512 * 1024, 512 * 1024, 256);
76
77/// Renderer-independent form of the default heterogeneous-frame budget.
78///
79/// Allows a world source and a screen source, with the sum of their default
80/// command, vertex, upload, and draw limits. No textures are included.
81pub const DEFAULT_FRAME_LIMITS: FrameLimits = FrameLimits::new(
82    2,
83    10_000 + 256,
84    2_000_000 + 3_072,
85    128 * 1024 * 1024 + 512 * 1024,
86    0,
87    10_000 + 256,
88);
89
90/// Work limits for a single composed presentation frame.
91///
92/// This type deliberately does not mention `wgpu` or Sim;Engine's
93/// renderer-only `FrameBudget`, so the same application configuration remains
94/// available in a headless build. The desktop bridge converts these values at
95/// its feature boundary.
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub struct FrameLimits {
98    max_passes: usize,
99    max_commands: usize,
100    max_vertices: usize,
101    max_upload_bytes: usize,
102    max_texture_bytes: usize,
103    max_draw_calls: usize,
104}
105
106impl FrameLimits {
107    /// Creates exact limits for one composed frame.
108    pub const fn new(
109        max_passes: usize,
110        max_commands: usize,
111        max_vertices: usize,
112        max_upload_bytes: usize,
113        max_texture_bytes: usize,
114        max_draw_calls: usize,
115    ) -> Self {
116        Self {
117            max_passes,
118            max_commands,
119            max_vertices,
120            max_upload_bytes,
121            max_texture_bytes,
122            max_draw_calls,
123        }
124    }
125
126    /// Returns the maximum number of ordered render sources.
127    pub const fn max_passes(self) -> usize {
128        self.max_passes
129    }
130
131    /// Returns the maximum number of referenced scene commands.
132    pub const fn max_commands(self) -> usize {
133        self.max_commands
134    }
135
136    /// Returns the maximum number of referenced or generated vertices.
137    pub const fn max_vertices(self) -> usize {
138        self.max_vertices
139    }
140
141    /// Returns the maximum bytes uploaded while preparing a frame.
142    pub const fn max_upload_bytes(self) -> usize {
143        self.max_upload_bytes
144    }
145
146    /// Returns the maximum nominal retained texture bytes referenced by a frame.
147    pub const fn max_texture_bytes(self) -> usize {
148        self.max_texture_bytes
149    }
150
151    /// Returns the maximum conservative draw-call count.
152    pub const fn max_draw_calls(self) -> usize {
153        self.max_draw_calls
154    }
155}
156
157impl Default for FrameLimits {
158    fn default() -> Self {
159        DEFAULT_FRAME_LIMITS
160    }
161}
162
163/// Configurable CPU extraction and presentation limits for the first slice.
164///
165/// All values are fixed before the application starts. Zero per-kind limits
166/// are valid. The world Scene command budget limits circles, rectangles, and
167/// nonzero lines together. Screen rectangles use a separate ScreenScene budget;
168/// the desktop compositor applies FrameLimits to their combined presentation.
169#[derive(Debug, Clone, Copy, PartialEq, Eq)]
170pub struct RenderLimits {
171    screen_scene_reuse: bool,
172    max_world_circles: usize,
173    max_world_rectangles: usize,
174    max_world_lines: usize,
175    max_screen_rectangles: usize,
176    max_screen_lines: usize,
177    max_screen_circles: usize,
178    max_screen_polylines: usize,
179    max_screen_polyline_points: usize,
180    max_screen_images: usize,
181    #[cfg(feature = "headless-text")]
182    max_screen_texts: usize,
183    #[cfg(feature = "headless-text")]
184    max_screen_text_bytes: usize,
185    #[cfg(feature = "headless-text")]
186    max_screen_text_glyphs: usize,
187    world_scene_budget: SceneBudget,
188    screen_scene_budget: SceneBudget,
189    frame_limits: FrameLimits,
190    three_d: ThreeDRenderLimits,
191}
192
193impl RenderLimits {
194    /// Creates limits with an explicit world circle cap and default remaining caps.
195    ///
196    /// Use [`RenderLimits::with_max_world_rectangles`] and
197    /// [`RenderLimits::with_max_world_lines`] to replace those caps without
198    /// changing this source-compatible constructor. Screen rectangles start
199    /// with [`DEFAULT_MAX_SCREEN_RECTANGLES`] and [`DEFAULT_SCREEN_SCENE_BUDGET`].
200    pub const fn new(
201        max_world_circles: usize,
202        world_scene_budget: SceneBudget,
203        frame_limits: FrameLimits,
204    ) -> Self {
205        Self {
206            screen_scene_reuse: true,
207            max_world_circles,
208            max_world_rectangles: DEFAULT_MAX_WORLD_RECTANGLES,
209            max_world_lines: DEFAULT_MAX_WORLD_LINES,
210            max_screen_rectangles: DEFAULT_MAX_SCREEN_RECTANGLES,
211            max_screen_lines: 256,
212            max_screen_circles: 256,
213            max_screen_polylines: 256,
214            max_screen_polyline_points: 65_536,
215            max_screen_images: 0,
216            #[cfg(feature = "headless-text")]
217            max_screen_texts: 0,
218            #[cfg(feature = "headless-text")]
219            max_screen_text_bytes: 0,
220            #[cfg(feature = "headless-text")]
221            max_screen_text_glyphs: 0,
222            world_scene_budget,
223            screen_scene_budget: DEFAULT_SCREEN_SCENE_BUDGET,
224            frame_limits,
225            three_d: ThreeDRenderLimits::new(0, 0, 0),
226        }
227    }
228
229    /// Whether exact validated screen snapshots/sub-runs may be reused on CPU.
230    /// Enabled by default; independent of desktop GPU retention and interpolation.
231    pub const fn screen_scene_reuse(self) -> bool {
232        self.screen_scene_reuse
233    }
234
235    /// Disables/enables CPU screen reuse for diagnostics with the same budgets.
236    /// Disabled mode reconstructs scenes without relaxing any checks. This does
237    /// not disable native Prepared/Compact retention or change rendered semantics.
238    pub const fn with_screen_scene_reuse(mut self, enabled: bool) -> Self {
239        self.screen_scene_reuse = enabled;
240        self
241    }
242
243    /// Returns the maximum number of extracted world circles.
244    pub const fn max_world_circles(self) -> usize {
245        self.max_world_circles
246    }
247
248    /// Returns the maximum number of extracted world rectangles.
249    pub const fn max_world_rectangles(self) -> usize {
250        self.max_world_rectangles
251    }
252
253    /// Returns the maximum number of enabled managed line sources inspected.
254    ///
255    /// Zero-vector sources count toward this limit even though they emit no
256    /// resolved record or Scene command.
257    pub const fn max_world_lines(self) -> usize {
258        self.max_world_lines
259    }
260
261    /// Returns the maximum number of enabled managed screen rectangles extracted.
262    pub const fn max_screen_rectangles(self) -> usize {
263        self.max_screen_rectangles
264    }
265
266    /// Returns the maximum screen-line source count; default 256, including empty clips.
267    pub const fn max_screen_lines(self) -> usize {
268        self.max_screen_lines
269    }
270    /// Returns the maximum screen-circle source count; default 256, including empty clips.
271    pub const fn max_screen_circles(self) -> usize {
272        self.max_screen_circles
273    }
274    /// Returns the enabled open-path count limit (256 by default), including hidden clips.
275    pub const fn max_screen_polylines(self) -> usize {
276        self.max_screen_polylines
277    }
278    /// Sets the open-path count limit independently of line/circle limits.
279    pub const fn with_max_screen_polylines(mut self, count: usize) -> Self {
280        self.max_screen_polylines = count;
281        self
282    }
283    /// Returns the total enabled path-point limit (65,536 by default), including
284    /// hidden clips and shared paths counted once for each occurrence.
285    pub const fn max_screen_polyline_points(self) -> usize {
286        self.max_screen_polyline_points
287    }
288    /// Sets aggregate open-path points inspected per frame, separate from the
289    /// SceneBudget charged for visible commands/points and per-path construction.
290    pub const fn with_max_screen_polyline_points(mut self, count: usize) -> Self {
291        self.max_screen_polyline_points = count;
292        self
293    }
294    /// Sets the screen-line count limit independently of shared scene work/byte limits.
295    pub const fn with_max_screen_lines(mut self, count: usize) -> Self {
296        self.max_screen_lines = count;
297        self
298    }
299    /// Sets the screen-circle count limit independently of shared scene work/byte limits.
300    pub const fn with_max_screen_circles(mut self, count: usize) -> Self {
301        self.max_screen_circles = count;
302        self
303    }
304
305    /// Returns the enabled screen-image count limit (zero by default).
306    pub const fn max_screen_images(self) -> usize {
307        self.max_screen_images
308    }
309
310    /// Returns the enabled screen-text source count limit, zero by default.
311    #[cfg(feature = "headless-text")]
312    pub const fn max_screen_texts(self) -> usize {
313        self.max_screen_texts
314    }
315
316    /// Returns the aggregate UTF-8 byte allowance for one screen-text snapshot.
317    ///
318    /// Each enabled visual counts its complete string, even when several share
319    /// the same prepared text. This is a work limit, not a retained-memory cap.
320    #[cfg(feature = "headless-text")]
321    pub const fn max_screen_text_bytes(self) -> usize {
322        self.max_screen_text_bytes
323    }
324
325    /// Returns the aggregate shaped-glyph allowance for screen text.
326    ///
327    /// Each enabled visual counts its prepared glyphs, including whitespace.
328    /// Multiple placements of one shared string each consume this allowance.
329    #[cfg(feature = "headless-text")]
330    pub const fn max_screen_text_glyphs(self) -> usize {
331        self.max_screen_text_glyphs
332    }
333
334    /// Enables a bounded number of screen labels without changing other caps.
335    ///
336    /// Text is disabled by default. Also set the text byte and glyph allowances
337    /// and desktop frame limits for glyph draws and font-atlas texture storage.
338    #[cfg(feature = "headless-text")]
339    pub const fn with_max_screen_texts(mut self, limit: usize) -> Self {
340        self.max_screen_texts = limit;
341        self
342    }
343
344    /// Replaces only the aggregate screen-text UTF-8 byte allowance.
345    ///
346    /// Zero permits empty strings only; text source and glyph caps still apply.
347    #[cfg(feature = "headless-text")]
348    pub const fn with_max_screen_text_bytes(mut self, limit: usize) -> Self {
349        self.max_screen_text_bytes = limit;
350        self
351    }
352
353    /// Replaces only the aggregate screen-text shaped-glyph allowance.
354    ///
355    /// Zero permits labels with no shaped glyphs; it does not disable their
356    /// source count or UTF-8 byte checks.
357    #[cfg(feature = "headless-text")]
358    pub const fn with_max_screen_text_glyphs(mut self, limit: usize) -> Self {
359        self.max_screen_text_glyphs = limit;
360        self
361    }
362
363    /// Returns opt-in object, triangle, and physical-target caps for real 3D.
364    pub const fn three_d(self) -> ThreeDRenderLimits {
365        self.three_d
366    }
367
368    /// Replaces only the independent 3D prepass limits.
369    ///
370    /// Final target composition also needs a pass and color texture allowance
371    /// in FrameLimits. The default zero limits do not enable 3D rendering.
372    pub const fn with_three_d_render_limits(mut self, limits: ThreeDRenderLimits) -> Self {
373        self.three_d = limits;
374        self
375    }
376
377    /// Enables a bounded number of screen images without changing other limits.
378    ///
379    /// The default is zero. Also configure FrameLimits with texture storage
380    /// and enough passes for images interleaved with rectangle runs. Each image
381    /// initially uses one compositor source; this is not an atlas-batch API.
382    pub const fn with_max_screen_images(mut self, limit: usize) -> Self {
383        self.max_screen_images = limit;
384        self
385    }
386
387    /// Replaces only aggregate presentation limits, preserving source/Scene caps.
388    pub const fn with_frame_limits(mut self, limits: FrameLimits) -> Self {
389        self.frame_limits = limits;
390        self
391    }
392
393    /// Replaces the rectangle staging limit without changing other budgets.
394    ///
395    /// Zero is valid and disables managed rectangle extraction. The Scene
396    /// command budget still limits the combined primitive count.
397    pub const fn with_max_world_rectangles(mut self, limit: usize) -> Self {
398        self.max_world_rectangles = limit;
399        self
400    }
401
402    /// Replaces the line-source staging limit without changing other budgets.
403    ///
404    /// Zero is valid and disables managed line extraction. The Scene command
405    /// budget still limits all nonzero primitives together.
406    pub const fn with_max_world_lines(mut self, limit: usize) -> Self {
407        self.max_world_lines = limit;
408        self
409    }
410
411    /// Replaces the screen rectangle staging cap without changing other limits.
412    ///
413    /// Zero disables screen rectangle extraction. The screen Scene command
414    /// budget may impose a smaller cap independently.
415    pub const fn with_max_screen_rectangles(mut self, limit: usize) -> Self {
416        self.max_screen_rectangles = limit;
417        self
418    }
419
420    /// Replaces the logical-screen Scene budget without changing other limits.
421    ///
422    /// Zero budget fields are valid and are enforced during extraction.
423    /// This does not change the desktop compositor's aggregate FrameLimits.
424    pub const fn with_screen_scene_budget(mut self, budget: SceneBudget) -> Self {
425        self.screen_scene_budget = budget;
426        self
427    }
428
429    /// Returns the budget applied to the world-space `Scene`.
430    pub const fn world_scene_budget(self) -> SceneBudget {
431        self.world_scene_budget
432    }
433
434    /// Returns the bounded work allowance for the logical-screen `ScreenScene`.
435    pub const fn screen_scene_budget(self) -> SceneBudget {
436        self.screen_scene_budget
437    }
438
439    /// Returns renderer-independent limits for one composed frame.
440    pub const fn frame_limits(self) -> FrameLimits {
441        self.frame_limits
442    }
443}
444
445impl Default for RenderLimits {
446    fn default() -> Self {
447        Self::new(
448            DEFAULT_MAX_WORLD_CIRCLES,
449            DEFAULT_WORLD_SCENE_BUDGET,
450            DEFAULT_FRAME_LIMITS,
451        )
452    }
453}
454
455#[cfg(test)]
456mod tests {
457    use super::*;
458
459    #[test]
460    fn defaults_match_the_first_slice_contract() {
461        let limits = RenderLimits::default();
462        let world = limits.world_scene_budget();
463        let screen = limits.screen_scene_budget();
464        let frame = limits.frame_limits();
465
466        assert_eq!(limits.max_world_circles(), 10_000);
467        assert_eq!(limits.max_world_rectangles(), 10_000);
468        assert_eq!(limits.max_world_lines(), 10_000);
469        assert_eq!(limits.max_screen_rectangles(), 256);
470        assert_eq!(world.max_commands(), 10_000);
471        assert_eq!(world.max_points(), 0);
472        assert_eq!(world.max_tessellated_vertices(), 2_000_000);
473        assert_eq!(world.max_retained_bytes(), 8 * 1024 * 1024);
474        assert_eq!(world.max_allocation_bytes(), 16 * 1024 * 1024);
475        assert_eq!(world.max_upload_bytes(), 128 * 1024 * 1024);
476        assert_eq!(world.max_draw_batches(), 10_000);
477
478        assert_eq!(screen.max_commands(), 256);
479        assert_eq!(screen.max_points(), 65_536);
480        assert_eq!(screen.max_tessellated_vertices(), 3_072);
481        assert_eq!(screen.max_retained_bytes(), 256 * 1024);
482        assert_eq!(screen.max_allocation_bytes(), 512 * 1024);
483        assert_eq!(screen.max_upload_bytes(), 512 * 1024);
484        assert_eq!(screen.max_draw_batches(), 256);
485
486        assert_eq!(frame.max_passes(), 2);
487        assert_eq!(
488            frame.max_commands(),
489            world.max_commands() + screen.max_commands()
490        );
491        assert_eq!(
492            frame.max_vertices(),
493            world.max_tessellated_vertices() + screen.max_tessellated_vertices()
494        );
495        assert_eq!(
496            frame.max_upload_bytes(),
497            world.max_upload_bytes() + screen.max_upload_bytes()
498        );
499        assert_eq!(frame.max_texture_bytes(), 0);
500        assert_eq!(
501            frame.max_draw_calls(),
502            world.max_draw_batches() + screen.max_draw_batches()
503        );
504    }
505
506    #[test]
507    fn rectangle_limit_builder_is_additive_and_allows_zero() {
508        let original = RenderLimits::new(7, DEFAULT_WORLD_SCENE_BUDGET, FrameLimits::default());
509        let changed = original.with_max_world_rectangles(0);
510
511        assert_eq!(changed.max_world_circles(), 7);
512        assert_eq!(changed.max_world_rectangles(), 0);
513        assert_eq!(changed.world_scene_budget(), original.world_scene_budget());
514        assert_eq!(changed.frame_limits(), original.frame_limits());
515    }
516
517    #[test]
518    fn line_limit_builder_is_additive_and_allows_zero() {
519        let original = RenderLimits::new(7, DEFAULT_WORLD_SCENE_BUDGET, FrameLimits::default());
520        let changed = original.with_max_world_lines(0);
521
522        assert_eq!(changed.max_world_circles(), 7);
523        assert_eq!(
524            changed.max_world_rectangles(),
525            original.max_world_rectangles()
526        );
527        assert_eq!(changed.max_world_lines(), 0);
528        assert_eq!(changed.world_scene_budget(), original.world_scene_budget());
529        assert_eq!(changed.frame_limits(), original.frame_limits());
530    }
531
532    #[test]
533    fn screen_limit_builders_preserve_world_and_custom_frame_limits() {
534        let frame = FrameLimits::new(1, 2, 3, 4, 5, 6);
535        let world = SceneBudget::new(7, 8, 9, 10, 11, 12, 13);
536        let original = RenderLimits::new(14, world, frame)
537            .with_max_world_rectangles(15)
538            .with_max_world_lines(16);
539        let zero = SceneBudget::new(0, 0, 0, 0, 0, 0, 0);
540        let changed = original
541            .with_max_screen_rectangles(0)
542            .with_screen_scene_budget(zero);
543        assert_eq!(changed.max_screen_rectangles(), 0);
544        assert_eq!(changed.screen_scene_budget(), zero);
545        assert_eq!(changed.max_world_circles(), original.max_world_circles());
546        assert_eq!(
547            changed.max_world_rectangles(),
548            original.max_world_rectangles()
549        );
550        assert_eq!(changed.max_world_lines(), original.max_world_lines());
551        assert_eq!(changed.world_scene_budget(), world);
552        assert_eq!(changed.frame_limits(), frame);
553        assert_eq!(
554            original.with_max_screen_rectangles(0).screen_scene_budget(),
555            original.screen_scene_budget()
556        );
557        assert_eq!(
558            original
559                .with_screen_scene_budget(zero)
560                .max_screen_rectangles(),
561            original.max_screen_rectangles()
562        );
563    }
564
565    #[test]
566    fn default_screen_budget_fits_every_allowed_square_rectangle()
567    -> Result<(), sim_engine::SceneError> {
568        use sim_engine::{
569            Color, LogicalScreenPosition, LogicalScreenVector, ScreenScene, ShapeStyle,
570        };
571
572        let limits = RenderLimits::default();
573        let mut scene = ScreenScene::with_budget(Color::TRANSPARENT, limits.screen_scene_budget())?;
574        for _ in 0..limits.max_screen_rectangles() {
575            scene.try_square_rect(
576                LogicalScreenPosition::default(),
577                LogicalScreenVector::new(16.0, 8.0),
578                ShapeStyle::filled(Color::WHITE),
579            )?;
580        }
581        assert_eq!(scene.command_count(), 256);
582        // Engine uses a conservative four-triangle estimate even for square corners.
583        assert_eq!(scene.statistics().estimated_tessellated_vertices(), 3_072);
584        assert_eq!(scene.statistics().estimated_draw_batches(), 256);
585        Ok(())
586    }
587}