1use std::borrow::Cow;
4
5use spatialrust_core::{SpatialError, SpatialResult};
6use spatialrust_image::{Image, ImageMetadata, ImageView};
7
8use super::transfer_packing::{pack_rgba8, unpack_rgba8};
9use crate::WgpuRuntime;
10
11const BYTES_PER_TEXEL: u64 = 4;
12
13struct UploadPlan {
14 width: u32,
15 height: u32,
16 row_bytes: u32,
17 storage_bytes: u64,
18 packed_len: usize,
19}
20
21struct ReadbackPlan {
22 row_bytes: u32,
23 padded_row: u32,
24 staging_bytes: u64,
25 staging_len: usize,
26 output_len: usize,
27}
28
29fn invalid_transfer() -> SpatialError {
30 SpatialError::InvalidArgument(
31 "GpuImage transfer requires positive supported dimensions, 1..=4 channels and representable byte lengths".to_owned(),
32 )
33}
34
35fn transfer_dimensions(
36 width: u32,
37 height: u32,
38 channels: usize,
39 limits: &wgpu::Limits,
40) -> SpatialResult<u32> {
41 if width == 0
42 || height == 0
43 || !(1..=4).contains(&channels)
44 || width > limits.max_texture_dimension_2d
45 || height > limits.max_texture_dimension_2d
46 {
47 return Err(invalid_transfer());
48 }
49 width.checked_mul(BYTES_PER_TEXEL as u32).ok_or_else(invalid_transfer)
50}
51
52fn host_length(bytes: u64) -> SpatialResult<usize> {
53 if bytes > isize::MAX as u64 {
54 return Err(invalid_transfer());
55 }
56 usize::try_from(bytes).map_err(|_| invalid_transfer())
57}
58
59fn upload_plan(
60 width: usize,
61 height: usize,
62 channels: usize,
63 limits: &wgpu::Limits,
64) -> SpatialResult<UploadPlan> {
65 let width = u32::try_from(width).map_err(|_| invalid_transfer())?;
66 let height = u32::try_from(height).map_err(|_| invalid_transfer())?;
67 let row_bytes = transfer_dimensions(width, height, channels, limits)?;
68 let storage_bytes = texture_bytes(width, height)?;
69 let packed_len = host_length(storage_bytes)?;
70 Ok(UploadPlan { width, height, row_bytes, storage_bytes, packed_len })
71}
72
73fn upload_texels<const CHANNELS: usize>(
74 view: ImageView<'_, u8, CHANNELS>,
75 packed_len: usize,
76) -> Cow<'_, [u8]> {
77 if CHANNELS == 4 {
78 if let Some(pixels) = view.as_packed_slice() {
79 return Cow::Borrowed(pixels);
80 }
81 }
82 Cow::Owned(pack_rgba8(view, packed_len))
83}
84
85fn readback_plan(
86 width: u32,
87 height: u32,
88 channels: usize,
89 limits: &wgpu::Limits,
90) -> SpatialResult<ReadbackPlan> {
91 let row_bytes = transfer_dimensions(width, height, channels, limits)?;
92 let alignment = u64::from(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT);
93 let padded_row = u32::try_from(u64::from(row_bytes).div_ceil(alignment) * alignment)
94 .map_err(|_| invalid_transfer())?;
95 let staging_bytes = u64::from(padded_row) * u64::from(height);
96 if staging_bytes > limits.max_buffer_size {
97 return Err(invalid_transfer());
98 }
99 let staging_len = host_length(staging_bytes)?;
100 let output_len = host_length(u64::from(width) * u64::from(height) * channels as u64)?;
101 Ok(ReadbackPlan { row_bytes, padded_row, staging_bytes, staging_len, output_len })
102}
103
104#[derive(Clone, Debug, Default, PartialEq, Eq)]
106pub struct GpuImageReceipt {
107 host_to_device_bytes: u64,
108 gpu_to_gpu_bytes: u64,
109 device_to_host_bytes: u64,
110 stages: Vec<&'static str>,
111}
112
113impl GpuImageReceipt {
114 #[must_use]
116 pub const fn host_to_device_bytes(&self) -> u64 {
117 self.host_to_device_bytes
118 }
119
120 #[must_use]
123 pub const fn gpu_to_gpu_bytes(&self) -> u64 {
124 self.gpu_to_gpu_bytes
125 }
126
127 #[must_use]
129 pub const fn device_to_host_bytes(&self) -> u64 {
130 self.device_to_host_bytes
131 }
132
133 #[must_use]
135 pub fn stages(&self) -> &[&'static str] {
136 &self.stages
137 }
138
139 pub fn validate_resident_chain(&self, expected_upload_bytes: u64) -> SpatialResult<()> {
143 if self.host_to_device_bytes != expected_upload_bytes {
144 return Err(SpatialError::InvalidArgument(format!(
145 "resident chain expected {expected_upload_bytes} host-to-device bytes, recorded {}",
146 self.host_to_device_bytes
147 )));
148 }
149 if self.device_to_host_bytes != 0 {
150 return Err(SpatialError::InvalidArgument(format!(
151 "resident chain forbids device-to-host transfers, recorded {} bytes",
152 self.device_to_host_bytes
153 )));
154 }
155 Ok(())
156 }
157
158 pub(crate) fn record_host_to_device(&mut self, bytes: u64, stage: &'static str) {
159 self.host_to_device_bytes = self.host_to_device_bytes.saturating_add(bytes);
160 self.stages.push(stage);
161 }
162
163 pub(crate) fn record_gpu_to_gpu(&mut self, bytes: u64, stage: &'static str) {
164 self.gpu_to_gpu_bytes = self.gpu_to_gpu_bytes.saturating_add(bytes);
165 self.stages.push(stage);
166 }
167
168 pub(crate) fn record_device_to_host(&mut self, bytes: u64, stage: &'static str) {
169 self.device_to_host_bytes = self.device_to_host_bytes.saturating_add(bytes);
170 self.stages.push(stage);
171 }
172
173 pub(crate) fn merge_from(&mut self, other: &Self) {
174 self.host_to_device_bytes =
175 self.host_to_device_bytes.saturating_add(other.host_to_device_bytes);
176 self.gpu_to_gpu_bytes = self.gpu_to_gpu_bytes.saturating_add(other.gpu_to_gpu_bytes);
177 self.device_to_host_bytes =
178 self.device_to_host_bytes.saturating_add(other.device_to_host_bytes);
179 self.stages.extend_from_slice(&other.stages);
180 }
181}
182
183pub struct GpuImage {
188 width: u32,
189 height: u32,
190 channels: u32,
191 device_key: std::sync::Arc<()>,
192 texture: wgpu::Texture,
193 storage_bytes: u64,
194 metadata: ImageMetadata,
195 receipt: GpuImageReceipt,
196}
197
198impl GpuImage {
199 pub fn upload_u8<const CHANNELS: usize>(
204 runtime: &WgpuRuntime,
205 view: ImageView<'_, u8, CHANNELS>,
206 ) -> SpatialResult<Self> {
207 let plan = upload_plan(view.width(), view.height(), CHANNELS, &runtime.device().limits())?;
208 let (width, height) = (plan.width, plan.height);
209 let texture = create_texture(runtime, width, height, "gpu-image-upload");
210 let texels = upload_texels(view, plan.packed_len);
211 runtime.queue().write_texture(
212 wgpu::TexelCopyTextureInfo {
213 texture: &texture,
214 mip_level: 0,
215 origin: wgpu::Origin3d::ZERO,
216 aspect: wgpu::TextureAspect::All,
217 },
218 &texels,
219 wgpu::TexelCopyBufferLayout {
220 offset: 0,
221 bytes_per_row: Some(plan.row_bytes),
222 rows_per_image: Some(height),
223 },
224 extent(width, height),
225 );
226 let storage_bytes = plan.storage_bytes;
227 let mut receipt = GpuImageReceipt::default();
228 receipt.record_host_to_device(storage_bytes, "upload_u8_texture");
229 Ok(Self {
230 width,
231 height,
232 channels: CHANNELS as u32,
233 device_key: runtime_device_key(runtime),
234 texture,
235 storage_bytes,
236 metadata: view.metadata(),
237 receipt,
238 })
239 }
240
241 pub fn readback_u8<const CHANNELS: usize>(
246 &mut self,
247 runtime: &WgpuRuntime,
248 ) -> SpatialResult<Image<u8, CHANNELS>> {
249 self.validate_runtime(runtime)?;
250 if self.channels as usize != CHANNELS {
251 return Err(SpatialError::InvalidArgument(format!(
252 "GpuImage has {} channels but readback requested {CHANNELS}",
253 self.channels
254 )));
255 }
256 let plan = readback_plan(self.width, self.height, CHANNELS, &runtime.device().limits())?;
257 let staging = runtime.device().create_buffer(&wgpu::BufferDescriptor {
258 label: Some("gpu-image-texture-readback"),
259 size: plan.staging_bytes,
260 usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
261 mapped_at_creation: false,
262 });
263 let mut encoder =
264 runtime.device().create_command_encoder(&wgpu::CommandEncoderDescriptor {
265 label: Some("gpu-image-texture-readback-encoder"),
266 });
267 encoder.copy_texture_to_buffer(
268 wgpu::TexelCopyTextureInfo {
269 texture: &self.texture,
270 mip_level: 0,
271 origin: wgpu::Origin3d::ZERO,
272 aspect: wgpu::TextureAspect::All,
273 },
274 wgpu::TexelCopyBufferInfo {
275 buffer: &staging,
276 layout: wgpu::TexelCopyBufferLayout {
277 offset: 0,
278 bytes_per_row: Some(plan.padded_row),
279 rows_per_image: Some(self.height),
280 },
281 },
282 extent(self.width, self.height),
283 );
284 runtime.queue().submit(Some(encoder.finish()));
285 let data = with_staging_bytes(runtime.device(), &staging, plan.staging_len, |rgba| {
286 unpack_rgba8::<CHANNELS>(
287 rgba,
288 plan.row_bytes as usize / BYTES_PER_TEXEL as usize,
289 self.height as usize,
290 plan.padded_row as usize,
291 plan.output_len,
292 )
293 })?;
294 self.receipt.record_device_to_host(self.storage_bytes, "readback_u8_texture");
295 Image::try_new_with_metadata(self.width as usize, self.height as usize, data, self.metadata)
296 .map_err(|error| SpatialError::InvalidArgument(error.to_string()))
297 }
298
299 #[must_use]
301 pub const fn width(&self) -> u32 {
302 self.width
303 }
304
305 #[must_use]
307 pub const fn height(&self) -> u32 {
308 self.height
309 }
310
311 #[must_use]
313 pub const fn channels(&self) -> u32 {
314 self.channels
315 }
316
317 #[must_use]
319 pub const fn metadata(&self) -> ImageMetadata {
320 self.metadata
321 }
322
323 #[must_use]
325 pub const fn receipt(&self) -> &GpuImageReceipt {
326 &self.receipt
327 }
328
329 pub fn recycle(self, runtime: &WgpuRuntime) {
331 if self.validate_runtime(runtime).is_ok() {
332 runtime.recycle_image_texture(self.width, self.height, self.texture);
333 }
334 }
335
336 pub(crate) fn validate_runtime(&self, runtime: &WgpuRuntime) -> SpatialResult<()> {
337 if !std::sync::Arc::ptr_eq(&self.device_key, &runtime_device_key(runtime)) {
338 return Err(SpatialError::InvalidArgument(
339 "GpuImage belongs to a different runtime device".to_owned(),
340 ));
341 }
342 Ok(())
343 }
344
345 pub(crate) const fn storage_bytes(&self) -> u64 {
346 self.storage_bytes
347 }
348
349 pub(crate) const fn texture(&self) -> &wgpu::Texture {
350 &self.texture
351 }
352
353 pub(crate) fn view(&self) -> wgpu::TextureView {
354 self.texture.create_view(&wgpu::TextureViewDescriptor::default())
355 }
356
357 pub(crate) fn from_parts(
358 runtime: &WgpuRuntime,
359 width: u32,
360 height: u32,
361 channels: u32,
362 texture: wgpu::Texture,
363 metadata: ImageMetadata,
364 receipt: GpuImageReceipt,
365 ) -> SpatialResult<Self> {
366 if width == 0 || height == 0 || !(1..=4).contains(&channels) {
367 return Err(SpatialError::InvalidArgument(
368 "GpuImage dimensions/channels must be positive with 1..=4 channels".to_owned(),
369 ));
370 }
371 Ok(Self {
372 width,
373 height,
374 channels,
375 device_key: runtime_device_key(runtime),
376 texture,
377 storage_bytes: texture_bytes(width, height)?,
378 metadata,
379 receipt,
380 })
381 }
382}
383
384pub(crate) fn create_texture(
385 runtime: &WgpuRuntime,
386 width: u32,
387 height: u32,
388 label: &'static str,
389) -> wgpu::Texture {
390 runtime.acquire_image_texture(width, height, label)
391}
392
393const fn extent(width: u32, height: u32) -> wgpu::Extent3d {
394 wgpu::Extent3d { width, height, depth_or_array_layers: 1 }
395}
396
397fn texture_bytes(width: u32, height: u32) -> SpatialResult<u64> {
398 (u64::from(width) * u64::from(height)).checked_mul(BYTES_PER_TEXEL).ok_or_else(invalid_transfer)
399}
400
401#[cfg(all(test, not(target_arch = "wasm32")))]
402#[path = "transfer_tests.rs"]
403mod transfer_tests;
404
405#[cfg(all(test, not(target_arch = "wasm32")))]
406#[path = "transfer_packing_gpu_tests.rs"]
407mod transfer_packing_gpu_tests;
408
409#[cfg(all(test, not(target_arch = "wasm32")))]
410#[path = "packed_upload_tests.rs"]
411mod packed_upload_tests;
412
413#[cfg(all(test, not(target_arch = "wasm32")))]
414#[path = "mapped_readback_tests.rs"]
415mod mapped_readback_tests;
416
417pub(crate) fn runtime_device_key(runtime: &WgpuRuntime) -> std::sync::Arc<()> {
418 runtime.profiling_identity()
419}
420
421#[cfg(all(test, not(target_arch = "wasm32")))]
422pub(crate) fn read_staging_bytes(
423 device: &wgpu::Device,
424 staging_buffer: &wgpu::Buffer,
425 len: usize,
426) -> SpatialResult<Vec<u8>> {
427 with_staging_bytes(device, staging_buffer, len, <[u8]>::to_vec)
428}
429
430struct StagingUnmap<'a>(&'a wgpu::Buffer);
432
433impl Drop for StagingUnmap<'_> {
434 fn drop(&mut self) {
435 self.0.unmap();
436 }
437}
438
439pub(super) fn with_staging_bytes<T>(
440 device: &wgpu::Device,
441 staging_buffer: &wgpu::Buffer,
442 len: usize,
443 decode: impl FnOnce(&[u8]) -> T,
444) -> SpatialResult<T> {
445 let slice = staging_buffer.slice(..);
446 let (sender, receiver) = std::sync::mpsc::channel();
447 slice.map_async(wgpu::MapMode::Read, move |result| {
448 let _ = sender.send(result);
449 });
450 device.poll(wgpu::Maintain::Wait);
451 receiver
452 .recv()
453 .map_err(|_| SpatialError::InvalidArgument("failed to receive wgpu map result".to_owned()))?
454 .map_err(|error| {
455 SpatialError::InvalidArgument(format!("failed to map wgpu texture: {error}"))
456 })?;
457 let _unmap = StagingUnmap(staging_buffer);
458 let data = slice.get_mapped_range();
459 Ok(decode(&data[..len]))
460}