Skip to main content

sim_engine/renderer/image/
updates.rs

1use std::sync::Arc;
2
3use super::{
4    Image2d, ImageBatch2d, ImageBatchBudget, ImageBatchUploadReport, ImageError, ImageInstance,
5    ImageSprite2d, logical_image_region_is_portable, preflight_image_batch_capacity, proof,
6};
7use crate::renderer::{WgpuRenderer, submit_pending_uploads};
8
9pub(in crate::renderer) fn batch_retained_bytes(count: usize) -> usize {
10    count.saturating_mul(ImageBatchBudget::RETAINED_BYTES_PER_SPRITE)
11}
12
13impl WgpuRenderer {
14    /// Atomically updates retained sprite descriptions from borrowed input.
15    ///
16    /// Reuses both CPU arrays and the GPU buffer while capacity permits. Equal
17    /// input submits no upload. Shrinking, including to zero sprites, retains
18    /// capacity. Growth reserves exact bounded replacement arrays before changing
19    /// drawable state. Synchronous validation/allocation errors preserve the old
20    /// batch. Device failure is not a rollback of already submitted GPU work.
21    ///
22    /// The original image and current renderer generation must match. The queue
23    /// orders uploads after previously submitted draws; the frame borrow prevents
24    /// updating a batch still referenced by an unsubmitted composer.
25    pub fn update_image_batch(
26        &self,
27        image: &Image2d,
28        batch: &mut ImageBatch2d,
29        sprites: &[ImageSprite2d],
30    ) -> Result<ImageBatchUploadReport, ImageError> {
31        self.validate_image_batch(image, batch)?;
32        update_image_batch_resources(
33            &self.device,
34            &self.queue,
35            image,
36            batch,
37            sprites.iter().copied(),
38            sprites.len(),
39            batch.budget,
40        )
41    }
42}
43
44fn replacement_array<T: Copy>(
45    current_capacity: usize,
46    count: usize,
47    compact: bool,
48) -> Result<Option<Vec<T>>, ImageError> {
49    if count <= current_capacity && !compact {
50        return Ok(None);
51    }
52    let mut replacement = Vec::new();
53    replacement
54        .try_reserve_exact(count)
55        .map_err(|_| ImageError::AllocationFailed {
56            requested_bytes: count.saturating_mul(std::mem::size_of::<T>()),
57        })?;
58    Ok(Some(replacement))
59}
60
61fn instance_for(image: &Image2d, sprite: ImageSprite2d) -> ImageInstance {
62    let origin = sprite.destination.origin().to_vec2();
63    let viewport = sprite.destination.viewport();
64    let source = sprite.source;
65    ImageInstance {
66        destination: [origin.x, origin.y, viewport.width(), viewport.height()],
67        uv_rect: [
68            (source.x as f32 + 0.5) / image.width as f32,
69            (source.y as f32 + 0.5) / image.height as f32,
70            (source.x as f32 + source.width as f32 - 0.5) / image.width as f32,
71            (source.y as f32 + source.height as f32 - 0.5) / image.height as f32,
72        ],
73        tint: sprite.tint.to_array(),
74    }
75}
76
77#[allow(clippy::too_many_arguments)]
78pub(in crate::renderer) fn update_image_batch_resources<I>(
79    device: &wgpu::Device,
80    queue: &wgpu::Queue,
81    image: &Image2d,
82    batch: &mut ImageBatch2d,
83    sprites: I,
84    count: usize,
85    budget: ImageBatchBudget,
86) -> Result<ImageBatchUploadReport, ImageError>
87where
88    I: Iterator<Item = ImageSprite2d> + Clone,
89{
90    if !Arc::ptr_eq(&image.renderer_identity, &batch.renderer_identity)
91        || !Arc::ptr_eq(&image.resource_identity, &batch.image_identity)
92    {
93        return Err(ImageError::RendererMismatch);
94    }
95    preflight_image_batch_capacity(device, count, budget)?;
96    if sprites.clone().count() != count {
97        return Err(ImageError::InvalidSprite);
98    }
99    let mut destinations_unchanged = count == batch.sprites.len();
100    for (index, sprite) in sprites.clone().enumerate() {
101        if !sprite.source.fits(image.width, image.height)
102            || !sprite.tint.is_normalized()
103            || !logical_image_region_is_portable(sprite.destination)
104        {
105            return Err(ImageError::InvalidSprite);
106        }
107        destinations_unchanged = destinations_unchanged
108            && batch.sprites.get(index).is_some_and(|previous| {
109                proof::destination_bits(*previous) == proof::destination_bits(sprite)
110            });
111    }
112
113    let old_cpu = batch.recovery_memory_bytes();
114    let old_gpu = batch.gpu_allocation_bytes();
115    if batch.sprites.iter().copied().eq(sprites.clone()) && old_cpu <= budget.max_retained_bytes {
116        batch.budget = budget;
117        return Ok(report(batch, 0, false, old_cpu, old_gpu));
118    }
119    let compact = old_cpu > budget.max_retained_bytes;
120    let new_sprites: Option<Vec<ImageSprite2d>> =
121        replacement_array(batch.sprites.capacity(), count, compact)?;
122    let new_instances: Option<Vec<ImageInstance>> =
123        replacement_array(batch.instances.capacity(), count, compact)?;
124    let sprite_capacity = new_sprites
125        .as_ref()
126        .map_or(batch.sprites.capacity(), Vec::capacity);
127    let instance_capacity = new_instances
128        .as_ref()
129        .map_or(batch.instances.capacity(), Vec::capacity);
130    let cpu_bytes = sprite_capacity
131        .saturating_mul(std::mem::size_of::<ImageSprite2d>())
132        .saturating_add(instance_capacity.saturating_mul(std::mem::size_of::<ImageInstance>()));
133    if cpu_bytes > budget.max_retained_bytes {
134        return Err(ImageError::BatchBudgetExceeded {
135            limit: budget.max_retained_bytes,
136            actual: cpu_bytes,
137        });
138    }
139    let peak_cpu = old_cpu
140        .saturating_add(new_sprites.as_ref().map_or(0, |v| {
141            v.capacity()
142                .saturating_mul(std::mem::size_of::<ImageSprite2d>())
143        }))
144        .saturating_add(new_instances.as_ref().map_or(0, |v| {
145            v.capacity()
146                .saturating_mul(std::mem::size_of::<ImageInstance>())
147        }));
148    let gpu_bytes = count.max(1) * std::mem::size_of::<ImageInstance>();
149    let replacement = (gpu_bytes > old_gpu).then(|| {
150        device.create_buffer(&wgpu::BufferDescriptor {
151            label: Some("sim-engine grown image sprite instances"),
152            size: gpu_bytes as u64,
153            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
154            mapped_at_creation: false,
155        })
156    });
157    let replaced = replacement.is_some();
158    let peak_gpu = old_gpu.saturating_add(if replaced { gpu_bytes } else { 0 });
159    // No remaining synchronous rejection precedes publishing the new arrays.
160    // UV/tint never participate in the geometry proof. Keep that exact result
161    // when every ordered destination component is bit-identical; any changed
162    // position, size or count invalidates before the new arrays are published.
163    if !destinations_unchanged {
164        batch.geometry_proof.invalidate();
165    }
166    if let Some(values) = new_sprites {
167        batch.sprites = values;
168    }
169    if let Some(values) = new_instances {
170        batch.instances = values;
171    }
172    if let Some(buffer) = replacement {
173        batch.instance_buffer = buffer;
174    }
175    batch.sprites.clear();
176    batch.instances.clear();
177    for sprite in sprites {
178        batch.instances.push(instance_for(image, sprite));
179        batch.sprites.push(sprite);
180    }
181    batch.budget = budget;
182    let uploaded = count * std::mem::size_of::<ImageInstance>();
183    if uploaded > 0 {
184        queue.write_buffer(
185            &batch.instance_buffer,
186            0,
187            bytemuck::cast_slice(&batch.instances),
188        );
189        submit_pending_uploads(queue);
190    }
191    Ok(report(batch, uploaded, replaced, peak_cpu, peak_gpu))
192}
193
194fn report(
195    batch: &ImageBatch2d,
196    uploaded: usize,
197    replaced: bool,
198    peak_cpu: usize,
199    peak_gpu: usize,
200) -> ImageBatchUploadReport {
201    ImageBatchUploadReport {
202        uploaded_instance_bytes: uploaded,
203        replaced_instance_buffer: replaced,
204        sprite_count: batch.sprite_count(),
205        retained_capacity: batch.capacity(),
206        gpu_capacity: batch.gpu_allocation_bytes() / std::mem::size_of::<ImageInstance>(),
207        retained_bytes: batch.recovery_memory_bytes(),
208        peak_retained_bytes: peak_cpu,
209        peak_gpu_bytes: peak_gpu,
210    }
211}