1use alloc::boxed::Box;
2use alloc::sync::Arc;
3use core::{mem, ops::Range};
4
5use arrayvec::ArrayVec;
6
7use super::{conv, Command as C};
8
9#[derive(Clone, Copy, Debug, Default)]
10struct TextureSlotDesc {
11 tex_target: super::BindTarget,
12 sampler_index: Option<u8>,
13}
14
15pub(super) struct State {
16 topology: u32,
17 primitive: super::PrimitiveState,
18 index_format: wgt::IndexFormat,
19 index_offset: wgt::BufferAddress,
20 vertex_buffers: [(
21 Option<super::VertexBufferDesc>,
22 Option<super::BufferBinding>,
23 ); crate::MAX_VERTEX_BUFFERS],
24 vertex_attributes: ArrayVec<super::AttributeDesc, { super::MAX_VERTEX_ATTRIBUTES }>,
25 color_targets: ArrayVec<super::ColorTargetDesc, { crate::MAX_COLOR_ATTACHMENTS }>,
26 stencil: super::StencilState,
27 depth_bias: wgt::DepthBiasState,
28 alpha_to_coverage_enabled: bool,
29 samplers: [Option<glow::Sampler>; super::MAX_SAMPLERS],
30 texture_slots: [TextureSlotDesc; super::MAX_TEXTURE_SLOTS],
31 render_size: wgt::Extent3d,
32 resolve_attachments: ArrayVec<(u32, super::TextureView), { crate::MAX_COLOR_ATTACHMENTS }>,
33 invalidate_attachments: ArrayVec<u32, { crate::MAX_COLOR_ATTACHMENTS + 2 }>,
34 has_pass_label: bool,
35 instance_vbuf_mask: usize,
36 dirty_vbuf_mask: usize,
37 active_first_instance: u32,
38 current_immediates_data: [u32; super::MAX_IMMEDIATES],
40 end_of_pass_timestamp: Option<glow::Query>,
41 clip_distance_count: u32,
42 last_attribute_buffer: Option<glow::Buffer>,
44}
45
46impl Default for State {
47 fn default() -> Self {
48 Self {
49 topology: Default::default(),
50 primitive: Default::default(),
51 index_format: Default::default(),
52 index_offset: Default::default(),
53 vertex_buffers: Default::default(),
54 vertex_attributes: Default::default(),
55 color_targets: Default::default(),
56 stencil: Default::default(),
57 depth_bias: Default::default(),
58 alpha_to_coverage_enabled: Default::default(),
59 samplers: Default::default(),
60 texture_slots: Default::default(),
61 render_size: Default::default(),
62 resolve_attachments: Default::default(),
63 invalidate_attachments: Default::default(),
64 has_pass_label: Default::default(),
65 instance_vbuf_mask: Default::default(),
66 dirty_vbuf_mask: Default::default(),
67 active_first_instance: Default::default(),
68 current_immediates_data: [0; super::MAX_IMMEDIATES],
69 end_of_pass_timestamp: Default::default(),
70 clip_distance_count: Default::default(),
71 last_attribute_buffer: Default::default(),
72 }
73 }
74}
75
76impl super::CommandBuffer {
77 fn clear(&mut self) {
78 self.label = None;
79 self.commands.clear();
80 self.data_bytes.clear();
81 self.queries.clear();
82 }
83
84 fn add_marker(&mut self, marker: &str) -> Range<u32> {
85 super::debug_text::add_marker(&mut self.data_bytes, marker)
86 }
87
88 fn add_immediates_data(&mut self, data: &[u32]) -> Range<u32> {
89 let data_raw = bytemuck::cast_slice(data);
90 let start = self.data_bytes.len();
91 assert!(start < u32::MAX as usize);
92 self.data_bytes.extend_from_slice(data_raw);
93 let end = self.data_bytes.len();
94 assert!(end < u32::MAX as usize);
95 (start as u32)..(end as u32)
96 }
97}
98
99impl Drop for super::CommandEncoder {
100 fn drop(&mut self) {
101 use crate::CommandEncoder;
102 unsafe { self.discard_encoding() }
103 self.counters.command_encoders.sub(1);
104 }
105}
106
107impl super::CommandEncoder {
108 fn rebind_stencil_func(&mut self) {
109 fn make(s: &super::StencilSide, face: u32) -> C {
110 C::SetStencilFunc {
111 face,
112 function: s.function,
113 reference: s.reference,
114 read_mask: s.mask_read,
115 }
116 }
117
118 let s = &self.state.stencil;
119 if s.front.function == s.back.function
120 && s.front.mask_read == s.back.mask_read
121 && s.front.reference == s.back.reference
122 {
123 self.cmd_buffer
124 .commands
125 .push(make(&s.front, glow::FRONT_AND_BACK));
126 } else {
127 self.cmd_buffer.commands.push(make(&s.front, glow::FRONT));
128 self.cmd_buffer.commands.push(make(&s.back, glow::BACK));
129 }
130 }
131
132 fn rebind_vertex_data(&mut self, first_instance: u32) {
133 if self
134 .private_caps
135 .contains(super::PrivateCapabilities::VERTEX_BUFFER_LAYOUT)
136 {
137 for (index, pair) in self.state.vertex_buffers.iter().enumerate() {
138 if self.state.dirty_vbuf_mask & (1 << index) == 0 {
139 continue;
140 }
141 let (buffer_desc, vb) = match *pair {
142 (Some(ref vb_desc), Some(ref vb)) => (vb_desc.clone(), vb),
143 (_, _) => continue,
145 };
146 let instance_offset = match buffer_desc.step {
147 wgt::VertexStepMode::Vertex => 0,
148 wgt::VertexStepMode::Instance => first_instance * buffer_desc.stride,
149 };
150
151 self.cmd_buffer.commands.push(C::SetVertexBuffer {
152 index: index as u32,
153 buffer: super::BufferBinding {
154 raw: vb.raw,
155 offset: vb.offset + instance_offset as wgt::BufferAddress,
156 },
157 buffer_desc,
158 });
159 self.state.dirty_vbuf_mask ^= 1 << index;
160 }
161 } else {
162 let mut vbuf_mask = 0;
163 let last_buffer = self.state.last_attribute_buffer;
167 for first in [true, false] {
168 for attribute in self.state.vertex_attributes.iter() {
169 if self.state.dirty_vbuf_mask & (1 << attribute.buffer_index) == 0 {
170 continue;
171 }
172 let (buffer_desc, vb) =
173 match self.state.vertex_buffers[attribute.buffer_index as usize] {
174 (Some(ref vb_desc), Some(ref vb)) => (vb_desc.clone(), vb),
175 (_, _) => continue,
177 };
178 if (last_buffer == Some(vb.raw)) != first {
179 continue;
180 }
181
182 let mut attribute_desc = attribute.clone();
183 attribute_desc.offset += vb.offset as u32;
184 if buffer_desc.step == wgt::VertexStepMode::Instance {
185 attribute_desc.offset += buffer_desc.stride * first_instance;
186 }
187
188 self.cmd_buffer.commands.push(C::SetVertexAttribute {
189 buffer: Some(vb.raw),
190 buffer_desc,
191 attribute_desc,
192 });
193 self.state.last_attribute_buffer = Some(vb.raw);
194 vbuf_mask |= 1 << attribute.buffer_index;
195 }
196 }
197 self.state.dirty_vbuf_mask ^= vbuf_mask;
198 }
199 }
200
201 fn rebind_sampler_states(&mut self, dirty_textures: u32, dirty_samplers: u32) {
202 for (texture_index, slot) in self.state.texture_slots.iter().enumerate() {
203 if dirty_textures & (1 << texture_index) != 0
204 || slot
205 .sampler_index
206 .is_some_and(|si| dirty_samplers & (1 << si) != 0)
207 {
208 let sampler = slot
209 .sampler_index
210 .and_then(|si| self.state.samplers[si as usize]);
211 self.cmd_buffer
212 .commands
213 .push(C::BindSampler(texture_index as u32, sampler));
214 }
215 }
216 }
217
218 fn prepare_draw(&mut self, first_instance: u32) {
219 let emulated_first_instance_value = if self
222 .private_caps
223 .contains(super::PrivateCapabilities::FULLY_FEATURED_INSTANCING)
224 {
225 0
226 } else {
227 first_instance
228 };
229
230 if emulated_first_instance_value != self.state.active_first_instance {
231 self.state.dirty_vbuf_mask |= self.state.instance_vbuf_mask;
233 self.state.active_first_instance = emulated_first_instance_value;
234 }
235 if self.state.dirty_vbuf_mask != 0 {
236 self.rebind_vertex_data(emulated_first_instance_value);
237 }
238 }
239
240 fn set_pipeline_inner(&mut self, inner: &Arc<super::PipelineInner>) {
241 self.cmd_buffer.commands.push(C::SetProgram(Arc::clone(inner)));
242
243 let mut dirty_textures = 0u32;
245 for (texture_index, (slot, &sampler_index)) in self
246 .state
247 .texture_slots
248 .iter_mut()
249 .zip(inner.sampler_map.iter())
250 .enumerate()
251 {
252 if slot.sampler_index != sampler_index {
253 slot.sampler_index = sampler_index;
254 dirty_textures |= 1 << texture_index;
255 }
256 }
257 if dirty_textures != 0 {
258 self.rebind_sampler_states(dirty_textures, 0);
259 }
260 }
261}
262
263impl crate::CommandEncoder for super::CommandEncoder {
264 type A = super::Api;
265
266 unsafe fn begin_encoding(&mut self, label: crate::Label) -> Result<(), crate::DeviceError> {
267 self.state = State::default();
268 self.cmd_buffer.label = label.map(super::debug_text::label);
269 Ok(())
270 }
271 unsafe fn discard_encoding(&mut self) {
272 self.cmd_buffer.clear();
273 }
274 unsafe fn end_encoding(&mut self) -> Result<super::CommandBuffer, crate::DeviceError> {
275 Ok(mem::take(&mut self.cmd_buffer))
276 }
277 unsafe fn reset_all<I>(&mut self, _command_buffers: I) {
278 }
280
281 unsafe fn transition_buffers<'a, T>(&mut self, barriers: T)
282 where
283 T: Iterator<Item = crate::BufferBarrier<'a, super::Buffer>>,
284 {
285 if !self
286 .private_caps
287 .contains(super::PrivateCapabilities::MEMORY_BARRIERS)
288 {
289 return;
290 }
291 for bar in barriers {
292 if !bar.usage.from.contains(wgt::BufferUses::STORAGE_READ_WRITE) {
294 continue;
295 }
296 self.cmd_buffer
297 .commands
298 .push(C::BufferBarrier(bar.buffer.raw.unwrap(), bar.usage.to));
299 }
300 }
301
302 unsafe fn transition_textures<'a, T>(&mut self, barriers: T)
303 where
304 T: Iterator<Item = crate::TextureBarrier<'a, super::Texture>>,
305 {
306 if !self
307 .private_caps
308 .contains(super::PrivateCapabilities::MEMORY_BARRIERS)
309 {
310 return;
311 }
312
313 let mut combined_usage = wgt::TextureUses::empty();
314 for bar in barriers {
315 if !bar.usage.from.intersects(
318 wgt::TextureUses::STORAGE_READ_WRITE | wgt::TextureUses::STORAGE_WRITE_ONLY,
319 ) {
320 continue;
321 }
322 combined_usage |= bar.usage.to;
325 }
326
327 if !combined_usage.is_empty() {
328 self.cmd_buffer
329 .commands
330 .push(C::TextureBarrier(combined_usage));
331 }
332 }
333
334 unsafe fn clear_buffer(&mut self, buffer: &super::Buffer, range: crate::MemoryRange) {
335 self.cmd_buffer
336 .commands
337 .push(C::ClearBuffer(Box::new(super::ClearBufferOp {
338 dst: buffer.clone(),
339 dst_target: buffer.target,
340 range,
341 })));
342 }
343
344 unsafe fn copy_buffer_to_buffer<T>(
345 &mut self,
346 src: &super::Buffer,
347 dst: &super::Buffer,
348 regions: T,
349 ) where
350 T: Iterator<Item = crate::BufferCopy>,
351 {
352 let (src_target, dst_target) = if src.target == dst.target {
353 (glow::COPY_READ_BUFFER, glow::COPY_WRITE_BUFFER)
354 } else {
355 (src.target, dst.target)
356 };
357 for copy in regions {
358 self.cmd_buffer
359 .commands
360 .push(C::CopyBufferToBuffer(Box::new(super::BufferToBufferCopy {
361 src: src.clone(),
362 src_target,
363 dst: dst.clone(),
364 dst_target,
365 copy,
366 })))
367 }
368 }
369
370 #[cfg(webgl)]
371 unsafe fn copy_external_image_to_texture<T>(
372 &mut self,
373 src: &wgt::CopyExternalImageSourceInfo,
374 dst: &super::Texture,
375 dst_premultiplication: bool,
376 regions: T,
377 ) where
378 T: Iterator<Item = crate::TextureCopy>,
379 {
380 let (dst_raw, dst_target) = dst.inner.as_native();
381 for copy in regions {
382 self.cmd_buffer
383 .commands
384 .push(C::CopyExternalImageToTexture(Box::new(
385 super::ExternalImageToTextureCopy {
386 src: src.clone(),
387 dst: dst_raw,
388 dst_target,
389 dst_format: dst.format,
390 dst_premultiplication,
391 copy,
392 },
393 )))
394 }
395 }
396
397 unsafe fn copy_texture_to_texture<T>(
398 &mut self,
399 src: &super::Texture,
400 _src_usage: wgt::TextureUses,
401 dst: &super::Texture,
402 regions: T,
403 ) where
404 T: Iterator<Item = crate::TextureCopy>,
405 {
406 for mut copy in regions {
407 copy.clamp_size_to_virtual(&src.copy_size, &dst.copy_size);
408 let command = match (&src.inner, &dst.inner) {
409 (super::TextureInner::DefaultRenderbuffer, _) => {
410 let (texture, target) = dst.inner.as_native();
411 C::CopyCanvasToTexture(Box::new(super::CanvasCopy {
412 texture,
413 target,
414 copy,
415 }))
416 }
417 (_, super::TextureInner::DefaultRenderbuffer) => {
418 let (texture, target) = src.inner.as_native();
419 C::CopyTextureToCanvas(Box::new(super::CanvasCopy {
420 texture,
421 target,
422 copy,
423 }))
424 }
425 _ => {
426 let (src_raw, src_target) = src.inner.as_native();
427 let (dst_raw, dst_target) = dst.inner.as_native();
428 C::CopyTextureToTexture(Box::new(super::TextureToTextureCopy {
429 src: src_raw,
430 src_target,
431 dst: dst_raw,
432 dst_target,
433 copy,
434 }))
435 }
436 };
437 self.cmd_buffer.commands.push(command);
438 }
439 }
440
441 unsafe fn copy_buffer_to_texture<T>(
442 &mut self,
443 src: &super::Buffer,
444 dst: &super::Texture,
445 regions: T,
446 ) where
447 T: Iterator<Item = crate::BufferTextureCopy>,
448 {
449 let (dst_raw, dst_target) = dst.inner.as_native();
450
451 for mut copy in regions {
452 copy.clamp_size_to_virtual(&dst.copy_size);
453 self.cmd_buffer
454 .commands
455 .push(C::CopyBufferToTexture(Box::new(
456 super::BufferToTextureCopy {
457 src: src.clone(),
458 src_target: src.target,
459 dst: dst_raw,
460 dst_target,
461 dst_format: dst.format,
462 copy,
463 },
464 )))
465 }
466 }
467
468 unsafe fn copy_texture_to_buffer<T>(
469 &mut self,
470 src: &super::Texture,
471 _src_usage: wgt::TextureUses,
472 dst: &super::Buffer,
473 regions: T,
474 ) where
475 T: Iterator<Item = crate::BufferTextureCopy>,
476 {
477 let (src_raw, src_target) = src.inner.as_native();
478 for mut copy in regions {
479 copy.clamp_size_to_virtual(&src.copy_size);
480 self.cmd_buffer
481 .commands
482 .push(C::CopyTextureToBuffer(Box::new(
483 super::TextureToBufferCopy {
484 src: src_raw,
485 src_target,
486 src_format: src.format,
487 dst: dst.clone(),
488 dst_target: dst.target,
489 copy,
490 },
491 )))
492 }
493 }
494
495 unsafe fn begin_query(&mut self, set: &super::QuerySet, index: u32) {
496 let query = set.queries[index as usize];
497 self.cmd_buffer
498 .commands
499 .push(C::BeginQuery(query, set.target));
500 }
501 unsafe fn end_query(&mut self, set: &super::QuerySet, _index: u32) {
502 self.cmd_buffer.commands.push(C::EndQuery(set.target));
503 }
504 unsafe fn write_timestamp(&mut self, set: &super::QuerySet, index: u32) {
505 let query = set.queries[index as usize];
506 self.cmd_buffer.commands.push(C::TimestampQuery(query));
507 }
508 unsafe fn reset_queries(&mut self, _set: &super::QuerySet, _range: Range<u32>) {
509 }
511 unsafe fn copy_query_results(
512 &mut self,
513 set: &super::QuerySet,
514 range: Range<u32>,
515 buffer: &super::Buffer,
516 offset: wgt::BufferAddress,
517 _stride: wgt::BufferSize,
518 ) {
519 let start = self.cmd_buffer.queries.len();
520 self.cmd_buffer
521 .queries
522 .extend_from_slice(&set.queries[range.start as usize..range.end as usize]);
523 let query_range = start as u32..self.cmd_buffer.queries.len() as u32;
524 self.cmd_buffer
525 .commands
526 .push(C::CopyQueryResults(Box::new(super::QueryResultsCopy {
527 query_range,
528 dst: buffer.clone(),
529 dst_target: buffer.target,
530 dst_offset: offset,
531 })));
532 }
533
534 unsafe fn begin_render_pass(
537 &mut self,
538 desc: &crate::RenderPassDescriptor<super::QuerySet, super::TextureView>,
539 ) -> Result<(), crate::DeviceError> {
540 debug_assert!(self.state.end_of_pass_timestamp.is_none());
541 if let Some(ref t) = desc.timestamp_writes {
542 if let Some(index) = t.beginning_of_pass_write_index {
543 unsafe { self.write_timestamp(t.query_set, index) }
544 }
545 self.state.end_of_pass_timestamp = t
546 .end_of_pass_write_index
547 .map(|index| t.query_set.queries[index as usize]);
548 }
549
550 self.state.render_size = desc.extent;
551 self.state.resolve_attachments.clear();
552 self.state.invalidate_attachments.clear();
553 if let Some(label) = desc.label {
554 let range = self.cmd_buffer.add_marker(label);
555 self.cmd_buffer.commands.push(C::PushDebugGroup(range));
556 self.state.has_pass_label = true;
557 }
558
559 let rendering_to_external_framebuffer = desc
560 .color_attachments
561 .iter()
562 .filter_map(|at| at.as_ref())
563 .any(|at| match at.target.view.inner {
564 #[cfg(webgl)]
565 super::TextureInner::ExternalFramebuffer { .. } => true,
566 #[cfg(native)]
567 super::TextureInner::ExternalNativeFramebuffer { .. } => true,
568 _ => false,
569 });
570
571 if rendering_to_external_framebuffer && desc.color_attachments.len() != 1 {
572 panic!("Multiple render attachments with external framebuffers are not supported.");
573 }
574
575 assert!(desc.color_attachments.len() <= 32);
577
578 match desc
579 .color_attachments
580 .first()
581 .filter(|at| at.is_some())
582 .and_then(|at| at.as_ref().map(|at| &at.target.view.inner))
583 {
584 Some(&super::TextureInner::DefaultRenderbuffer) => {
587 self.cmd_buffer
588 .commands
589 .push(C::ResetFramebuffer { is_default: true });
590 if let Some(ref dsat) = desc.depth_stencil_attachment {
591 if dsat.depth_ops.contains(crate::AttachmentOps::STORE_DISCARD) {
592 self.state.invalidate_attachments.push(glow::DEPTH);
593 }
594 if dsat.stencil_ops.contains(crate::AttachmentOps::STORE_DISCARD) {
595 self.state.invalidate_attachments.push(glow::STENCIL);
596 }
597 }
598 }
599 _ => {
600 self.cmd_buffer
602 .commands
603 .push(C::ResetFramebuffer { is_default: false });
604
605 for (i, cat) in desc.color_attachments.iter().enumerate() {
606 if let Some(cat) = cat.as_ref() {
607 let attachment = glow::COLOR_ATTACHMENT0 + i as u32;
608 if let Some(ref rat) = cat.resolve_target {
610 if matches!(rat.view.inner, super::TextureInner::Texture { .. })
611 && self.private_caps.contains(
612 super::PrivateCapabilities::MULTISAMPLED_RENDER_TO_TEXTURE,
613 )
614 && !cat.ops.contains(crate::AttachmentOps::STORE)
615 && i == 0
617 {
618 self.cmd_buffer.commands.push(C::BindAttachment(Box::new(
619 super::AttachmentBinding {
620 attachment,
621 view: rat.view.clone(),
622 depth_slice: None,
623 sample_count: desc.sample_count,
624 },
625 )));
626 continue;
627 }
628 }
629 self.cmd_buffer.commands.push(C::BindAttachment(Box::new(
630 super::AttachmentBinding {
631 attachment,
632 view: cat.target.view.clone(),
633 depth_slice: cat.depth_slice,
634 sample_count: 1,
635 },
636 )));
637 if let Some(ref rat) = cat.resolve_target {
638 self.state
639 .resolve_attachments
640 .push((attachment, rat.view.clone()));
641 }
642 if cat.ops.contains(crate::AttachmentOps::STORE_DISCARD) {
643 self.state.invalidate_attachments.push(attachment);
644 }
645 }
646 }
647 if let Some(ref dsat) = desc.depth_stencil_attachment {
648 let aspects = dsat.target.view.aspects;
649 let attachment = match aspects {
650 crate::FormatAspects::DEPTH => glow::DEPTH_ATTACHMENT,
651 crate::FormatAspects::STENCIL => glow::STENCIL_ATTACHMENT,
652 _ => glow::DEPTH_STENCIL_ATTACHMENT,
653 };
654 self.cmd_buffer.commands.push(C::BindAttachment(Box::new(
655 super::AttachmentBinding {
656 attachment,
657 view: dsat.target.view.clone(),
658 depth_slice: None,
659 sample_count: 1,
660 },
661 )));
662 if aspects.contains(crate::FormatAspects::DEPTH)
663 && dsat.depth_ops.contains(crate::AttachmentOps::STORE_DISCARD)
664 {
665 self.state
666 .invalidate_attachments
667 .push(glow::DEPTH_ATTACHMENT);
668 }
669 if aspects.contains(crate::FormatAspects::STENCIL)
670 && dsat
671 .stencil_ops
672 .contains(crate::AttachmentOps::STORE_DISCARD)
673 {
674 self.state
675 .invalidate_attachments
676 .push(glow::STENCIL_ATTACHMENT);
677 }
678 }
679 }
680 }
681
682 let rect = crate::Rect {
683 x: 0,
684 y: 0,
685 w: desc.extent.width as i32,
686 h: desc.extent.height as i32,
687 };
688 self.cmd_buffer.commands.push(C::SetScissor(rect.clone()));
689 self.cmd_buffer.commands.push(C::SetViewport {
690 rect,
691 depth: 0.0..1.0,
692 });
693
694 let rendering_to_default_framebuffer = matches!(
697 desc.color_attachments
698 .first()
699 .and_then(|at| at.as_ref())
700 .map(|at| &at.target.view.inner),
701 Some(super::TextureInner::DefaultRenderbuffer)
702 );
703 if !rendering_to_external_framebuffer && !rendering_to_default_framebuffer {
704 self.cmd_buffer
706 .commands
707 .push(C::SetDrawColorBuffers(desc.color_attachments.len() as u8));
708 }
709
710 for (i, cat) in desc
712 .color_attachments
713 .iter()
714 .filter_map(|at| at.as_ref())
715 .enumerate()
716 {
717 if cat.ops.contains(crate::AttachmentOps::LOAD_CLEAR) {
718 let c = &cat.clear_value;
719 self.cmd_buffer.commands.push(
720 match cat.target.view.format.sample_type(None, None).unwrap() {
721 wgt::TextureSampleType::Float { .. } => C::ClearColorF {
722 draw_buffer: i as u32,
723 color: [c.r as f32, c.g as f32, c.b as f32, c.a as f32],
724 is_srgb: cat.target.view.format.is_srgb(),
725 },
726 wgt::TextureSampleType::Uint => C::ClearColorU(
727 i as u32,
728 [c.r as u32, c.g as u32, c.b as u32, c.a as u32],
729 ),
730 wgt::TextureSampleType::Sint => C::ClearColorI(
731 i as u32,
732 [c.r as i32, c.g as i32, c.b as i32, c.a as i32],
733 ),
734 wgt::TextureSampleType::Depth => unreachable!(),
735 },
736 );
737 }
738 }
739
740 if let Some(ref dsat) = desc.depth_stencil_attachment {
741 let clear_depth = dsat.depth_ops.contains(crate::AttachmentOps::LOAD_CLEAR);
742 let clear_stencil = dsat.stencil_ops.contains(crate::AttachmentOps::LOAD_CLEAR);
743
744 if clear_depth && clear_stencil {
745 self.cmd_buffer.commands.push(C::ClearDepthAndStencil(
746 dsat.clear_value.0,
747 dsat.clear_value.1,
748 ));
749 } else if clear_depth {
750 self.cmd_buffer
751 .commands
752 .push(C::ClearDepth(dsat.clear_value.0));
753 } else if clear_stencil {
754 self.cmd_buffer
755 .commands
756 .push(C::ClearStencil(dsat.clear_value.1));
757 }
758 }
759 Ok(())
760 }
761 unsafe fn end_render_pass(&mut self) {
762 for (attachment, dst) in self.state.resolve_attachments.drain(..) {
763 self.cmd_buffer.commands.push(C::ResolveAttachment(Box::new(
764 super::AttachmentResolve {
765 attachment,
766 dst,
767 size: self.state.render_size,
768 },
769 )));
770 }
771 if !self.state.invalidate_attachments.is_empty() {
772 self.cmd_buffer.commands.push(C::InvalidateAttachments(
773 self.state.invalidate_attachments.clone(),
774 ));
775 self.state.invalidate_attachments.clear();
776 }
777 if self.state.has_pass_label {
778 self.cmd_buffer.commands.push(C::PopDebugGroup);
779 self.state.has_pass_label = false;
780 }
781 self.state.instance_vbuf_mask = 0;
782 self.state.dirty_vbuf_mask = 0;
783 self.state.active_first_instance = 0;
784 self.state.color_targets.clear();
785 for vat in &self.state.vertex_attributes {
786 self.cmd_buffer
787 .commands
788 .push(C::UnsetVertexAttribute(vat.location));
789 }
790 self.state.vertex_attributes.clear();
791 self.state.primitive = super::PrimitiveState::default();
792
793 if let Some(query) = self.state.end_of_pass_timestamp.take() {
794 self.cmd_buffer.commands.push(C::TimestampQuery(query));
795 }
796 }
797
798 unsafe fn set_bind_group(
799 &mut self,
800 layout: &super::PipelineLayout,
801 index: u32,
802 group: &super::BindGroup,
803 dynamic_offsets: &[wgt::DynamicOffset],
804 ) {
805 let mut do_index = 0;
806 let mut dirty_textures = 0u32;
807 let mut dirty_samplers = 0u32;
808 let group_info = layout.group_infos[index as usize].as_ref().unwrap();
809
810 for (binding_layout, raw_binding) in group_info.entries.iter().zip(group.contents.iter()) {
811 let slot = group_info.binding_to_slot[binding_layout.binding as usize] as u32;
812 match *raw_binding {
813 super::RawBinding::Buffer {
814 raw,
815 offset: base_offset,
816 size,
817 } => {
818 let mut offset = base_offset;
819 let target = match binding_layout.ty {
820 wgt::BindingType::Buffer {
821 ty,
822 has_dynamic_offset,
823 min_binding_size: _,
824 } => {
825 if has_dynamic_offset {
826 offset += dynamic_offsets[do_index] as i32;
827 do_index += 1;
828 }
829 match ty {
830 wgt::BufferBindingType::Uniform => glow::UNIFORM_BUFFER,
831 wgt::BufferBindingType::Storage { .. } => {
832 glow::SHADER_STORAGE_BUFFER
833 }
834 }
835 }
836 _ => unreachable!(),
837 };
838 self.cmd_buffer.commands.push(C::BindBuffer {
839 target,
840 slot,
841 buffer: raw,
842 offset,
843 size,
844 });
845 }
846 super::RawBinding::Sampler(sampler) => {
847 dirty_samplers |= 1 << slot;
848 self.state.samplers[slot as usize] = Some(sampler);
849 }
850 super::RawBinding::Texture {
851 raw,
852 target,
853 aspects,
854 ref mip_levels,
855 } => {
856 dirty_textures |= 1 << slot;
857 self.state.texture_slots[slot as usize].tex_target = target;
858 self.cmd_buffer.commands.push(C::BindTexture {
859 slot,
860 texture: raw,
861 target,
862 aspects,
863 mip_levels: mip_levels.clone(),
864 });
865 }
866 super::RawBinding::Image(ref binding) => {
867 self.cmd_buffer.commands.push(C::BindImage {
868 slot,
869 binding: binding.clone(),
870 });
871 }
872 }
873 }
874
875 self.rebind_sampler_states(dirty_textures, dirty_samplers);
876 }
877
878 unsafe fn set_immediates(
879 &mut self,
880 _layout: &super::PipelineLayout,
881 offset_bytes: u32,
882 data: &[u32],
883 ) {
884 let start_words = offset_bytes / 4;
892 let end_words = start_words + data.len() as u32;
893 self.state.current_immediates_data[start_words as usize..end_words as usize]
894 .copy_from_slice(data);
895
896 let data = self
899 .cmd_buffer
900 .add_immediates_data(&self.state.current_immediates_data);
901 self.cmd_buffer.commands.push(C::SetImmediates { data });
902 }
903
904 unsafe fn insert_debug_marker(&mut self, label: &str) {
905 let range = self.cmd_buffer.add_marker(label);
906 self.cmd_buffer.commands.push(C::InsertDebugMarker(range));
907 }
908 unsafe fn begin_debug_marker(&mut self, group_label: &str) {
909 let range = self.cmd_buffer.add_marker(group_label);
910 self.cmd_buffer.commands.push(C::PushDebugGroup(range));
911 }
912 unsafe fn end_debug_marker(&mut self) {
913 self.cmd_buffer.commands.push(C::PopDebugGroup);
914 }
915
916 unsafe fn set_render_pipeline(&mut self, pipeline: &super::RenderPipeline) {
917 self.state.topology = conv::map_primitive_topology(pipeline.primitive.topology);
918
919 if self
920 .private_caps
921 .contains(super::PrivateCapabilities::VERTEX_BUFFER_LAYOUT)
922 {
923 for vat in pipeline.vertex_attributes.iter() {
924 let vb = pipeline.vertex_buffers[vat.buffer_index as usize]
925 .as_ref()
926 .unwrap();
927 self.cmd_buffer.commands.push(C::SetVertexAttribute {
929 buffer: None,
930 buffer_desc: vb.clone(),
931 attribute_desc: vat.clone(),
932 });
933 }
934 } else {
935 for vat in &self.state.vertex_attributes {
936 self.cmd_buffer
937 .commands
938 .push(C::UnsetVertexAttribute(vat.location));
939 }
940 self.state.vertex_attributes.clear();
941
942 self.state.dirty_vbuf_mask = 0;
943 for vat in pipeline.vertex_attributes.iter() {
945 self.state.dirty_vbuf_mask |= 1 << vat.buffer_index;
947 self.state.vertex_attributes.push(vat.clone());
948 }
949 }
950
951 self.state.instance_vbuf_mask = 0;
952 for (index, (&mut (ref mut state_desc, _), pipe_desc)) in self
954 .state
955 .vertex_buffers
956 .iter_mut()
957 .zip(pipeline.vertex_buffers.iter())
958 .enumerate()
959 {
960 let Some(pipe_desc) = pipe_desc else {
961 continue;
962 };
963 if pipe_desc.step == wgt::VertexStepMode::Instance {
964 self.state.instance_vbuf_mask |= 1 << index;
965 }
966 if state_desc.as_ref() != Some(pipe_desc) {
967 self.state.dirty_vbuf_mask |= 1 << index;
968 *state_desc = Some(pipe_desc.clone());
969 }
970 }
971
972 self.set_pipeline_inner(&pipeline.inner);
973
974 let prim_state = conv::map_primitive_state(&pipeline.primitive);
976 if prim_state != self.state.primitive {
977 self.cmd_buffer
978 .commands
979 .push(C::SetPrimitive(prim_state.clone()));
980 self.state.primitive = prim_state;
981 }
982
983 let mut aspects = crate::FormatAspects::empty();
985 if pipeline.depth_bias != self.state.depth_bias {
986 self.state.depth_bias = pipeline.depth_bias;
987 self.cmd_buffer
988 .commands
989 .push(C::SetDepthBias(pipeline.depth_bias));
990 }
991 if let Some(ref depth) = pipeline.depth {
992 aspects |= crate::FormatAspects::DEPTH;
993 self.cmd_buffer.commands.push(C::SetDepth(depth.clone()));
994 }
995 if let Some(ref stencil) = pipeline.stencil {
996 aspects |= crate::FormatAspects::STENCIL;
997 self.state.stencil = stencil.clone();
998 self.rebind_stencil_func();
999 if stencil.front.ops == stencil.back.ops
1000 && stencil.front.mask_write == stencil.back.mask_write
1001 {
1002 self.cmd_buffer.commands.push(C::SetStencilOps {
1003 face: glow::FRONT_AND_BACK,
1004 write_mask: stencil.front.mask_write,
1005 ops: stencil.front.ops.clone(),
1006 });
1007 } else {
1008 self.cmd_buffer.commands.push(C::SetStencilOps {
1009 face: glow::FRONT,
1010 write_mask: stencil.front.mask_write,
1011 ops: stencil.front.ops.clone(),
1012 });
1013 self.cmd_buffer.commands.push(C::SetStencilOps {
1014 face: glow::BACK,
1015 write_mask: stencil.back.mask_write,
1016 ops: stencil.back.ops.clone(),
1017 });
1018 }
1019 }
1020 self.cmd_buffer
1021 .commands
1022 .push(C::ConfigureDepthStencil(aspects));
1023
1024 if pipeline.alpha_to_coverage_enabled != self.state.alpha_to_coverage_enabled {
1026 self.state.alpha_to_coverage_enabled = pipeline.alpha_to_coverage_enabled;
1027 self.cmd_buffer
1028 .commands
1029 .push(C::SetAlphaToCoverage(pipeline.alpha_to_coverage_enabled));
1030 }
1031
1032 if self.state.color_targets[..] != pipeline.color_targets[..] {
1034 if pipeline
1035 .color_targets
1036 .iter()
1037 .skip(1)
1038 .any(|ct| *ct != pipeline.color_targets[0])
1039 {
1040 for (index, ct) in pipeline.color_targets.iter().enumerate() {
1041 self.cmd_buffer.commands.push(C::SetColorTarget {
1042 draw_buffer_index: Some(index as u32),
1043 desc: ct.clone(),
1044 });
1045 }
1046 } else {
1047 self.cmd_buffer.commands.push(C::SetColorTarget {
1048 draw_buffer_index: None,
1049 desc: pipeline.color_targets.first().cloned().unwrap_or_default(),
1050 });
1051 }
1052 }
1053 self.state.color_targets.clear();
1054 for ct in pipeline.color_targets.iter() {
1055 self.state.color_targets.push(ct.clone());
1056 }
1057
1058 if pipeline.inner.clip_distance_count != self.state.clip_distance_count {
1060 self.cmd_buffer.commands.push(C::SetClipDistances {
1061 old_count: self.state.clip_distance_count,
1062 new_count: pipeline.inner.clip_distance_count,
1063 });
1064 self.state.clip_distance_count = pipeline.inner.clip_distance_count;
1065 }
1066 }
1067
1068 unsafe fn set_index_buffer<'a>(
1069 &mut self,
1070 binding: crate::BufferBinding<'a, super::Buffer>,
1071 format: wgt::IndexFormat,
1072 ) {
1073 self.state.index_offset = binding.offset;
1074 self.state.index_format = format;
1075 self.cmd_buffer
1076 .commands
1077 .push(C::SetIndexBuffer(binding.buffer.raw.unwrap()));
1078 }
1079 unsafe fn set_vertex_buffer<'a>(
1080 &mut self,
1081 index: u32,
1082 binding: crate::BufferBinding<'a, super::Buffer>,
1083 ) {
1084 self.state.dirty_vbuf_mask |= 1 << index;
1085 let (_, ref mut vb) = self.state.vertex_buffers[index as usize];
1086 *vb = Some(super::BufferBinding {
1087 raw: binding.buffer.raw.unwrap(),
1088 offset: binding.offset,
1089 });
1090 }
1091 unsafe fn set_viewport(&mut self, rect: &crate::Rect<f32>, depth: Range<f32>) {
1092 self.cmd_buffer.commands.push(C::SetViewport {
1093 rect: crate::Rect {
1094 x: rect.x as i32,
1095 y: rect.y as i32,
1096 w: rect.w as i32,
1097 h: rect.h as i32,
1098 },
1099 depth,
1100 });
1101 }
1102 unsafe fn set_scissor_rect(&mut self, rect: &crate::Rect<u32>) {
1103 self.cmd_buffer.commands.push(C::SetScissor(crate::Rect {
1104 x: rect.x as i32,
1105 y: rect.y as i32,
1106 w: rect.w as i32,
1107 h: rect.h as i32,
1108 }));
1109 }
1110 unsafe fn set_stencil_reference(&mut self, value: u32) {
1111 self.state.stencil.front.reference = value;
1112 self.state.stencil.back.reference = value;
1113 self.rebind_stencil_func();
1114 }
1115 unsafe fn set_blend_constants(&mut self, color: &[f32; 4]) {
1116 self.cmd_buffer.commands.push(C::SetBlendConstant(*color));
1117 }
1118
1119 unsafe fn draw(
1120 &mut self,
1121 first_vertex: u32,
1122 vertex_count: u32,
1123 first_instance: u32,
1124 instance_count: u32,
1125 ) {
1126 self.prepare_draw(first_instance);
1127 self.cmd_buffer.commands.push(C::Draw {
1128 topology: self.state.topology,
1129 first_vertex,
1130 vertex_count,
1131 first_instance,
1132 instance_count,
1133 });
1134 }
1135 unsafe fn draw_indexed(
1136 &mut self,
1137 first_index: u32,
1138 index_count: u32,
1139 base_vertex: i32,
1140 first_instance: u32,
1141 instance_count: u32,
1142 ) {
1143 self.prepare_draw(first_instance);
1144 let (index_size, index_type) = match self.state.index_format {
1145 wgt::IndexFormat::Uint16 => (2, glow::UNSIGNED_SHORT),
1146 wgt::IndexFormat::Uint32 => (4, glow::UNSIGNED_INT),
1147 };
1148 let index_offset = self.state.index_offset + index_size * first_index as wgt::BufferAddress;
1149 self.cmd_buffer.commands.push(C::DrawIndexed {
1150 topology: self.state.topology,
1151 index_type,
1152 index_offset,
1153 index_count,
1154 base_vertex,
1155 first_instance,
1156 instance_count,
1157 });
1158 }
1159 unsafe fn draw_mesh_tasks(
1160 &mut self,
1161 _group_count_x: u32,
1162 _group_count_y: u32,
1163 _group_count_z: u32,
1164 ) {
1165 unreachable!()
1166 }
1167 unsafe fn draw_indirect(
1168 &mut self,
1169 buffer: &super::Buffer,
1170 offset: wgt::BufferAddress,
1171 draw_count: u32,
1172 ) {
1173 self.prepare_draw(0);
1174 for draw in 0..draw_count as wgt::BufferAddress {
1175 let indirect_offset =
1176 offset + draw * size_of::<wgt::DrawIndirectArgs>() as wgt::BufferAddress;
1177 self.cmd_buffer.commands.push(C::DrawIndirect {
1178 topology: self.state.topology,
1179 indirect_buf: buffer.raw.unwrap(),
1180 indirect_offset,
1181 });
1182 }
1183 }
1184 unsafe fn draw_indexed_indirect(
1185 &mut self,
1186 buffer: &super::Buffer,
1187 offset: wgt::BufferAddress,
1188 draw_count: u32,
1189 ) {
1190 self.prepare_draw(0);
1191 let index_type = match self.state.index_format {
1192 wgt::IndexFormat::Uint16 => glow::UNSIGNED_SHORT,
1193 wgt::IndexFormat::Uint32 => glow::UNSIGNED_INT,
1194 };
1195 for draw in 0..draw_count as wgt::BufferAddress {
1196 let indirect_offset =
1197 offset + draw * size_of::<wgt::DrawIndexedIndirectArgs>() as wgt::BufferAddress;
1198 self.cmd_buffer.commands.push(C::DrawIndexedIndirect {
1199 topology: self.state.topology,
1200 index_type,
1201 indirect_buf: buffer.raw.unwrap(),
1202 indirect_offset,
1203 });
1204 }
1205 }
1206 unsafe fn draw_mesh_tasks_indirect(
1207 &mut self,
1208 _buffer: &<Self::A as crate::Api>::Buffer,
1209 _offset: wgt::BufferAddress,
1210 _draw_count: u32,
1211 ) {
1212 unreachable!()
1213 }
1214 unsafe fn draw_indirect_count(
1215 &mut self,
1216 _buffer: &super::Buffer,
1217 _offset: wgt::BufferAddress,
1218 _count_buffer: &super::Buffer,
1219 _count_offset: wgt::BufferAddress,
1220 _max_count: u32,
1221 ) {
1222 unreachable!()
1223 }
1224 unsafe fn draw_indexed_indirect_count(
1225 &mut self,
1226 _buffer: &super::Buffer,
1227 _offset: wgt::BufferAddress,
1228 _count_buffer: &super::Buffer,
1229 _count_offset: wgt::BufferAddress,
1230 _max_count: u32,
1231 ) {
1232 unreachable!()
1233 }
1234 unsafe fn draw_mesh_tasks_indirect_count(
1235 &mut self,
1236 _buffer: &<Self::A as crate::Api>::Buffer,
1237 _offset: wgt::BufferAddress,
1238 _count_buffer: &<Self::A as crate::Api>::Buffer,
1239 _count_offset: wgt::BufferAddress,
1240 _max_count: u32,
1241 ) {
1242 unreachable!()
1243 }
1244
1245 unsafe fn begin_compute_pass(&mut self, desc: &crate::ComputePassDescriptor<super::QuerySet>) {
1248 debug_assert!(self.state.end_of_pass_timestamp.is_none());
1249 if let Some(ref t) = desc.timestamp_writes {
1250 if let Some(index) = t.beginning_of_pass_write_index {
1251 unsafe { self.write_timestamp(t.query_set, index) }
1252 }
1253 self.state.end_of_pass_timestamp = t
1254 .end_of_pass_write_index
1255 .map(|index| t.query_set.queries[index as usize]);
1256 }
1257
1258 if let Some(label) = desc.label {
1259 let range = self.cmd_buffer.add_marker(label);
1260 self.cmd_buffer.commands.push(C::PushDebugGroup(range));
1261 self.state.has_pass_label = true;
1262 }
1263 }
1264 unsafe fn end_compute_pass(&mut self) {
1265 if self.state.has_pass_label {
1266 self.cmd_buffer.commands.push(C::PopDebugGroup);
1267 self.state.has_pass_label = false;
1268 }
1269
1270 if let Some(query) = self.state.end_of_pass_timestamp.take() {
1271 self.cmd_buffer.commands.push(C::TimestampQuery(query));
1272 }
1273 }
1274
1275 unsafe fn set_compute_pipeline(&mut self, pipeline: &super::ComputePipeline) {
1276 self.set_pipeline_inner(&pipeline.inner);
1277 }
1278
1279 unsafe fn dispatch_workgroups(&mut self, count: [u32; 3]) {
1280 if count.contains(&0) {
1282 return;
1283 }
1284 self.cmd_buffer.commands.push(C::Dispatch(count));
1285 }
1286 unsafe fn dispatch_workgroups_indirect(
1287 &mut self,
1288 buffer: &super::Buffer,
1289 offset: wgt::BufferAddress,
1290 ) {
1291 self.cmd_buffer.commands.push(C::DispatchIndirect {
1292 indirect_buf: buffer.raw.unwrap(),
1293 indirect_offset: offset,
1294 });
1295 }
1296
1297 unsafe fn build_acceleration_structures<'a, T>(
1298 &mut self,
1299 _descriptor_count: u32,
1300 _descriptors: T,
1301 ) where
1302 super::Api: 'a,
1303 T: IntoIterator<
1304 Item = crate::BuildAccelerationStructureDescriptor<
1305 'a,
1306 super::Buffer,
1307 super::AccelerationStructure,
1308 >,
1309 >,
1310 {
1311 unimplemented!()
1312 }
1313
1314 unsafe fn place_acceleration_structure_barrier(
1315 &mut self,
1316 _barriers: crate::AccelerationStructureBarrier,
1317 ) {
1318 unimplemented!()
1319 }
1320
1321 unsafe fn copy_acceleration_structure_to_acceleration_structure(
1322 &mut self,
1323 _src: &super::AccelerationStructure,
1324 _dst: &super::AccelerationStructure,
1325 _copy: wgt::AccelerationStructureCopy,
1326 ) {
1327 unimplemented!()
1328 }
1329
1330 unsafe fn read_acceleration_structure_compact_size(
1331 &mut self,
1332 _acceleration_structure: &super::AccelerationStructure,
1333 _buf: &super::Buffer,
1334 ) {
1335 unimplemented!()
1336 }
1337
1338 unsafe fn set_acceleration_structure_dependencies(
1339 _command_buffers: &[&super::CommandBuffer],
1340 _dependencies: &[&super::AccelerationStructure],
1341 ) {
1342 unimplemented!()
1343 }
1344
1345 unsafe fn begin_ray_tracing_pass(&mut self, _desc: &crate::RayTracingPassDescriptor) {
1346 unimplemented!()
1347 }
1348
1349 unsafe fn end_ray_tracing_pass(&mut self) {
1350 unimplemented!()
1351 }
1352
1353 unsafe fn set_ray_tracing_pipeline(
1354 &mut self,
1355 _pipeline: &<Self::A as crate::Api>::RayTracingPipeline,
1356 ) {
1357 unimplemented!()
1358 }
1359
1360 unsafe fn trace_rays(
1361 &mut self,
1362 _count: [u32; 3],
1363 _ray_generation_group_data: crate::PipelineGroupData<super::Buffer>,
1364 _miss_group_data: crate::PipelineGroupData<super::Buffer>,
1365 _intersection_group_data: crate::PipelineGroupData<super::Buffer>,
1366 ) {
1367 unimplemented!()
1368 }
1369}