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
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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
//! Screenshot capture system and request handling.

use bevy::camera::primitives::Aabb;
use bevy::diagnostic::FrameCount;
use bevy::ecs::system::SystemParam;
use bevy::prelude::*;
use bevy::render::view::screenshot::{Screenshot, ScreenshotCaptured};
use bevy::sprite::Sprite;
use bevy::window::PrimaryWindow;
use chrono::{DateTime, Local};
use crossbeam_channel::{Receiver, Sender};

use crate::buffer::{CapturedScreenshot, ImageValidation, ScreenshotBufferManager};
use crate::save::SaveTaskSender;

/// A rectangular region to crop from the full screenshot.
#[derive(Clone, Debug)]
pub struct CropRegion {
    /// X coordinate of the top-left corner (in pixels).
    pub x: u32,
    /// Y coordinate of the top-left corner (in pixels).
    pub y: u32,
    /// Width of the crop region (in pixels).
    pub width: u32,
    /// Height of the crop region (in pixels).
    pub height: u32,
}

impl CropRegion {
    /// Create a new crop region.
    pub fn new(x: u32, y: u32, width: u32, height: u32) -> Self {
        Self {
            x,
            y,
            width,
            height,
        }
    }

    /// Clamp the crop region to fit within the given image dimensions.
    /// Returns None if the region is completely outside the image bounds.
    pub fn clamp_to_bounds(self, image_width: u32, image_height: u32) -> Option<Self> {
        // If starting position is beyond image, nothing to crop
        if self.x >= image_width || self.y >= image_height {
            return None;
        }

        // Clamp width and height to not exceed image bounds
        let clamped_width = (self.width).min(image_width.saturating_sub(self.x));
        let clamped_height = (self.height).min(image_height.saturating_sub(self.y));

        // If clamped dimensions are zero, nothing to crop
        if clamped_width == 0 || clamped_height == 0 {
            return None;
        }

        Some(Self {
            x: self.x,
            y: self.y,
            width: clamped_width,
            height: clamped_height,
        })
    }
}

/// Settings for entity-focused screenshots.
///
/// Use `Default::default()` to get sensible defaults. New fields may be added
/// in future versions with defaults, so always construct using `Default` or
/// the builder methods.
#[derive(Clone, Debug)]
pub struct EntityScreenshotSettings {
    /// Padding around the entity in pixels (default: 20).
    pub padding: u32,
    /// Fallback size (width, height) when entity has no Sprite/Aabb (default: 64x64).
    pub fallback_size: (u32, u32),
}

impl Default for EntityScreenshotSettings {
    fn default() -> Self {
        Self {
            padding: 20,
            fallback_size: (64, 64),
        }
    }
}

impl EntityScreenshotSettings {
    /// Create settings with custom padding.
    pub fn with_padding(mut self, padding: u32) -> Self {
        self.padding = padding;
        self
    }

    /// Create settings with custom fallback size.
    pub fn with_fallback_size(mut self, width: u32, height: u32) -> Self {
        self.fallback_size = (width, height);
        self
    }
}

/// Resource that tracks the render system readiness.
///
/// Screenshots taken before the render system is ready will result in empty or
/// invalid images. This resource tracks whether we've seen at least one successful
/// frame render.
#[derive(Resource, Default)]
pub struct RenderReadiness {
    /// Number of frames that have been rendered since the plugin was initialized.
    pub frames_rendered: u32,
    /// Whether the render system is considered ready for screenshots.
    pub is_ready: bool,
}

impl RenderReadiness {
    /// Minimum number of frames to wait before considering render ready.
    /// This accounts for GPU initialization and first-frame setup.
    pub const MIN_FRAMES_FOR_READY: u32 = 3;

    /// Check if render is ready for screenshots.
    pub fn ready(&self) -> bool {
        self.is_ready && self.frames_rendered >= Self::MIN_FRAMES_FOR_READY
    }
}

/// Resource that tracks whether the application is shutting down.
///
/// When the app begins shutdown, screenshot captures should be skipped
/// to prevent capturing invalid frame data.
#[derive(Resource, Default)]
pub struct ShutdownState {
    /// Whether shutdown has been initiated.
    pub is_shutting_down: bool,
}

/// A request to capture a screenshot.
#[derive(Message, Clone)]
pub struct ScreenshotRequest {
    /// The key/category for this screenshot.
    pub key: String,

    /// User-provided description.
    pub description: String,

    /// Timestamp when the request was made.
    pub timestamp: DateTime<Local>,

    /// Optional crop region to extract from the full screenshot.
    pub crop_region: Option<CropRegion>,
}

impl ScreenshotRequest {
    /// Create a new screenshot request.
    pub fn new(key: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            key: key.into(),
            description: description.into(),
            timestamp: Local::now(),
            crop_region: None,
        }
    }

    /// Create a new screenshot request with a crop region.
    pub fn with_crop(
        key: impl Into<String>,
        description: impl Into<String>,
        crop_region: CropRegion,
    ) -> Self {
        Self {
            key: key.into(),
            description: description.into(),
            timestamp: Local::now(),
            crop_region: Some(crop_region),
        }
    }
}

/// Resource for sending screenshot requests.
#[derive(Resource)]
pub struct ScreenshotRequestSender(pub Sender<ScreenshotRequest>);

/// Resource for receiving screenshot requests.
#[derive(Resource)]
pub struct ScreenshotRequestReceiver(pub Receiver<ScreenshotRequest>);

/// System parameter for triggering screenshots from game systems.
#[derive(SystemParam)]
pub struct ScreenshotTrigger<'w> {
    sender: Res<'w, ScreenshotRequestSender>,
}

impl ScreenshotTrigger<'_> {
    /// Request a screenshot with the default key.
    pub fn capture(&self, description: impl Into<String>) {
        self.capture_with_key("default", description);
    }

    /// Request a screenshot with a specific key/category.
    pub fn capture_with_key(&self, key: impl Into<String>, description: impl Into<String>) {
        let request = ScreenshotRequest::new(key, description);
        // Use try_send to never block - drop if channel full
        let _ = self.sender.0.try_send(request);
    }
}

/// Marker component to track pending screenshot metadata.
#[derive(Component)]
pub struct PendingScreenshot {
    pub key: String,
    pub description: String,
    pub timestamp: DateTime<Local>,
    /// The frame number when the screenshot was requested.
    /// This is the render frame (1 behind game thread).
    pub frame_number: u32,
    /// Optional crop region to extract from the full screenshot.
    pub crop_region: Option<CropRegion>,
}

/// System that processes screenshot requests and spawns Screenshot components.
pub fn process_screenshot_requests(
    mut commands: Commands,
    receiver: Res<ScreenshotRequestReceiver>,
    windows: Query<Entity, With<PrimaryWindow>>,
    render_readiness: Res<RenderReadiness>,
    shutdown_state: Res<ShutdownState>,
    frame_count: Res<FrameCount>,
) {
    // Skip processing if shutting down
    if shutdown_state.is_shutting_down {
        // Drain and discard requests during shutdown
        while receiver.0.try_recv().is_ok() {}
        return;
    }

    // Check render readiness
    if !render_readiness.ready() {
        // Drain and discard requests, but warn the user
        let mut dropped_count = 0;
        while receiver.0.try_recv().is_ok() {
            dropped_count += 1;
        }
        if dropped_count > 0 {
            bevy::log::warn!(
                "Dropped {} screenshot request(s): render system not ready yet. \
                 Wait at least {} frames after startup before taking screenshots. \
                 (Current frame: {})",
                dropped_count,
                RenderReadiness::MIN_FRAMES_FOR_READY,
                render_readiness.frames_rendered
            );
        }
        return;
    }

    // Get the current frame count. Since FrameCount is updated in Last schedule,
    // reading it during Update gives us the previous frame's count, which
    // represents the last completed render frame (1 behind game thread).
    let current_frame = frame_count.0;

    // Drain all pending requests
    while let Ok(request) = receiver.0.try_recv() {
        let Ok(_window_entity) = windows.single() else {
            bevy::log::warn!("No primary window found for screenshot");
            continue;
        };

        // Spawn a screenshot request entity with metadata
        commands.spawn((
            Screenshot::primary_window(),
            PendingScreenshot {
                key: request.key,
                description: request.description,
                timestamp: request.timestamp,
                frame_number: current_frame,
                crop_region: request.crop_region,
            },
        ));
    }
}

/// System that updates render readiness tracking.
pub fn update_render_readiness(mut readiness: ResMut<RenderReadiness>) {
    readiness.frames_rendered = readiness.frames_rendered.saturating_add(1);
    if readiness.frames_rendered >= RenderReadiness::MIN_FRAMES_FOR_READY {
        readiness.is_ready = true;
    }
}

/// System that detects application shutdown.
pub fn detect_shutdown(
    mut shutdown_state: ResMut<ShutdownState>,
    mut exit_events: MessageReader<AppExit>,
) {
    for _ in exit_events.read() {
        if !shutdown_state.is_shutting_down {
            bevy::log::info!("Screenshot system: shutdown detected, stopping capture");
            shutdown_state.is_shutting_down = true;
        }
    }
}

/// System that handles captured screenshots via observer.
pub fn handle_screenshot_captured(
    trigger: On<ScreenshotCaptured>,
    mut commands: Commands,
    pending_query: Query<&PendingScreenshot>,
    mut buffer_manager: ResMut<ScreenshotBufferManager>,
    save_sender: Res<SaveTaskSender>,
    shutdown_state: Res<ShutdownState>,
) {
    let entity = trigger.entity;
    let captured = trigger.event();

    // Skip if shutting down
    if shutdown_state.is_shutting_down {
        commands.entity(entity).despawn();
        bevy::log::debug!("Screenshot discarded: application is shutting down");
        return;
    }

    // Get the pending screenshot metadata
    let Ok(pending) = pending_query.get(entity) else {
        bevy::log::warn!("Screenshot captured but no pending metadata found");
        return;
    };

    // ScreenshotCaptured contains the image
    let screenshot = CapturedScreenshot {
        image: captured.image.clone(),
        timestamp: pending.timestamp,
        description: pending.description.clone(),
        key: pending.key.clone(),
        frame_number: pending.frame_number,
        crop_region: pending.crop_region.clone(),
    };

    // Validate the captured image
    match screenshot.validate() {
        ImageValidation::Valid => {
            // Push to ring buffer
            buffer_manager.push(screenshot.clone());

            // Queue for disk save if auto_save enabled
            let config = buffer_manager.config();
            let should_save = config
                .keys
                .get(&pending.key)
                .and_then(|k| k.auto_save)
                .unwrap_or(config.auto_save);

            if should_save {
                let _ = save_sender.0.try_send(screenshot);
            }

            bevy::log::debug!(
                "Screenshot captured: key='{}', description='{}'",
                pending.key,
                pending.description
            );
        }
        ImageValidation::ZeroDimensions { width, height } => {
            bevy::log::warn!(
                "Screenshot discarded (key='{}', description='{}'): \
                 image has zero dimensions ({}x{}). \
                 This may indicate the screenshot was captured before the render system was ready.",
                pending.key,
                pending.description,
                width,
                height
            );
        }
        ImageValidation::EmptyData => {
            bevy::log::warn!(
                "Screenshot discarded (key='{}', description='{}'): \
                 image has empty data. \
                 This may indicate the screenshot was captured during shutdown or before render was ready.",
                pending.key,
                pending.description
            );
        }
        ImageValidation::DataSizeMismatch {
            expected,
            actual,
            width,
            height,
        } => {
            bevy::log::warn!(
                "Screenshot discarded (key='{}', description='{}'): \
                 image data size mismatch (expected {} bytes for {}x{}, got {} bytes). \
                 The image may be corrupted.",
                pending.key,
                pending.description,
                expected,
                width,
                height,
                actual
            );
        }
    }

    // Clean up the entity
    commands.entity(entity).despawn();
}

/// System parameter for triggering entity-focused screenshots from game systems.
///
/// This is a separate system parameter from `ScreenshotTrigger` because it requires
/// additional queries for camera and entity transforms. Use this when you want to
/// capture a screenshot cropped to a specific entity.
///
/// Supports both 2D and 3D cameras:
/// - For 2D scenes, uses `Camera2d` and entity `Sprite`/`Aabb` for sizing
/// - For 3D scenes, uses `Camera3d` and projects 3D `Aabb` bounds to screen space
///
/// The macro `screenshot_entity!` provides the same interface for both 2D and 3D.
#[derive(SystemParam)]
pub struct EntityScreenshotTrigger<'w, 's> {
    sender: Res<'w, ScreenshotRequestSender>,
    /// Query for 2D cameras
    camera_2d_query: Query<'w, 's, (&'static Camera, &'static GlobalTransform), With<Camera2d>>,
    /// Query for 3D cameras
    camera_3d_query: Query<'w, 's, (&'static Camera, &'static GlobalTransform), With<Camera3d>>,
    /// Query for entity transforms and optional size components
    entity_query: Query<'w, 's, (&'static GlobalTransform, Option<&'static Sprite>, Option<&'static Aabb>)>,
    window_query: Query<'w, 's, &'static Window, With<PrimaryWindow>>,
}

impl EntityScreenshotTrigger<'_, '_> {
    /// Capture a screenshot of an entity with the default key and default settings.
    pub fn capture(&self, entity: Entity) {
        self.capture_with_key(entity, "default", "", EntityScreenshotSettings::default());
    }

    /// Capture a screenshot of an entity with a specific key.
    pub fn capture_key(&self, entity: Entity, key: impl Into<String>) {
        self.capture_with_key(entity, key, "", EntityScreenshotSettings::default());
    }

    /// Capture a screenshot of an entity with a specific key and description.
    pub fn capture_key_desc(
        &self,
        entity: Entity,
        key: impl Into<String>,
        description: impl Into<String>,
    ) {
        self.capture_with_key(entity, key, description, EntityScreenshotSettings::default());
    }

    /// Capture a screenshot of an entity with full configuration.
    ///
    /// Automatically detects whether to use 2D or 3D camera:
    /// - Tries 2D camera first (for 2D scenes with Camera2d)
    /// - Falls back to 3D camera (for 3D scenes with Camera3d)
    pub fn capture_with_key(
        &self,
        entity: Entity,
        key: impl Into<String>,
        description: impl Into<String>,
        settings: EntityScreenshotSettings,
    ) {
        let key = key.into();
        let description = description.into();

        // Get entity transform and size info
        let Ok((entity_transform, sprite, aabb)) = self.entity_query.get(entity) else {
            bevy::log::warn!(
                "Entity screenshot failed: entity {:?} not found or missing required components",
                entity
            );
            return;
        };

        // Get window scale factor (for retina/HiDPI displays)
        let scale_factor = self
            .window_query
            .single()
            .map(|w| w.scale_factor())
            .unwrap_or(1.0);

        // Try 2D camera first (preferred for 2D scenes)
        if let Ok((camera, camera_transform)) = self.camera_2d_query.single() {
            self.capture_with_camera_2d(
                camera,
                camera_transform,
                entity_transform,
                sprite,
                aabb,
                scale_factor,
                &key,
                &description,
                &settings,
            );
            return;
        }

        // Try 3D camera as fallback (for 3D scenes)
        if let Ok((camera, camera_transform)) = self.camera_3d_query.single() {
            self.capture_with_camera_3d(
                camera,
                camera_transform,
                entity_transform,
                aabb,
                scale_factor,
                &key,
                &description,
                &settings,
            );
            return;
        }

        // No camera found
        bevy::log::warn!("Entity screenshot failed: no 2D or 3D camera found");
    }

    /// Capture entity screenshot using a 2D camera.
    ///
    /// Uses the entity's Sprite or Aabb for sizing in 2D screen space.
    fn capture_with_camera_2d(
        &self,
        camera: &Camera,
        camera_transform: &GlobalTransform,
        entity_transform: &GlobalTransform,
        sprite: Option<&Sprite>,
        aabb: Option<&Aabb>,
        scale_factor: f32,
        key: &str,
        description: &str,
        settings: &EntityScreenshotSettings,
    ) {
        // Calculate entity size (in logical pixels) for 2D
        let entity_size = self.get_entity_size_2d(sprite, aabb, settings);

        // Get entity center position in world coordinates
        let entity_pos = entity_transform.translation();

        // Convert world position to viewport coordinates (logical pixels)
        let viewport_center = match camera.world_to_viewport(camera_transform, entity_pos) {
            Ok(pos) => pos,
            Err(_) => {
                bevy::log::warn!(
                    "Entity screenshot (2D): entity is outside camera viewport, capturing with fallback"
                );
                // Still try to capture - it will be clamped
                let request = ScreenshotRequest::new(key, description);
                let _ = self.sender.0.try_send(request);
                return;
            }
        };

        // Calculate crop region from center point and size
        let crop_region = self.calculate_crop_region(
            viewport_center,
            entity_size,
            scale_factor,
            settings.padding,
        );

        let request = ScreenshotRequest::with_crop(key, description, crop_region);
        let _ = self.sender.0.try_send(request);
    }

    /// Capture entity screenshot using a 3D camera.
    ///
    /// Projects the entity's 3D Aabb corners to screen space to determine bounds.
    fn capture_with_camera_3d(
        &self,
        camera: &Camera,
        camera_transform: &GlobalTransform,
        entity_transform: &GlobalTransform,
        aabb: Option<&Aabb>,
        scale_factor: f32,
        key: &str,
        description: &str,
        settings: &EntityScreenshotSettings,
    ) {
        // Get entity center position in world coordinates
        let entity_pos = entity_transform.translation();

        // For 3D, we need to project the Aabb corners to screen space
        // to account for perspective and entity rotation
        let screen_bounds = if let Some(aabb) = aabb {
            self.project_aabb_to_screen(
                camera,
                camera_transform,
                entity_transform,
                aabb,
            )
        } else {
            // No Aabb, just project the center point and use fallback size
            None
        };

        match screen_bounds {
            Some((min_screen, max_screen)) => {
                // We have valid projected bounds
                let center = Vec2::new(
                    (min_screen.x + max_screen.x) / 2.0,
                    (min_screen.y + max_screen.y) / 2.0,
                );
                let size = Vec2::new(
                    max_screen.x - min_screen.x,
                    max_screen.y - min_screen.y,
                );

                let crop_region = self.calculate_crop_region(
                    center,
                    size,
                    scale_factor,
                    settings.padding,
                );

                let request = ScreenshotRequest::with_crop(key, description, crop_region);
                let _ = self.sender.0.try_send(request);
            }
            None => {
                // Couldn't project bounds, try center point with fallback size
                match camera.world_to_viewport(camera_transform, entity_pos) {
                    Ok(viewport_center) => {
                        let fallback_size = Vec2::new(
                            settings.fallback_size.0 as f32,
                            settings.fallback_size.1 as f32,
                        );
                        let crop_region = self.calculate_crop_region(
                            viewport_center,
                            fallback_size,
                            scale_factor,
                            settings.padding,
                        );
                        let request = ScreenshotRequest::with_crop(key, description, crop_region);
                        let _ = self.sender.0.try_send(request);
                    }
                    Err(_) => {
                        bevy::log::warn!(
                            "Entity screenshot (3D): entity is outside camera viewport, capturing full window"
                        );
                        let request = ScreenshotRequest::new(key, description);
                        let _ = self.sender.0.try_send(request);
                    }
                }
            }
        }
    }

    /// Project a 3D Aabb to screen space bounds.
    ///
    /// Returns the min and max screen coordinates (in logical pixels) of the projected Aabb,
    /// or None if the Aabb is not visible (all corners behind camera or outside viewport).
    fn project_aabb_to_screen(
        &self,
        camera: &Camera,
        camera_transform: &GlobalTransform,
        entity_transform: &GlobalTransform,
        aabb: &Aabb,
    ) -> Option<(Vec2, Vec2)> {
        let half_extents = aabb.half_extents;
        let center = aabb.center;

        // Generate all 8 corners of the Aabb in local space
        let corners_local = [
            Vec3::new(center.x - half_extents.x, center.y - half_extents.y, center.z - half_extents.z),
            Vec3::new(center.x + half_extents.x, center.y - half_extents.y, center.z - half_extents.z),
            Vec3::new(center.x - half_extents.x, center.y + half_extents.y, center.z - half_extents.z),
            Vec3::new(center.x + half_extents.x, center.y + half_extents.y, center.z - half_extents.z),
            Vec3::new(center.x - half_extents.x, center.y - half_extents.y, center.z + half_extents.z),
            Vec3::new(center.x + half_extents.x, center.y - half_extents.y, center.z + half_extents.z),
            Vec3::new(center.x - half_extents.x, center.y + half_extents.y, center.z + half_extents.z),
            Vec3::new(center.x + half_extents.x, center.y + half_extents.y, center.z + half_extents.z),
        ];

        // Transform corners to world space and project to screen
        let mut min_screen = Vec2::new(f32::MAX, f32::MAX);
        let mut max_screen = Vec2::new(f32::MIN, f32::MIN);
        let mut any_visible = false;

        for corner_local in corners_local {
            // Transform to world space
            let corner_world = entity_transform.transform_point(corner_local);

            // Project to viewport (screen) coordinates
            if let Ok(screen_pos) = camera.world_to_viewport(camera_transform, corner_world) {
                any_visible = true;
                min_screen.x = min_screen.x.min(screen_pos.x);
                min_screen.y = min_screen.y.min(screen_pos.y);
                max_screen.x = max_screen.x.max(screen_pos.x);
                max_screen.y = max_screen.y.max(screen_pos.y);
            }
        }

        if any_visible {
            Some((min_screen, max_screen))
        } else {
            None
        }
    }

    /// Calculate crop region from center point and size.
    ///
    /// Handles conversion from logical to physical pixels.
    fn calculate_crop_region(
        &self,
        viewport_center: Vec2,
        entity_size: Vec2,
        scale_factor: f32,
        padding: u32,
    ) -> CropRegion {
        // Convert to physical pixels (screenshot is in physical pixels)
        let screen_center = viewport_center * scale_factor;
        let physical_entity_size = entity_size * scale_factor;
        let physical_padding = padding as f32 * scale_factor;

        // Calculate crop region with padding (in physical pixels)
        let half_width = physical_entity_size.x / 2.0 + physical_padding;
        let half_height = physical_entity_size.y / 2.0 + physical_padding;

        let crop_x = (screen_center.x - half_width).max(0.0) as u32;
        let crop_y = (screen_center.y - half_height).max(0.0) as u32;
        let crop_width = (half_width * 2.0) as u32;
        let crop_height = (half_height * 2.0) as u32;

        CropRegion::new(crop_x, crop_y, crop_width, crop_height)
    }

    /// Get entity size from Sprite, Aabb, or fallback to settings (for 2D).
    fn get_entity_size_2d(
        &self,
        sprite: Option<&Sprite>,
        aabb: Option<&Aabb>,
        settings: &EntityScreenshotSettings,
    ) -> Vec2 {
        // Priority 1: Sprite custom_size
        if let Some(sprite) = sprite {
            if let Some(custom_size) = sprite.custom_size {
                return custom_size;
            }
        }

        // Priority 2: Aabb (use X and Y extents for 2D)
        if let Some(aabb) = aabb {
            let half_extents = aabb.half_extents;
            return Vec2::new(half_extents.x * 2.0, half_extents.y * 2.0);
        }

        // Priority 3: Fallback size from settings
        Vec2::new(settings.fallback_size.0 as f32, settings.fallback_size.1 as f32)
    }
}

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

    mod crop_region {
        use super::*;

        #[test]
        fn test_new() {
            let region = CropRegion::new(10, 20, 100, 200);
            assert_eq!(region.x, 10);
            assert_eq!(region.y, 20);
            assert_eq!(region.width, 100);
            assert_eq!(region.height, 200);
        }

        #[test]
        fn test_clamp_to_bounds_fully_inside() {
            let region = CropRegion::new(10, 10, 50, 50);
            let clamped = region.clamp_to_bounds(100, 100);
            assert!(clamped.is_some());
            let c = clamped.unwrap();
            assert_eq!(c.x, 10);
            assert_eq!(c.y, 10);
            assert_eq!(c.width, 50);
            assert_eq!(c.height, 50);
        }

        #[test]
        fn test_clamp_to_bounds_extends_right() {
            let region = CropRegion::new(80, 10, 50, 50);
            let clamped = region.clamp_to_bounds(100, 100);
            assert!(clamped.is_some());
            let c = clamped.unwrap();
            assert_eq!(c.x, 80);
            assert_eq!(c.y, 10);
            assert_eq!(c.width, 20); // Clamped from 50 to 20
            assert_eq!(c.height, 50);
        }

        #[test]
        fn test_clamp_to_bounds_extends_bottom() {
            let region = CropRegion::new(10, 80, 50, 50);
            let clamped = region.clamp_to_bounds(100, 100);
            assert!(clamped.is_some());
            let c = clamped.unwrap();
            assert_eq!(c.x, 10);
            assert_eq!(c.y, 80);
            assert_eq!(c.width, 50);
            assert_eq!(c.height, 20); // Clamped from 50 to 20
        }

        #[test]
        fn test_clamp_to_bounds_extends_both() {
            let region = CropRegion::new(80, 80, 50, 50);
            let clamped = region.clamp_to_bounds(100, 100);
            assert!(clamped.is_some());
            let c = clamped.unwrap();
            assert_eq!(c.x, 80);
            assert_eq!(c.y, 80);
            assert_eq!(c.width, 20);
            assert_eq!(c.height, 20);
        }

        #[test]
        fn test_clamp_to_bounds_completely_outside_x() {
            let region = CropRegion::new(100, 10, 50, 50);
            let clamped = region.clamp_to_bounds(100, 100);
            assert!(clamped.is_none());
        }

        #[test]
        fn test_clamp_to_bounds_completely_outside_y() {
            let region = CropRegion::new(10, 100, 50, 50);
            let clamped = region.clamp_to_bounds(100, 100);
            assert!(clamped.is_none());
        }

        #[test]
        fn test_clamp_to_bounds_zero_width_after_clamp() {
            let region = CropRegion::new(100, 10, 50, 50);
            let clamped = region.clamp_to_bounds(100, 100);
            assert!(clamped.is_none());
        }

        #[test]
        fn test_clamp_to_bounds_zero_height_after_clamp() {
            let region = CropRegion::new(10, 100, 50, 50);
            let clamped = region.clamp_to_bounds(100, 100);
            assert!(clamped.is_none());
        }

        #[test]
        fn test_clamp_to_bounds_at_origin() {
            let region = CropRegion::new(0, 0, 50, 50);
            let clamped = region.clamp_to_bounds(100, 100);
            assert!(clamped.is_some());
            let c = clamped.unwrap();
            assert_eq!(c.x, 0);
            assert_eq!(c.y, 0);
            assert_eq!(c.width, 50);
            assert_eq!(c.height, 50);
        }

        #[test]
        fn test_clamp_to_bounds_exact_fit() {
            let region = CropRegion::new(0, 0, 100, 100);
            let clamped = region.clamp_to_bounds(100, 100);
            assert!(clamped.is_some());
            let c = clamped.unwrap();
            assert_eq!(c.x, 0);
            assert_eq!(c.y, 0);
            assert_eq!(c.width, 100);
            assert_eq!(c.height, 100);
        }
    }

    mod entity_screenshot_settings {
        use super::*;

        #[test]
        fn test_default_values() {
            let settings = EntityScreenshotSettings::default();
            assert_eq!(settings.padding, 20);
            assert_eq!(settings.fallback_size, (64, 64));
        }

        #[test]
        fn test_with_padding() {
            let settings = EntityScreenshotSettings::default().with_padding(50);
            assert_eq!(settings.padding, 50);
            assert_eq!(settings.fallback_size, (64, 64)); // Unchanged
        }

        #[test]
        fn test_with_fallback_size() {
            let settings = EntityScreenshotSettings::default().with_fallback_size(128, 256);
            assert_eq!(settings.padding, 20); // Unchanged
            assert_eq!(settings.fallback_size, (128, 256));
        }

        #[test]
        fn test_builder_chain() {
            let settings = EntityScreenshotSettings::default()
                .with_padding(100)
                .with_fallback_size(200, 300);
            assert_eq!(settings.padding, 100);
            assert_eq!(settings.fallback_size, (200, 300));
        }
    }

    mod screenshot_request {
        use super::*;

        #[test]
        fn test_new_without_crop() {
            let request = ScreenshotRequest::new("test_key", "test_desc");
            assert_eq!(request.key, "test_key");
            assert_eq!(request.description, "test_desc");
            assert!(request.crop_region.is_none());
        }

        #[test]
        fn test_with_crop() {
            let crop = CropRegion::new(10, 20, 100, 200);
            let request = ScreenshotRequest::with_crop("test_key", "test_desc", crop);
            assert_eq!(request.key, "test_key");
            assert_eq!(request.description, "test_desc");
            assert!(request.crop_region.is_some());
            let c = request.crop_region.unwrap();
            assert_eq!(c.x, 10);
            assert_eq!(c.y, 20);
            assert_eq!(c.width, 100);
            assert_eq!(c.height, 200);
        }
    }

    /// Tests for 3D-specific crop region calculations.
    ///
    /// These tests verify the pure calculation logic without requiring a full Bevy app.
    mod crop_region_3d {
        use super::*;

        /// Helper to create a crop region from screen bounds (center + size).
        fn crop_region_from_bounds(center: Vec2, size: Vec2, scale_factor: f32, padding: u32) -> CropRegion {
            let screen_center = center * scale_factor;
            let physical_size = size * scale_factor;
            let physical_padding = padding as f32 * scale_factor;

            let half_width = physical_size.x / 2.0 + physical_padding;
            let half_height = physical_size.y / 2.0 + physical_padding;

            let crop_x = (screen_center.x - half_width).max(0.0) as u32;
            let crop_y = (screen_center.y - half_height).max(0.0) as u32;
            let crop_width = (half_width * 2.0) as u32;
            let crop_height = (half_height * 2.0) as u32;

            CropRegion::new(crop_x, crop_y, crop_width, crop_height)
        }

        #[test]
        fn test_crop_region_centered_no_padding() {
            // Entity at center of 800x600 screen, size 100x100, no padding, scale 1.0
            let center = Vec2::new(400.0, 300.0);
            let size = Vec2::new(100.0, 100.0);
            let region = crop_region_from_bounds(center, size, 1.0, 0);

            assert_eq!(region.x, 350); // 400 - 50
            assert_eq!(region.y, 250); // 300 - 50
            assert_eq!(region.width, 100);
            assert_eq!(region.height, 100);
        }

        #[test]
        fn test_crop_region_with_padding() {
            // Entity at center, size 100x100, 20px padding
            let center = Vec2::new(400.0, 300.0);
            let size = Vec2::new(100.0, 100.0);
            let region = crop_region_from_bounds(center, size, 1.0, 20);

            assert_eq!(region.x, 330); // 400 - 50 - 20
            assert_eq!(region.y, 230); // 300 - 50 - 20
            assert_eq!(region.width, 140); // 100 + 40
            assert_eq!(region.height, 140);
        }

        #[test]
        fn test_crop_region_with_hidpi_scale() {
            // Entity at center, size 100x100, 20px padding, 2x scale (retina)
            let center = Vec2::new(400.0, 300.0);
            let size = Vec2::new(100.0, 100.0);
            let region = crop_region_from_bounds(center, size, 2.0, 20);

            // All values doubled due to 2x scale
            assert_eq!(region.x, 660); // (400 - 50 - 20) * 2
            assert_eq!(region.y, 460); // (300 - 50 - 20) * 2
            assert_eq!(region.width, 280); // 140 * 2
            assert_eq!(region.height, 280);
        }

        #[test]
        fn test_crop_region_near_edge_clamped() {
            // Entity near top-left corner, would extend outside screen
            let center = Vec2::new(30.0, 30.0);
            let size = Vec2::new(100.0, 100.0);
            let region = crop_region_from_bounds(center, size, 1.0, 10);

            // X and Y clamped to 0 (can't be negative)
            assert_eq!(region.x, 0);
            assert_eq!(region.y, 0);
            // Width/height calculated from center, not clamped here
            assert_eq!(region.width, 120); // 50 + 10 * 2
            assert_eq!(region.height, 120);
        }

        #[test]
        fn test_crop_region_asymmetric_size() {
            // Entity with different width and height (e.g., stretched ball)
            let center = Vec2::new(400.0, 300.0);
            let size = Vec2::new(80.0, 120.0); // Stretched vertically
            let region = crop_region_from_bounds(center, size, 1.0, 10);

            assert_eq!(region.x, 350); // 400 - 40 - 10
            assert_eq!(region.y, 230); // 300 - 60 - 10
            assert_eq!(region.width, 100); // 80 + 20
            assert_eq!(region.height, 140); // 120 + 20
        }

        #[test]
        fn test_crop_region_small_entity_large_padding() {
            // Very small entity with large padding
            let center = Vec2::new(400.0, 300.0);
            let size = Vec2::new(10.0, 10.0);
            let region = crop_region_from_bounds(center, size, 1.0, 100);

            assert_eq!(region.x, 295); // 400 - 5 - 100
            assert_eq!(region.y, 195); // 300 - 5 - 100
            assert_eq!(region.width, 210); // 10 + 200
            assert_eq!(region.height, 210);
        }

        #[test]
        fn test_crop_region_fractional_scale() {
            // Test with non-integer scale factor (e.g., 1.5x)
            let center = Vec2::new(400.0, 300.0);
            let size = Vec2::new(100.0, 100.0);
            let region = crop_region_from_bounds(center, size, 1.5, 20);

            // Values scaled by 1.5, then truncated to u32
            assert_eq!(region.x, 495); // (400 - 50 - 20) * 1.5 = 495
            assert_eq!(region.y, 345); // (300 - 50 - 20) * 1.5 = 345
            assert_eq!(region.width, 210); // 140 * 1.5 = 210
            assert_eq!(region.height, 210);
        }
    }

    /// Tests for 3D Aabb corner generation.
    mod aabb_corners {
        use super::*;

        #[test]
        fn test_unit_aabb_corners() {
            // Unit Aabb centered at origin
            let _aabb = Aabb {
                center: Vec3A::ZERO,
                half_extents: Vec3A::ONE,
            };

            // Verify we can generate 8 corners from unit half-extents
            let corners = [
                Vec3::new(-1.0, -1.0, -1.0),
                Vec3::new(1.0, -1.0, -1.0),
                Vec3::new(-1.0, 1.0, -1.0),
                Vec3::new(1.0, 1.0, -1.0),
                Vec3::new(-1.0, -1.0, 1.0),
                Vec3::new(1.0, -1.0, 1.0),
                Vec3::new(-1.0, 1.0, 1.0),
                Vec3::new(1.0, 1.0, 1.0),
            ];

            // All corners should be at distance sqrt(3) from origin
            for corner in corners {
                let dist = corner.length();
                assert!((dist - 3.0_f32.sqrt()).abs() < 0.001);
            }
        }

        #[test]
        fn test_offset_aabb_corners() {
            // Aabb offset from origin
            let aabb = Aabb {
                center: Vec3A::new(10.0, 20.0, 30.0),
                half_extents: Vec3A::new(1.0, 2.0, 3.0),
            };

            // Min corner should be at (9, 18, 27)
            let min_corner = Vec3::new(
                aabb.center.x - aabb.half_extents.x,
                aabb.center.y - aabb.half_extents.y,
                aabb.center.z - aabb.half_extents.z,
            );
            assert_eq!(min_corner, Vec3::new(9.0, 18.0, 27.0));

            // Max corner should be at (11, 22, 33)
            let max_corner = Vec3::new(
                aabb.center.x + aabb.half_extents.x,
                aabb.center.y + aabb.half_extents.y,
                aabb.center.z + aabb.half_extents.z,
            );
            assert_eq!(max_corner, Vec3::new(11.0, 22.0, 33.0));
        }

        #[test]
        fn test_screen_bounds_from_corners() {
            // Simulate projected screen coordinates from 8 corners
            let screen_points = vec![
                Vec2::new(100.0, 150.0),
                Vec2::new(200.0, 150.0),
                Vec2::new(100.0, 250.0),
                Vec2::new(200.0, 250.0),
                Vec2::new(120.0, 170.0),
                Vec2::new(180.0, 170.0),
                Vec2::new(120.0, 230.0),
                Vec2::new(180.0, 230.0),
            ];

            let mut min_screen = Vec2::new(f32::MAX, f32::MAX);
            let mut max_screen = Vec2::new(f32::MIN, f32::MIN);

            for pt in &screen_points {
                min_screen.x = min_screen.x.min(pt.x);
                min_screen.y = min_screen.y.min(pt.y);
                max_screen.x = max_screen.x.max(pt.x);
                max_screen.y = max_screen.y.max(pt.y);
            }

            assert_eq!(min_screen, Vec2::new(100.0, 150.0));
            assert_eq!(max_screen, Vec2::new(200.0, 250.0));

            // Calculate center and size from bounds
            let center = Vec2::new(
                (min_screen.x + max_screen.x) / 2.0,
                (min_screen.y + max_screen.y) / 2.0,
            );
            let size = Vec2::new(
                max_screen.x - min_screen.x,
                max_screen.y - min_screen.y,
            );

            assert_eq!(center, Vec2::new(150.0, 200.0));
            assert_eq!(size, Vec2::new(100.0, 100.0));
        }

        #[test]
        fn test_partial_visibility() {
            // Simulate case where only some corners project successfully
            // (some corners behind camera return None)
            let projected_points: Vec<Option<Vec2>> = vec![
                Some(Vec2::new(100.0, 150.0)),
                Some(Vec2::new(200.0, 150.0)),
                None, // Behind camera
                None, // Behind camera
                Some(Vec2::new(120.0, 170.0)),
                Some(Vec2::new(180.0, 170.0)),
                None, // Behind camera
                None, // Behind camera
            ];

            let mut min_screen = Vec2::new(f32::MAX, f32::MAX);
            let mut max_screen = Vec2::new(f32::MIN, f32::MIN);
            let mut any_visible = false;

            for pt_opt in &projected_points {
                if let Some(pt) = pt_opt {
                    any_visible = true;
                    min_screen.x = min_screen.x.min(pt.x);
                    min_screen.y = min_screen.y.min(pt.y);
                    max_screen.x = max_screen.x.max(pt.x);
                    max_screen.y = max_screen.y.max(pt.y);
                }
            }

            assert!(any_visible);
            assert_eq!(min_screen, Vec2::new(100.0, 150.0));
            assert_eq!(max_screen, Vec2::new(200.0, 170.0));
        }

        #[test]
        fn test_no_visibility() {
            // All corners behind camera
            let projected_points: Vec<Option<Vec2>> = vec![
                None, None, None, None, None, None, None, None,
            ];

            let mut any_visible = false;
            for pt_opt in &projected_points {
                if pt_opt.is_some() {
                    any_visible = true;
                }
            }

            assert!(!any_visible);
        }
    }
}