1#[cfg(not(any(windows, webgl)))]
84mod egl;
85#[cfg(Emscripten)]
86mod emscripten;
87#[cfg(webgl)]
88mod web;
89#[cfg(windows)]
90mod wgl;
91
92mod adapter;
93mod command;
94mod conv;
95mod device;
96mod fence;
97mod gl_state;
98mod queue;
99
100pub use fence::Fence;
101
102#[cfg(not(any(windows, webgl)))]
103pub use self::egl::{AdapterContext, AdapterContextLock};
104#[cfg(not(any(windows, webgl)))]
105pub use self::egl::{Instance, Surface};
106
107#[cfg(webgl)]
108pub use self::web::AdapterContext;
109#[cfg(webgl)]
110pub use self::web::{Instance, Surface, ask_only_for_used_extensions};
111
112#[cfg(windows)]
113use self::wgl::AdapterContext;
114#[cfg(windows)]
115pub use self::wgl::{Instance, Surface};
116
117use alloc::{boxed::Box, string::String, string::ToString as _, sync::Arc, vec::Vec};
118use core::{
119 fmt,
120 ops::Range,
121 sync::atomic::{AtomicU32, AtomicU8, AtomicUsize},
122};
123use parking_lot::Mutex;
124
125use arrayvec::ArrayVec;
126use glow::HasContext;
127use naga::FastHashMap;
128
129use crate::{CopyExtent, TextureDescriptor};
130
131#[derive(Clone, Debug)]
132pub struct Api;
133
134const MAX_TEXTURE_SLOTS: usize = 16;
137const MAX_SAMPLERS: usize = 16;
138const MAX_VERTEX_ATTRIBUTES: usize = 16;
139const ZERO_BUFFER_SIZE: usize = 256 << 10;
140const MAX_IMMEDIATES: usize = 64;
141const MAX_IMMEDIATES_COMMANDS: usize = MAX_IMMEDIATES * crate::MAX_CONCURRENT_SHADER_STAGES;
143
144impl crate::Api for Api {
145 const VARIANT: wgt::Backend = wgt::Backend::Gl;
146
147 type Instance = Instance;
148 type Surface = Surface;
149 type Adapter = Adapter;
150 type Device = Device;
151
152 type Queue = Queue;
153 type CommandEncoder = CommandEncoder;
154 type CommandBuffer = CommandBuffer;
155
156 type Buffer = Buffer;
157 type Texture = Texture;
158 type SurfaceTexture = Texture;
159 type TextureView = TextureView;
160 type Sampler = Sampler;
161 type QuerySet = QuerySet;
162 type Fence = Fence;
163 type AccelerationStructure = AccelerationStructure;
164 type PipelineCache = PipelineCache;
165
166 type BindGroupLayout = BindGroupLayout;
167 type BindGroup = BindGroup;
168 type PipelineLayout = PipelineLayout;
169 type ShaderModule = ShaderModule;
170 type RenderPipeline = RenderPipeline;
171 type ComputePipeline = ComputePipeline;
172 type RayTracingPipeline = RayTracingPipeline;
173}
174
175crate::impl_dyn_resource!(
176 Adapter,
177 AccelerationStructure,
178 BindGroup,
179 BindGroupLayout,
180 Buffer,
181 CommandBuffer,
182 CommandEncoder,
183 ComputePipeline,
184 Device,
185 Fence,
186 Instance,
187 PipelineCache,
188 PipelineLayout,
189 QuerySet,
190 Queue,
191 RenderPipeline,
192 RayTracingPipeline,
193 Sampler,
194 ShaderModule,
195 Surface,
196 Texture,
197 TextureView
198);
199
200bitflags::bitflags! {
201 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
204 struct PrivateCapabilities: u32 {
205 const BUFFER_ALLOCATION = 1 << 0;
207 const SHADER_BINDING_LAYOUT = 1 << 1;
209 const SHADER_TEXTURE_SHADOW_LOD = 1 << 2;
211 const MEMORY_BARRIERS = 1 << 3;
213 const VERTEX_BUFFER_LAYOUT = 1 << 4;
215 const INDEX_BUFFER_ROLE_CHANGE = 1 << 5;
218 const GET_BUFFER_SUB_DATA = 1 << 7;
220 const COLOR_BUFFER_HALF_FLOAT = 1 << 8;
222 const COLOR_BUFFER_FLOAT = 1 << 9;
224 const QUERY_BUFFERS = 1 << 11;
226 const QUERY_64BIT = 1 << 12;
228 const TEXTURE_STORAGE = 1 << 13;
230 const DEBUG_FNS = 1 << 14;
232 const INVALIDATE_FRAMEBUFFER = 1 << 15;
234 const FULLY_FEATURED_INSTANCING = 1 << 16;
238 const MULTISAMPLED_RENDER_TO_TEXTURE = 1 << 17;
240 const TEXTURE_FORMAT_NORM16 = 1 << 18;
244 const TEXTURE_FORMAT_SNORM16_RENDERABLE = 1 << 19;
248 const TEXTURE_FORMAT_NORM16_STORAGE = 1 << 20;
253 }
254}
255
256bitflags::bitflags! {
257 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
259 struct Workarounds: u32 {
260 const MESA_I915_SRGB_SHADER_CLEAR = 1 << 0;
267 const EMULATE_BUFFER_MAP = 1 << 1;
269 }
270}
271
272type BindTarget = u32;
273
274#[derive(Debug, Default, Clone, Copy)]
275enum VertexAttribKind {
276 #[default]
277 Float, Integer, }
281
282#[derive(Clone, Debug)]
283pub struct TextureFormatDesc {
284 pub internal: u32,
285 pub external: u32,
286 pub data_type: u32,
287}
288
289struct AdapterShared {
290 context: AdapterContext,
291 private_caps: PrivateCapabilities,
292 features: wgt::Features,
293 limits: wgt::Limits,
294 workarounds: Workarounds,
295 options: wgt::GlBackendOptions,
296 shading_language_version: naga::back::glsl::Version,
297 next_shader_id: AtomicU32,
298 program_cache: Mutex<ProgramCache>,
299 unread_links: AtomicUsize,
302 es: bool,
303
304 max_msaa_samples: i32,
308}
309
310impl fmt::Debug for AdapterShared {
311 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312 let Self {
313 context: _, private_caps,
315 features,
316 limits,
317 workarounds,
318 options,
319 shading_language_version,
320 next_shader_id,
321 program_cache: _,
322 unread_links,
323 es,
324 max_msaa_samples,
325 } = self;
326 f.debug_struct("AdapterShared")
327 .field("private_caps", private_caps)
328 .field("features", features)
329 .field("limits", limits)
330 .field("workarounds", workarounds)
331 .field("options", options)
332 .field("shading_language_version", shading_language_version)
333 .field("next_shader_id", next_shader_id)
334 .field("unread_links", unread_links)
335 .field("es", es)
336 .field("max_msaa_samples", max_msaa_samples)
337 .finish_non_exhaustive()
338 }
339}
340
341#[derive(Debug)]
342pub struct Adapter {
343 shared: Arc<AdapterShared>,
344}
345
346#[derive(Debug)]
347pub struct Device {
348 shared: Arc<AdapterShared>,
349 main_vao: glow::VertexArray,
350 #[cfg(all(native, feature = "renderdoc"))]
351 render_doc: crate::auxil::renderdoc::RenderDoc,
352 counters: Arc<wgt::HalCounters>,
353}
354
355impl Drop for Device {
356 fn drop(&mut self) {
357 let gl = &self.shared.context.lock();
358 unsafe { gl.delete_vertex_array(self.main_vao) };
359 }
360}
361
362#[derive(Debug)]
363pub struct ShaderClearProgram {
364 pub program: glow::Program,
365 pub color_uniform_location: glow::UniformLocation,
366}
367
368#[derive(Debug)]
369pub struct Queue {
370 shared: Arc<AdapterShared>,
371 features: wgt::Features,
372 draw_fbo: glow::Framebuffer,
373 copy_fbo: glow::Framebuffer,
374 shader_clear_program: Option<ShaderClearProgram>,
377 zero_buffer: glow::Buffer,
380 temp_query_results: Mutex<Vec<u64>>,
381 draw_buffer_count: AtomicU8,
382 current_index_buffer: Mutex<Option<glow::Buffer>>,
383 gl_state: Mutex<gl_state::GlState>,
386}
387
388impl Drop for Queue {
389 fn drop(&mut self) {
390 let gl = &self.shared.context.lock();
391 unsafe { gl.delete_framebuffer(self.draw_fbo) };
392 unsafe { gl.delete_framebuffer(self.copy_fbo) };
393 unsafe { gl.delete_buffer(self.zero_buffer) };
394 }
395}
396
397#[derive(Clone, Debug)]
398pub struct Buffer {
399 raw: Option<glow::Buffer>,
400 target: BindTarget,
401 size: wgt::BufferAddress,
402 map_flags: u32,
404 map_state: Arc<MaybeMutex<BufferMapState>>,
408 drop_guard: Option<Arc<crate::DropGuard>>,
414}
415
416#[derive(Clone, Debug)]
417struct BufferMapState {
418 mapped: bool,
421 data: Option<Vec<u8>>,
422 offset_of_current_mapping: wgt::BufferAddress,
423}
424
425#[cfg(send_sync)]
426static_assertions::assert_impl_all!(Buffer: Send, Sync);
427
428impl crate::DynBuffer for Buffer {}
429
430#[derive(Clone, Debug)]
431pub enum TextureInner {
432 Renderbuffer {
433 raw: glow::Renderbuffer,
434 },
435 DefaultRenderbuffer,
436 Texture {
437 raw: glow::Texture,
438 target: BindTarget,
439 },
440 #[cfg(webgl)]
441 ExternalFramebuffer {
445 inner: web_sys::WebGlFramebuffer,
446 },
447 #[cfg(native)]
448 ExternalNativeFramebuffer {
454 inner: glow::NativeFramebuffer,
455 },
456}
457
458#[cfg(send_sync)]
459unsafe impl Sync for TextureInner {}
460#[cfg(send_sync)]
461unsafe impl Send for TextureInner {}
462
463impl TextureInner {
464 fn as_native(&self) -> (glow::Texture, BindTarget) {
465 match *self {
466 Self::Renderbuffer { .. } | Self::DefaultRenderbuffer => {
467 panic!("Unexpected renderbuffer");
468 }
469 Self::Texture { raw, target } => (raw, target),
470 #[cfg(webgl)]
471 Self::ExternalFramebuffer { .. } => panic!("Unexpected external framebuffer"),
472 #[cfg(native)]
473 Self::ExternalNativeFramebuffer { .. } => panic!("unexpected external framebuffer"),
474 }
475 }
476}
477
478#[derive(Debug)]
479pub struct Texture {
480 pub inner: TextureInner,
481 pub mip_level_count: u32,
482 pub array_layer_count: u32,
483 pub format: wgt::TextureFormat,
484 pub format_desc: TextureFormatDesc,
485 pub copy_size: CopyExtent,
486
487 pub drop_guard: Option<crate::DropGuard>,
490}
491
492impl crate::DynTexture for Texture {}
493impl crate::DynSurfaceTexture for Texture {
494 fn image_id(&self) -> Option<u64> {
499 match self.inner {
500 TextureInner::DefaultRenderbuffer => None,
501 _ => Some(0),
502 }
503 }
504}
505
506impl core::borrow::Borrow<dyn crate::DynTexture> for Texture {
507 fn borrow(&self) -> &dyn crate::DynTexture {
508 self
509 }
510}
511
512impl Texture {
513 pub fn default_framebuffer(format: wgt::TextureFormat) -> Self {
514 Self {
515 inner: TextureInner::DefaultRenderbuffer,
516 drop_guard: None,
517 mip_level_count: 1,
518 array_layer_count: 1,
519 format,
520 format_desc: TextureFormatDesc {
521 internal: 0,
522 external: 0,
523 data_type: 0,
524 },
525 copy_size: CopyExtent {
526 width: 0,
527 height: 0,
528 depth: 0,
529 },
530 }
531 }
532
533 fn get_info_from_desc(desc: &TextureDescriptor) -> u32 {
535 match desc.dimension {
536 wgt::TextureDimension::D1 => glow::TEXTURE_2D,
539 wgt::TextureDimension::D2 => {
540 match (desc.is_cube_compatible(), desc.size.depth_or_array_layers) {
542 (false, 1) => glow::TEXTURE_2D,
543 (false, _) => glow::TEXTURE_2D_ARRAY,
544 (true, 6) => glow::TEXTURE_CUBE_MAP,
545 (true, _) => glow::TEXTURE_CUBE_MAP_ARRAY,
546 }
547 }
548 wgt::TextureDimension::D3 => glow::TEXTURE_3D,
549 }
550 }
551
552 fn log_failing_target_heuristics(view_dimension: wgt::TextureViewDimension, target: u32) {
554 let expected_target = match view_dimension {
555 wgt::TextureViewDimension::D1 => glow::TEXTURE_2D,
556 wgt::TextureViewDimension::D2 => glow::TEXTURE_2D,
557 wgt::TextureViewDimension::D2Array => glow::TEXTURE_2D_ARRAY,
558 wgt::TextureViewDimension::Cube => glow::TEXTURE_CUBE_MAP,
559 wgt::TextureViewDimension::CubeArray => glow::TEXTURE_CUBE_MAP_ARRAY,
560 wgt::TextureViewDimension::D3 => glow::TEXTURE_3D,
561 };
562
563 if expected_target == target {
564 return;
565 }
566
567 let buffer;
568 let got = match target {
569 glow::TEXTURE_2D => "D2",
570 glow::TEXTURE_2D_ARRAY => "D2Array",
571 glow::TEXTURE_CUBE_MAP => "Cube",
572 glow::TEXTURE_CUBE_MAP_ARRAY => "CubeArray",
573 glow::TEXTURE_3D => "D3",
574 target => {
575 buffer = target.to_string();
576 &buffer
577 }
578 };
579
580 log::error!(
581 concat!(
582 "wgpu-hal heuristics assumed that ",
583 "the view dimension will be equal to `{}` rather than `{:?}`.\n",
584 "`D2` textures with ",
585 "`depth_or_array_layers == 1` ",
586 "are assumed to have view dimension `D2`\n",
587 "`D2` textures with ",
588 "`depth_or_array_layers > 1` ",
589 "are assumed to have view dimension `D2Array`\n",
590 "`D2` textures with ",
591 "`depth_or_array_layers == 6` ",
592 "are assumed to have view dimension `Cube`\n",
593 "`D2` textures with ",
594 "`depth_or_array_layers > 6 && depth_or_array_layers % 6 == 0` ",
595 "are assumed to have view dimension `CubeArray`\n",
596 ),
597 got,
598 view_dimension,
599 );
600 }
601}
602
603#[derive(Clone, Debug)]
604pub struct TextureView {
605 inner: TextureInner,
606 aspects: crate::FormatAspects,
607 mip_levels: Range<u32>,
608 array_layers: Range<u32>,
609 format: wgt::TextureFormat,
610}
611
612impl crate::DynTextureView for TextureView {}
613
614#[derive(Debug)]
615pub struct Sampler {
616 raw: glow::Sampler,
617}
618
619impl crate::DynSampler for Sampler {}
620
621#[derive(Debug)]
622pub struct BindGroupLayout {
623 entries: Arc<[wgt::BindGroupLayoutEntry]>,
624}
625
626impl crate::DynBindGroupLayout for BindGroupLayout {}
627
628#[derive(Debug)]
629struct BindGroupLayoutInfo {
630 entries: Arc<[wgt::BindGroupLayoutEntry]>,
631 binding_to_slot: Box<[u8]>,
637}
638
639#[derive(Debug)]
640pub struct PipelineLayout {
641 group_infos: Box<[Option<BindGroupLayoutInfo>]>,
642 naga_options: naga::back::glsl::Options,
643}
644
645impl crate::DynPipelineLayout for PipelineLayout {}
646
647impl PipelineLayout {
648 fn get_slot(&self, br: &naga::ResourceBinding) -> u8 {
652 let group_info = self.group_infos[br.group as usize].as_ref().unwrap();
653 group_info.binding_to_slot[br.binding as usize]
654 }
655}
656
657#[derive(Debug)]
658enum BindingRegister {
659 UniformBuffers,
660 StorageBuffers,
661 Textures,
662 Images,
663}
664
665#[derive(Debug)]
666enum RawBinding {
667 Buffer {
668 raw: glow::Buffer,
669 offset: i32,
670 size: i32,
671 },
672 Texture {
673 raw: glow::Texture,
674 target: BindTarget,
675 aspects: crate::FormatAspects,
676 mip_levels: Range<u32>,
677 },
679 Image(ImageBinding),
680 Sampler(glow::Sampler),
681}
682
683#[derive(Debug)]
684pub struct BindGroup {
685 contents: Box<[RawBinding]>,
686}
687
688impl crate::DynBindGroup for BindGroup {}
689
690type ShaderId = u32;
691
692#[derive(Debug)]
693pub enum ShaderModuleSource {
694 Naga(crate::NagaShader),
695 Passthrough { source: String },
696 Templates(&'static [crate::GlslTemplate]),
697}
698
699#[derive(Debug)]
700pub struct ShaderModule {
701 source: ShaderModuleSource,
702 label: Option<String>,
703 id: ShaderId,
704}
705
706impl crate::DynShaderModule for ShaderModule {}
707
708#[derive(Clone, Debug, Default)]
709struct VertexFormatDesc {
710 element_count: i32,
711 element_format: u32,
712 attrib_kind: VertexAttribKind,
713}
714
715#[derive(Clone, Debug, Default)]
716struct AttributeDesc {
717 location: u32,
718 offset: u32,
719 buffer_index: u32,
720 format_desc: VertexFormatDesc,
721}
722
723#[derive(Clone, Debug)]
724struct BufferBinding {
725 raw: glow::Buffer,
726 offset: wgt::BufferAddress,
727}
728
729#[derive(Clone, Debug)]
730struct ImageBinding {
731 raw: glow::Texture,
732 mip_level: u32,
733 array_layer: Option<u32>,
734 access: u32,
735 format: u32,
736}
737
738#[derive(Clone, Debug, Default, PartialEq)]
739struct VertexBufferDesc {
740 step: wgt::VertexStepMode,
741 stride: u32,
742}
743
744#[derive(Clone, Debug)]
745struct ImmediateDesc {
746 location: glow::UniformLocation,
747 ty: nt::glsl::GlslUniformType,
748 offset: u32,
749}
750
751#[cfg(send_sync)]
752unsafe impl Sync for ImmediateDesc {}
753#[cfg(send_sync)]
754unsafe impl Send for ImmediateDesc {}
755
756type SamplerBindMap = [Option<u8>; MAX_TEXTURE_SLOTS];
759
760#[derive(Debug)]
761struct PipelineInner {
762 program: glow::Program,
763 sampler_map: SamplerBindMap,
764 clip_distance_count: u32,
765 link: Mutex<ProgramLink>,
768}
769
770#[derive(Debug)]
772struct ProgramLink {
773 pending: Option<Box<device::PendingLink>>,
774 linked: Option<Arc<LinkedProgram>>,
775}
776
777#[derive(Debug, Default)]
779struct LinkedProgram {
780 first_instance_location: Option<glow::UniformLocation>,
781 immediates_descs: ArrayVec<ImmediateDesc, MAX_IMMEDIATES_COMMANDS>,
782}
783
784#[cfg(send_sync)]
785unsafe impl Sync for PipelineInner {}
786#[cfg(send_sync)]
787unsafe impl Send for PipelineInner {}
788
789#[derive(Clone, Debug)]
790struct DepthState {
791 function: u32,
792 mask: bool,
793}
794
795#[derive(Clone, Debug, PartialEq)]
796struct BlendComponent {
797 src: u32,
798 dst: u32,
799 equation: u32,
800}
801
802#[derive(Clone, Debug, PartialEq)]
803struct BlendDesc {
804 alpha: BlendComponent,
805 color: BlendComponent,
806}
807
808#[derive(Clone, Debug, Default, PartialEq)]
809struct ColorTargetDesc {
810 mask: wgt::ColorWrites,
811 blend: Option<BlendDesc>,
812}
813
814#[derive(Debug, PartialEq, Eq, Hash)]
815struct ProgramStage {
816 naga_stage: naga::ShaderStage,
817 shader_id: ShaderId,
818 entry_point: String,
819 zero_initialize_workgroup_memory: bool,
820 constant_hash: Vec<u8>,
821}
822
823#[derive(Debug, PartialEq, Eq, Hash)]
824struct ProgramCacheKey {
825 stages: ArrayVec<ProgramStage, 3>,
826 group_to_binding_to_slot: Box<[Option<Box<[u8]>>]>,
827 force_point_size: bool,
828}
829
830type ProgramCache = FastHashMap<ProgramCacheKey, Result<Arc<PipelineInner>, crate::PipelineError>>;
831
832#[derive(Debug)]
833pub struct RenderPipeline {
834 inner: Arc<PipelineInner>,
835 primitive: wgt::PrimitiveState,
836 vertex_buffers: Box<[Option<VertexBufferDesc>]>,
837 vertex_attributes: Box<[AttributeDesc]>,
838 color_targets: Box<[ColorTargetDesc]>,
839 depth: Option<DepthState>,
840 depth_bias: wgt::DepthBiasState,
841 stencil: Option<StencilState>,
842 alpha_to_coverage_enabled: bool,
843}
844
845impl crate::DynRenderPipeline for RenderPipeline {}
846
847#[cfg(send_sync)]
848static_assertions::assert_impl_all!(RenderPipeline: Send, Sync);
849
850#[derive(Debug)]
851pub struct ComputePipeline {
852 inner: Arc<PipelineInner>,
853}
854
855impl crate::DynComputePipeline for ComputePipeline {}
856
857#[derive(Debug)]
858pub struct RayTracingPipeline {}
859
860impl crate::DynRayTracingPipeline for RayTracingPipeline {}
861
862#[cfg(send_sync)]
863static_assertions::assert_impl_all!(ComputePipeline: Send, Sync);
864
865#[derive(Debug)]
866pub struct QuerySet {
867 queries: Box<[glow::Query]>,
868 target: BindTarget,
869}
870
871impl crate::DynQuerySet for QuerySet {}
872
873#[derive(Debug)]
874pub struct AccelerationStructure;
875
876impl crate::DynAccelerationStructure for AccelerationStructure {}
877
878#[derive(Debug)]
879pub struct PipelineCache;
880
881impl crate::DynPipelineCache for PipelineCache {}
882
883#[derive(Clone, Debug, PartialEq)]
884struct StencilOps {
885 pass: u32,
886 fail: u32,
887 depth_fail: u32,
888}
889
890impl Default for StencilOps {
891 fn default() -> Self {
892 Self {
893 pass: glow::KEEP,
894 fail: glow::KEEP,
895 depth_fail: glow::KEEP,
896 }
897 }
898}
899
900#[derive(Clone, Debug, PartialEq)]
901struct StencilSide {
902 function: u32,
903 mask_read: u32,
904 mask_write: u32,
905 reference: u32,
906 ops: StencilOps,
907}
908
909impl Default for StencilSide {
910 fn default() -> Self {
911 Self {
912 function: glow::ALWAYS,
913 mask_read: 0xFF,
914 mask_write: 0xFF,
915 reference: 0,
916 ops: StencilOps::default(),
917 }
918 }
919}
920
921#[derive(Debug, Clone, Default)]
922struct StencilState {
923 front: StencilSide,
924 back: StencilSide,
925}
926
927#[derive(Clone, Debug, Default, PartialEq)]
928struct PrimitiveState {
929 front_face: u32,
930 cull_face: u32,
931 unclipped_depth: bool,
932 polygon_mode: u32,
933}
934
935type InvalidatedAttachments = ArrayVec<u32, { crate::MAX_COLOR_ATTACHMENTS + 2 }>;
936
937#[derive(Debug)]
938struct ClearBufferOp {
939 dst: Buffer,
940 dst_target: BindTarget,
941 range: crate::MemoryRange,
942}
943
944#[derive(Debug)]
945struct BufferToBufferCopy {
946 src: Buffer,
947 src_target: BindTarget,
948 dst: Buffer,
949 dst_target: BindTarget,
950 copy: crate::BufferCopy,
951}
952
953#[cfg(webgl)]
954#[derive(Debug)]
955struct ExternalImageToTextureCopy {
956 src: wgt::CopyExternalImageSourceInfo,
957 dst: glow::Texture,
958 dst_target: BindTarget,
959 dst_format: wgt::TextureFormat,
960 dst_premultiplication: bool,
961 copy: crate::TextureCopy,
962}
963
964#[derive(Debug)]
965struct TextureToTextureCopy {
966 src: glow::Texture,
967 src_target: BindTarget,
968 dst: glow::Texture,
969 dst_target: BindTarget,
970 copy: crate::TextureCopy,
971}
972
973#[derive(Debug)]
976struct CanvasCopy {
977 texture: glow::Texture,
978 target: BindTarget,
979 copy: crate::TextureCopy,
980}
981
982#[derive(Debug)]
983struct BufferToTextureCopy {
984 src: Buffer,
985 #[allow(unused)]
986 src_target: BindTarget,
987 dst: glow::Texture,
988 dst_target: BindTarget,
989 dst_format: wgt::TextureFormat,
990 copy: crate::BufferTextureCopy,
991}
992
993#[derive(Debug)]
994struct TextureToBufferCopy {
995 src: glow::Texture,
996 src_target: BindTarget,
997 src_format: wgt::TextureFormat,
998 dst: Buffer,
999 #[allow(unused)]
1000 dst_target: BindTarget,
1001 copy: crate::BufferTextureCopy,
1002}
1003
1004#[derive(Debug)]
1005struct QueryResultsCopy {
1006 query_range: Range<u32>,
1007 dst: Buffer,
1008 dst_target: BindTarget,
1009 dst_offset: wgt::BufferAddress,
1010}
1011
1012#[derive(Debug)]
1013struct AttachmentBinding {
1014 attachment: u32,
1015 view: TextureView,
1016 depth_slice: Option<u32>,
1017 sample_count: u32,
1018}
1019
1020#[derive(Debug)]
1021struct AttachmentResolve {
1022 attachment: u32,
1023 dst: TextureView,
1024 size: wgt::Extent3d,
1025}
1026
1027#[derive(Debug)]
1028enum Command {
1029 Draw {
1030 topology: u32,
1031 first_vertex: u32,
1032 vertex_count: u32,
1033 first_instance: u32,
1034 instance_count: u32,
1035 },
1036 DrawIndexed {
1037 topology: u32,
1038 index_type: u32,
1039 index_count: u32,
1040 index_offset: wgt::BufferAddress,
1041 base_vertex: i32,
1042 first_instance: u32,
1043 instance_count: u32,
1044 },
1045 DrawIndirect {
1046 topology: u32,
1047 indirect_buf: glow::Buffer,
1048 indirect_offset: wgt::BufferAddress,
1049 },
1050 DrawIndexedIndirect {
1051 topology: u32,
1052 index_type: u32,
1053 indirect_buf: glow::Buffer,
1054 indirect_offset: wgt::BufferAddress,
1055 },
1056 Dispatch([u32; 3]),
1057 DispatchIndirect {
1058 indirect_buf: glow::Buffer,
1059 indirect_offset: wgt::BufferAddress,
1060 },
1061 ClearBuffer(Box<ClearBufferOp>),
1062 CopyBufferToBuffer(Box<BufferToBufferCopy>),
1063 #[cfg(webgl)]
1064 CopyExternalImageToTexture(Box<ExternalImageToTextureCopy>),
1065 CopyTextureToTexture(Box<TextureToTextureCopy>),
1066 CopyCanvasToTexture(Box<CanvasCopy>),
1067 CopyTextureToCanvas(Box<CanvasCopy>),
1068 CopyBufferToTexture(Box<BufferToTextureCopy>),
1069 CopyTextureToBuffer(Box<TextureToBufferCopy>),
1070 SetIndexBuffer(glow::Buffer),
1071 BeginQuery(glow::Query, BindTarget),
1072 EndQuery(BindTarget),
1073 TimestampQuery(glow::Query),
1074 CopyQueryResults(Box<QueryResultsCopy>),
1075 ResetFramebuffer {
1076 is_default: bool,
1077 },
1078 BindAttachment(Box<AttachmentBinding>),
1079 ResolveAttachment(Box<AttachmentResolve>),
1080 InvalidateAttachments(InvalidatedAttachments),
1081 SetDrawColorBuffers(u8),
1082 ClearColorF {
1083 draw_buffer: u32,
1084 color: [f32; 4],
1085 is_srgb: bool,
1086 },
1087 ClearColorU(u32, [u32; 4]),
1088 ClearColorI(u32, [i32; 4]),
1089 ClearDepth(f32),
1090 ClearStencil(u32),
1091 ClearDepthAndStencil(f32, u32),
1096 BufferBarrier(glow::Buffer, wgt::BufferUses),
1097 TextureBarrier(wgt::TextureUses),
1098 SetViewport {
1099 rect: crate::Rect<i32>,
1100 depth: Range<f32>,
1101 },
1102 SetScissor(crate::Rect<i32>),
1103 SetStencilFunc {
1104 face: u32,
1105 function: u32,
1106 reference: u32,
1107 read_mask: u32,
1108 },
1109 SetStencilOps {
1110 face: u32,
1111 write_mask: u32,
1112 ops: StencilOps,
1113 },
1114 SetDepth(DepthState),
1115 SetDepthBias(wgt::DepthBiasState),
1116 ConfigureDepthStencil(crate::FormatAspects),
1117 SetAlphaToCoverage(bool),
1118 SetVertexAttribute {
1119 buffer: Option<glow::Buffer>,
1120 buffer_desc: VertexBufferDesc,
1121 attribute_desc: AttributeDesc,
1122 },
1123 UnsetVertexAttribute(u32),
1124 SetVertexBuffer {
1125 index: u32,
1126 buffer: BufferBinding,
1127 buffer_desc: VertexBufferDesc,
1128 },
1129 SetProgram(Arc<PipelineInner>),
1130 SetPrimitive(PrimitiveState),
1131 SetBlendConstant([f32; 4]),
1132 SetColorTarget {
1133 draw_buffer_index: Option<u32>,
1134 desc: ColorTargetDesc,
1135 },
1136 BindBuffer {
1137 target: BindTarget,
1138 slot: u32,
1139 buffer: glow::Buffer,
1140 offset: i32,
1141 size: i32,
1142 },
1143 BindSampler(u32, Option<glow::Sampler>),
1144 BindTexture {
1145 slot: u32,
1146 texture: glow::Texture,
1147 target: BindTarget,
1148 aspects: crate::FormatAspects,
1149 mip_levels: Range<u32>,
1150 },
1151 BindImage {
1152 slot: u32,
1153 binding: ImageBinding,
1154 },
1155 InsertDebugMarker(Range<u32>),
1156 PushDebugGroup(Range<u32>),
1157 PopDebugGroup,
1158 SetImmediates {
1159 data: Range<u32>,
1162 },
1163 SetClipDistances {
1164 old_count: u32,
1165 new_count: u32,
1166 },
1167}
1168
1169#[derive(Default)]
1170pub struct CommandBuffer {
1171 label: Option<String>,
1172 commands: Vec<Command>,
1173 data_bytes: Vec<u8>,
1174 queries: Vec<glow::Query>,
1175}
1176
1177impl crate::DynCommandBuffer for CommandBuffer {}
1178
1179impl fmt::Debug for CommandBuffer {
1180 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1181 let mut builder = f.debug_struct("CommandBuffer");
1182 if let Some(ref label) = self.label {
1183 builder.field("label", label);
1184 }
1185 builder.finish()
1186 }
1187}
1188
1189#[cfg(send_sync)]
1190unsafe impl Sync for CommandBuffer {}
1191#[cfg(send_sync)]
1192unsafe impl Send for CommandBuffer {}
1193
1194pub struct CommandEncoder {
1199 cmd_buffer: CommandBuffer,
1200 state: command::State,
1201 private_caps: PrivateCapabilities,
1202 counters: Arc<wgt::HalCounters>,
1203}
1204
1205impl fmt::Debug for CommandEncoder {
1206 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1207 f.debug_struct("CommandEncoder")
1208 .field("cmd_buffer", &self.cmd_buffer)
1209 .finish()
1210 }
1211}
1212
1213#[cfg(send_sync)]
1214unsafe impl Sync for CommandEncoder {}
1215#[cfg(send_sync)]
1216unsafe impl Send for CommandEncoder {}
1217
1218#[cfg(not(webgl))]
1219fn gl_debug_message_callback(source: u32, gltype: u32, id: u32, severity: u32, message: &str) {
1220 let source_str = match source {
1221 glow::DEBUG_SOURCE_API => "API",
1222 glow::DEBUG_SOURCE_WINDOW_SYSTEM => "Window System",
1223 glow::DEBUG_SOURCE_SHADER_COMPILER => "ShaderCompiler",
1224 glow::DEBUG_SOURCE_THIRD_PARTY => "Third Party",
1225 glow::DEBUG_SOURCE_APPLICATION => "Application",
1226 glow::DEBUG_SOURCE_OTHER => "Other",
1227 _ => unreachable!(),
1228 };
1229
1230 let log_severity = match severity {
1231 glow::DEBUG_SEVERITY_HIGH => log::Level::Error,
1232 glow::DEBUG_SEVERITY_MEDIUM => log::Level::Warn,
1233 glow::DEBUG_SEVERITY_LOW => log::Level::Debug,
1234 glow::DEBUG_SEVERITY_NOTIFICATION => log::Level::Trace,
1235 _ => unreachable!(),
1236 };
1237
1238 let type_str = match gltype {
1239 glow::DEBUG_TYPE_DEPRECATED_BEHAVIOR => "Deprecated Behavior",
1240 glow::DEBUG_TYPE_ERROR => "Error",
1241 glow::DEBUG_TYPE_MARKER => "Marker",
1242 glow::DEBUG_TYPE_OTHER => "Other",
1243 glow::DEBUG_TYPE_PERFORMANCE => "Performance",
1244 glow::DEBUG_TYPE_POP_GROUP => "Pop Group",
1245 glow::DEBUG_TYPE_PORTABILITY => "Portability",
1246 glow::DEBUG_TYPE_PUSH_GROUP => "Push Group",
1247 glow::DEBUG_TYPE_UNDEFINED_BEHAVIOR => "Undefined Behavior",
1248 _ => unreachable!(),
1249 };
1250
1251 let _ = std::panic::catch_unwind(|| {
1252 log::log!(
1253 log_severity,
1254 "GLES: [{source_str}/{type_str}] ID {id} : {message}"
1255 );
1256 });
1257
1258 #[cfg(feature = "validation_canary")]
1259 if cfg!(debug_assertions) && log_severity == log::Level::Error {
1260 crate::VALIDATION_CANARY.add(message.to_string());
1262 }
1263}
1264
1265cfg_if::cfg_if! {
1267 if #[cfg(gles_with_std)] {
1268 type MaybeMutex<T> = std::sync::Mutex<T>;
1269
1270 fn lock<T>(mutex: &MaybeMutex<T>) -> std::sync::MutexGuard<'_, T> {
1271 mutex.lock().unwrap()
1272 }
1273 } else {
1274 #[cfg(all(send_sync, not(feature = "fragile-send-sync-non-atomic-wasm")))]
1278 compile_error!("cannot provide non-fragile Send+Sync without std");
1279
1280 type MaybeMutex<T> = core::cell::RefCell<T>;
1281
1282 fn lock<T>(mutex: &MaybeMutex<T>) -> core::cell::RefMut<'_, T> {
1283 mutex.borrow_mut()
1284 }
1285 }
1286}