1#[cfg(feature = "trace")]
2use alloc::string::ToString as _;
3use alloc::{boxed::Box, string::String, sync::Arc, vec, vec::Vec};
4use core::{
5 iter,
6 mem::{self, ManuallyDrop},
7 num::NonZeroU64,
8 ptr::NonNull,
9 sync::atomic::Ordering,
10};
11use smallvec::SmallVec;
12use thiserror::Error;
13use wgt::{
14 error::{ErrorType, WebGpuError},
15 AccelerationStructureFlags,
16};
17
18use super::{life::LifetimeTracker, Device};
19#[cfg(feature = "trace")]
20use crate::device::trace::{Action, IntoTrace};
21use crate::{
22 api_log,
23 command::{
24 extract_texture_selector, validate_linear_texture_data, validate_texture_buffer_copy,
25 validate_texture_copy_dst_format, validate_texture_copy_range, ClearError,
26 CommandAllocator, CommandBuffer, CommandEncoder, CommandEncoderError, CopySide,
27 TransferError,
28 },
29 device::{DeviceError, QueueDescriptor, WaitIdleError},
30 get_lowest_common_denom, hal_label,
31 init_tracker::{has_copy_partial_init_tracker_coverage, TextureInitRange},
32 lock::{rank, Mutex, MutexGuard, RwLock, RwLockWriteGuard},
33 ray_tracing::{BlasCompactReadyPendingClosure, CompactBlasError},
34 resource::{
35 Blas, BlasCompactState, BlasDescriptor, BlasState, Buffer, BufferAccessError,
36 BufferMapState, DestroyedBuffer, DestroyedQuerySet, DestroyedResourceError,
37 DestroyedTexture, FlushedStagingBuffer, InvalidOrDestroyedResourceError,
38 InvalidResourceError, Labeled, ParentDevice, ResourceErrorIdent, ResourceState,
39 StagingBuffer, Texture, TextureInner, Trackable, TrackingData,
40 },
41 resource_log,
42 scratch::ScratchBuffer,
43 snatch::{SnatchGuard, Snatchable},
44 track::{self, Tracker, TrackerIndex},
45 FastHashMap, LabelHelpers, SubmissionIndex,
46};
47use crate::{device::resource::CommandIndices, resource::RawResourceAccess};
48
49pub struct Queue {
50 raw: Box<dyn hal::DynQueue>,
51 pub(crate) pending_writes: Mutex<PendingWrites>,
52 life_tracker: Mutex<LifetimeTracker>,
53 label: String,
54 pub(crate) device: Arc<Device>,
56}
57
58impl Queue {
59 pub(crate) fn new(
60 device: Arc<Device>,
61 raw: Box<dyn hal::DynQueue>,
62 desc: QueueDescriptor,
63 instance_flags: wgt::InstanceFlags,
64 ) -> Result<Self, DeviceError> {
65 let pending_encoder = device
66 .command_allocator
67 .acquire_encoder(device.raw(), raw.as_ref())
68 .map_err(DeviceError::from_hal);
69
70 let pending_encoder = match pending_encoder {
71 Ok(pending_encoder) => pending_encoder,
72 Err(e) => {
73 return Err(e);
74 }
75 };
76
77 let mut pending_writes = PendingWrites::new(pending_encoder, instance_flags);
78
79 let zero_buffer = device.zero_buffer.as_ref();
80 pending_writes.activate();
81 unsafe {
82 pending_writes
83 .command_encoder
84 .transition_buffers(&[hal::BufferBarrier {
85 buffer: zero_buffer,
86 usage: hal::StateTransition {
87 from: wgt::BufferUses::empty(),
88 to: wgt::BufferUses::COPY_DST,
89 },
90 }]);
91 pending_writes
92 .command_encoder
93 .clear_buffer(zero_buffer, 0..super::ZERO_BUFFER_SIZE);
94 pending_writes
95 .command_encoder
96 .transition_buffers(&[hal::BufferBarrier {
97 buffer: zero_buffer,
98 usage: hal::StateTransition {
99 from: wgt::BufferUses::COPY_DST,
100 to: wgt::BufferUses::COPY_SRC,
101 },
102 }]);
103 }
104
105 Ok(Queue {
106 raw,
107 device,
108 label: desc.label.to_string(),
109 pending_writes: Mutex::new(rank::QUEUE_PENDING_WRITES, pending_writes),
110 life_tracker: Mutex::new(rank::QUEUE_LIFE_TRACKER, LifetimeTracker::new()),
111 })
112 }
113
114 pub(crate) fn raw(&self) -> &dyn hal::DynQueue {
115 self.raw.as_ref()
116 }
117
118 #[track_caller]
119 pub(crate) fn lock_life<'a>(&'a self) -> MutexGuard<'a, LifetimeTracker> {
120 self.life_tracker.lock()
121 }
122
123 pub(crate) fn prepare_surface_texture_for_present(
128 &self,
129 texture: &Arc<Texture>,
130 ) -> Result<(), DeviceError> {
131 let snatch_guard = self.device.snatchable_lock.read();
132 let submission = self
133 .allocate_submission(snatch_guard)
134 .map_err(|(_index, e)| e)?;
135 let device = &self.device;
136
137 let needs_clear = {
139 let status = texture.initialization_status.read();
140 status
141 .mips
142 .first()
143 .is_some_and(|mip| mip.check(0..1).is_some())
144 };
145
146 let mut pending_writes = self.pending_writes.lock();
147
148 if needs_clear {
149 let encoder = pending_writes.activate();
152 let mut trackers = device.trackers.lock();
153 crate::command::clear_texture(
154 texture,
155 TextureInitRange {
156 mip_range: 0..1,
157 layer_range: 0..1,
158 },
159 None,
160 encoder,
161 &mut trackers.textures,
162 &device.alignments,
163 device.zero_buffer.as_ref(),
164 &submission.snatch_guard,
165 device.instance_flags,
166 )
167 .map_err(|e| match e {
168 ClearError::Device(e) => e,
169 _ => DeviceError::Lost,
170 })?;
171 texture.initialization_status.write().mips[0].drain(0..1);
172 }
173
174 let pending = {
180 let mut trackers = device.trackers.lock();
181 let pending: Vec<track::PendingTransition<wgt::TextureUses>> = trackers
182 .textures
183 .set_single(
184 texture,
185 texture.full_range.clone(),
186 wgt::TextureUses::PRESENT,
187 )
188 .collect();
189 pending
190 };
191
192 if pending.is_empty() {
193 debug_assert!(!needs_clear);
199 return Ok(());
200 }
201
202 {
204 let raw_texture = texture
205 .raw(&submission.snatch_guard)
206 .ok_or(DeviceError::Lost)?;
207 let barriers: Vec<hal::TextureBarrier<'_, dyn hal::DynTexture>> = pending
208 .into_iter()
209 .map(|pt| pt.into_hal(raw_texture))
210 .collect();
211
212 let encoder = pending_writes.activate();
213 unsafe {
217 encoder.transition_textures(&barriers);
218 }
219 }
220
221 pending_writes.insert_texture(texture);
228
229 submission.submit(pending_writes)?;
230
231 Ok(())
232 }
233
234 pub(crate) fn maintain(
242 &self,
243 submission_index: u64,
244 snatch_guard: &SnatchGuard,
245 ) -> (
246 SmallVec<[SubmittedWorkDoneClosure; 1]>,
247 Vec<super::BufferMapPendingClosure>,
248 Vec<BlasCompactReadyPendingClosure>,
249 bool,
250 ) {
251 let mut life_tracker = self.lock_life();
252 let submission_closures = life_tracker.triage_submissions(submission_index);
253
254 let mapping_closures = life_tracker.handle_mapping(snatch_guard);
255 let blas_closures = life_tracker.handle_compact_read_back();
256
257 let queue_empty = life_tracker.queue_empty();
258
259 (
260 submission_closures,
261 mapping_closures,
262 blas_closures,
263 queue_empty,
264 )
265 }
266}
267
268crate::impl_resource_type!(Queue);
269crate::impl_labeled!(Queue);
270crate::impl_parent_device!(Queue);
271crate::impl_storage_item!(Queue);
272
273impl Drop for Queue {
274 #[allow(trivial_casts)]
275 fn drop(&mut self) {
276 profiling::scope!("Queue::drop");
277 api_log!("Queue::drop {:?}", self as *const _);
278 resource_log!("Drop {}", self.error_ident());
279
280 match unsafe { self.raw.wait_for_idle() } {
283 Ok(()) => {}
284 Err(hal::DeviceError::Lost) => {
285 self.device.handle_hal_error(hal::DeviceError::Lost);
286 }
287 Err(e) => {
288 panic!("Unexpected error while waiting for queue idle on drop: {e:?}");
289 }
290 }
291
292 let last_successful_submission_index = self
293 .device
294 .last_successful_submission_index
295 .load(Ordering::Acquire);
296
297 let snatch_guard = self.device.snatchable_lock.read();
298 let (submission_closures, mapping_closures, blas_compact_ready_closures, queue_empty) =
299 self.maintain(last_successful_submission_index, &snatch_guard);
300 drop(snatch_guard);
301
302 assert!(queue_empty);
303
304 let closures = crate::device::UserClosures {
305 mappings: mapping_closures,
306 blas_compact_ready: blas_compact_ready_closures,
307 submissions: submission_closures,
308 device_lost_invocations: SmallVec::new(),
309 };
310
311 closures.fire();
312 }
313}
314
315#[cfg(send_sync)]
316pub type SubmittedWorkDoneClosure = Box<dyn FnOnce() + Send + 'static>;
317#[cfg(not(send_sync))]
318pub type SubmittedWorkDoneClosure = Box<dyn FnOnce() + 'static>;
319
320#[derive(Debug)]
331pub enum TempResource {
332 StagingBuffer(FlushedStagingBuffer),
333 ScratchBuffer(ScratchBuffer),
334 DestroyedBuffer(DestroyedBuffer),
335 DestroyedTexture(DestroyedTexture),
336 DestroyedQuerySet(DestroyedQuerySet),
337}
338
339pub(crate) struct EncoderInFlight {
345 inner: crate::command::InnerCommandEncoder,
346 pub(crate) trackers: Tracker,
347 pub(crate) temp_resources: Vec<TempResource>,
348 _indirect_draw_validation_resources: crate::indirect_validation::DrawResources,
350
351 pub(crate) pending_buffers: FastHashMap<TrackerIndex, Arc<Buffer>>,
353 pub(crate) pending_textures: FastHashMap<TrackerIndex, Arc<Texture>>,
355 pub(crate) pending_blas_s: FastHashMap<TrackerIndex, Arc<Blas>>,
357}
358
359#[derive(Debug)]
384pub(crate) struct PendingWrites {
385 pub command_encoder: Box<dyn hal::DynCommandEncoder>,
387
388 pub is_recording: bool,
394
395 temp_resources: Vec<TempResource>,
396 dst_buffers: FastHashMap<TrackerIndex, Arc<Buffer>>,
397 dst_textures: FastHashMap<TrackerIndex, Arc<Texture>>,
398 copied_blas_s: FastHashMap<TrackerIndex, Arc<Blas>>,
399 instance_flags: wgt::InstanceFlags,
400}
401
402impl PendingWrites {
403 pub fn new(
404 command_encoder: Box<dyn hal::DynCommandEncoder>,
405 instance_flags: wgt::InstanceFlags,
406 ) -> Self {
407 Self {
408 command_encoder,
409 is_recording: false,
410 temp_resources: Vec::new(),
411 dst_buffers: FastHashMap::default(),
412 dst_textures: FastHashMap::default(),
413 copied_blas_s: FastHashMap::default(),
414 instance_flags,
415 }
416 }
417
418 pub fn insert_buffer(&mut self, buffer: &Arc<Buffer>) {
419 self.dst_buffers
420 .insert(buffer.tracker_index(), buffer.clone());
421 }
422
423 pub fn insert_texture(&mut self, texture: &Arc<Texture>) {
424 self.dst_textures
425 .insert(texture.tracker_index(), texture.clone());
426 }
427
428 pub fn insert_blas(&mut self, blas: &Arc<Blas>) {
429 self.copied_blas_s
430 .insert(blas.tracker_index(), blas.clone());
431 }
432
433 pub fn contains_buffer(&self, buffer: &Arc<Buffer>) -> bool {
434 self.dst_buffers.contains_key(&buffer.tracker_index())
435 }
436
437 pub fn contains_texture(&self, texture: &Arc<Texture>) -> bool {
438 self.dst_textures.contains_key(&texture.tracker_index())
439 }
440
441 pub fn consume_temp(&mut self, resource: TempResource) {
442 self.temp_resources.push(resource);
443 }
444
445 pub fn consume(&mut self, buffer: FlushedStagingBuffer) {
446 self.temp_resources
447 .push(TempResource::StagingBuffer(buffer));
448 }
449
450 pub fn clear_buffer(
451 &mut self,
452 device: &Arc<Device>,
453 buffer: &Arc<Buffer>,
454 range: core::ops::Range<wgt::BufferAddress>,
455 snatch_guard: &SnatchGuard,
456 ) -> Result<(), QueueWriteError> {
457 let barriers = {
458 let mut trackers = device.trackers.lock();
459 trackers
460 .buffers
461 .set_single(buffer, wgt::BufferUses::COPY_DST)
462 .map(|pending| pending.into_hal(buffer, snatch_guard))
463 };
464
465 let dst_raw = buffer.try_raw(snatch_guard)?;
466
467 let encoder = self.activate();
468 unsafe {
469 encoder.transition_buffers(barriers.as_slice());
470 encoder.clear_buffer(dst_raw, range.clone());
471 }
472
473 self.insert_buffer(buffer);
474
475 buffer.initialization_status.write().drain(range);
478
479 Ok(())
480 }
481
482 fn pre_submit(
483 &mut self,
484 command_allocator: &CommandAllocator,
485 device: &Arc<Device>,
486 queue: &Queue,
487 ) -> Result<Option<EncoderInFlight>, DeviceError> {
488 if self.is_recording {
489 let pending_buffers = mem::take(&mut self.dst_buffers);
490 let pending_textures = mem::take(&mut self.dst_textures);
491 let pending_blas_s = mem::take(&mut self.copied_blas_s);
492
493 let cmd_buf = unsafe { self.command_encoder.end_encoding() }
494 .map_err(|e| device.handle_hal_error(e))?;
495 self.is_recording = false;
496
497 let new_encoder = command_allocator
498 .acquire_encoder(device.raw(), queue.raw())
499 .map_err(|e| device.handle_hal_error(e))?;
500
501 let encoder = EncoderInFlight {
502 inner: crate::command::InnerCommandEncoder {
503 raw: ManuallyDrop::new(mem::replace(&mut self.command_encoder, new_encoder)),
504 list: vec![cmd_buf],
505 device: device.clone(),
506 is_open: false,
507 api: crate::command::EncodingApi::InternalUse,
508 label: "(wgpu internal) PendingWrites command encoder".into(),
509 },
510 trackers: Tracker::new(device.ordered_buffer_usages, device.ordered_texture_usages),
511 temp_resources: mem::take(&mut self.temp_resources),
512 _indirect_draw_validation_resources: crate::indirect_validation::DrawResources::new(
513 device.clone(),
514 ),
515 pending_buffers,
516 pending_textures,
517 pending_blas_s,
518 };
519 Ok(Some(encoder))
520 } else {
521 self.dst_buffers.clear();
522 self.dst_textures.clear();
523 self.copied_blas_s.clear();
524 Ok(None)
525 }
526 }
527
528 pub fn activate(&mut self) -> &mut dyn hal::DynCommandEncoder {
529 if !self.is_recording {
530 unsafe {
531 self.command_encoder
532 .begin_encoding(hal_label(
533 Some("(wgpu internal) PendingWrites"),
534 self.instance_flags,
535 ))
536 .unwrap();
537 }
538 self.is_recording = true;
539 }
540 self.command_encoder.as_mut()
541 }
542}
543
544impl Drop for PendingWrites {
545 fn drop(&mut self) {
546 unsafe {
547 if self.is_recording {
548 self.command_encoder.discard_encoding();
549 }
550 }
551 }
552}
553
554#[derive(Clone, Debug, Error)]
555#[non_exhaustive]
556pub enum QueueWriteError {
557 #[error(transparent)]
558 Queue(#[from] DeviceError),
559 #[error(transparent)]
560 Transfer(#[from] TransferError),
561 #[error(transparent)]
562 MemoryInitFailure(#[from] ClearError),
563 #[error(transparent)]
564 DestroyedResource(#[from] DestroyedResourceError),
565 #[error(transparent)]
566 InvalidResource(#[from] InvalidResourceError),
567}
568
569impl From<InvalidOrDestroyedResourceError> for QueueWriteError {
570 fn from(e: InvalidOrDestroyedResourceError) -> Self {
571 match e {
572 InvalidOrDestroyedResourceError::InvalidResource(e) => Self::InvalidResource(e),
573 InvalidOrDestroyedResourceError::DestroyedResource(e) => Self::DestroyedResource(e),
574 }
575 }
576}
577
578impl WebGpuError for QueueWriteError {
579 fn webgpu_error_type(&self) -> ErrorType {
580 match self {
581 Self::Queue(e) => e.webgpu_error_type(),
582 Self::Transfer(e) => e.webgpu_error_type(),
583 Self::MemoryInitFailure(e) => e.webgpu_error_type(),
584 Self::DestroyedResource(e) => e.webgpu_error_type(),
585 Self::InvalidResource(e) => e.webgpu_error_type(),
586 }
587 }
588}
589
590#[derive(Clone, Debug, Error)]
591#[non_exhaustive]
592pub enum QueueSubmitError {
593 #[error(transparent)]
594 Queue(#[from] DeviceError),
595 #[error(transparent)]
596 DestroyedResource(#[from] DestroyedResourceError),
597 #[error("{0} is still mapped")]
598 BufferStillMapped(ResourceErrorIdent),
599 #[error(transparent)]
600 InvalidResource(#[from] InvalidResourceError),
601 #[error(transparent)]
602 CommandEncoder(#[from] CommandEncoderError),
603 #[error(transparent)]
604 ValidateAsActionsError(#[from] crate::ray_tracing::ValidateAsActionsError),
605}
606
607impl From<InvalidOrDestroyedResourceError> for QueueSubmitError {
608 fn from(e: InvalidOrDestroyedResourceError) -> Self {
609 match e {
610 InvalidOrDestroyedResourceError::InvalidResource(e) => Self::InvalidResource(e),
611 InvalidOrDestroyedResourceError::DestroyedResource(e) => Self::DestroyedResource(e),
612 }
613 }
614}
615
616impl WebGpuError for QueueSubmitError {
617 fn webgpu_error_type(&self) -> ErrorType {
618 match self {
619 Self::Queue(e) => e.webgpu_error_type(),
620 Self::CommandEncoder(e) => e.webgpu_error_type(),
621 Self::ValidateAsActionsError(e) => e.webgpu_error_type(),
622 Self::InvalidResource(e) => e.webgpu_error_type(),
623 Self::DestroyedResource(_) | Self::BufferStillMapped(_) => ErrorType::Validation,
624 }
625 }
626}
627
628pub(crate) struct PendingSubmission<'a> {
676 queue: &'a Queue,
677
678 command_index_guard: RwLockWriteGuard<'a, CommandIndices>,
688
689 snatch_guard: SnatchGuard<'a>,
691
692 pub executions: Vec<EncoderInFlight>,
695
696 surface_textures: FastHashMap<*const Texture, Arc<Texture>>,
702
703 pub index: SubmissionIndex,
705}
706
707pub(crate) struct SubmissionResult<'a> {
708 pub snatch_guard: SnatchGuard<'a>,
709}
710
711impl<'a> PendingSubmission<'a> {
712 fn submit(
713 self,
714 pending_writes: MutexGuard<'a, PendingWrites>,
715 ) -> Result<SubmissionResult<'a>, DeviceError> {
716 self.queue.submit_pending_submission(pending_writes, self)
717 }
718}
719
720impl Queue {
723 pub(crate) fn write_buffer_inner(
724 &self,
725 buffer: Arc<Buffer>,
726 buffer_offset: wgt::BufferAddress,
727 data: &[u8],
728 ) -> Result<(), QueueWriteError> {
729 profiling::scope!("Queue::write_buffer");
730 api_log!("Queue::write_buffer");
731
732 #[cfg(feature = "trace")]
733 if let Some(ref mut trace) = *self.device.trace.lock() {
734 use crate::device::trace::DataKind;
735 let size = data.len() as u64;
736 let data = trace.make_binary(DataKind::Bin, data);
737 trace.add(Action::WriteBuffer {
738 id: buffer.to_trace(),
739 data,
740 offset: buffer_offset,
741 size,
742 queued: true,
743 });
744 }
745
746 buffer.check_is_valid()?;
747 self.device.check_is_valid()?;
748
749 let data_size = data.len() as wgt::BufferAddress;
750
751 self.same_device_as(buffer.as_ref())?;
752
753 let data_size = if let Some(data_size) = wgt::BufferSize::new(data_size) {
754 data_size
755 } else {
756 self.validate_write_buffer_impl(buffer.as_ref(), buffer_offset, 0)?;
761
762 log::trace!("Ignoring write_buffer of size 0");
763 return Ok(());
764 };
765
766 let mut staging_buffer = StagingBuffer::new(&self.device, data_size)?;
770
771 let staging_buffer = {
772 profiling::scope!("copy");
773 staging_buffer.write(data);
774 staging_buffer.flush()
775 };
776
777 let snatch_guard = self.device.snatchable_lock.read();
778 let mut pending_writes = self.pending_writes.lock();
779
780 let result = self.write_staging_buffer_impl(
781 &snatch_guard,
782 &mut pending_writes,
783 &staging_buffer,
784 buffer,
785 buffer_offset,
786 );
787
788 pending_writes.consume(staging_buffer);
789
790 result
791 }
792
793 pub fn write_buffer(
794 &self,
795 buffer: Arc<Buffer>,
796 buffer_offset: wgt::BufferAddress,
797 data: &[u8],
798 ) {
799 if let Err(error) = self.write_buffer_inner(buffer, buffer_offset, data) {
800 self.device
801 .handle_error(error, Some(self.label()), "Queue::write_buffer");
802 }
803 }
804
805 pub fn create_staging_buffer(
806 &self,
807 buffer_size: wgt::BufferSize,
808 ) -> Result<(StagingBuffer, NonNull<u8>), QueueWriteError> {
809 profiling::scope!("Queue::create_staging_buffer");
810 resource_log!("Queue::create_staging_buffer");
811
812 self.device.check_is_valid()?;
813
814 let staging_buffer = StagingBuffer::new(&self.device, buffer_size)?;
815 let ptr = unsafe { staging_buffer.ptr() };
816
817 Ok((staging_buffer, ptr))
818 }
819
820 pub fn write_staging_buffer(
821 &self,
822 buffer: Arc<Buffer>,
823 buffer_offset: wgt::BufferAddress,
824 staging_buffer: StagingBuffer,
825 ) -> Result<(), QueueWriteError> {
826 profiling::scope!("Queue::write_staging_buffer");
827
828 buffer.check_is_valid()?;
829 self.device.check_is_valid()?;
830
831 let staging_buffer = staging_buffer.flush();
836
837 let snatch_guard = self.device.snatchable_lock.read();
838 let mut pending_writes = self.pending_writes.lock();
839
840 let result = self.write_staging_buffer_impl(
841 &snatch_guard,
842 &mut pending_writes,
843 &staging_buffer,
844 buffer,
845 buffer_offset,
846 );
847
848 drop(snatch_guard);
849
850 pending_writes.consume(staging_buffer);
851
852 drop(pending_writes);
853
854 result
855 }
856
857 pub fn validate_write_buffer(
858 &self,
859 buffer: Arc<Buffer>,
860 buffer_offset: u64,
861 buffer_size: wgt::BufferSize,
862 ) -> Result<(), QueueWriteError> {
863 profiling::scope!("Queue::validate_write_buffer");
864
865 self.device.check_is_valid()?;
866 buffer.check_is_valid()?;
867
868 self.validate_write_buffer_impl(&buffer, buffer_offset, buffer_size.into())?;
869
870 Ok(())
871 }
872
873 fn validate_write_buffer_impl(
874 &self,
875 buffer: &Buffer,
876 buffer_offset: u64,
877 buffer_size: u64,
878 ) -> Result<(), TransferError> {
879 if !matches!(&*buffer.map_state.lock(), BufferMapState::Idle) {
880 return Err(TransferError::BufferNotAvailable);
881 }
882 buffer.check_usage(wgt::BufferUsages::COPY_DST)?;
883 if !buffer_size.is_multiple_of(wgt::COPY_BUFFER_ALIGNMENT) {
884 return Err(TransferError::UnalignedCopySize(buffer_size));
885 }
886 if !buffer_offset.is_multiple_of(wgt::COPY_BUFFER_ALIGNMENT) {
887 return Err(TransferError::UnalignedBufferOffset(buffer_offset));
888 }
889
890 if buffer_offset > buffer.size {
891 return Err(TransferError::BufferStartOffsetOverrun {
892 start_offset: buffer_offset,
893 buffer_size: buffer.size,
894 side: CopySide::Destination,
895 });
896 }
897 if buffer_size > buffer.size - buffer_offset {
898 return Err(TransferError::BufferEndOffsetOverrun {
899 start_offset: buffer_offset,
900 size: buffer_size,
901 buffer_size: buffer.size,
902 side: CopySide::Destination,
903 });
904 }
905
906 Ok(())
907 }
908
909 fn write_staging_buffer_impl(
910 &self,
911 snatch_guard: &SnatchGuard,
912 pending_writes: &mut PendingWrites,
913 staging_buffer: &FlushedStagingBuffer,
914 buffer: Arc<Buffer>,
915 buffer_offset: u64,
916 ) -> Result<(), QueueWriteError> {
917 self.device.check_is_valid()?;
918
919 let transition = {
920 let mut trackers = self.device.trackers.lock();
921 trackers
922 .buffers
923 .set_single(&buffer, wgt::BufferUses::COPY_DST)
924 };
925
926 let dst_raw = buffer.try_raw(snatch_guard)?;
927
928 self.same_device_as(buffer.as_ref())?;
929
930 self.validate_write_buffer_impl(&buffer, buffer_offset, staging_buffer.size.into())?;
931
932 let region = hal::BufferCopy {
933 src_offset: 0,
934 dst_offset: buffer_offset,
935 size: staging_buffer.size,
936 };
937 let barriers = iter::once(hal::BufferBarrier {
938 buffer: staging_buffer.raw(),
939 usage: hal::StateTransition {
940 from: wgt::BufferUses::MAP_WRITE,
941 to: wgt::BufferUses::COPY_SRC,
942 },
943 })
944 .chain(transition.map(|pending| pending.into_hal(&buffer, snatch_guard)))
945 .collect::<Vec<_>>();
946 let encoder = pending_writes.activate();
947 unsafe {
948 encoder.transition_buffers(&barriers);
949 encoder.copy_buffer_to_buffer(staging_buffer.raw(), dst_raw, &[region]);
950 }
951
952 pending_writes.insert_buffer(&buffer);
953
954 {
957 buffer
958 .initialization_status
959 .write()
960 .drain(buffer_offset..(buffer_offset + staging_buffer.size.get()));
961 }
962
963 Ok(())
964 }
965
966 pub fn write_texture_inner(
967 &self,
968 destination: wgt::TexelCopyTextureInfo<Arc<Texture>>,
969 data: &[u8],
970 data_layout: &wgt::TexelCopyBufferLayout,
971 size: &wgt::Extent3d,
972 ) -> Result<(), QueueWriteError> {
973 profiling::scope!("Queue::write_texture");
974 api_log!("Queue::write_texture");
975
976 #[cfg(feature = "trace")]
977 if let Some(ref mut trace) = *self.device.trace.lock() {
978 use crate::device::trace::DataKind;
979 let data = trace.make_binary(DataKind::Bin, data);
980 trace.add(Action::WriteTexture {
981 to: destination.to_trace(),
982 data,
983 layout: *data_layout,
984 size: *size,
985 });
986 }
987
988 self.device.check_is_valid()?;
989
990 let dst = destination.texture;
991 let destination = wgt::TexelCopyTextureInfo {
992 texture: (),
993 mip_level: destination.mip_level,
994 origin: destination.origin,
995 aspect: destination.aspect,
996 };
997
998 self.same_device_as(dst.as_ref())?;
999
1000 dst.check_valid()?;
1001
1002 dst.check_usage(wgt::TextureUsages::COPY_DST)
1003 .map_err(TransferError::MissingTextureUsage)?;
1004
1005 let (hal_copy_size, array_layer_count) =
1008 validate_texture_copy_range(&destination, &dst.desc, CopySide::Destination, size)?;
1009
1010 let (selector, dst_base) = extract_texture_selector(&destination, size, &dst)?;
1011
1012 validate_texture_copy_dst_format(dst.desc.format, destination.aspect)?;
1013
1014 validate_texture_buffer_copy(
1015 &destination,
1016 dst_base.aspect,
1017 &dst.desc,
1018 data_layout,
1019 false, )?;
1021
1022 let (required_bytes_in_copy, _source_bytes_per_array_layer, _) =
1025 validate_linear_texture_data(
1026 data_layout,
1027 dst.desc.format,
1028 destination.aspect,
1029 data.len() as wgt::BufferAddress,
1030 CopySide::Source,
1031 size,
1032 )?;
1033
1034 if dst.desc.format.is_depth_stencil_format() {
1035 self.device
1036 .require_downlevel_flags(wgt::DownlevelFlags::DEPTH_TEXTURE_AND_BUFFER_COPIES)
1037 .map_err(TransferError::from)?;
1038 }
1039
1040 let snatch_guard = self.device.snatchable_lock.read();
1041
1042 let dst_raw = dst.try_inner(&snatch_guard)?.raw();
1043
1044 if size.width == 0 || size.height == 0 || size.depth_or_array_layers == 0 {
1047 log::trace!("Ignoring write_texture of size 0");
1048 return Ok(());
1049 }
1050
1051 let mut pending_writes = self.pending_writes.lock();
1052 let encoder = pending_writes.activate();
1053
1054 let init_layer_range = if dst.desc.dimension == wgt::TextureDimension::D3 {
1060 0..1
1062 } else {
1063 destination.origin.z..destination.origin.z + size.depth_or_array_layers
1064 };
1065 let layer_ranges_to_clear = {
1066 let mut dst_initialization_status = dst.initialization_status.write();
1067 if dst_initialization_status.mips[destination.mip_level as usize]
1068 .check(init_layer_range.clone())
1069 .is_some()
1070 {
1071 if has_copy_partial_init_tracker_coverage(size, &destination, &dst.desc) {
1072 dst_initialization_status.mips[destination.mip_level as usize]
1073 .drain(init_layer_range)
1074 .collect::<Vec<core::ops::Range<u32>>>()
1075 } else {
1076 dst_initialization_status.mips[destination.mip_level as usize]
1077 .drain(init_layer_range);
1078 vec![]
1079 }
1080 } else {
1081 vec![]
1082 }
1083 };
1084 if !layer_ranges_to_clear.is_empty() {
1085 let mut trackers = self.device.trackers.lock();
1086 for layer_range in layer_ranges_to_clear {
1087 crate::command::clear_texture(
1088 &dst,
1089 TextureInitRange {
1090 mip_range: destination.mip_level..(destination.mip_level + 1),
1091 layer_range,
1092 },
1093 None,
1094 encoder,
1095 &mut trackers.textures,
1096 &self.device.alignments,
1097 self.device.zero_buffer.as_ref(),
1098 &snatch_guard,
1099 self.device.instance_flags,
1100 )
1101 .map_err(QueueWriteError::from)?;
1102 }
1103 }
1104
1105 let (block_width, block_height) = dst.desc.format.block_dimensions();
1106 let width_in_blocks = size.width / block_width;
1107 let height_in_blocks = size.height / block_height;
1108
1109 let block_size = dst
1110 .desc
1111 .format
1112 .block_copy_size(Some(destination.aspect))
1113 .unwrap();
1114 let bytes_in_last_row = width_in_blocks * block_size;
1115
1116 let bytes_per_row = data_layout.bytes_per_row.unwrap_or(bytes_in_last_row);
1117 let rows_per_image = data_layout.rows_per_image.unwrap_or(height_in_blocks);
1118
1119 let bytes_per_row_alignment = get_lowest_common_denom(
1120 self.device.alignments.buffer_copy_pitch.get() as u32,
1121 block_size,
1122 );
1123 assert!(u32::MAX - bytes_in_last_row >= bytes_per_row_alignment);
1124 let stage_bytes_per_row = wgt::math::align_to(bytes_in_last_row, bytes_per_row_alignment);
1125
1126 let staging_buffer = if stage_bytes_per_row == bytes_per_row {
1130 profiling::scope!("copy aligned");
1131 let stage_size = wgt::BufferSize::new(required_bytes_in_copy).unwrap();
1133 let mut staging_buffer = StagingBuffer::new(&self.device, stage_size)?;
1134 staging_buffer.write(&data[data_layout.offset as usize..]);
1135 staging_buffer
1136 } else {
1137 profiling::scope!("copy chunked");
1138 let block_rows_in_copy = u64::from(size.depth_or_array_layers - 1)
1140 * u64::from(rows_per_image)
1141 + u64::from(height_in_blocks);
1142 let stage_size = u64::from(stage_bytes_per_row)
1145 .checked_mul(block_rows_in_copy)
1146 .and_then(wgt::BufferSize::new)
1147 .unwrap();
1148 let mut staging_buffer = StagingBuffer::new(&self.device, stage_size)?;
1149 for layer in 0..u64::from(size.depth_or_array_layers) {
1150 let rows_offset = layer * u64::from(rows_per_image);
1151 for row in rows_offset..rows_offset + u64::from(height_in_blocks) {
1152 let src_offset = data_layout.offset + row * u64::from(bytes_per_row);
1153 let dst_offset = row * u64::from(stage_bytes_per_row);
1154 unsafe {
1155 staging_buffer.write_with_offset(
1156 data,
1157 src_offset as isize,
1158 dst_offset as isize,
1159 bytes_in_last_row as usize,
1160 )
1161 }
1162 }
1163 }
1164 staging_buffer
1165 };
1166
1167 let staging_buffer = staging_buffer.flush();
1168
1169 let regions = (0..array_layer_count)
1170 .map(|array_layer_offset| {
1171 let mut texture_base = dst_base.clone();
1172 texture_base.array_layer += array_layer_offset;
1173 hal::BufferTextureCopy {
1174 buffer_layout: wgt::TexelCopyBufferLayout {
1175 offset: array_layer_offset as u64
1176 * rows_per_image as u64
1177 * stage_bytes_per_row as u64,
1178 bytes_per_row: Some(stage_bytes_per_row),
1179 rows_per_image: Some(rows_per_image),
1180 },
1181 texture_base,
1182 size: hal_copy_size,
1183 }
1184 })
1185 .collect::<Vec<_>>();
1186
1187 {
1188 let buffer_barrier = hal::BufferBarrier {
1189 buffer: staging_buffer.raw(),
1190 usage: hal::StateTransition {
1191 from: wgt::BufferUses::MAP_WRITE,
1192 to: wgt::BufferUses::COPY_SRC,
1193 },
1194 };
1195
1196 let mut trackers = self.device.trackers.lock();
1197 let transition =
1198 trackers
1199 .textures
1200 .set_single(&dst, selector, wgt::TextureUses::COPY_DST);
1201 let texture_barriers = transition
1202 .map(|pending| pending.into_hal(dst_raw))
1203 .collect::<Vec<_>>();
1204
1205 unsafe {
1206 encoder.transition_textures(&texture_barriers);
1207 encoder.transition_buffers(&[buffer_barrier]);
1208 encoder.copy_buffer_to_texture(staging_buffer.raw(), dst_raw, ®ions);
1209 }
1210 }
1211
1212 pending_writes.consume(staging_buffer);
1213 pending_writes.insert_texture(&dst);
1214
1215 Ok(())
1216 }
1217
1218 pub fn write_texture(
1219 &self,
1220 destination: wgt::TexelCopyTextureInfo<Arc<Texture>>,
1221 data: &[u8],
1222 data_layout: &wgt::TexelCopyBufferLayout,
1223 size: &wgt::Extent3d,
1224 ) {
1225 if let Err(error) = self.write_texture_inner(destination, data, data_layout, size) {
1226 self.device
1227 .handle_error(error, Some(self.label()), "Queue::write_texture");
1228 }
1229 }
1230
1231 #[cfg(webgl)]
1232 pub fn copy_external_image_to_texture(
1233 &self,
1234 source: &wgt::CopyExternalImageSourceInfo,
1235 destination: wgt::CopyExternalImageDestInfo<Arc<Texture>>,
1236 size: wgt::Extent3d,
1237 ) -> Result<(), QueueWriteError> {
1238 use crate::conv;
1239
1240 profiling::scope!("Queue::copy_external_image_to_texture");
1241
1242 self.device.check_is_valid()?;
1243
1244 let mut needs_flag = false;
1245 needs_flag |= source.origin != wgt::Origin2d::ZERO;
1249 needs_flag |= destination.color_space != wgt::PredefinedColorSpace::Srgb;
1250 #[allow(clippy::bool_comparison)]
1251 if matches!(source.source, wgt::ExternalImageSource::ImageBitmap(_)) {
1252 needs_flag |= source.flip_y != false;
1253 needs_flag |= destination.premultiplied_alpha != false;
1254 }
1255
1256 if needs_flag {
1257 self.device
1258 .require_downlevel_flags(wgt::DownlevelFlags::UNRESTRICTED_EXTERNAL_TEXTURE_COPIES)
1259 .map_err(TransferError::from)?;
1260 }
1261
1262 let src_width = source.source.width();
1263 let src_height = source.source.height();
1264
1265 let dst = destination.texture;
1266 let premultiplied_alpha = destination.premultiplied_alpha;
1267 let destination = wgt::TexelCopyTextureInfo {
1268 texture: (),
1269 mip_level: destination.mip_level,
1270 origin: destination.origin,
1271 aspect: destination.aspect,
1272 };
1273
1274 dst.check_valid()?;
1275
1276 if !conv::is_valid_external_image_copy_dst_texture_format(dst.desc.format) {
1277 return Err(
1278 TransferError::ExternalCopyToForbiddenTextureFormat(dst.desc.format).into(),
1279 );
1280 }
1281 if dst.desc.dimension != wgt::TextureDimension::D2 {
1282 return Err(TransferError::InvalidDimensionExternal.into());
1283 }
1284 dst.check_usage(wgt::TextureUsages::COPY_DST | wgt::TextureUsages::RENDER_ATTACHMENT)
1285 .map_err(TransferError::MissingTextureUsage)?;
1286 if dst.desc.sample_count != 1 {
1287 return Err(TransferError::InvalidSampleCount {
1288 sample_count: dst.desc.sample_count,
1289 }
1290 .into());
1291 }
1292
1293 if source.origin.x > src_width || src_width - source.origin.x < size.width {
1294 return Err(TransferError::TextureOverrun {
1295 start_offset: source.origin.x,
1296 end_offset: source.origin.x.saturating_add(size.width),
1297 texture_size: src_width,
1298 dimension: crate::resource::TextureErrorDimension::X,
1299 side: CopySide::Source,
1300 }
1301 .into());
1302 }
1303 if source.origin.y > src_height || src_height - source.origin.y < size.height {
1304 return Err(TransferError::TextureOverrun {
1305 start_offset: source.origin.y,
1306 end_offset: source.origin.y.saturating_add(size.height),
1307 texture_size: src_height,
1308 dimension: crate::resource::TextureErrorDimension::Y,
1309 side: CopySide::Source,
1310 }
1311 .into());
1312 }
1313 if size.depth_or_array_layers != 1 {
1314 return Err(TransferError::TextureOverrun {
1315 start_offset: 0,
1316 end_offset: size.depth_or_array_layers,
1317 texture_size: 1,
1318 dimension: crate::resource::TextureErrorDimension::Z,
1319 side: CopySide::Source,
1320 }
1321 .into());
1322 }
1323
1324 let (hal_copy_size, _) =
1327 validate_texture_copy_range(&destination, &dst.desc, CopySide::Destination, &size)?;
1328
1329 let (selector, dst_base) = extract_texture_selector(&destination, &size, &dst)?;
1330
1331 let snatch_guard = self.device.snatchable_lock.read();
1332
1333 let dst_raw = dst.try_raw(&snatch_guard)?;
1334
1335 if size.width == 0 || size.height == 0 || size.depth_or_array_layers == 0 {
1338 log::trace!("Ignoring copy_external_image_to_texture of size 0");
1339 return Ok(());
1340 }
1341
1342 let mut pending_writes = self.pending_writes.lock();
1343 let encoder = pending_writes.activate();
1344
1345 let init_layer_range = if dst.desc.dimension == wgt::TextureDimension::D3 {
1351 0..1
1353 } else {
1354 destination.origin.z..destination.origin.z + size.depth_or_array_layers
1355 };
1356 let layer_ranges_to_clear = {
1357 let mut dst_initialization_status = dst.initialization_status.write();
1358 if dst_initialization_status.mips[destination.mip_level as usize]
1359 .check(init_layer_range.clone())
1360 .is_some()
1361 {
1362 if has_copy_partial_init_tracker_coverage(&size, &destination, &dst.desc) {
1363 dst_initialization_status.mips[destination.mip_level as usize]
1364 .drain(init_layer_range)
1365 .collect::<Vec<core::ops::Range<u32>>>()
1366 } else {
1367 dst_initialization_status.mips[destination.mip_level as usize]
1368 .drain(init_layer_range);
1369 vec![]
1370 }
1371 } else {
1372 vec![]
1373 }
1374 };
1375 if !layer_ranges_to_clear.is_empty() {
1376 let mut trackers = self.device.trackers.lock();
1377 for layer_range in layer_ranges_to_clear {
1378 crate::command::clear_texture(
1379 &dst,
1380 TextureInitRange {
1381 mip_range: destination.mip_level..(destination.mip_level + 1),
1382 layer_range,
1383 },
1384 None,
1385 encoder,
1386 &mut trackers.textures,
1387 &self.device.alignments,
1388 self.device.zero_buffer.as_ref(),
1389 &snatch_guard,
1390 self.device.instance_flags,
1391 )
1392 .map_err(QueueWriteError::from)?;
1393 }
1394 }
1395
1396 let regions = hal::TextureCopy {
1397 src_base: hal::TextureCopyBase {
1398 mip_level: 0,
1399 array_layer: 0,
1400 origin: source.origin.to_3d(0),
1401 aspect: hal::FormatAspects::COLOR,
1402 },
1403 dst_base,
1404 size: hal_copy_size,
1405 };
1406
1407 let mut trackers = self.device.trackers.lock();
1408 let transitions = trackers
1409 .textures
1410 .set_single(&dst, selector, wgt::TextureUses::COPY_DST);
1411
1412 let encoder_webgl = encoder
1415 .as_any_mut()
1416 .downcast_mut::<hal::gles::CommandEncoder>()
1417 .unwrap();
1418 let dst_raw_webgl = dst_raw
1419 .as_any()
1420 .downcast_ref::<hal::gles::Texture>()
1421 .unwrap();
1422 let transitions_webgl = transitions.map(|pending| {
1423 let dyn_transition = pending.into_hal(dst_raw);
1424 hal::TextureBarrier {
1425 texture: dst_raw_webgl,
1426 range: dyn_transition.range,
1427 usage: dyn_transition.usage,
1428 queue_family_ownership_transfer: None,
1429 }
1430 });
1431
1432 use hal::CommandEncoder as _;
1433 unsafe {
1434 encoder_webgl.transition_textures(transitions_webgl);
1435 encoder_webgl.copy_external_image_to_texture(
1436 source,
1437 dst_raw_webgl,
1438 premultiplied_alpha,
1439 iter::once(regions),
1440 );
1441 }
1442
1443 pending_writes.insert_texture(&dst);
1444
1445 Ok(())
1446 }
1447
1448 pub fn flush_writes_for_buffer(
1450 &self,
1451 buffer: &Arc<Buffer>,
1452 snatch_guard: SnatchGuard,
1453 ) -> Result<(), BufferAccessError> {
1454 let submission = self
1455 .allocate_submission(snatch_guard)
1456 .map_err(|(_index, e)| e)?;
1457
1458 let pending_writes = self.pending_writes.lock();
1459 if !pending_writes.contains_buffer(buffer) {
1460 return Ok(());
1461 }
1462
1463 submission.submit(pending_writes)?;
1464
1465 Ok(())
1466 }
1467
1468 fn flush_pending_writes(&self) -> Result<Option<SubmissionIndex>, DeviceError> {
1469 let snatch_guard = self.device.snatchable_lock.read();
1470 let submission = self
1471 .allocate_submission(snatch_guard)
1472 .map_err(|(_index, e)| e)?;
1473 let submit_index = submission.index;
1474 let pending_writes = self.pending_writes.lock();
1475 if pending_writes.is_recording {
1476 submission.submit(pending_writes)?;
1477 Ok(Some(submit_index))
1478 } else {
1479 Ok(None)
1480 }
1481 }
1482
1483 #[cfg(feature = "trace")]
1484 fn trace_submission(
1485 &self,
1486 submit_index: SubmissionIndex,
1487 commands: Vec<crate::command::Command<crate::command::PointerReferences>>,
1488 ) {
1489 if let Some(ref mut trace) = *self.device.trace.lock() {
1490 trace.add(Action::Submit(submit_index, commands));
1491 }
1492 }
1493
1494 #[cfg(feature = "trace")]
1495 fn trace_failed_submission(
1496 &self,
1497 submit_index: SubmissionIndex,
1498 commands: Option<Vec<crate::command::Command<crate::command::PointerReferences>>>,
1499 error: String,
1500 ) {
1501 if let Some(ref mut trace) = *self.device.trace.lock() {
1502 trace.add(Action::FailedCommands {
1503 commands,
1504 failed_at_submit: Some(submit_index),
1505 error,
1506 });
1507 }
1508 }
1509
1510 fn submit_inner(
1511 &self,
1512 command_buffers: &[Arc<CommandBuffer>],
1513 ) -> Result<SubmissionIndex, (SubmissionIndex, QueueSubmitError)> {
1514 profiling::scope!("Queue::submit");
1515 api_log!("Queue::submit");
1516
1517 let snatch_guard = self.device.snatchable_lock.read();
1518 let mut submission = self
1519 .allocate_submission(snatch_guard)
1520 .map_err(|(index, e)| (index, e.into()))?;
1521 let submit_index = submission.index;
1522
1523 let mut lose_device_on_error = false;
1527
1528 let res = 'error: {
1529 let mut used_surface_textures = track::TextureUsageScope::default();
1530 let mut baked_command_buffers = Vec::with_capacity(command_buffers.len());
1531
1532 if !command_buffers.is_empty() {
1533 profiling::scope!("prepare");
1534
1535 let mut first_error = None;
1536
1537 #[deny(clippy::question_mark_used)]
1540 for command_buffer in command_buffers {
1541 profiling::scope!("process command buffer");
1542
1543 used_surface_textures.set_size(self.device.tracker_indices.textures.size());
1546
1547 #[cfg_attr(not(feature = "trace"), expect(unused_mut))]
1551 let mut cmd_buf_data = command_buffer.take_finished();
1552
1553 if first_error.is_some() {
1554 continue;
1555 }
1556
1557 #[cfg(feature = "trace")]
1558 let trace_commands = cmd_buf_data
1559 .as_mut()
1560 .ok()
1561 .and_then(|data| mem::take(&mut data.trace_commands));
1562
1563 let mut baked = match cmd_buf_data {
1564 Ok(cmd_buf_data) => {
1565 let res = validate_command_buffer(
1566 command_buffer,
1567 self,
1568 &cmd_buf_data,
1569 &submission.snatch_guard,
1570 &mut submission.surface_textures,
1571 &mut used_surface_textures,
1572 &mut submission.command_index_guard,
1573 );
1574 if let Err(err) = res {
1575 #[cfg(feature = "trace")]
1576 self.trace_failed_submission(
1577 submit_index,
1578 trace_commands,
1579 err.to_string(),
1580 );
1581 first_error.get_or_insert(err);
1582 continue;
1583 }
1584
1585 #[cfg(feature = "trace")]
1586 if let Some(commands) = trace_commands {
1587 self.trace_submission(submit_index, commands);
1588 }
1589
1590 cmd_buf_data
1591 .set_acceleration_structure_dependencies(&submission.snatch_guard);
1592 cmd_buf_data.into_baked_commands()
1593 }
1594 Err(err) => {
1595 #[cfg(feature = "trace")]
1596 self.trace_failed_submission(
1597 submit_index,
1598 trace_commands,
1599 err.to_string(),
1600 );
1601 first_error.get_or_insert(err.into());
1602 continue;
1603 }
1604 };
1605
1606 if let Err(e) = baked
1607 .process_deferred_query_set_resolves(&self.device, &submission.snatch_guard)
1608 {
1609 break 'error Err(e.into());
1610 }
1611
1612 baked_command_buffers.push(baked);
1613 }
1614
1615 if let Some(first_error) = first_error {
1616 break 'error Err(first_error);
1617 }
1618
1619 lose_device_on_error = true;
1632
1633 let mut trackers = self.device.trackers.lock();
1635
1636 for mut baked in baked_command_buffers {
1637 profiling::scope!("process baked commands");
1638
1639 if let Err(e) = baked.encoder.open_pass(hal_label(
1641 Some("(wgpu internal) Transit"),
1642 self.device.instance_flags,
1643 )) {
1644 break 'error Err(e.into());
1645 }
1646
1647 baked.initialize_buffer_memory(&mut trackers, &submission.snatch_guard);
1648
1649 let depth_slice_discards = match baked.initialize_texture_memory(
1650 &mut trackers,
1651 &self.device,
1652 &submission.snatch_guard,
1653 ) {
1654 Ok(discards) => discards,
1655 Err(e) => {
1656 break 'error Err(QueueSubmitError::CommandEncoder(
1657 CommandEncoderError::Clear(e),
1658 ));
1659 }
1660 };
1661
1662 CommandEncoder::insert_barriers_from_device_tracker(
1665 baked.encoder.raw.as_mut(),
1666 &mut trackers,
1667 &baked.trackers,
1668 &submission.snatch_guard,
1669 );
1670
1671 if let Err(e) = baked.encoder.close_and_push_front() {
1672 break 'error Err(e.into());
1673 }
1674
1675 if !depth_slice_discards.is_empty() || !used_surface_textures.is_empty() {
1676 if let Err(e) = baked.encoder.open_pass(hal_label(
1677 Some("(wgpu internal) Finalize"),
1678 self.device.instance_flags,
1679 )) {
1680 break 'error Err(e.into());
1681 }
1682
1683 if let Err(e) = baked.initialize_discarded_depth_slices(
1684 depth_slice_discards,
1685 &mut trackers,
1686 &self.device,
1687 &submission.snatch_guard,
1688 ) {
1689 break 'error Err(QueueSubmitError::CommandEncoder(
1690 CommandEncoderError::Clear(e),
1691 ));
1692 }
1693
1694 let texture_barriers = trackers
1698 .textures
1699 .set_from_usage_scope_and_drain_transitions(
1700 &used_surface_textures,
1701 &submission.snatch_guard,
1702 )
1703 .collect::<Vec<_>>();
1704 unsafe {
1705 baked.encoder.raw.transition_textures(&texture_barriers);
1706 };
1707 if let Err(e) = baked.encoder.close() {
1708 break 'error Err(e.into());
1709 }
1710 used_surface_textures = track::TextureUsageScope::default();
1711 }
1712
1713 submission.executions.push(EncoderInFlight {
1715 inner: baked.encoder,
1716 trackers: baked.trackers,
1717 temp_resources: baked.temp_resources,
1718 _indirect_draw_validation_resources: baked
1719 .indirect_draw_validation_resources,
1720 pending_buffers: FastHashMap::default(),
1721 pending_textures: FastHashMap::default(),
1722 pending_blas_s: FastHashMap::default(),
1723 });
1724 }
1725 }
1726
1727 let pending_writes = self.pending_writes.lock();
1728
1729 let SubmissionResult { snatch_guard } = match submission.submit(pending_writes) {
1730 Ok(result) => result,
1731 Err(e) => break 'error Err(e.into()),
1732 };
1733
1734 profiling::scope!("cleanup");
1735
1736 lose_device_on_error = false;
1740
1741 let (closures, result) = self.device.maintain(wgt::PollType::Poll, snatch_guard);
1745 match result {
1746 Ok(status) => {
1747 debug_assert!(matches!(
1748 status,
1749 wgt::PollStatus::QueueEmpty | wgt::PollStatus::Poll
1750 ));
1751 }
1752 Err(WaitIdleError::Device(err)) => break 'error Err(QueueSubmitError::Queue(err)),
1753 Err(WaitIdleError::WrongSubmissionIndex(..)) => {
1754 unreachable!("Cannot get WrongSubmissionIndex from Poll")
1755 }
1756 Err(WaitIdleError::Timeout) => unreachable!("Cannot get Timeout from Poll"),
1757 };
1758
1759 Ok(closures)
1760 }; let callbacks = match res {
1763 Ok(ok) => ok,
1764 Err(e) => {
1765 if lose_device_on_error {
1766 self.device.lose("submission failed");
1767 }
1768 return Err((submit_index, e));
1769 }
1770 };
1771
1772 callbacks.fire();
1774
1775 self.device.lose_if_oom();
1776
1777 api_log!("Queue::submit returned submit index {submit_index}");
1778
1779 Ok(submit_index)
1780 }
1781
1782 pub fn submit(&self, command_buffers: &[Arc<CommandBuffer>]) -> SubmissionIndex {
1783 match self.submit_inner(command_buffers) {
1784 Ok(submit_index) => submit_index,
1785 Err((submit_index, e)) => {
1786 self.device
1787 .handle_error(e, Some(self.label()), "Queue::submit");
1788 submit_index
1789 }
1790 }
1791 }
1792
1793 fn allocate_submission<'a>(
1816 &'a self,
1817 snatch_guard: SnatchGuard<'a>,
1818 ) -> Result<PendingSubmission<'a>, (SubmissionIndex, DeviceError)> {
1819 let mut command_index_guard = self.device.command_indices.write();
1820 command_index_guard.active_submission_index += 1;
1821 let index = command_index_guard.active_submission_index;
1822
1823 if let Err(e) = self.device.check_is_valid() {
1824 return Err((index, e));
1825 }
1826
1827 let submission = PendingSubmission {
1828 queue: self,
1829 command_index_guard,
1830 snatch_guard,
1831 executions: Vec::new(),
1832 surface_textures: FastHashMap::default(),
1833 index,
1834 };
1835
1836 Ok(submission)
1837 }
1838
1839 fn submit_pending_submission<'a>(
1855 &self,
1856 mut pending_writes: MutexGuard<'_, PendingWrites>,
1857 prepared: PendingSubmission<'a>,
1858 ) -> Result<SubmissionResult<'a>, DeviceError> {
1859 let PendingSubmission {
1860 queue: _,
1861 snatch_guard,
1862 command_index_guard,
1863 mut executions,
1864 mut surface_textures,
1865 index: submit_index,
1866 } = prepared;
1867
1868 let mut used_surface_textures = track::TextureUsageScope::default();
1869 used_surface_textures.set_size(self.device.tracker_indices.textures.size());
1870 for texture in pending_writes.dst_textures.values() {
1871 match texture.try_inner(&snatch_guard) {
1872 Ok(TextureInner::Native { .. }) => {}
1873 Ok(TextureInner::Surface { .. }) => {
1874 surface_textures.insert(Arc::as_ptr(texture), texture.clone());
1876
1877 unsafe {
1878 used_surface_textures
1879 .merge_single(texture, None, wgt::TextureUses::PRESENT)
1880 .unwrap()
1881 };
1882 }
1883 Err(InvalidOrDestroyedResourceError::DestroyedResource(_)) => {}
1888 Err(InvalidOrDestroyedResourceError::InvalidResource(_)) => {
1889 unreachable!()
1890 }
1891 }
1892 }
1893
1894 if !used_surface_textures.is_empty() {
1895 let mut trackers = self.device.trackers.lock();
1896
1897 let texture_barriers = trackers
1898 .textures
1899 .set_from_usage_scope_and_drain_transitions(&used_surface_textures, &snatch_guard)
1900 .collect::<Vec<_>>();
1901 unsafe {
1902 pending_writes
1903 .command_encoder
1904 .transition_textures(&texture_barriers);
1905 };
1906 }
1907
1908 match pending_writes.pre_submit(&self.device.command_allocator, &self.device, self) {
1909 Ok(Some(pending_execution)) => {
1910 executions.insert(0, pending_execution);
1911 }
1912 Ok(None) => {}
1913 Err(e) => return Err(e),
1914 }
1915 let hal_command_buffers = executions
1916 .iter()
1917 .flat_map(|e| e.inner.list.iter().map(|b| b.as_ref()))
1918 .collect::<Vec<_>>();
1919
1920 {
1921 let mut submit_surface_textures =
1922 SmallVec::<[&dyn hal::DynSurfaceTexture; 2]>::with_capacity(surface_textures.len());
1923 for texture in surface_textures.values() {
1924 let raw = match texture.try_inner(&snatch_guard).ok() {
1925 Some(TextureInner::Surface { raw, .. }) => raw.as_ref(),
1926 _ => unreachable!(),
1927 };
1928 submit_surface_textures.push(raw);
1929 }
1930
1931 unsafe {
1932 self.raw().submit(
1933 &hal_command_buffers,
1934 &submit_surface_textures,
1935 (self.device.fence.as_ref(), submit_index),
1936 )
1937 }
1938 .map_err(|e| self.device.handle_hal_error(e))?;
1939
1940 drop(pending_writes);
1944
1945 self.device
1947 .last_successful_submission_index
1948 .fetch_max(submit_index, Ordering::SeqCst);
1949 }
1950
1951 self.lock_life().track_submission(submit_index, executions);
1953
1954 drop(command_index_guard);
1960
1961 Ok(SubmissionResult { snatch_guard })
1962 }
1963
1964 pub(crate) fn get_raw_timestamp_period(&self) -> f32 {
1965 unsafe { self.raw().get_timestamp_period() }
1966 }
1967
1968 pub fn get_timestamp_period(&self) -> f32 {
1969 if self.device.timestamp_normalizer.get().unwrap().enabled() {
1970 return 1.0;
1971 }
1972
1973 self.get_raw_timestamp_period()
1974 }
1975
1976 pub fn on_submitted_work_done(
1978 &self,
1979 closure: SubmittedWorkDoneClosure,
1980 ) -> Option<SubmissionIndex> {
1981 api_log!("Queue::on_submitted_work_done");
1982
1983 let _: Result<_, DeviceError> = self.flush_pending_writes();
1987
1988 self.lock_life().add_work_done_closure(closure)
1989 }
1990
1991 #[allow(trivial_casts)]
1992 pub fn compact_blas(&self, blas: &Arc<Blas>) -> (Arc<Blas>, Option<CompactBlasError>) {
1993 api_log!(
1994 "Queue::compact_blas {:?}, {:?}",
1995 self as *const _,
1996 Arc::as_ptr(blas)
1997 );
1998
1999 let (blas, error) = match self.compact_blas_inner(blas) {
2000 Ok(blas) => (blas, None),
2001 Err(err) => {
2002 let new_label = blas.label.clone() + " (compacted)";
2003 (
2004 Blas::invalid(
2005 self.device.clone(),
2006 &BlasDescriptor {
2007 label: Some(new_label.into()),
2008 flags: blas.flags,
2009 update_mode: blas.update_mode,
2010 },
2011 ),
2012 Some(err),
2013 )
2014 }
2015 };
2016
2017 (blas, error)
2020 }
2021
2022 pub(crate) fn compact_blas_inner(
2023 &self,
2024 blas: &Arc<Blas>,
2025 ) -> Result<Arc<Blas>, CompactBlasError> {
2026 profiling::scope!("Queue::compact_blas");
2027 api_log!("Queue::compact_blas");
2028
2029 let new_label = blas.label.clone() + " (compacted)";
2030
2031 self.device.check_is_valid()?;
2032
2033 self.device
2034 .require_features(wgpu_types::Features::EXPERIMENTAL_RAY_QUERY)?;
2035
2036 blas.check_is_valid()?;
2037 self.same_device_as(blas.as_ref())?;
2038
2039 let device = blas.device.clone();
2040
2041 let snatch_guard = device.snatchable_lock.read();
2042
2043 let BlasCompactState::Ready { size } = *blas.compacted_state.lock() else {
2044 return Err(CompactBlasError::BlasNotReady);
2045 };
2046
2047 let mut size_info = blas.size_info;
2048 size_info.acceleration_structure_size = size;
2049
2050 let mut command_indices_lock = device.command_indices.write();
2051 let mut pending_writes = self.pending_writes.lock();
2052 let cmd_buf_raw = pending_writes.activate();
2053
2054 let raw = unsafe {
2055 device
2056 .raw()
2057 .create_acceleration_structure(&hal::AccelerationStructureDescriptor {
2058 label: hal_label(Some(&new_label), device.instance_flags),
2059 size: size_info.acceleration_structure_size,
2060 format: hal::AccelerationStructureFormat::BottomLevel,
2061 allow_compaction: false,
2062 })
2063 }
2064 .map_err(DeviceError::from_hal)?;
2065
2066 let src_raw = blas.try_raw(&snatch_guard)?;
2067
2068 unsafe {
2069 cmd_buf_raw.copy_acceleration_structure_to_acceleration_structure(
2070 src_raw,
2071 raw.as_ref(),
2072 wgt::AccelerationStructureCopy::Compact,
2073 )
2074 };
2075
2076 let handle = unsafe {
2077 device
2078 .raw()
2079 .get_acceleration_structure_device_address(raw.as_ref())
2080 };
2081
2082 command_indices_lock.next_acceleration_structure_build_command_index += 1;
2083 let built_index =
2084 NonZeroU64::new(command_indices_lock.next_acceleration_structure_build_command_index)
2085 .unwrap();
2086
2087 let new_blas = Arc::new(Blas {
2088 state: ResourceState::Valid(BlasState {
2089 raw: Snatchable::new(raw),
2090 }),
2091 device: device.clone(),
2092 size_info,
2093 sizes: blas.sizes.clone(),
2094 flags: blas.flags & !AccelerationStructureFlags::ALLOW_COMPACTION,
2095 update_mode: blas.update_mode,
2096 built_index: RwLock::new(rank::BLAS_BUILT_INDEX, Some(built_index)),
2098 handle,
2099 label: new_label,
2100 tracking_data: TrackingData::new(blas.device.tracker_indices.blas_s.clone()),
2101 compaction_buffer: None,
2102 compacted_state: Mutex::new(rank::BLAS_COMPACTION_STATE, BlasCompactState::Compacted),
2103 });
2104
2105 pending_writes.insert_blas(blas);
2106 pending_writes.insert_blas(&new_blas);
2107
2108 let old_blas_size = blas.size_info.acceleration_structure_size;
2110 let new_blas_size = new_blas.size_info.acceleration_structure_size;
2111
2112 api_log!("CommandEncoder::compact_blas {:?} (size: {old_blas_size}) -> {:?} (size: {new_blas_size})", Arc::as_ptr(blas), Arc::as_ptr(&new_blas));
2113
2114 Ok(new_blas)
2115 }
2116}
2117
2118fn validate_command_buffer(
2119 command_buffer: &CommandBuffer,
2120 queue: &Queue,
2121 cmd_buf_data: &crate::command::CommandBufferMutable,
2122 snatch_guard: &SnatchGuard,
2123 surface_textures: &mut FastHashMap<*const Texture, Arc<Texture>>,
2124 used_surface_textures: &mut track::TextureUsageScope,
2125 command_index_guard: &mut RwLockWriteGuard<CommandIndices>,
2126) -> Result<(), QueueSubmitError> {
2127 command_buffer.same_device_as(queue)?;
2128
2129 {
2130 profiling::scope!("check resource state");
2131
2132 {
2133 profiling::scope!("buffers");
2134 for buffer in cmd_buf_data.trackers.buffers.used_resources() {
2135 buffer.check_destroyed(snatch_guard)?;
2136
2137 match *buffer.map_state.lock() {
2138 BufferMapState::Idle => (),
2139 _ => return Err(QueueSubmitError::BufferStillMapped(buffer.error_ident())),
2140 }
2141 }
2142 }
2143 {
2144 profiling::scope!("textures");
2145 for texture in cmd_buf_data.trackers.textures.used_resources() {
2146 let should_extend = match texture.try_inner(snatch_guard)? {
2147 TextureInner::Native { .. } => false,
2148 TextureInner::Surface { .. } => {
2149 surface_textures.insert(Arc::as_ptr(texture), texture.clone());
2151
2152 true
2153 }
2154 };
2155 if should_extend {
2156 unsafe {
2157 used_surface_textures
2158 .merge_single(texture, None, wgt::TextureUses::PRESENT)
2159 .unwrap();
2160 };
2161 }
2162 }
2163 }
2164 {
2165 profiling::scope!("query sets");
2166 for query_set in cmd_buf_data.trackers.query_sets.used_resources() {
2167 query_set.try_raw(snatch_guard)?;
2168 }
2169 }
2170 {
2174 profiling::scope!("bind groups");
2175 for bind_group in &cmd_buf_data.trackers.bind_groups {
2176 bind_group.try_raw(snatch_guard)?;
2178 }
2179 }
2180
2181 if let Err(e) =
2182 cmd_buf_data.validate_acceleration_structure_actions(snatch_guard, command_index_guard)
2183 {
2184 return Err(e.into());
2185 }
2186 }
2187 Ok(())
2188}