1use super::*;
2
3const IMAGE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8UnormSrgb;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub struct ImageBudget {
8 max_width: u32,
9 max_height: u32,
10 max_bytes: usize,
11}
12
13impl ImageBudget {
14 pub fn new(max_width: u32, max_height: u32, max_bytes: usize) -> Result<Self, ImageError> {
16 if max_width == 0 || max_height == 0 || max_bytes < 4 {
17 return Err(ImageError::InvalidBudget);
18 }
19 Ok(Self {
20 max_width,
21 max_height,
22 max_bytes,
23 })
24 }
25
26 pub const fn max_width(self) -> u32 {
28 self.max_width
29 }
30
31 pub const fn max_height(self) -> u32 {
33 self.max_height
34 }
35
36 pub const fn max_bytes(self) -> usize {
38 self.max_bytes
39 }
40}
41
42impl Default for ImageBudget {
43 fn default() -> Self {
44 Self {
45 max_width: 4096,
46 max_height: 4096,
47 max_bytes: 64 * 1024 * 1024,
48 }
49 }
50}
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub struct ImageTexelRect {
55 x: u32,
56 y: u32,
57 width: u32,
58 height: u32,
59}
60
61impl ImageTexelRect {
62 pub fn new(x: u32, y: u32, width: u32, height: u32) -> Result<Self, ImageError> {
64 if width == 0 || height == 0 {
65 return Err(ImageError::ZeroDimension);
66 }
67 x.checked_add(width)
68 .zip(y.checked_add(height))
69 .ok_or(ImageError::DimensionsTooLarge)?;
70 Ok(Self {
71 x,
72 y,
73 width,
74 height,
75 })
76 }
77
78 pub const fn x(self) -> u32 {
80 self.x
81 }
82
83 pub const fn y(self) -> u32 {
85 self.y
86 }
87
88 pub const fn width(self) -> u32 {
90 self.width
91 }
92
93 pub const fn height(self) -> u32 {
95 self.height
96 }
97
98 pub(super) fn fits(self, width: u32, height: u32) -> bool {
99 self.x
100 .checked_add(self.width)
101 .is_some_and(|maximum| maximum <= width)
102 && self
103 .y
104 .checked_add(self.height)
105 .is_some_and(|maximum| maximum <= height)
106 }
107}
108
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
111pub enum ImageSampling {
112 #[default]
114 Nearest,
115 Linear,
117}
118
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub enum ImageError {
122 ZeroDimension,
124 InvalidBudget,
126 DimensionsTooLarge,
128 InvalidPixelCount,
130 BudgetExceeded {
132 limit: usize,
134 actual: usize,
136 },
137 AllocationFailed {
140 requested_bytes: usize,
142 },
143 RendererMismatch,
145 RecoverySourceMismatch,
147 UpdateRegionOutOfBounds,
149 InvalidSprite,
151 BatchBudgetExceeded {
153 limit: usize,
155 actual: usize,
157 },
158}
159
160impl fmt::Display for ImageError {
161 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
162 match self {
163 Self::ZeroDimension => write!(formatter, "image dimensions must be non-zero"),
164 Self::InvalidBudget => write!(
165 formatter,
166 "resource budget must fit at least one image texel or batch element"
167 ),
168 Self::DimensionsTooLarge => write!(formatter, "image dimensions exceed limits"),
169 Self::InvalidPixelCount => write!(formatter, "image RGBA byte count is invalid"),
170 Self::BudgetExceeded { limit, actual } => {
171 write!(
172 formatter,
173 "image requires {actual} bytes, over limit {limit}"
174 )
175 }
176 Self::AllocationFailed { requested_bytes } => write!(
177 formatter,
178 "could not reserve {requested_bytes} bytes for image storage or staging"
179 ),
180 Self::RendererMismatch => write!(formatter, "image belongs to another renderer"),
181 Self::RecoverySourceMismatch => {
182 write!(
183 formatter,
184 "image is not a restored copy of the recovery source"
185 )
186 }
187 Self::UpdateRegionOutOfBounds => write!(formatter, "image update is out of bounds"),
188 Self::InvalidSprite => write!(formatter, "image sprite source or tint is invalid"),
189 Self::BatchBudgetExceeded { limit, actual } => {
190 write!(formatter, "image batch work {actual} exceeds limit {limit}")
191 }
192 }
193 }
194}
195
196impl Error for ImageError {}
197
198#[derive(Debug, Clone, Copy, PartialEq, Eq)]
200pub struct ImageUploadReport {
201 uploaded_bytes: usize,
202 replaced_texture: bool,
203}
204
205impl ImageUploadReport {
206 pub const fn uploaded_bytes(self) -> usize {
208 self.uploaded_bytes
209 }
210
211 pub const fn replaced_texture(self) -> bool {
213 self.replaced_texture
214 }
215}
216
217#[derive(Debug, Clone, Copy, PartialEq, Eq)]
223pub struct ImageBatchUploadReport {
224 uploaded_instance_bytes: usize,
225 replaced_instance_buffer: bool,
226}
227
228impl ImageBatchUploadReport {
229 pub const fn uploaded_instance_bytes(self) -> usize {
231 self.uploaded_instance_bytes
232 }
233
234 pub const fn replaced_instance_buffer(self) -> bool {
236 self.replaced_instance_buffer
237 }
238}
239
240pub struct Image2d {
246 renderer_identity: Arc<()>,
247 pub(super) resource_identity: Arc<()>,
248 pub(super) recovery_identity: Arc<()>,
249 texture: wgpu::Texture,
250 pub(super) view: wgpu::TextureView,
251 width: u32,
252 height: u32,
253 pixels: Vec<u8>,
254 budget: ImageBudget,
255}
256
257impl Image2d {
258 pub const fn width(&self) -> u32 {
260 self.width
261 }
262
263 pub const fn height(&self) -> u32 {
265 self.height
266 }
267
268 pub const fn size(&self) -> (u32, u32) {
270 (self.width, self.height)
271 }
272
273 pub const fn budget(&self) -> ImageBudget {
275 self.budget
276 }
277
278 pub fn pixels(&self) -> &[u8] {
280 &self.pixels
281 }
282
283 pub fn recovery_memory_bytes(&self) -> usize {
285 self.pixels.capacity()
286 }
287
288 pub fn gpu_allocation_bytes(&self) -> usize {
291 self.pixels.len()
292 }
293
294 pub fn full_rect(&self) -> ImageTexelRect {
296 ImageTexelRect {
297 x: 0,
298 y: 0,
299 width: self.width,
300 height: self.height,
301 }
302 }
303}
304
305#[derive(Debug, Clone, Copy, PartialEq)]
307pub struct ImageSprite2d {
308 source: ImageTexelRect,
309 destination: LogicalViewportRegion,
310 tint: Color,
311}
312
313impl ImageSprite2d {
314 pub fn new(
316 source: ImageTexelRect,
317 destination: LogicalViewportRegion,
318 tint: Color,
319 ) -> Result<Self, ImageError> {
320 let origin = destination.origin().to_vec2();
321 let end = origin + destination.viewport().size();
322 if !tint.is_normalized() || !origin.is_finite() || !end.is_finite() {
323 return Err(ImageError::InvalidSprite);
324 }
325 Ok(Self {
326 source,
327 destination,
328 tint,
329 })
330 }
331
332 pub const fn source(self) -> ImageTexelRect {
334 self.source
335 }
336
337 pub const fn destination(self) -> LogicalViewportRegion {
339 self.destination
340 }
341
342 pub const fn tint(self) -> Color {
344 self.tint
345 }
346}
347
348#[derive(Debug, Clone, Copy, PartialEq, Eq)]
350pub struct ImageBatchBudget {
351 max_sprites: usize,
352 max_retained_bytes: usize,
353}
354
355impl ImageBatchBudget {
356 pub fn new(max_sprites: usize, max_retained_bytes: usize) -> Result<Self, ImageError> {
358 if max_sprites == 0 || max_retained_bytes < std::mem::size_of::<ImageSprite2d>() {
359 return Err(ImageError::InvalidBudget);
360 }
361 Ok(Self {
362 max_sprites,
363 max_retained_bytes,
364 })
365 }
366
367 pub const fn max_sprites(self) -> usize {
369 self.max_sprites
370 }
371
372 pub const fn max_retained_bytes(self) -> usize {
374 self.max_retained_bytes
375 }
376}
377
378impl Default for ImageBatchBudget {
379 fn default() -> Self {
380 Self {
381 max_sprites: 100_000,
382 max_retained_bytes: 16 * 1024 * 1024,
383 }
384 }
385}
386
387pub struct ImageBatch2d {
394 renderer_identity: Arc<()>,
395 image_identity: Arc<()>,
396 pub(super) image_recovery_identity: Arc<()>,
397 pub(super) instance_buffer: wgpu::Buffer,
398 sprites: Vec<ImageSprite2d>,
399 budget: ImageBatchBudget,
400}
401
402impl ImageBatch2d {
403 pub fn sprite_count(&self) -> usize {
405 self.sprites.len()
406 }
407
408 pub fn sprites(&self) -> &[ImageSprite2d] {
410 &self.sprites
411 }
412
413 pub const fn budget(&self) -> ImageBatchBudget {
415 self.budget
416 }
417
418 pub fn recovery_memory_bytes(&self) -> usize {
420 self.sprites
421 .capacity()
422 .saturating_mul(std::mem::size_of::<ImageSprite2d>())
423 }
424
425 pub fn gpu_allocation_bytes(&self) -> usize {
427 self.sprites
428 .len()
429 .max(1)
430 .saturating_mul(std::mem::size_of::<ImageInstance>())
431 }
432}
433
434#[repr(C)]
435#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
436pub(super) struct ImageInstance {
437 pub(super) destination: [f32; 4],
438 pub(super) uv_rect: [f32; 4],
439 pub(super) tint: [f32; 4],
440}
441
442impl ImageInstance {
443 const ATTRIBUTES: [wgpu::VertexAttribute; 3] =
444 wgpu::vertex_attr_array![0 => Float32x4, 1 => Float32x4, 2 => Float32x4];
445 const LAYOUT: wgpu::VertexBufferLayout<'static> = wgpu::VertexBufferLayout {
446 array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
447 step_mode: wgpu::VertexStepMode::Instance,
448 attributes: &Self::ATTRIBUTES,
449 };
450}
451
452#[repr(C)]
453#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
454pub(super) struct ImageUniform {
455 pub(super) destination: [f32; 4],
456 pub(super) uv_rect: [f32; 4],
457 pub(super) tint: [f32; 4],
458 pub(super) world_clip_x: [f32; 4],
459 pub(super) world_clip_y: [f32; 4],
460 pub(super) world_mode: [f32; 4],
461}
462
463pub(super) struct ImageRenderer {
464 pub(super) pipeline: wgpu::RenderPipeline,
465 pub(super) batch_pipeline: wgpu::RenderPipeline,
466 pub(super) bind_group_layout: wgpu::BindGroupLayout,
467 nearest_sampler: wgpu::Sampler,
468 linear_sampler: wgpu::Sampler,
469}
470
471impl ImageRenderer {
472 pub(super) fn new(
473 device: &wgpu::Device,
474 format: wgpu::TextureFormat,
475 sample_count: u32,
476 ) -> Self {
477 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
478 label: Some("sim-engine image shader"),
479 source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("image.wgsl"))),
480 });
481 let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
482 label: Some("sim-engine image bind group layout"),
483 entries: &[
484 wgpu::BindGroupLayoutEntry {
485 binding: 0,
486 visibility: wgpu::ShaderStages::FRAGMENT,
487 ty: wgpu::BindingType::Texture {
488 multisampled: false,
489 view_dimension: wgpu::TextureViewDimension::D2,
490 sample_type: wgpu::TextureSampleType::Float { filterable: true },
491 },
492 count: None,
493 },
494 wgpu::BindGroupLayoutEntry {
495 binding: 1,
496 visibility: wgpu::ShaderStages::FRAGMENT,
497 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
498 count: None,
499 },
500 wgpu::BindGroupLayoutEntry {
501 binding: 2,
502 visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
503 ty: wgpu::BindingType::Buffer {
504 ty: wgpu::BufferBindingType::Uniform,
505 has_dynamic_offset: false,
506 min_binding_size: None,
507 },
508 count: None,
509 },
510 ],
511 });
512 let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
513 label: Some("sim-engine image pipeline layout"),
514 bind_group_layouts: &[Some(&bind_group_layout)],
515 immediate_size: 0,
516 });
517 let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
518 label: Some("sim-engine image pipeline"),
519 layout: Some(&layout),
520 vertex: wgpu::VertexState {
521 module: &shader,
522 entry_point: Some("image_vs_main"),
523 compilation_options: wgpu::PipelineCompilationOptions::default(),
524 buffers: &[],
525 },
526 primitive: wgpu::PrimitiveState {
527 topology: wgpu::PrimitiveTopology::TriangleList,
528 ..Default::default()
529 },
530 depth_stencil: None,
531 multisample: wgpu::MultisampleState {
532 count: sample_count,
533 ..Default::default()
534 },
535 fragment: Some(wgpu::FragmentState {
536 module: &shader,
537 entry_point: Some("image_fs_main"),
538 compilation_options: wgpu::PipelineCompilationOptions::default(),
539 targets: &[Some(wgpu::ColorTargetState {
540 format,
541 blend: Some(wgpu::BlendState::ALPHA_BLENDING),
542 write_mask: wgpu::ColorWrites::ALL,
543 })],
544 }),
545 multiview_mask: None,
546 cache: None,
547 });
548 let batch_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
549 label: Some("sim-engine image batch pipeline"),
550 layout: Some(&layout),
551 vertex: wgpu::VertexState {
552 module: &shader,
553 entry_point: Some("image_batch_vs_main"),
554 compilation_options: wgpu::PipelineCompilationOptions::default(),
555 buffers: &[Some(ImageInstance::LAYOUT)],
556 },
557 primitive: wgpu::PrimitiveState {
558 topology: wgpu::PrimitiveTopology::TriangleList,
559 ..Default::default()
560 },
561 depth_stencil: None,
562 multisample: wgpu::MultisampleState {
563 count: sample_count,
564 ..Default::default()
565 },
566 fragment: Some(wgpu::FragmentState {
567 module: &shader,
568 entry_point: Some("image_fs_main"),
569 compilation_options: wgpu::PipelineCompilationOptions::default(),
570 targets: &[Some(wgpu::ColorTargetState {
571 format,
572 blend: Some(wgpu::BlendState::ALPHA_BLENDING),
573 write_mask: wgpu::ColorWrites::ALL,
574 })],
575 }),
576 multiview_mask: None,
577 cache: None,
578 });
579 let nearest_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
580 label: Some("sim-engine nearest image sampler"),
581 mag_filter: wgpu::FilterMode::Nearest,
582 min_filter: wgpu::FilterMode::Nearest,
583 ..Default::default()
584 });
585 let linear_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
586 label: Some("sim-engine linear image sampler"),
587 mag_filter: wgpu::FilterMode::Linear,
588 min_filter: wgpu::FilterMode::Linear,
589 ..Default::default()
590 });
591 Self {
592 pipeline,
593 batch_pipeline,
594 bind_group_layout,
595 nearest_sampler,
596 linear_sampler,
597 }
598 }
599
600 pub(super) fn sampler(&self, sampling: ImageSampling) -> &wgpu::Sampler {
601 match sampling {
602 ImageSampling::Nearest => &self.nearest_sampler,
603 ImageSampling::Linear => &self.linear_sampler,
604 }
605 }
606}
607
608impl WgpuRenderer {
609 pub fn create_image_rgba8(
611 &self,
612 width: u32,
613 height: u32,
614 pixels: Vec<u8>,
615 budget: ImageBudget,
616 ) -> Result<Image2d, ImageError> {
617 create_image_resources(
618 &self.device,
619 &self.queue,
620 Arc::clone(&self.renderer_identity),
621 width,
622 height,
623 pixels,
624 budget,
625 )
626 }
627
628 pub fn create_image_rgba8_from_slice(
630 &self,
631 width: u32,
632 height: u32,
633 pixels: &[u8],
634 budget: ImageBudget,
635 ) -> Result<Image2d, ImageError> {
636 let byte_count = validate_image_shape(
637 width,
638 height,
639 pixels.len(),
640 budget,
641 self.device.limits().max_texture_dimension_2d,
642 )?;
643 let mut owned = Vec::new();
644 owned
645 .try_reserve_exact(byte_count)
646 .map_err(|_| ImageError::AllocationFailed {
647 requested_bytes: byte_count,
648 })?;
649 owned.extend_from_slice(pixels);
650 self.create_image_rgba8(width, height, owned, budget)
651 }
652
653 pub fn replace_image_rgba8(
655 &self,
656 image: &mut Image2d,
657 width: u32,
658 height: u32,
659 pixels: Vec<u8>,
660 ) -> Result<ImageUploadReport, ImageError> {
661 self.validate_image(image)?;
662 let replacement = self.create_image_rgba8(width, height, pixels, image.budget)?;
663 let uploaded_bytes = replacement.pixels.len();
664 *image = replacement;
665 Ok(ImageUploadReport {
666 uploaded_bytes,
667 replaced_texture: true,
668 })
669 }
670
671 pub fn update_image_region(
673 &self,
674 image: &mut Image2d,
675 region: ImageTexelRect,
676 pixels: &[u8],
677 ) -> Result<ImageUploadReport, ImageError> {
678 self.validate_image(image)?;
679 let required = validate_image_region_upload(image, region, pixels.len())?;
680 write_image_texture(
681 &self.queue,
682 &image.texture,
683 region.x,
684 region.y,
685 region.width,
686 region.height,
687 pixels,
688 );
689 let source_stride = region.width as usize * 4;
690 let destination_stride = image.width as usize * 4;
691 for row in 0..region.height as usize {
692 let source_start = row * source_stride;
693 let destination_start =
694 (region.y as usize + row) * destination_stride + region.x as usize * 4;
695 image.pixels[destination_start..destination_start + source_stride]
696 .copy_from_slice(&pixels[source_start..source_start + source_stride]);
697 }
698 Ok(ImageUploadReport {
699 uploaded_bytes: required,
700 replaced_texture: false,
701 })
702 }
703
704 pub fn restore_image(&self, source: &Image2d) -> Result<Image2d, ImageError> {
706 let mut restored = self.create_image_rgba8_from_slice(
707 source.width,
708 source.height,
709 &source.pixels,
710 source.budget,
711 )?;
712 restored.recovery_identity = Arc::clone(&source.recovery_identity);
713 Ok(restored)
714 }
715
716 pub fn create_image_batch(
718 &self,
719 image: &Image2d,
720 sprites: Vec<ImageSprite2d>,
721 budget: ImageBatchBudget,
722 ) -> Result<ImageBatch2d, ImageError> {
723 self.validate_image(image)?;
724 create_image_batch_resources(
725 &self.device,
726 &self.queue,
727 Arc::clone(&self.renderer_identity),
728 image,
729 sprites,
730 budget,
731 )
732 }
733
734 pub fn replace_image_batch(
736 &self,
737 image: &Image2d,
738 batch: &mut ImageBatch2d,
739 sprites: Vec<ImageSprite2d>,
740 ) -> Result<ImageBatchUploadReport, ImageError> {
741 self.validate_image_batch(image, batch)?;
742 let replacement = self.create_image_batch(image, sprites, batch.budget)?;
743 let uploaded_bytes = replacement
744 .sprites
745 .len()
746 .saturating_mul(std::mem::size_of::<ImageInstance>());
747 *batch = replacement;
748 Ok(ImageBatchUploadReport {
749 uploaded_instance_bytes: uploaded_bytes,
750 replaced_instance_buffer: true,
751 })
752 }
753
754 pub fn restore_image_batch(
756 &self,
757 image: &Image2d,
758 source: &ImageBatch2d,
759 ) -> Result<ImageBatch2d, ImageError> {
760 self.validate_image(image)?;
761 if !Arc::ptr_eq(&image.recovery_identity, &source.image_recovery_identity) {
762 return Err(ImageError::RecoverySourceMismatch);
763 }
764 preflight_image_batch_capacity(&self.device, source.sprites.len(), source.budget)?;
765 let mut sprites = Vec::new();
766 let requested_bytes = source
767 .sprites
768 .len()
769 .checked_mul(std::mem::size_of::<ImageSprite2d>())
770 .ok_or(ImageError::DimensionsTooLarge)?;
771 sprites
772 .try_reserve_exact(source.sprites.len())
773 .map_err(|_| ImageError::AllocationFailed { requested_bytes })?;
774 sprites.extend_from_slice(&source.sprites);
775 self.create_image_batch(image, sprites, source.budget)
776 }
777
778 pub(super) fn validate_image(&self, image: &Image2d) -> Result<(), ImageError> {
779 prepared_scene_belongs_to(&self.renderer_identity, &image.renderer_identity)
780 .then_some(())
781 .ok_or(ImageError::RendererMismatch)
782 }
783
784 pub(super) fn validate_image_batch(
785 &self,
786 image: &Image2d,
787 batch: &ImageBatch2d,
788 ) -> Result<(), ImageError> {
789 self.validate_image(image)?;
790 if !prepared_scene_belongs_to(&self.renderer_identity, &batch.renderer_identity)
791 || !prepared_scene_belongs_to(&image.resource_identity, &batch.image_identity)
792 {
793 return Err(ImageError::RendererMismatch);
794 }
795 Ok(())
796 }
797}
798
799pub(super) fn validate_image_region_upload(
800 image: &Image2d,
801 region: ImageTexelRect,
802 pixel_count: usize,
803) -> Result<usize, ImageError> {
804 if !region.fits(image.width, image.height) {
805 return Err(ImageError::UpdateRegionOutOfBounds);
806 }
807 let required =
808 image_byte_count(region.width, region.height).ok_or(ImageError::DimensionsTooLarge)?;
809 if pixel_count != required {
810 return Err(ImageError::InvalidPixelCount);
811 }
812 Ok(required)
813}
814
815#[allow(clippy::too_many_arguments)]
816pub(super) fn create_image_batch_resources(
817 device: &wgpu::Device,
818 queue: &wgpu::Queue,
819 renderer_identity: Arc<()>,
820 image: &Image2d,
821 sprites: Vec<ImageSprite2d>,
822 budget: ImageBatchBudget,
823) -> Result<ImageBatch2d, ImageError> {
824 preflight_image_batch_capacity(device, sprites.len(), budget)?;
825 let gpu_bytes = sprites
826 .len()
827 .max(1)
828 .checked_mul(std::mem::size_of::<ImageInstance>())
829 .ok_or(ImageError::DimensionsTooLarge)?;
830 if sprites.iter().any(|sprite| {
831 !sprite.source.fits(image.width, image.height)
832 || !sprite.tint.is_normalized()
833 || !logical_image_region_is_portable(sprite.destination)
834 }) {
835 return Err(ImageError::InvalidSprite);
836 }
837 let sprites = compact_vec_with_byte_limit(sprites, budget.max_retained_bytes, |actual| {
838 ImageError::BatchBudgetExceeded {
839 limit: budget.max_retained_bytes,
840 actual,
841 }
842 })?;
843 let mut instances = Vec::new();
844 instances
845 .try_reserve_exact(sprites.len())
846 .map_err(|_| ImageError::AllocationFailed {
847 requested_bytes: sprites
848 .len()
849 .saturating_mul(std::mem::size_of::<ImageInstance>()),
850 })?;
851 for sprite in &sprites {
852 let origin = sprite.destination.origin().to_vec2();
853 let viewport = sprite.destination.viewport();
854 let image_width = image.width as f32;
855 let image_height = image.height as f32;
856 let source = sprite.source;
857 let instance = ImageInstance {
858 destination: [origin.x, origin.y, viewport.width(), viewport.height()],
859 uv_rect: [
860 (source.x as f32 + 0.5) / image_width,
861 (source.y as f32 + 0.5) / image_height,
862 (source.x as f32 + source.width as f32 - 0.5) / image_width,
863 (source.y as f32 + source.height as f32 - 0.5) / image_height,
864 ],
865 tint: sprite.tint.to_array(),
866 };
867 if !instance
868 .destination
869 .iter()
870 .chain(instance.uv_rect.iter())
871 .chain(instance.tint.iter())
872 .all(|value| value.is_finite())
873 {
874 return Err(ImageError::InvalidSprite);
875 }
876 instances.push(instance);
877 }
878 let instance_buffer = device.create_buffer(&wgpu::BufferDescriptor {
879 label: Some("sim-engine retained image sprite instances"),
880 size: gpu_bytes as wgpu::BufferAddress,
881 usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
882 mapped_at_creation: false,
883 });
884 if !instances.is_empty() {
885 queue.write_buffer(&instance_buffer, 0, bytemuck::cast_slice(&instances));
886 submit_pending_uploads(queue);
887 }
888 Ok(ImageBatch2d {
889 renderer_identity,
890 image_identity: Arc::clone(&image.resource_identity),
891 image_recovery_identity: Arc::clone(&image.recovery_identity),
892 instance_buffer,
893 sprites,
894 budget,
895 })
896}
897
898pub(super) fn logical_image_region_is_portable(region: LogicalViewportRegion) -> bool {
899 let origin = region.origin().to_vec2();
900 let size = region.viewport().size();
901 [origin.x, origin.y, size.x, size.y]
902 .into_iter()
903 .all(is_portable_shader_source)
904 && shader_interval_sum_range([
905 (f64::from(origin.x), f64::from(origin.x)),
906 (0.0, f64::from(size.x)),
907 ])
908 .is_some()
909 && shader_interval_sum_range([
910 (f64::from(origin.y), f64::from(origin.y)),
911 (0.0, f64::from(size.y)),
912 ])
913 .is_some()
914}
915
916#[allow(clippy::too_many_arguments)]
917pub(super) fn create_image_resources(
918 device: &wgpu::Device,
919 queue: &wgpu::Queue,
920 renderer_identity: Arc<()>,
921 width: u32,
922 height: u32,
923 pixels: Vec<u8>,
924 budget: ImageBudget,
925) -> Result<Image2d, ImageError> {
926 validate_image_shape(
927 width,
928 height,
929 pixels.len(),
930 budget,
931 device.limits().max_texture_dimension_2d,
932 )?;
933 let pixels = compact_vec_with_byte_limit(pixels, budget.max_bytes, |actual| {
936 ImageError::BudgetExceeded {
937 limit: budget.max_bytes,
938 actual,
939 }
940 })?;
941 let texture = device.create_texture(&wgpu::TextureDescriptor {
942 label: Some("sim-engine retained RGBA image"),
943 size: wgpu::Extent3d {
944 width,
945 height,
946 depth_or_array_layers: 1,
947 },
948 mip_level_count: 1,
949 sample_count: 1,
950 dimension: wgpu::TextureDimension::D2,
951 format: IMAGE_FORMAT,
952 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
953 view_formats: &[],
954 });
955 write_image_texture(queue, &texture, 0, 0, width, height, &pixels);
956 let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
957 Ok(Image2d {
958 renderer_identity,
959 resource_identity: Arc::new(()),
960 recovery_identity: Arc::new(()),
961 texture,
962 view,
963 width,
964 height,
965 pixels,
966 budget,
967 })
968}
969
970fn compact_vec_with_byte_limit<T: Copy>(
971 values: Vec<T>,
972 maximum_bytes: usize,
973 capacity_error: impl FnOnce(usize) -> ImageError,
974) -> Result<Vec<T>, ImageError> {
975 let element_size = std::mem::size_of::<T>();
976 let allocation_bytes = values.capacity().saturating_mul(element_size);
977 if allocation_bytes <= maximum_bytes {
978 return Ok(values);
979 }
980 let requested_bytes = values
981 .len()
982 .checked_mul(element_size)
983 .ok_or(ImageError::DimensionsTooLarge)?;
984 let mut compact = Vec::new();
985 compact
986 .try_reserve_exact(values.len())
987 .map_err(|_| ImageError::AllocationFailed { requested_bytes })?;
988 compact.extend_from_slice(&values);
989 let actual = compact.capacity().saturating_mul(element_size);
990 if actual > maximum_bytes {
991 return Err(capacity_error(actual));
992 }
993 Ok(compact)
994}
995
996pub(super) fn validate_image_shape(
997 width: u32,
998 height: u32,
999 pixel_count: usize,
1000 budget: ImageBudget,
1001 max_texture_dimension: u32,
1002) -> Result<usize, ImageError> {
1003 if width == 0 || height == 0 {
1004 return Err(ImageError::ZeroDimension);
1005 }
1006 if width > budget.max_width
1007 || height > budget.max_height
1008 || width > max_texture_dimension
1009 || height > max_texture_dimension
1010 || width.checked_mul(4).is_none()
1011 {
1012 return Err(ImageError::DimensionsTooLarge);
1013 }
1014 let bytes = image_byte_count(width, height).ok_or(ImageError::DimensionsTooLarge)?;
1015 if bytes > budget.max_bytes {
1016 return Err(ImageError::BudgetExceeded {
1017 limit: budget.max_bytes,
1018 actual: bytes,
1019 });
1020 }
1021 if pixel_count != bytes {
1022 return Err(ImageError::InvalidPixelCount);
1023 }
1024 Ok(bytes)
1025}
1026
1027pub(super) fn preflight_image_batch_capacity(
1028 device: &wgpu::Device,
1029 sprite_count: usize,
1030 budget: ImageBatchBudget,
1031) -> Result<(), ImageError> {
1032 if sprite_count > budget.max_sprites {
1033 return Err(ImageError::BatchBudgetExceeded {
1034 limit: budget.max_sprites,
1035 actual: sprite_count,
1036 });
1037 }
1038 if u32::try_from(sprite_count).is_err() {
1039 return Err(ImageError::DimensionsTooLarge);
1040 }
1041 let retained_bytes = sprite_count
1042 .checked_mul(std::mem::size_of::<ImageSprite2d>())
1043 .ok_or(ImageError::DimensionsTooLarge)?;
1044 if retained_bytes > budget.max_retained_bytes {
1045 return Err(ImageError::BatchBudgetExceeded {
1046 limit: budget.max_retained_bytes,
1047 actual: retained_bytes,
1048 });
1049 }
1050 let gpu_bytes = sprite_count
1051 .max(1)
1052 .checked_mul(std::mem::size_of::<ImageInstance>())
1053 .ok_or(ImageError::DimensionsTooLarge)?;
1054 if gpu_bytes as u64 > device.limits().max_buffer_size {
1055 return Err(ImageError::DimensionsTooLarge);
1056 }
1057 Ok(())
1058}
1059
1060fn image_byte_count(width: u32, height: u32) -> Option<usize> {
1061 (width as usize)
1062 .checked_mul(height as usize)?
1063 .checked_mul(4)
1064}
1065
1066#[allow(clippy::too_many_arguments)]
1067fn write_image_texture(
1068 queue: &wgpu::Queue,
1069 texture: &wgpu::Texture,
1070 x: u32,
1071 y: u32,
1072 width: u32,
1073 height: u32,
1074 pixels: &[u8],
1075) {
1076 queue.write_texture(
1077 wgpu::TexelCopyTextureInfo {
1078 texture,
1079 mip_level: 0,
1080 origin: wgpu::Origin3d { x, y, z: 0 },
1081 aspect: wgpu::TextureAspect::All,
1082 },
1083 pixels,
1084 wgpu::TexelCopyBufferLayout {
1085 offset: 0,
1086 bytes_per_row: Some(width * 4),
1087 rows_per_image: Some(height),
1088 },
1089 wgpu::Extent3d {
1090 width,
1091 height,
1092 depth_or_array_layers: 1,
1093 },
1094 );
1095 submit_pending_uploads(queue);
1096}
1097
1098#[cfg(test)]
1099mod tests {
1100 use super::*;
1101
1102 #[test]
1103 fn image_shape_checks_budget_device_and_exact_pixels_before_allocation() {
1104 let budget = ImageBudget::new(8, 8, 8 * 8 * 4).unwrap();
1105 assert_eq!(validate_image_shape(8, 8, 256, budget, 8), Ok(256));
1106 assert_eq!(
1107 validate_image_shape(8, 8, 255, budget, 8),
1108 Err(ImageError::InvalidPixelCount)
1109 );
1110 assert_eq!(
1111 validate_image_shape(9, 1, 36, budget, 16),
1112 Err(ImageError::DimensionsTooLarge)
1113 );
1114 let strict = ImageBudget::new(8, 8, 64).unwrap();
1115 assert_eq!(
1116 validate_image_shape(8, 8, 256, strict, 8),
1117 Err(ImageError::BudgetExceeded {
1118 limit: 64,
1119 actual: 256,
1120 })
1121 );
1122 }
1123
1124 #[test]
1125 fn atlas_rect_rejects_empty_and_overflowing_ranges() {
1126 assert_eq!(
1127 ImageTexelRect::new(0, 0, 0, 1),
1128 Err(ImageError::ZeroDimension)
1129 );
1130 assert_eq!(
1131 ImageTexelRect::new(u32::MAX, 0, 2, 1),
1132 Err(ImageError::DimensionsTooLarge)
1133 );
1134 assert!(ImageTexelRect::new(1, 2, 3, 4).unwrap().fits(4, 6));
1135 }
1136
1137 #[test]
1138 fn retained_sprite_region_must_fit_portable_shader_sources() {
1139 let subnormal = LogicalViewportRegion::new(
1140 LogicalScreenPosition::new(f32::from_bits(1), 0.0),
1141 LogicalViewport::new(1.0, 1.0).unwrap(),
1142 )
1143 .unwrap();
1144 let overflowing = LogicalViewportRegion::new(
1145 LogicalScreenPosition::new(2.0e38, 0.0),
1146 LogicalViewport::new(2.0e38, 1.0).unwrap(),
1147 )
1148 .unwrap();
1149 assert!(!logical_image_region_is_portable(subnormal));
1150 assert!(!logical_image_region_is_portable(overflowing));
1151 }
1152
1153 #[test]
1154 fn sprite_rejects_finite_inputs_whose_logical_extent_overflows() {
1155 let source = ImageTexelRect::new(0, 0, 1, 1).unwrap();
1156 let destination = LogicalViewportRegion::new(
1157 LogicalScreenPosition::new(f32::MAX, 0.0),
1158 LogicalViewport::new(f32::MAX, 1.0).unwrap(),
1159 )
1160 .unwrap();
1161 assert_eq!(
1162 ImageSprite2d::new(source, destination, Color::WHITE),
1163 Err(ImageError::InvalidSprite)
1164 );
1165 }
1166
1167 #[test]
1168 fn texture_and_batch_upload_reports_have_distinct_resource_semantics() {
1169 let replacement = ImageUploadReport {
1170 uploaded_bytes: 64,
1171 replaced_texture: true,
1172 };
1173 let region = ImageUploadReport {
1174 uploaded_bytes: 16,
1175 replaced_texture: false,
1176 };
1177 let batch = ImageBatchUploadReport {
1178 uploaded_instance_bytes: 96,
1179 replaced_instance_buffer: true,
1180 };
1181
1182 assert!(replacement.replaced_texture());
1183 assert!(!region.replaced_texture());
1184 assert_eq!(replacement.uploaded_bytes(), 64);
1185 assert_eq!(region.uploaded_bytes(), 16);
1186 assert!(batch.replaced_instance_buffer());
1187 assert_eq!(batch.uploaded_instance_bytes(), 96);
1188 }
1189}