sim-logic 0.1.0

A code-first application and logic layer for Sim;Engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
//! Renderer-independent limits for visual extraction and presentation.

use crate::three_d::ThreeDRenderLimits;
use bevy_ecs::{
    prelude::{Res, Resource},
    system::SystemParam,
};
use sim_engine::{LogicalViewport, SceneBudget};

#[path = "feedback.rs"]
mod feedback;
pub use feedback::{
    PresentationBudgetRejection, PresentationBudgetResource, PresentationBudgetStage,
    PresentationFeedback,
};

/// Validated logical viewport supplied to the current application frame.
///
/// FrameUpdate systems may use this for camera or screen-layout decisions.
/// Headless callers provide the same value explicitly through `FrameRequest`.
#[derive(Debug, Clone, Copy, PartialEq, Resource)]
pub(crate) struct FrameViewportState(LogicalViewport);

impl FrameViewportState {
    pub const fn new(viewport: LogicalViewport) -> Self {
        Self(viewport)
    }

    pub const fn logical(self) -> LogicalViewport {
        self.0
    }
}

/// Read-only validated logical viewport for the current FrameUpdate.
///
/// It is intentionally unavailable to FixedUpdate systems so a resize cannot
/// silently affect fixed simulation rules.
#[derive(SystemParam)]
pub struct FrameViewport<'w> {
    state: Res<'w, FrameViewportState>,
}

impl FrameViewport<'_> {
    /// Returns the current logical pixel dimensions.
    pub fn logical(&self) -> LogicalViewport {
        self.state.logical()
    }
}

/// Maximum world-space circles extracted by the default setup.
pub const DEFAULT_MAX_WORLD_CIRCLES: usize = 10_000;

/// Maximum world-space rectangles extracted by the default setup.
pub const DEFAULT_MAX_WORLD_RECTANGLES: usize = 10_000;

/// Maximum world-space line sources extracted by the default setup.
pub const DEFAULT_MAX_WORLD_LINES: usize = 10_000;

/// Maximum logical-screen rectangles extracted by the default setup.
pub const DEFAULT_MAX_SCREEN_RECTANGLES: usize = 256;

/// Bounded work accepted by the default world-space scene.
pub const DEFAULT_WORLD_SCENE_BUDGET: SceneBudget = SceneBudget::new(
    10_000,
    0,
    2_000_000,
    8 * 1024 * 1024,
    16 * 1024 * 1024,
    128 * 1024 * 1024,
    10_000,
);

/// Bounded work accepted by the default logical-screen scene.
pub const DEFAULT_SCREEN_SCENE_BUDGET: SceneBudget =
    SceneBudget::new(256, 65_536, 3_072, 256 * 1024, 512 * 1024, 512 * 1024, 256);

/// Renderer-independent form of the default heterogeneous-frame budget.
///
/// Allows a world source and a screen source, with the sum of their default
/// command, vertex, upload, and draw limits. No textures are included.
pub const DEFAULT_FRAME_LIMITS: FrameLimits = FrameLimits::new(
    2,
    10_000 + 256,
    2_000_000 + 3_072,
    128 * 1024 * 1024 + 512 * 1024,
    0,
    10_000 + 256,
);

/// Work limits for a single composed presentation frame.
///
/// This type deliberately does not mention `wgpu` or Sim;Engine's
/// renderer-only `FrameBudget`, so the same application configuration remains
/// available in a headless build. The desktop bridge converts these values at
/// its feature boundary.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FrameLimits {
    max_passes: usize,
    max_commands: usize,
    max_vertices: usize,
    max_upload_bytes: usize,
    max_texture_bytes: usize,
    max_draw_calls: usize,
}

impl FrameLimits {
    /// Creates exact limits for one composed frame.
    pub const fn new(
        max_passes: usize,
        max_commands: usize,
        max_vertices: usize,
        max_upload_bytes: usize,
        max_texture_bytes: usize,
        max_draw_calls: usize,
    ) -> Self {
        Self {
            max_passes,
            max_commands,
            max_vertices,
            max_upload_bytes,
            max_texture_bytes,
            max_draw_calls,
        }
    }

    /// Returns the maximum number of ordered render sources.
    pub const fn max_passes(self) -> usize {
        self.max_passes
    }

    /// Returns the maximum number of referenced scene commands.
    pub const fn max_commands(self) -> usize {
        self.max_commands
    }

    /// Returns the maximum number of referenced or generated vertices.
    pub const fn max_vertices(self) -> usize {
        self.max_vertices
    }

    /// Returns the maximum bytes uploaded while preparing a frame.
    pub const fn max_upload_bytes(self) -> usize {
        self.max_upload_bytes
    }

    /// Returns the maximum nominal retained texture bytes referenced by a frame.
    pub const fn max_texture_bytes(self) -> usize {
        self.max_texture_bytes
    }

    /// Returns the maximum conservative draw-call count.
    pub const fn max_draw_calls(self) -> usize {
        self.max_draw_calls
    }
}

impl Default for FrameLimits {
    fn default() -> Self {
        DEFAULT_FRAME_LIMITS
    }
}

/// Configurable CPU extraction and presentation limits for the first slice.
///
/// All values are fixed before the application starts. Zero per-kind limits
/// are valid. The world Scene command budget limits circles, rectangles, and
/// nonzero lines together. Screen rectangles use a separate ScreenScene budget;
/// the desktop compositor applies FrameLimits to their combined presentation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RenderLimits {
    screen_scene_reuse: bool,
    max_world_circles: usize,
    max_world_rectangles: usize,
    max_world_lines: usize,
    max_screen_rectangles: usize,
    max_screen_lines: usize,
    max_screen_circles: usize,
    max_screen_polylines: usize,
    max_screen_polyline_points: usize,
    max_screen_images: usize,
    #[cfg(feature = "headless-text")]
    max_screen_texts: usize,
    #[cfg(feature = "headless-text")]
    max_screen_text_bytes: usize,
    #[cfg(feature = "headless-text")]
    max_screen_text_glyphs: usize,
    world_scene_budget: SceneBudget,
    screen_scene_budget: SceneBudget,
    frame_limits: FrameLimits,
    three_d: ThreeDRenderLimits,
}

impl RenderLimits {
    /// Creates limits with an explicit world circle cap and default remaining caps.
    ///
    /// Use [`RenderLimits::with_max_world_rectangles`] and
    /// [`RenderLimits::with_max_world_lines`] to replace those caps without
    /// changing this source-compatible constructor. Screen rectangles start
    /// with [`DEFAULT_MAX_SCREEN_RECTANGLES`] and [`DEFAULT_SCREEN_SCENE_BUDGET`].
    pub const fn new(
        max_world_circles: usize,
        world_scene_budget: SceneBudget,
        frame_limits: FrameLimits,
    ) -> Self {
        Self {
            screen_scene_reuse: true,
            max_world_circles,
            max_world_rectangles: DEFAULT_MAX_WORLD_RECTANGLES,
            max_world_lines: DEFAULT_MAX_WORLD_LINES,
            max_screen_rectangles: DEFAULT_MAX_SCREEN_RECTANGLES,
            max_screen_lines: 256,
            max_screen_circles: 256,
            max_screen_polylines: 256,
            max_screen_polyline_points: 65_536,
            max_screen_images: 0,
            #[cfg(feature = "headless-text")]
            max_screen_texts: 0,
            #[cfg(feature = "headless-text")]
            max_screen_text_bytes: 0,
            #[cfg(feature = "headless-text")]
            max_screen_text_glyphs: 0,
            world_scene_budget,
            screen_scene_budget: DEFAULT_SCREEN_SCENE_BUDGET,
            frame_limits,
            three_d: ThreeDRenderLimits::new(0, 0, 0),
        }
    }

    /// Whether exact validated screen snapshots/sub-runs may be reused on CPU.
    /// Enabled by default; independent of desktop GPU retention and interpolation.
    pub const fn screen_scene_reuse(self) -> bool {
        self.screen_scene_reuse
    }

    /// Disables/enables CPU screen reuse for diagnostics with the same budgets.
    /// Disabled mode reconstructs scenes without relaxing any checks. This does
    /// not disable native Prepared/Compact retention or change rendered semantics.
    pub const fn with_screen_scene_reuse(mut self, enabled: bool) -> Self {
        self.screen_scene_reuse = enabled;
        self
    }

    /// Returns the maximum number of extracted world circles.
    pub const fn max_world_circles(self) -> usize {
        self.max_world_circles
    }

    /// Returns the maximum number of extracted world rectangles.
    pub const fn max_world_rectangles(self) -> usize {
        self.max_world_rectangles
    }

    /// Returns the maximum number of enabled managed line sources inspected.
    ///
    /// Zero-vector sources count toward this limit even though they emit no
    /// resolved record or Scene command.
    pub const fn max_world_lines(self) -> usize {
        self.max_world_lines
    }

    /// Returns the maximum number of enabled managed screen rectangles extracted.
    pub const fn max_screen_rectangles(self) -> usize {
        self.max_screen_rectangles
    }

    /// Returns the maximum screen-line source count; default 256, including empty clips.
    pub const fn max_screen_lines(self) -> usize {
        self.max_screen_lines
    }
    /// Returns the maximum screen-circle source count; default 256, including empty clips.
    pub const fn max_screen_circles(self) -> usize {
        self.max_screen_circles
    }
    /// Returns the enabled open-path count limit (256 by default), including hidden clips.
    pub const fn max_screen_polylines(self) -> usize {
        self.max_screen_polylines
    }
    /// Sets the open-path count limit independently of line/circle limits.
    pub const fn with_max_screen_polylines(mut self, count: usize) -> Self {
        self.max_screen_polylines = count;
        self
    }
    /// Returns the total enabled path-point limit (65,536 by default), including
    /// hidden clips and shared paths counted once for each occurrence.
    pub const fn max_screen_polyline_points(self) -> usize {
        self.max_screen_polyline_points
    }
    /// Sets aggregate open-path points inspected per frame, separate from the
    /// SceneBudget charged for visible commands/points and per-path construction.
    pub const fn with_max_screen_polyline_points(mut self, count: usize) -> Self {
        self.max_screen_polyline_points = count;
        self
    }
    /// Sets the screen-line count limit independently of shared scene work/byte limits.
    pub const fn with_max_screen_lines(mut self, count: usize) -> Self {
        self.max_screen_lines = count;
        self
    }
    /// Sets the screen-circle count limit independently of shared scene work/byte limits.
    pub const fn with_max_screen_circles(mut self, count: usize) -> Self {
        self.max_screen_circles = count;
        self
    }

    /// Returns the enabled screen-image count limit (zero by default).
    pub const fn max_screen_images(self) -> usize {
        self.max_screen_images
    }

    /// Returns the enabled screen-text source count limit, zero by default.
    #[cfg(feature = "headless-text")]
    pub const fn max_screen_texts(self) -> usize {
        self.max_screen_texts
    }

    /// Returns the aggregate UTF-8 byte allowance for one screen-text snapshot.
    ///
    /// Each enabled visual counts its complete string, even when several share
    /// the same prepared text. This is a work limit, not a retained-memory cap.
    #[cfg(feature = "headless-text")]
    pub const fn max_screen_text_bytes(self) -> usize {
        self.max_screen_text_bytes
    }

    /// Returns the aggregate shaped-glyph allowance for screen text.
    ///
    /// Each enabled visual counts its prepared glyphs, including whitespace.
    /// Multiple placements of one shared string each consume this allowance.
    #[cfg(feature = "headless-text")]
    pub const fn max_screen_text_glyphs(self) -> usize {
        self.max_screen_text_glyphs
    }

    /// Enables a bounded number of screen labels without changing other caps.
    ///
    /// Text is disabled by default. Also set the text byte and glyph allowances
    /// and desktop frame limits for glyph draws and font-atlas texture storage.
    #[cfg(feature = "headless-text")]
    pub const fn with_max_screen_texts(mut self, limit: usize) -> Self {
        self.max_screen_texts = limit;
        self
    }

    /// Replaces only the aggregate screen-text UTF-8 byte allowance.
    ///
    /// Zero permits empty strings only; text source and glyph caps still apply.
    #[cfg(feature = "headless-text")]
    pub const fn with_max_screen_text_bytes(mut self, limit: usize) -> Self {
        self.max_screen_text_bytes = limit;
        self
    }

    /// Replaces only the aggregate screen-text shaped-glyph allowance.
    ///
    /// Zero permits labels with no shaped glyphs; it does not disable their
    /// source count or UTF-8 byte checks.
    #[cfg(feature = "headless-text")]
    pub const fn with_max_screen_text_glyphs(mut self, limit: usize) -> Self {
        self.max_screen_text_glyphs = limit;
        self
    }

    /// Returns opt-in object, triangle, and physical-target caps for real 3D.
    pub const fn three_d(self) -> ThreeDRenderLimits {
        self.three_d
    }

    /// Replaces only the independent 3D prepass limits.
    ///
    /// Final target composition also needs a pass and color texture allowance
    /// in FrameLimits. The default zero limits do not enable 3D rendering.
    pub const fn with_three_d_render_limits(mut self, limits: ThreeDRenderLimits) -> Self {
        self.three_d = limits;
        self
    }

    /// Enables a bounded number of screen images without changing other limits.
    ///
    /// The default is zero. Also configure FrameLimits with texture storage
    /// and enough passes for images interleaved with rectangle runs. Each image
    /// initially uses one compositor source; this is not an atlas-batch API.
    pub const fn with_max_screen_images(mut self, limit: usize) -> Self {
        self.max_screen_images = limit;
        self
    }

    /// Replaces only aggregate presentation limits, preserving source/Scene caps.
    pub const fn with_frame_limits(mut self, limits: FrameLimits) -> Self {
        self.frame_limits = limits;
        self
    }

    /// Replaces the rectangle staging limit without changing other budgets.
    ///
    /// Zero is valid and disables managed rectangle extraction. The Scene
    /// command budget still limits the combined primitive count.
    pub const fn with_max_world_rectangles(mut self, limit: usize) -> Self {
        self.max_world_rectangles = limit;
        self
    }

    /// Replaces the line-source staging limit without changing other budgets.
    ///
    /// Zero is valid and disables managed line extraction. The Scene command
    /// budget still limits all nonzero primitives together.
    pub const fn with_max_world_lines(mut self, limit: usize) -> Self {
        self.max_world_lines = limit;
        self
    }

    /// Replaces the screen rectangle staging cap without changing other limits.
    ///
    /// Zero disables screen rectangle extraction. The screen Scene command
    /// budget may impose a smaller cap independently.
    pub const fn with_max_screen_rectangles(mut self, limit: usize) -> Self {
        self.max_screen_rectangles = limit;
        self
    }

    /// Replaces the logical-screen Scene budget without changing other limits.
    ///
    /// Zero budget fields are valid and are enforced during extraction.
    /// This does not change the desktop compositor's aggregate FrameLimits.
    pub const fn with_screen_scene_budget(mut self, budget: SceneBudget) -> Self {
        self.screen_scene_budget = budget;
        self
    }

    /// Returns the budget applied to the world-space `Scene`.
    pub const fn world_scene_budget(self) -> SceneBudget {
        self.world_scene_budget
    }

    /// Returns the bounded work allowance for the logical-screen `ScreenScene`.
    pub const fn screen_scene_budget(self) -> SceneBudget {
        self.screen_scene_budget
    }

    /// Returns renderer-independent limits for one composed frame.
    pub const fn frame_limits(self) -> FrameLimits {
        self.frame_limits
    }
}

impl Default for RenderLimits {
    fn default() -> Self {
        Self::new(
            DEFAULT_MAX_WORLD_CIRCLES,
            DEFAULT_WORLD_SCENE_BUDGET,
            DEFAULT_FRAME_LIMITS,
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn defaults_match_the_first_slice_contract() {
        let limits = RenderLimits::default();
        let world = limits.world_scene_budget();
        let screen = limits.screen_scene_budget();
        let frame = limits.frame_limits();

        assert_eq!(limits.max_world_circles(), 10_000);
        assert_eq!(limits.max_world_rectangles(), 10_000);
        assert_eq!(limits.max_world_lines(), 10_000);
        assert_eq!(limits.max_screen_rectangles(), 256);
        assert_eq!(world.max_commands(), 10_000);
        assert_eq!(world.max_points(), 0);
        assert_eq!(world.max_tessellated_vertices(), 2_000_000);
        assert_eq!(world.max_retained_bytes(), 8 * 1024 * 1024);
        assert_eq!(world.max_allocation_bytes(), 16 * 1024 * 1024);
        assert_eq!(world.max_upload_bytes(), 128 * 1024 * 1024);
        assert_eq!(world.max_draw_batches(), 10_000);

        assert_eq!(screen.max_commands(), 256);
        assert_eq!(screen.max_points(), 65_536);
        assert_eq!(screen.max_tessellated_vertices(), 3_072);
        assert_eq!(screen.max_retained_bytes(), 256 * 1024);
        assert_eq!(screen.max_allocation_bytes(), 512 * 1024);
        assert_eq!(screen.max_upload_bytes(), 512 * 1024);
        assert_eq!(screen.max_draw_batches(), 256);

        assert_eq!(frame.max_passes(), 2);
        assert_eq!(
            frame.max_commands(),
            world.max_commands() + screen.max_commands()
        );
        assert_eq!(
            frame.max_vertices(),
            world.max_tessellated_vertices() + screen.max_tessellated_vertices()
        );
        assert_eq!(
            frame.max_upload_bytes(),
            world.max_upload_bytes() + screen.max_upload_bytes()
        );
        assert_eq!(frame.max_texture_bytes(), 0);
        assert_eq!(
            frame.max_draw_calls(),
            world.max_draw_batches() + screen.max_draw_batches()
        );
    }

    #[test]
    fn rectangle_limit_builder_is_additive_and_allows_zero() {
        let original = RenderLimits::new(7, DEFAULT_WORLD_SCENE_BUDGET, FrameLimits::default());
        let changed = original.with_max_world_rectangles(0);

        assert_eq!(changed.max_world_circles(), 7);
        assert_eq!(changed.max_world_rectangles(), 0);
        assert_eq!(changed.world_scene_budget(), original.world_scene_budget());
        assert_eq!(changed.frame_limits(), original.frame_limits());
    }

    #[test]
    fn line_limit_builder_is_additive_and_allows_zero() {
        let original = RenderLimits::new(7, DEFAULT_WORLD_SCENE_BUDGET, FrameLimits::default());
        let changed = original.with_max_world_lines(0);

        assert_eq!(changed.max_world_circles(), 7);
        assert_eq!(
            changed.max_world_rectangles(),
            original.max_world_rectangles()
        );
        assert_eq!(changed.max_world_lines(), 0);
        assert_eq!(changed.world_scene_budget(), original.world_scene_budget());
        assert_eq!(changed.frame_limits(), original.frame_limits());
    }

    #[test]
    fn screen_limit_builders_preserve_world_and_custom_frame_limits() {
        let frame = FrameLimits::new(1, 2, 3, 4, 5, 6);
        let world = SceneBudget::new(7, 8, 9, 10, 11, 12, 13);
        let original = RenderLimits::new(14, world, frame)
            .with_max_world_rectangles(15)
            .with_max_world_lines(16);
        let zero = SceneBudget::new(0, 0, 0, 0, 0, 0, 0);
        let changed = original
            .with_max_screen_rectangles(0)
            .with_screen_scene_budget(zero);
        assert_eq!(changed.max_screen_rectangles(), 0);
        assert_eq!(changed.screen_scene_budget(), zero);
        assert_eq!(changed.max_world_circles(), original.max_world_circles());
        assert_eq!(
            changed.max_world_rectangles(),
            original.max_world_rectangles()
        );
        assert_eq!(changed.max_world_lines(), original.max_world_lines());
        assert_eq!(changed.world_scene_budget(), world);
        assert_eq!(changed.frame_limits(), frame);
        assert_eq!(
            original.with_max_screen_rectangles(0).screen_scene_budget(),
            original.screen_scene_budget()
        );
        assert_eq!(
            original
                .with_screen_scene_budget(zero)
                .max_screen_rectangles(),
            original.max_screen_rectangles()
        );
    }

    #[test]
    fn default_screen_budget_fits_every_allowed_square_rectangle()
    -> Result<(), sim_engine::SceneError> {
        use sim_engine::{
            Color, LogicalScreenPosition, LogicalScreenVector, ScreenScene, ShapeStyle,
        };

        let limits = RenderLimits::default();
        let mut scene = ScreenScene::with_budget(Color::TRANSPARENT, limits.screen_scene_budget())?;
        for _ in 0..limits.max_screen_rectangles() {
            scene.try_square_rect(
                LogicalScreenPosition::default(),
                LogicalScreenVector::new(16.0, 8.0),
                ShapeStyle::filled(Color::WHITE),
            )?;
        }
        assert_eq!(scene.command_count(), 256);
        // Engine uses a conservative four-triangle estimate even for square corners.
        assert_eq!(scene.statistics().estimated_tessellated_vertices(), 3_072);
        assert_eq!(scene.statistics().estimated_draw_batches(), 256);
        Ok(())
    }
}