bevy_simple_screenshot 0.1.2

A plug-and-play screenshot library for Bevy 0.17+ with ring-buffered capture and automatic saving
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
//! Performance A/B Test: Compare FPS with and without screenshot plugin
//!
//! Run with: `cargo run --example perf_abtest`
//!
//! This example measures the performance impact of the screenshot plugin by comparing
//! FPS metrics between runs with and without the plugin enabled.
//!
//! ## CLI Options
//!
//! ```sh
//! # Run WITHOUT screenshot plugin (baseline)
//! cargo run --example perf_abtest
//!
//! # Run WITH screenshot plugin enabled
//! cargo run --example perf_abtest -- --enable-screenshot
//!
//! # Customize test duration (default: 30 seconds)
//! cargo run --example perf_abtest -- --duration 30
//!
//! # Entity-only mode (with screenshot enabled)
//! cargo run --example perf_abtest -- --enable-screenshot --entity-only
//!
//! # Screenshot frequency options:
//! # Frame-based: every N frames (default: 60, i.e., ~1/sec at 60fps)
//! cargo run --example perf_abtest -- --enable-screenshot --screenshot-interval 60
//!
//! # Time-based: N screenshots per second (overrides --screenshot-interval)
//! cargo run --example perf_abtest -- --enable-screenshot --sps 1    # 1/sec (one-off)
//! cargo run --example perf_abtest -- --enable-screenshot --sps 0.5  # 1 every 2 sec (heartbeat)
//! cargo run --example perf_abtest -- --enable-screenshot --sps 12   # 12/sec (sequence)
//! cargo run --example perf_abtest -- --enable-screenshot --sps 24   # 24/sec (video)
//! ```
//!
//! **Font requirement** (only when --enable-screenshot with burn-in):
//! ```sh
//! curl -L -o FiraMono-Medium.ttf "https://github.com/mozilla/Fira/raw/master/ttf/FiraMono-Medium.ttf"
//! ```

use bevy::prelude::*;
use clap::{Parser, ValueEnum};

#[derive(Parser, Debug)]
#[command(name = "perf_abtest")]
#[command(about = "Performance A/B test comparing FPS with and without screenshot plugin")]
struct Args {
    /// Enable the screenshot plugin (A/B test: with vs without)
    #[arg(long)]
    enable_screenshot: bool,

    /// Test duration in seconds
    #[arg(long, default_value = "30")]
    duration: f32,

    /// Enable entity-only mode (crop screenshot to the moving object)
    #[arg(long, short = 'e')]
    entity_only: bool,

    /// Padding around entity in pixels (only used with --entity-only)
    #[arg(long, default_value = "20")]
    padding: u32,

    /// Take a screenshot every N frames (default: 60, ~1/sec at 60fps)
    /// Ignored if --sps is specified
    #[arg(long, default_value = "60")]
    screenshot_interval: u32,

    /// Screenshots per second (time-based, overrides --screenshot-interval)
    /// Examples: 0.1 (1 every 10s), 0.5 (1 every 2s), 1 (1/sec), 12, 24
    #[arg(long)]
    sps: Option<f32>,

    /// Position of burn-in text
    #[arg(long, short, default_value = "upper-right")]
    position: PositionArg,

    /// Font size in pixels
    #[arg(long, short = 's', default_value = "18")]
    font_size: f32,

    /// Show the screenshot key in burn-in
    #[arg(long, short = 'k')]
    show_key: bool,

    /// Show the description in burn-in
    #[arg(long, short = 'd')]
    show_description: bool,

    /// Disable burn-in text overlay
    #[arg(long)]
    no_burn_in: bool,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum PositionArg {
    UpperLeft,
    UpperRight,
    LowerLeft,
    LowerRight,
}

/// Resource to store test configuration.
#[derive(Resource)]
struct TestConfig {
    enable_screenshot: bool,
    entity_only: bool,
    padding: u32,
    /// Frame-based interval (used when sps is None)
    screenshot_interval: u32,
    /// Time-based interval in seconds (derived from sps)
    screenshot_time_interval: Option<f32>,
    duration: f32,
}

/// Resource to track FPS metrics.
#[derive(Resource)]
struct FpsMetrics {
    frame_times: Vec<f32>,
    start_time: f32,
    test_duration: f32,
    min_fps: f32,
    max_fps: f32,
    frame_count: u32,
}

impl FpsMetrics {
    fn new(test_duration: f32) -> Self {
        Self {
            frame_times: Vec::with_capacity(10000),
            start_time: 0.0,
            test_duration,
            min_fps: f32::MAX,
            max_fps: f32::MIN,
            frame_count: 0,
        }
    }

    fn record_frame(&mut self, delta_secs: f32) {
        if delta_secs > 0.0 {
            let fps = 1.0 / delta_secs;
            self.frame_times.push(delta_secs);
            self.min_fps = self.min_fps.min(fps);
            self.max_fps = self.max_fps.max(fps);
            self.frame_count += 1;
        }
    }

    fn average_fps(&self) -> f32 {
        if self.frame_times.is_empty() {
            return 0.0;
        }
        let total_time: f32 = self.frame_times.iter().sum();
        self.frame_times.len() as f32 / total_time
    }

    fn percentile_fps(&self, percentile: f32) -> f32 {
        if self.frame_times.is_empty() {
            return 0.0;
        }
        let mut sorted_fps: Vec<f32> = self
            .frame_times
            .iter()
            .filter(|&&t| t > 0.0)
            .map(|&t| 1.0 / t)
            .collect();
        sorted_fps.sort_by(|a, b| a.partial_cmp(b).unwrap());
        let idx = ((sorted_fps.len() as f32 * percentile / 100.0) as usize)
            .min(sorted_fps.len().saturating_sub(1));
        sorted_fps[idx]
    }

    fn print_summary(&self, enable_screenshot: bool) {
        let mode = if enable_screenshot {
            "WITH screenshot plugin"
        } else {
            "WITHOUT screenshot plugin (baseline)"
        };

        println!("\n╔══════════════════════════════════════════════════════════════╗");
        println!("║              PERFORMANCE A/B TEST RESULTS                    ║");
        println!("╠══════════════════════════════════════════════════════════════╣");
        println!("║  Mode: {:54} ║", mode);
        println!("╠══════════════════════════════════════════════════════════════╣");
        println!("║  Total Frames:     {:>10}                               ║", self.frame_count);
        println!("║  Test Duration:    {:>10.2} seconds                      ║", self.test_duration);
        println!("╠══════════════════════════════════════════════════════════════╣");
        println!("║  Average FPS:      {:>10.2}                               ║", self.average_fps());
        println!("║  Min FPS:          {:>10.2}                               ║", self.min_fps);
        println!("║  Max FPS:          {:>10.2}                               ║", self.max_fps);
        println!("║  1% Low FPS:       {:>10.2}                               ║", self.percentile_fps(1.0));
        println!("║  5% Low FPS:       {:>10.2}                               ║", self.percentile_fps(5.0));
        println!("╚══════════════════════════════════════════════════════════════╝");
        println!();

        if enable_screenshot {
            println!("To compare, run without --enable-screenshot for baseline metrics.");
        } else {
            println!("To compare, run with --enable-screenshot to measure plugin overhead.");
        }
    }
}

fn main() {
    let args = Args::parse();

    // Compute time interval from sps if specified
    let screenshot_time_interval = args.sps.map(|sps| {
        if sps <= 0.0 {
            panic!("--sps must be positive");
        }
        1.0 / sps
    });

    println!("╔══════════════════════════════════════════════════════════════╗");
    println!("║              PERFORMANCE A/B TEST                            ║");
    println!("╠══════════════════════════════════════════════════════════════╣");
    println!(
        "║  Screenshot Plugin: {:42} ║",
        if args.enable_screenshot { "ENABLED" } else { "DISABLED (baseline)" }
    );
    if args.enable_screenshot {
        println!(
            "║  Mode: {:54} ║",
            if args.entity_only { "entity-only" } else { "full window" }
        );
        if let Some(sps) = args.sps {
            if sps >= 1.0 {
                println!("║  Screenshot Rate: {:>5.1} per second (time-based)              ║", sps);
            } else {
                println!("║  Screenshot Rate: 1 every {:>4.1}s (time-based)                 ║", 1.0 / sps);
            }
        } else {
            println!("║  Screenshot Interval: every {:>3} frames                       ║", args.screenshot_interval);
        }
        if args.entity_only {
            println!("║  Padding: {:>3}px                                              ║", args.padding);
        }
    }
    println!("║  Test Duration: {:>5.1} seconds                                ║", args.duration);
    println!("╚══════════════════════════════════════════════════════════════╝");
    println!();

    let mut app = App::new();

    app.add_plugins(DefaultPlugins.set(WindowPlugin {
        primary_window: Some(Window {
            title: format!(
                "Perf A/B Test - Screenshot {}",
                if args.enable_screenshot { "ON" } else { "OFF" }
            ),
            resolution: (800u32, 600u32).into(),
            ..default()
        }),
        ..default()
    }));

    // Conditionally add screenshot plugin
    if args.enable_screenshot {
        use bevy_simple_screenshot::prelude::*;

        let burn_in = if args.no_burn_in {
            BurnInConfig::default() // default is disabled
        } else {
            let position: BurnInPosition = match args.position {
                PositionArg::UpperLeft => BurnInPosition::UpperLeft,
                PositionArg::UpperRight => BurnInPosition::UpperRight,
                PositionArg::LowerLeft => BurnInPosition::LowerLeft,
                PositionArg::LowerRight => BurnInPosition::LowerRight,
            };
            BurnInConfig::enabled()
                .with_font("FiraMono-Medium.ttf")
                .with_position(position)
                .with_font_size(args.font_size)
                .with_show_key(args.show_key)
                .with_show_description(args.show_description)
        };

        app.add_plugins(ScreenshotBufferPlugin::with_config(
            ScreenshotConfig::default()
                .with_output_dir(".screenshots/perf_test")
                .with_buffer_capacity(5)
                .with_burn_in(burn_in),
        ));
    }

    app.insert_resource(TestConfig {
        enable_screenshot: args.enable_screenshot,
        entity_only: args.entity_only,
        padding: args.padding,
        screenshot_interval: args.screenshot_interval,
        screenshot_time_interval,
        duration: args.duration,
    })
    .insert_resource(FpsMetrics::new(args.duration))
    .add_systems(Startup, setup)
    .add_systems(Update, (move_object, animate_color, track_fps));

    // Only add screenshot system if enabled
    if args.enable_screenshot {
        app.add_systems(Update, take_screenshots);
    }

    app.run();
}

#[derive(Component)]
struct MovingObject {
    speed: f32,
}

/// Component for color animation.
#[derive(Component)]
struct ColorAnimation {
    speed: f32,
    phase: f32,
}

/// Resource to track screenshot timing.
#[derive(Resource)]
struct ScreenshotTimer {
    frame_counter: u32,
    last_screenshot_time: f32,
}

impl Default for ScreenshotTimer {
    fn default() -> Self {
        Self {
            frame_counter: 0,
            last_screenshot_time: -1000.0, // Ensure first screenshot happens immediately
        }
    }
}

fn setup(mut commands: Commands) {
    commands.spawn(Camera2d::default());

    // Moving sprite with color animation
    commands.spawn((
        Sprite {
            color: Color::srgb(1.0, 0.0, 0.0),
            custom_size: Some(Vec2::new(50.0, 50.0)),
            ..default()
        },
        Transform::from_translation(Vec3::new(-300.0, 0.0, 0.0)),
        MovingObject { speed: 150.0 },
        ColorAnimation {
            speed: 0.381,
            phase: 0.0,
        },
    ));

    commands.insert_resource(ScreenshotTimer::default());
}

fn move_object(time: Res<Time>, mut query: Query<(&mut Transform, &MovingObject)>) {
    for (mut transform, obj) in &mut query {
        transform.translation.x += obj.speed * time.delta_secs();

        // Reset when going off screen
        if transform.translation.x > 350.0 {
            transform.translation.x = -350.0;
        }
    }
}

fn animate_color(time: Res<Time>, mut query: Query<(&mut Sprite, &mut ColorAnimation)>) {
    for (mut sprite, mut anim) in &mut query {
        anim.phase += time.delta_secs() * anim.speed;
        let t = (anim.phase * std::f32::consts::PI).sin().abs();
        sprite.color = Color::srgb(1.0 - t, t, 0.0);
    }
}

#[allow(deprecated)]
fn track_fps(
    time: Res<Time>,
    config: Res<TestConfig>,
    mut metrics: ResMut<FpsMetrics>,
    mut exit: bevy::ecs::event::EventWriter<AppExit>,
) {
    let elapsed = time.elapsed_secs();

    // Initialize start time on first frame
    if metrics.frame_count == 0 {
        metrics.start_time = elapsed;
    }

    metrics.record_frame(time.delta_secs());

    // Check if test duration has elapsed
    let test_elapsed = elapsed - metrics.start_time;
    if test_elapsed >= config.duration {
        metrics.print_summary(config.enable_screenshot);
        exit.write(AppExit::Success);
    }
}

fn take_screenshots(
    time: Res<Time>,
    config: Res<TestConfig>,
    mut timer: ResMut<ScreenshotTimer>,
    trigger: bevy_simple_screenshot::prelude::ScreenshotTrigger,
    entity_trigger: bevy_simple_screenshot::prelude::EntityScreenshotTrigger,
    query: Query<Entity, With<MovingObject>>,
) {
    use bevy_simple_screenshot::prelude::*;

    timer.frame_counter += 1;

    // Determine if we should take a screenshot
    let should_capture = if let Some(interval_secs) = config.screenshot_time_interval {
        // Time-based triggering
        let elapsed = time.elapsed_secs();
        if elapsed - timer.last_screenshot_time >= interval_secs {
            timer.last_screenshot_time = elapsed;
            true
        } else {
            false
        }
    } else {
        // Frame-based triggering
        timer.frame_counter % config.screenshot_interval == 0
    };

    if !should_capture {
        return;
    }

    if config.entity_only {
        // Entity-focused screenshot
        for entity in &query {
            let settings = EntityScreenshotSettings::default().with_padding(config.padding);
            screenshot_entity!(&entity_trigger, entity, "perf_test", "entity", settings);
        }
    } else {
        // Full window screenshot
        screenshot!(&trigger, "perf_test", "frame");
    }
}