sim-engine 0.4.2

A validated high-performance visualization engine for simulations
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
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
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
use std::borrow::Cow;
use std::error::Error;
use std::fmt;
use std::sync::Arc;

use super::{
    Color, LogicalViewport, LogicalViewportRegion, RendererFrameError, Vec2, WgpuRenderer,
    is_portable_shader_source, prepared_scene_belongs_to, shader_interval_sum_range,
    submit_pending_uploads,
};

const IMAGE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8UnormSrgb;

mod updates;
pub(super) use updates::{batch_retained_bytes, update_image_batch_resources};
mod proof;
use proof::BatchProofCache;
#[cfg(test)]
pub(super) use proof::sprites_are_safe_for_target;

#[cfg(test)]
pub(super) use tests::verify_retained_ui_updates;

/// Immutable resource limits retained with an [`Image2d`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ImageBudget {
    max_width: u32,
    max_height: u32,
    max_bytes: usize,
}

impl ImageBudget {
    /// Creates non-zero image dimension and byte limits.
    pub fn new(max_width: u32, max_height: u32, max_bytes: usize) -> Result<Self, ImageError> {
        if max_width == 0 || max_height == 0 || max_bytes < 4 {
            return Err(ImageError::InvalidBudget);
        }
        Ok(Self {
            max_width,
            max_height,
            max_bytes,
        })
    }

    /// Returns maximum image width in physical texels.
    pub const fn max_width(self) -> u32 {
        self.max_width
    }

    /// Returns maximum image height in physical texels.
    pub const fn max_height(self) -> u32 {
        self.max_height
    }

    /// Returns maximum retained and GPU RGBA bytes.
    pub const fn max_bytes(self) -> usize {
        self.max_bytes
    }
}

impl Default for ImageBudget {
    fn default() -> Self {
        Self {
            max_width: 4096,
            max_height: 4096,
            max_bytes: 64 * 1024 * 1024,
        }
    }
}

/// Validated non-empty atlas rectangle in physical source texels.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ImageTexelRect {
    x: u32,
    y: u32,
    width: u32,
    height: u32,
}

impl ImageTexelRect {
    /// Creates a non-empty source rectangle. Image bounds are checked at use.
    pub fn new(x: u32, y: u32, width: u32, height: u32) -> Result<Self, ImageError> {
        if width == 0 || height == 0 {
            return Err(ImageError::ZeroDimension);
        }
        x.checked_add(width)
            .zip(y.checked_add(height))
            .ok_or(ImageError::DimensionsTooLarge)?;
        Ok(Self {
            x,
            y,
            width,
            height,
        })
    }

    /// Returns the left source texel.
    pub const fn x(self) -> u32 {
        self.x
    }

    /// Returns the top source texel.
    pub const fn y(self) -> u32 {
        self.y
    }

    /// Returns source width in texels.
    pub const fn width(self) -> u32 {
        self.width
    }

    /// Returns source height in texels.
    pub const fn height(self) -> u32 {
        self.height
    }

    pub(super) fn fits(self, width: u32, height: u32) -> bool {
        self.x
            .checked_add(self.width)
            .is_some_and(|maximum| maximum <= width)
            && self
                .y
                .checked_add(self.height)
                .is_some_and(|maximum| maximum <= height)
    }
}

/// Texture filtering used by a composed image or atlas region.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ImageSampling {
    /// Preserve exact texel boundaries for pixel art and masks.
    #[default]
    Nearest,
    /// Bilinearly interpolate neighboring source texels.
    Linear,
}

/// Independent presentation of one retained image batch or glyph run.
///
/// Translation uses top-left logical pixels in the pass's local coordinates.
/// It moves content before viewport placement, without moving the pass clip.
/// Tint multiplies each instance's straight-linear RGBA, including alpha.
/// Multiple draws can share immutable layout with different placements.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ImageBatchPlacement {
    translation: crate::LogicalScreenVector,
    tint: Color,
}

impl ImageBatchPlacement {
    /// Creates a portable logical translation and normalized multiplicative tint.
    /// Negative translation is supported. Target-dependent arithmetic is checked
    /// again before submission; leaving the target is ordinary clipping.
    pub fn new(translation: crate::LogicalScreenVector, tint: Color) -> Result<Self, ImageError> {
        let offset = translation.to_vec2();
        if ![offset.x, offset.y]
            .into_iter()
            .all(is_portable_shader_source)
            || !tint.is_normalized()
        {
            return Err(ImageError::InvalidPlacement);
        }
        Ok(Self { translation, tint })
    }

    /// Returns the content offset in local logical pixels.
    pub const fn translation(self) -> crate::LogicalScreenVector {
        self.translation
    }
    /// Returns the draw-wide straight-linear tint.
    pub const fn tint(self) -> Color {
        self.tint
    }
}

impl Default for ImageBatchPlacement {
    fn default() -> Self {
        Self {
            translation: crate::LogicalScreenVector::new(0.0, 0.0),
            tint: Color::WHITE,
        }
    }
}

/// Failure while creating, restoring, or updating an RGBA image.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImageError {
    /// A width or height was zero.
    ZeroDimension,
    /// A resource budget cannot fit its minimum image or batch element.
    InvalidBudget,
    /// Dimensions or their RGBA byte arithmetic exceed a configured/device limit.
    DimensionsTooLarge,
    /// Pixel data does not contain exactly width × height × four bytes.
    InvalidPixelCount,
    /// The image exceeds its host-selected byte limit.
    BudgetExceeded {
        /// Configured byte ceiling.
        limit: usize,
        /// Required RGBA bytes.
        actual: usize,
    },
    /// CPU recovery, conversion, or batch-staging storage could not be
    /// reserved.
    AllocationFailed {
        /// Bytes requested by the failed reservation.
        requested_bytes: usize,
    },
    /// A retained image belongs to another renderer generation.
    RendererMismatch,
    /// A recovery operation was given a different logical image than the source used.
    RecoverySourceMismatch,
    /// A partial update does not fit in the image.
    UpdateRegionOutOfBounds,
    /// A sprite source rectangle or tint is invalid for its image.
    InvalidSprite,
    /// Draw translation is outside the portable envelope or tint is not normalized.
    InvalidPlacement,
    /// A sprite batch exceeds its retained count or CPU metadata byte limit.
    BatchBudgetExceeded {
        /// Configured upper bound.
        limit: usize,
        /// Requested count or bytes.
        actual: usize,
    },
}

impl fmt::Display for ImageError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ZeroDimension => write!(formatter, "image dimensions must be non-zero"),
            Self::InvalidBudget => write!(
                formatter,
                "resource budget must fit at least one image texel or batch element"
            ),
            Self::DimensionsTooLarge => write!(formatter, "image dimensions exceed limits"),
            Self::InvalidPixelCount => write!(formatter, "image RGBA byte count is invalid"),
            Self::BudgetExceeded { limit, actual } => {
                write!(
                    formatter,
                    "image requires {actual} bytes, over limit {limit}"
                )
            }
            Self::AllocationFailed { requested_bytes } => write!(
                formatter,
                "could not reserve {requested_bytes} bytes for image storage or staging"
            ),
            Self::RendererMismatch => write!(formatter, "image belongs to another renderer"),
            Self::RecoverySourceMismatch => {
                write!(
                    formatter,
                    "image is not a restored copy of the recovery source"
                )
            }
            Self::UpdateRegionOutOfBounds => write!(formatter, "image update is out of bounds"),
            Self::InvalidSprite => write!(formatter, "image sprite source or tint is invalid"),
            Self::InvalidPlacement => {
                write!(formatter, "image batch translation or tint is invalid")
            }
            Self::BatchBudgetExceeded { limit, actual } => {
                write!(formatter, "image batch work {actual} exceeds limit {limit}")
            }
        }
    }
}

impl Error for ImageError {}

/// CPU outcome of a complete or partial image upload.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ImageUploadReport {
    uploaded_bytes: usize,
    replaced_texture: bool,
}

impl ImageUploadReport {
    /// Returns RGBA bytes submitted to the queue.
    pub const fn uploaded_bytes(self) -> usize {
        self.uploaded_bytes
    }

    /// Returns whether the operation replaced the underlying texture.
    pub const fn replaced_texture(self) -> bool {
        self.replaced_texture
    }
}

/// CPU outcome of replacing a retained image/sprite instance batch.
///
/// This report is intentionally distinct from [`ImageUploadReport`]: batch
/// replacement uploads instance-buffer records and does not replace or upload
/// the referenced image texture.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ImageBatchUploadReport {
    uploaded_instance_bytes: usize,
    replaced_instance_buffer: bool,
    sprite_count: usize,
    retained_capacity: usize,
    gpu_capacity: usize,
    retained_bytes: usize,
    peak_retained_bytes: usize,
    peak_gpu_bytes: usize,
}

impl ImageBatchUploadReport {
    /// Returns instance-buffer bytes submitted to the queue.
    pub const fn uploaded_instance_bytes(self) -> usize {
        self.uploaded_instance_bytes
    }

    /// Returns whether the operation replaced the underlying instance buffer.
    pub const fn replaced_instance_buffer(self) -> bool {
        self.replaced_instance_buffer
    }

    /// Returns the accepted logical sprite count, including zero for an empty update.
    pub const fn sprite_count(self) -> usize {
        self.sprite_count
    }

    /// Returns reusable CPU sprite/instance capacity, excluding allocator metadata.
    pub const fn retained_capacity(self) -> usize {
        self.retained_capacity
    }

    /// Returns reusable GPU instance capacity (an empty buffer has one slot).
    pub const fn gpu_capacity(self) -> usize {
        self.gpu_capacity
    }

    /// Returns retained CPU description and conversion-staging allocation bytes.
    pub const fn retained_bytes(self) -> usize {
        self.retained_bytes
    }

    /// Returns the maximum old-plus-new CPU allocation bytes owned during this update.
    /// Caller input and opaque allocator/backend staging are not included.
    pub const fn peak_retained_bytes(self) -> usize {
        self.peak_retained_bytes
    }

    /// Returns old-plus-new GPU instance-buffer bytes during replacement, or the
    /// reused allocation size. In-flight retirement remains owned by wgpu.
    pub const fn peak_gpu_bytes(self) -> usize {
        self.peak_gpu_bytes
    }
}

/// Renderer-owned straight-alpha sRGB RGBA image with exact recovery pixels.
///
/// Source bytes use row-major top-to-bottom `R8 G8 B8 A8` texels. The sRGB GPU
/// texture decodes RGB to linear light before tinting and alpha composition;
/// alpha remains linear. Retained bytes make device-loss restoration exact.
pub struct Image2d {
    renderer_identity: Arc<()>,
    pub(super) resource_identity: Arc<()>,
    pub(super) recovery_identity: Arc<()>,
    texture: wgpu::Texture,
    pub(super) view: wgpu::TextureView,
    width: u32,
    height: u32,
    pixels: Vec<u8>,
    budget: ImageBudget,
}

impl Image2d {
    /// Returns image width in source texels.
    pub const fn width(&self) -> u32 {
        self.width
    }

    /// Returns image height in source texels.
    pub const fn height(&self) -> u32 {
        self.height
    }

    /// Returns complete image dimensions.
    pub const fn size(&self) -> (u32, u32) {
        (self.width, self.height)
    }

    /// Returns the retained creation/replacement budget.
    pub const fn budget(&self) -> ImageBudget {
        self.budget
    }

    /// Returns exact CPU recovery pixels in row-major sRGB RGBA8 form.
    pub fn pixels(&self) -> &[u8] {
        &self.pixels
    }

    /// Returns retained CPU recovery bytes.
    pub fn recovery_memory_bytes(&self) -> usize {
        self.pixels.capacity()
    }

    /// Returns nominal single-level RGBA8 texel-storage bytes requested from
    /// the GPU, excluding backend row/tile/page alignment and metadata.
    pub fn gpu_allocation_bytes(&self) -> usize {
        self.pixels.len()
    }

    /// Returns a full-image atlas rectangle.
    pub fn full_rect(&self) -> ImageTexelRect {
        ImageTexelRect {
            x: 0,
            y: 0,
            width: self.width,
            height: self.height,
        }
    }
}

/// One validated atlas region placed in local logical-screen coordinates.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ImageSprite2d {
    source: ImageTexelRect,
    destination: LogicalViewportRegion,
    tint: Color,
}

impl ImageSprite2d {
    /// Creates a sprite. Atlas bounds are checked against an image at upload.
    pub fn new(
        source: ImageTexelRect,
        destination: LogicalViewportRegion,
        tint: Color,
    ) -> Result<Self, ImageError> {
        let origin = destination.origin().to_vec2();
        let end = origin + destination.viewport().size();
        if !tint.is_normalized() || !origin.is_finite() || !end.is_finite() {
            return Err(ImageError::InvalidSprite);
        }
        Ok(Self {
            source,
            destination,
            tint,
        })
    }

    /// Returns its physical atlas source rectangle.
    pub const fn source(self) -> ImageTexelRect {
        self.source
    }

    /// Returns its local logical destination rectangle.
    pub const fn destination(self) -> LogicalViewportRegion {
        self.destination
    }

    /// Returns its normalized straight-linear tint.
    pub const fn tint(self) -> Color {
        self.tint
    }
}

/// Hard retained-count and byte limits for an [`ImageBatch2d`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ImageBatchBudget {
    max_sprites: usize,
    max_retained_bytes: usize,
}

impl ImageBatchBudget {
    /// CPU bytes per sprite capacity slot: description plus conversion staging.
    /// Does not include image pixels, fixed inline handle/proof metadata,
    /// Vec headers or allocator metadata.
    pub const RETAINED_BYTES_PER_SPRITE: usize =
        std::mem::size_of::<ImageSprite2d>() + std::mem::size_of::<ImageInstance>();

    /// GPU instance record bytes; empty batches retain one minimum buffer slot.
    pub const GPU_BYTES_PER_SPRITE: usize = std::mem::size_of::<ImageInstance>();

    /// Creates non-zero sprite-count and retained-byte limits.
    pub fn new(max_sprites: usize, max_retained_bytes: usize) -> Result<Self, ImageError> {
        if max_sprites == 0 || max_retained_bytes < batch_retained_bytes(1) {
            return Err(ImageError::InvalidBudget);
        }
        Ok(Self {
            max_sprites,
            max_retained_bytes,
        })
    }

    /// Returns maximum sprite instances.
    pub const fn max_sprites(self) -> usize {
        self.max_sprites
    }

    /// Returns maximum retained CPU sprite-description and conversion-staging bytes.
    pub const fn max_retained_bytes(self) -> usize {
        self.max_retained_bytes
    }
}

impl Default for ImageBatchBudget {
    fn default() -> Self {
        Self {
            max_sprites: 100_000,
            max_retained_bytes: 16 * 1024 * 1024,
        }
    }
}

/// Renderer-owned atlas sprite batch drawn with at most one instanced draw call.
///
/// Sprite positions are local logical pixels and can be placed in any frame
/// viewport without rebuilding or uploading the batch. The exact CPU sprite
/// list is retained for renderer recovery. An empty batch is valid and emits
/// no draw call. One fixed inline entry reuses the exact geometry validation
/// result when ordered destination rectangles and their transform are unchanged;
/// position, size or count updates invalidate it, while UV/tint-only updates
/// preserve it. Restoration starts with no cached proof. This
/// does not skip drawing or upload validation and allocates no cache storage.
pub struct ImageBatch2d {
    renderer_identity: Arc<()>,
    image_identity: Arc<()>,
    pub(super) image_recovery_identity: Arc<()>,
    pub(super) instance_buffer: wgpu::Buffer,
    sprites: Vec<ImageSprite2d>,
    instances: Vec<ImageInstance>,
    budget: ImageBatchBudget,
    // Fixed inline metadata, not an allocation or caller-sized retained array.
    // Successful destination/count mutations invalidate this exact proof.
    geometry_proof: BatchProofCache,
}

impl ImageBatch2d {
    /// Returns retained sprite count.
    pub fn sprite_count(&self) -> usize {
        self.sprites.len()
    }

    /// Returns the exact retained sprite descriptions.
    pub fn sprites(&self) -> &[ImageSprite2d] {
        &self.sprites
    }

    /// Returns its creation/replacement budget.
    pub const fn budget(&self) -> ImageBatchBudget {
        self.budget
    }

    /// Returns retained CPU recovery and reusable conversion-staging bytes.
    /// Fixed inline handle/proof metadata is excluded, like Vec headers.
    pub fn recovery_memory_bytes(&self) -> usize {
        self.sprites
            .capacity()
            .saturating_mul(std::mem::size_of::<ImageSprite2d>())
            .saturating_add(
                self.instances
                    .capacity()
                    .saturating_mul(std::mem::size_of::<ImageInstance>()),
            )
    }

    /// Returns actual retained GPU buffer bytes, including reusable spare capacity.
    pub fn gpu_allocation_bytes(&self) -> usize {
        self.instance_buffer.size() as usize
    }

    /// Returns CPU capacity reusable without growing either retained array.
    pub fn capacity(&self) -> usize {
        self.sprites.capacity().min(self.instances.capacity())
    }

    pub(super) fn sprites_are_safe_for_target(
        &self,
        viewport_origin: Vec2,
        clip_transform: [f32; 4],
    ) -> bool {
        self.geometry_proof
            .validate(&self.sprites, viewport_origin, clip_transform)
    }
}

#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub(super) struct ImageInstance {
    pub(super) destination: [f32; 4],
    pub(super) uv_rect: [f32; 4],
    pub(super) tint: [f32; 4],
}

impl ImageInstance {
    const ATTRIBUTES: [wgpu::VertexAttribute; 3] =
        wgpu::vertex_attr_array![0 => Float32x4, 1 => Float32x4, 2 => Float32x4];
    const LAYOUT: wgpu::VertexBufferLayout<'static> = wgpu::VertexBufferLayout {
        array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
        step_mode: wgpu::VertexStepMode::Instance,
        attributes: &Self::ATTRIBUTES,
    };
}

#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub(super) struct ImageUniform {
    pub(super) destination: [f32; 4],
    pub(super) uv_rect: [f32; 4],
    pub(super) tint: [f32; 4],
    pub(super) world_clip_x: [f32; 4],
    pub(super) world_clip_y: [f32; 4],
    pub(super) world_mode: [f32; 4],
}

pub(super) fn batch_uniform(
    target: LogicalViewport,
    viewport_origin: Vec2,
    placement: ImageBatchPlacement,
) -> Result<ImageUniform, RendererFrameError> {
    let origin = viewport_origin + placement.translation().to_vec2();
    let destination = [2.0 / target.width(), -2.0 / target.height(), -1.0, 1.0];
    if ![origin.x, origin.y]
        .into_iter()
        .chain(destination)
        .all(is_portable_shader_source)
    {
        return Err(RendererFrameError::InvalidGeometryTransform);
    }
    Ok(ImageUniform {
        destination,
        uv_rect: [origin.x, origin.y, 0.0, 0.0],
        tint: placement.tint().to_array(),
        world_clip_x: [0.0; 4],
        world_clip_y: [0.0; 4],
        world_mode: [0.0; 4],
    })
}

pub(super) struct ImageRenderer {
    pub(super) pipeline: wgpu::RenderPipeline,
    pub(super) batch_pipeline: wgpu::RenderPipeline,
    pub(super) bind_group_layout: wgpu::BindGroupLayout,
    nearest_sampler: wgpu::Sampler,
    linear_sampler: wgpu::Sampler,
}

impl ImageRenderer {
    pub(super) fn new(
        device: &wgpu::Device,
        format: wgpu::TextureFormat,
        sample_count: u32,
    ) -> Self {
        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("sim-engine image shader"),
            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("../image.wgsl"))),
        });
        let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("sim-engine image bind group layout"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        multisampled: false,
                        view_dimension: wgpu::TextureViewDimension::D2,
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
            ],
        });
        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("sim-engine image pipeline layout"),
            bind_group_layouts: &[Some(&bind_group_layout)],
            immediate_size: 0,
        });
        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("sim-engine image pipeline"),
            layout: Some(&layout),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("image_vs_main"),
                compilation_options: wgpu::PipelineCompilationOptions::default(),
                buffers: &[],
            },
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                ..Default::default()
            },
            depth_stencil: None,
            multisample: wgpu::MultisampleState {
                count: sample_count,
                ..Default::default()
            },
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: Some("image_fs_main"),
                compilation_options: wgpu::PipelineCompilationOptions::default(),
                targets: &[Some(wgpu::ColorTargetState {
                    format,
                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
            }),
            multiview_mask: None,
            cache: None,
        });
        let batch_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("sim-engine image batch pipeline"),
            layout: Some(&layout),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("image_batch_vs_main"),
                compilation_options: wgpu::PipelineCompilationOptions::default(),
                buffers: &[Some(ImageInstance::LAYOUT)],
            },
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                ..Default::default()
            },
            depth_stencil: None,
            multisample: wgpu::MultisampleState {
                count: sample_count,
                ..Default::default()
            },
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: Some("image_fs_main"),
                compilation_options: wgpu::PipelineCompilationOptions::default(),
                targets: &[Some(wgpu::ColorTargetState {
                    format,
                    blend: Some(wgpu::BlendState::ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
            }),
            multiview_mask: None,
            cache: None,
        });
        let nearest_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("sim-engine nearest image sampler"),
            mag_filter: wgpu::FilterMode::Nearest,
            min_filter: wgpu::FilterMode::Nearest,
            ..Default::default()
        });
        let linear_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("sim-engine linear image sampler"),
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            ..Default::default()
        });
        Self {
            pipeline,
            batch_pipeline,
            bind_group_layout,
            nearest_sampler,
            linear_sampler,
        }
    }

    pub(super) fn sampler(&self, sampling: ImageSampling) -> &wgpu::Sampler {
        match sampling {
            ImageSampling::Nearest => &self.nearest_sampler,
            ImageSampling::Linear => &self.linear_sampler,
        }
    }
}

impl WgpuRenderer {
    /// Creates an image while taking ownership of its exact recovery pixels.
    pub fn create_image_rgba8(
        &self,
        width: u32,
        height: u32,
        pixels: Vec<u8>,
        budget: ImageBudget,
    ) -> Result<Image2d, ImageError> {
        create_image_resources(
            &self.device,
            &self.queue,
            Arc::clone(&self.renderer_identity),
            width,
            height,
            pixels,
            budget,
        )
    }

    /// Copies a bounded byte slice into a retained image recovery snapshot.
    pub fn create_image_rgba8_from_slice(
        &self,
        width: u32,
        height: u32,
        pixels: &[u8],
        budget: ImageBudget,
    ) -> Result<Image2d, ImageError> {
        let byte_count = validate_image_shape(
            width,
            height,
            pixels.len(),
            budget,
            self.device.limits().max_texture_dimension_2d,
        )?;
        let mut owned = Vec::new();
        owned
            .try_reserve_exact(byte_count)
            .map_err(|_| ImageError::AllocationFailed {
                requested_bytes: byte_count,
            })?;
        owned.extend_from_slice(pixels);
        self.create_image_rgba8(width, height, owned, budget)
    }

    /// Replaces dimensions and pixels atomically after full preflight.
    pub fn replace_image_rgba8(
        &self,
        image: &mut Image2d,
        width: u32,
        height: u32,
        pixels: Vec<u8>,
    ) -> Result<ImageUploadReport, ImageError> {
        self.validate_image(image)?;
        let replacement = self.create_image_rgba8(width, height, pixels, image.budget)?;
        let uploaded_bytes = replacement.pixels.len();
        *image = replacement;
        Ok(ImageUploadReport {
            uploaded_bytes,
            replaced_texture: true,
        })
    }

    /// Uploads one exact row-major RGBA region and updates recovery pixels.
    pub fn update_image_region(
        &self,
        image: &mut Image2d,
        region: ImageTexelRect,
        pixels: &[u8],
    ) -> Result<ImageUploadReport, ImageError> {
        self.validate_image(image)?;
        let required = validate_image_region_upload(image, region, pixels.len())?;
        write_image_texture(
            &self.queue,
            &image.texture,
            region.x,
            region.y,
            region.width,
            region.height,
            pixels,
        );
        let source_stride = region.width as usize * 4;
        let destination_stride = image.width as usize * 4;
        for row in 0..region.height as usize {
            let source_start = row * source_stride;
            let destination_start =
                (region.y as usize + row) * destination_stride + region.x as usize * 4;
            image.pixels[destination_start..destination_start + source_stride]
                .copy_from_slice(&pixels[source_start..source_start + source_stride]);
        }
        Ok(ImageUploadReport {
            uploaded_bytes: required,
            replaced_texture: false,
        })
    }

    /// Recreates an exact image for this renderer from retained source bytes.
    pub fn restore_image(&self, source: &Image2d) -> Result<Image2d, ImageError> {
        let mut restored = self.create_image_rgba8_from_slice(
            source.width,
            source.height,
            &source.pixels,
            source.budget,
        )?;
        restored.recovery_identity = Arc::clone(&source.recovery_identity);
        Ok(restored)
    }

    /// Creates one retained instanced batch tied to an image or atlas.
    pub fn create_image_batch(
        &self,
        image: &Image2d,
        sprites: Vec<ImageSprite2d>,
        budget: ImageBatchBudget,
    ) -> Result<ImageBatch2d, ImageError> {
        self.validate_image(image)?;
        create_image_batch_resources(
            &self.device,
            &self.queue,
            Arc::clone(&self.renderer_identity),
            image,
            sprites,
            budget,
        )
    }

    /// Updates a batch from owned input, reusing capacity when possible.
    /// Prefer [`Self::update_image_batch`] when the host retains its input storage.
    pub fn replace_image_batch(
        &self,
        image: &Image2d,
        batch: &mut ImageBatch2d,
        sprites: Vec<ImageSprite2d>,
    ) -> Result<ImageBatchUploadReport, ImageError> {
        self.update_image_batch(image, batch, &sprites)
    }

    /// Restores a batch against the restored copy of its original atlas.
    pub fn restore_image_batch(
        &self,
        image: &Image2d,
        source: &ImageBatch2d,
    ) -> Result<ImageBatch2d, ImageError> {
        self.validate_image(image)?;
        restore_image_batch_resources(
            &self.device,
            &self.queue,
            Arc::clone(&self.renderer_identity),
            image,
            source,
            source.budget,
        )
    }

    pub(super) fn validate_image(&self, image: &Image2d) -> Result<(), ImageError> {
        prepared_scene_belongs_to(&self.renderer_identity, &image.renderer_identity)
            .then_some(())
            .ok_or(ImageError::RendererMismatch)
    }

    pub(super) fn validate_image_batch(
        &self,
        image: &Image2d,
        batch: &ImageBatch2d,
    ) -> Result<(), ImageError> {
        self.validate_image(image)?;
        validate_batch_image(image, batch)
    }
}

pub(super) fn restore_image_batch_resources(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    renderer_identity: Arc<()>,
    image: &Image2d,
    source: &ImageBatch2d,
    budget: ImageBatchBudget,
) -> Result<ImageBatch2d, ImageError> {
    if !Arc::ptr_eq(&renderer_identity, &image.renderer_identity) {
        return Err(ImageError::RendererMismatch);
    }
    if !Arc::ptr_eq(&image.recovery_identity, &source.image_recovery_identity) {
        return Err(ImageError::RecoverySourceMismatch);
    }
    preflight_image_batch_capacity(device, source.sprites.len(), budget)?;
    let mut sprites = Vec::new();
    let requested_bytes = source
        .sprites
        .len()
        .checked_mul(std::mem::size_of::<ImageSprite2d>())
        .ok_or(ImageError::DimensionsTooLarge)?;
    sprites
        .try_reserve_exact(source.sprites.len())
        .map_err(|_| ImageError::AllocationFailed { requested_bytes })?;
    sprites.extend_from_slice(&source.sprites);
    create_image_batch_resources(device, queue, renderer_identity, image, sprites, budget)
}

pub(super) fn validate_batch_image(
    image: &Image2d,
    batch: &ImageBatch2d,
) -> Result<(), ImageError> {
    if !prepared_scene_belongs_to(&image.renderer_identity, &batch.renderer_identity)
        || !prepared_scene_belongs_to(&image.resource_identity, &batch.image_identity)
    {
        return Err(ImageError::RendererMismatch);
    }
    Ok(())
}

pub(super) fn validate_image_region_upload(
    image: &Image2d,
    region: ImageTexelRect,
    pixel_count: usize,
) -> Result<usize, ImageError> {
    if !region.fits(image.width, image.height) {
        return Err(ImageError::UpdateRegionOutOfBounds);
    }
    let required =
        image_byte_count(region.width, region.height).ok_or(ImageError::DimensionsTooLarge)?;
    if pixel_count != required {
        return Err(ImageError::InvalidPixelCount);
    }
    Ok(required)
}

#[allow(clippy::too_many_arguments)]
pub(super) fn create_image_batch_resources(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    renderer_identity: Arc<()>,
    image: &Image2d,
    sprites: Vec<ImageSprite2d>,
    budget: ImageBatchBudget,
) -> Result<ImageBatch2d, ImageError> {
    preflight_image_batch_capacity(device, sprites.len(), budget)?;
    let gpu_bytes = sprites
        .len()
        .max(1)
        .checked_mul(std::mem::size_of::<ImageInstance>())
        .ok_or(ImageError::DimensionsTooLarge)?;
    if sprites.iter().any(|sprite| {
        !sprite.source.fits(image.width, image.height)
            || !sprite.tint.is_normalized()
            || !logical_image_region_is_portable(sprite.destination)
    }) {
        return Err(ImageError::InvalidSprite);
    }
    let staging_bytes = sprites
        .len()
        .saturating_mul(std::mem::size_of::<ImageInstance>());
    let sprites = compact_vec_with_byte_limit(
        sprites,
        budget.max_retained_bytes.saturating_sub(staging_bytes),
        |actual| ImageError::BatchBudgetExceeded {
            limit: budget.max_retained_bytes,
            actual,
        },
    )?;
    let mut instances = Vec::new();
    instances
        .try_reserve_exact(sprites.len())
        .map_err(|_| ImageError::AllocationFailed {
            requested_bytes: sprites
                .len()
                .saturating_mul(std::mem::size_of::<ImageInstance>()),
        })?;
    for sprite in &sprites {
        let origin = sprite.destination.origin().to_vec2();
        let viewport = sprite.destination.viewport();
        let image_width = image.width as f32;
        let image_height = image.height as f32;
        let source = sprite.source;
        let instance = ImageInstance {
            destination: [origin.x, origin.y, viewport.width(), viewport.height()],
            uv_rect: [
                (source.x as f32 + 0.5) / image_width,
                (source.y as f32 + 0.5) / image_height,
                (source.x as f32 + source.width as f32 - 0.5) / image_width,
                (source.y as f32 + source.height as f32 - 0.5) / image_height,
            ],
            tint: sprite.tint.to_array(),
        };
        if !instance
            .destination
            .iter()
            .chain(instance.uv_rect.iter())
            .chain(instance.tint.iter())
            .all(|value| value.is_finite())
        {
            return Err(ImageError::InvalidSprite);
        }
        instances.push(instance);
    }
    let retained_bytes = sprites
        .capacity()
        .saturating_mul(std::mem::size_of::<ImageSprite2d>())
        .saturating_add(
            instances
                .capacity()
                .saturating_mul(std::mem::size_of::<ImageInstance>()),
        );
    if retained_bytes > budget.max_retained_bytes {
        return Err(ImageError::BatchBudgetExceeded {
            limit: budget.max_retained_bytes,
            actual: retained_bytes,
        });
    }
    let instance_buffer = device.create_buffer(&wgpu::BufferDescriptor {
        label: Some("sim-engine retained image sprite instances"),
        size: gpu_bytes as wgpu::BufferAddress,
        usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
        mapped_at_creation: false,
    });
    if !instances.is_empty() {
        queue.write_buffer(&instance_buffer, 0, bytemuck::cast_slice(&instances));
        submit_pending_uploads(queue);
    }
    Ok(ImageBatch2d {
        renderer_identity,
        image_identity: Arc::clone(&image.resource_identity),
        image_recovery_identity: Arc::clone(&image.recovery_identity),
        instance_buffer,
        sprites,
        instances,
        budget,
        geometry_proof: BatchProofCache::default(),
    })
}

pub(super) fn logical_image_region_is_portable(region: LogicalViewportRegion) -> bool {
    let origin = region.origin().to_vec2();
    let size = region.viewport().size();
    let components = [origin.x, origin.y, size.x, size.y];
    if !components.into_iter().all(is_portable_shader_source) {
        return false;
    }
    // A sufficient certificate for the exact two-term interval proof below.
    // Each signed partial sum and magnitude sum is <= MAX/2. There are at most
    // two rounding operations, so gamma(2) * MAX/2 + 2*MIN_POSITIVE cannot reach
    // the remaining MAX/2 headroom. Source subnormals were rejected above.
    // This skips no downstream target/clip proof and expands no accepted input.
    if components
        .into_iter()
        .all(|value| value.abs() <= super::MAX_PORTABLE_SHADER_VALUE * 0.25)
    {
        return true;
    }
    shader_interval_sum_range([
        (f64::from(origin.x), f64::from(origin.x)),
        (0.0, f64::from(size.x)),
    ])
    .is_some()
        && shader_interval_sum_range([
            (f64::from(origin.y), f64::from(origin.y)),
            (0.0, f64::from(size.y)),
        ])
        .is_some()
}

#[allow(clippy::too_many_arguments)]
pub(super) fn create_image_resources(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    renderer_identity: Arc<()>,
    width: u32,
    height: u32,
    pixels: Vec<u8>,
    budget: ImageBudget,
) -> Result<Image2d, ImageError> {
    validate_image_shape(
        width,
        height,
        pixels.len(),
        budget,
        device.limits().max_texture_dimension_2d,
    )?;
    // Do not retain an arbitrarily over-capacity caller allocation behind a
    // small logical image budget. Compaction finishes before GPU mutation.
    let pixels = compact_vec_with_byte_limit(pixels, budget.max_bytes, |actual| {
        ImageError::BudgetExceeded {
            limit: budget.max_bytes,
            actual,
        }
    })?;
    let texture = device.create_texture(&wgpu::TextureDescriptor {
        label: Some("sim-engine retained RGBA image"),
        size: wgpu::Extent3d {
            width,
            height,
            depth_or_array_layers: 1,
        },
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format: IMAGE_FORMAT,
        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
        view_formats: &[],
    });
    write_image_texture(queue, &texture, 0, 0, width, height, &pixels);
    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
    Ok(Image2d {
        renderer_identity,
        resource_identity: Arc::new(()),
        recovery_identity: Arc::new(()),
        texture,
        view,
        width,
        height,
        pixels,
        budget,
    })
}

fn compact_vec_with_byte_limit<T: Copy>(
    values: Vec<T>,
    maximum_bytes: usize,
    capacity_error: impl FnOnce(usize) -> ImageError,
) -> Result<Vec<T>, ImageError> {
    let element_size = std::mem::size_of::<T>();
    let allocation_bytes = values.capacity().saturating_mul(element_size);
    if allocation_bytes <= maximum_bytes {
        return Ok(values);
    }
    let requested_bytes = values
        .len()
        .checked_mul(element_size)
        .ok_or(ImageError::DimensionsTooLarge)?;
    let mut compact = Vec::new();
    compact
        .try_reserve_exact(values.len())
        .map_err(|_| ImageError::AllocationFailed { requested_bytes })?;
    compact.extend_from_slice(&values);
    let actual = compact.capacity().saturating_mul(element_size);
    if actual > maximum_bytes {
        return Err(capacity_error(actual));
    }
    Ok(compact)
}

pub(super) fn validate_image_shape(
    width: u32,
    height: u32,
    pixel_count: usize,
    budget: ImageBudget,
    max_texture_dimension: u32,
) -> Result<usize, ImageError> {
    if width == 0 || height == 0 {
        return Err(ImageError::ZeroDimension);
    }
    if width > budget.max_width
        || height > budget.max_height
        || width > max_texture_dimension
        || height > max_texture_dimension
        || width.checked_mul(4).is_none()
    {
        return Err(ImageError::DimensionsTooLarge);
    }
    let bytes = image_byte_count(width, height).ok_or(ImageError::DimensionsTooLarge)?;
    if bytes > budget.max_bytes {
        return Err(ImageError::BudgetExceeded {
            limit: budget.max_bytes,
            actual: bytes,
        });
    }
    if pixel_count != bytes {
        return Err(ImageError::InvalidPixelCount);
    }
    Ok(bytes)
}

pub(super) fn preflight_image_batch_capacity(
    device: &wgpu::Device,
    sprite_count: usize,
    budget: ImageBatchBudget,
) -> Result<(), ImageError> {
    if sprite_count > budget.max_sprites {
        return Err(ImageError::BatchBudgetExceeded {
            limit: budget.max_sprites,
            actual: sprite_count,
        });
    }
    if u32::try_from(sprite_count).is_err() {
        return Err(ImageError::DimensionsTooLarge);
    }
    let retained_bytes = sprite_count
        .checked_mul(batch_retained_bytes(1))
        .ok_or(ImageError::DimensionsTooLarge)?;
    if retained_bytes > budget.max_retained_bytes {
        return Err(ImageError::BatchBudgetExceeded {
            limit: budget.max_retained_bytes,
            actual: retained_bytes,
        });
    }
    let gpu_bytes = sprite_count
        .max(1)
        .checked_mul(std::mem::size_of::<ImageInstance>())
        .ok_or(ImageError::DimensionsTooLarge)?;
    if gpu_bytes as u64 > device.limits().max_buffer_size {
        return Err(ImageError::DimensionsTooLarge);
    }
    Ok(())
}

fn image_byte_count(width: u32, height: u32) -> Option<usize> {
    (width as usize)
        .checked_mul(height as usize)?
        .checked_mul(4)
}

#[allow(clippy::too_many_arguments)]
fn write_image_texture(
    queue: &wgpu::Queue,
    texture: &wgpu::Texture,
    x: u32,
    y: u32,
    width: u32,
    height: u32,
    pixels: &[u8],
) {
    queue.write_texture(
        wgpu::TexelCopyTextureInfo {
            texture,
            mip_level: 0,
            origin: wgpu::Origin3d { x, y, z: 0 },
            aspect: wgpu::TextureAspect::All,
        },
        pixels,
        wgpu::TexelCopyBufferLayout {
            offset: 0,
            bytes_per_row: Some(width * 4),
            rows_per_image: Some(height),
        },
        wgpu::Extent3d {
            width,
            height,
            depth_or_array_layers: 1,
        },
    );
    submit_pending_uploads(queue);
}

#[cfg(test)]
mod tests;