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> {
497 Some(0)
498 }
499}
500
501impl core::borrow::Borrow<dyn crate::DynTexture> for Texture {
502 fn borrow(&self) -> &dyn crate::DynTexture {
503 self
504 }
505}
506
507impl Texture {
508 pub fn default_framebuffer(format: wgt::TextureFormat) -> Self {
509 Self {
510 inner: TextureInner::DefaultRenderbuffer,
511 drop_guard: None,
512 mip_level_count: 1,
513 array_layer_count: 1,
514 format,
515 format_desc: TextureFormatDesc {
516 internal: 0,
517 external: 0,
518 data_type: 0,
519 },
520 copy_size: CopyExtent {
521 width: 0,
522 height: 0,
523 depth: 0,
524 },
525 }
526 }
527
528 fn get_info_from_desc(desc: &TextureDescriptor) -> u32 {
530 match desc.dimension {
531 wgt::TextureDimension::D1 => glow::TEXTURE_2D,
534 wgt::TextureDimension::D2 => {
535 match (desc.is_cube_compatible(), desc.size.depth_or_array_layers) {
537 (false, 1) => glow::TEXTURE_2D,
538 (false, _) => glow::TEXTURE_2D_ARRAY,
539 (true, 6) => glow::TEXTURE_CUBE_MAP,
540 (true, _) => glow::TEXTURE_CUBE_MAP_ARRAY,
541 }
542 }
543 wgt::TextureDimension::D3 => glow::TEXTURE_3D,
544 }
545 }
546
547 fn log_failing_target_heuristics(view_dimension: wgt::TextureViewDimension, target: u32) {
549 let expected_target = match view_dimension {
550 wgt::TextureViewDimension::D1 => glow::TEXTURE_2D,
551 wgt::TextureViewDimension::D2 => glow::TEXTURE_2D,
552 wgt::TextureViewDimension::D2Array => glow::TEXTURE_2D_ARRAY,
553 wgt::TextureViewDimension::Cube => glow::TEXTURE_CUBE_MAP,
554 wgt::TextureViewDimension::CubeArray => glow::TEXTURE_CUBE_MAP_ARRAY,
555 wgt::TextureViewDimension::D3 => glow::TEXTURE_3D,
556 };
557
558 if expected_target == target {
559 return;
560 }
561
562 let buffer;
563 let got = match target {
564 glow::TEXTURE_2D => "D2",
565 glow::TEXTURE_2D_ARRAY => "D2Array",
566 glow::TEXTURE_CUBE_MAP => "Cube",
567 glow::TEXTURE_CUBE_MAP_ARRAY => "CubeArray",
568 glow::TEXTURE_3D => "D3",
569 target => {
570 buffer = target.to_string();
571 &buffer
572 }
573 };
574
575 log::error!(
576 concat!(
577 "wgpu-hal heuristics assumed that ",
578 "the view dimension will be equal to `{}` rather than `{:?}`.\n",
579 "`D2` textures with ",
580 "`depth_or_array_layers == 1` ",
581 "are assumed to have view dimension `D2`\n",
582 "`D2` textures with ",
583 "`depth_or_array_layers > 1` ",
584 "are assumed to have view dimension `D2Array`\n",
585 "`D2` textures with ",
586 "`depth_or_array_layers == 6` ",
587 "are assumed to have view dimension `Cube`\n",
588 "`D2` textures with ",
589 "`depth_or_array_layers > 6 && depth_or_array_layers % 6 == 0` ",
590 "are assumed to have view dimension `CubeArray`\n",
591 ),
592 got,
593 view_dimension,
594 );
595 }
596}
597
598#[derive(Clone, Debug)]
599pub struct TextureView {
600 inner: TextureInner,
601 aspects: crate::FormatAspects,
602 mip_levels: Range<u32>,
603 array_layers: Range<u32>,
604 format: wgt::TextureFormat,
605}
606
607impl crate::DynTextureView for TextureView {}
608
609#[derive(Debug)]
610pub struct Sampler {
611 raw: glow::Sampler,
612}
613
614impl crate::DynSampler for Sampler {}
615
616#[derive(Debug)]
617pub struct BindGroupLayout {
618 entries: Arc<[wgt::BindGroupLayoutEntry]>,
619}
620
621impl crate::DynBindGroupLayout for BindGroupLayout {}
622
623#[derive(Debug)]
624struct BindGroupLayoutInfo {
625 entries: Arc<[wgt::BindGroupLayoutEntry]>,
626 binding_to_slot: Box<[u8]>,
632}
633
634#[derive(Debug)]
635pub struct PipelineLayout {
636 group_infos: Box<[Option<BindGroupLayoutInfo>]>,
637 naga_options: naga::back::glsl::Options,
638}
639
640impl crate::DynPipelineLayout for PipelineLayout {}
641
642impl PipelineLayout {
643 fn get_slot(&self, br: &naga::ResourceBinding) -> u8 {
647 let group_info = self.group_infos[br.group as usize].as_ref().unwrap();
648 group_info.binding_to_slot[br.binding as usize]
649 }
650}
651
652#[derive(Debug)]
653enum BindingRegister {
654 UniformBuffers,
655 StorageBuffers,
656 Textures,
657 Images,
658}
659
660#[derive(Debug)]
661enum RawBinding {
662 Buffer {
663 raw: glow::Buffer,
664 offset: i32,
665 size: i32,
666 },
667 Texture {
668 raw: glow::Texture,
669 target: BindTarget,
670 aspects: crate::FormatAspects,
671 mip_levels: Range<u32>,
672 },
674 Image(ImageBinding),
675 Sampler(glow::Sampler),
676}
677
678#[derive(Debug)]
679pub struct BindGroup {
680 contents: Box<[RawBinding]>,
681}
682
683impl crate::DynBindGroup for BindGroup {}
684
685type ShaderId = u32;
686
687#[derive(Debug)]
688pub enum ShaderModuleSource {
689 Naga(crate::NagaShader),
690 Passthrough { source: String },
691 Templates(&'static [crate::GlslTemplate]),
692}
693
694#[derive(Debug)]
695pub struct ShaderModule {
696 source: ShaderModuleSource,
697 label: Option<String>,
698 id: ShaderId,
699}
700
701impl crate::DynShaderModule for ShaderModule {}
702
703#[derive(Clone, Debug, Default)]
704struct VertexFormatDesc {
705 element_count: i32,
706 element_format: u32,
707 attrib_kind: VertexAttribKind,
708}
709
710#[derive(Clone, Debug, Default)]
711struct AttributeDesc {
712 location: u32,
713 offset: u32,
714 buffer_index: u32,
715 format_desc: VertexFormatDesc,
716}
717
718#[derive(Clone, Debug)]
719struct BufferBinding {
720 raw: glow::Buffer,
721 offset: wgt::BufferAddress,
722}
723
724#[derive(Clone, Debug)]
725struct ImageBinding {
726 raw: glow::Texture,
727 mip_level: u32,
728 array_layer: Option<u32>,
729 access: u32,
730 format: u32,
731}
732
733#[derive(Clone, Debug, Default, PartialEq)]
734struct VertexBufferDesc {
735 step: wgt::VertexStepMode,
736 stride: u32,
737}
738
739#[derive(Clone, Debug)]
740struct ImmediateDesc {
741 location: glow::UniformLocation,
742 ty: nt::glsl::GlslUniformType,
743 offset: u32,
744}
745
746#[cfg(send_sync)]
747unsafe impl Sync for ImmediateDesc {}
748#[cfg(send_sync)]
749unsafe impl Send for ImmediateDesc {}
750
751type SamplerBindMap = [Option<u8>; MAX_TEXTURE_SLOTS];
754
755#[derive(Debug)]
756struct PipelineInner {
757 program: glow::Program,
758 sampler_map: SamplerBindMap,
759 clip_distance_count: u32,
760 link: Mutex<ProgramLink>,
763}
764
765#[derive(Debug)]
767struct ProgramLink {
768 pending: Option<Box<device::PendingLink>>,
769 linked: Option<Arc<LinkedProgram>>,
770}
771
772#[derive(Debug, Default)]
774struct LinkedProgram {
775 first_instance_location: Option<glow::UniformLocation>,
776 immediates_descs: ArrayVec<ImmediateDesc, MAX_IMMEDIATES_COMMANDS>,
777}
778
779#[cfg(send_sync)]
780unsafe impl Sync for PipelineInner {}
781#[cfg(send_sync)]
782unsafe impl Send for PipelineInner {}
783
784#[derive(Clone, Debug)]
785struct DepthState {
786 function: u32,
787 mask: bool,
788}
789
790#[derive(Clone, Debug, PartialEq)]
791struct BlendComponent {
792 src: u32,
793 dst: u32,
794 equation: u32,
795}
796
797#[derive(Clone, Debug, PartialEq)]
798struct BlendDesc {
799 alpha: BlendComponent,
800 color: BlendComponent,
801}
802
803#[derive(Clone, Debug, Default, PartialEq)]
804struct ColorTargetDesc {
805 mask: wgt::ColorWrites,
806 blend: Option<BlendDesc>,
807}
808
809#[derive(Debug, PartialEq, Eq, Hash)]
810struct ProgramStage {
811 naga_stage: naga::ShaderStage,
812 shader_id: ShaderId,
813 entry_point: String,
814 zero_initialize_workgroup_memory: bool,
815 constant_hash: Vec<u8>,
816}
817
818#[derive(Debug, PartialEq, Eq, Hash)]
819struct ProgramCacheKey {
820 stages: ArrayVec<ProgramStage, 3>,
821 group_to_binding_to_slot: Box<[Option<Box<[u8]>>]>,
822 force_point_size: bool,
823}
824
825type ProgramCache = FastHashMap<ProgramCacheKey, Result<Arc<PipelineInner>, crate::PipelineError>>;
826
827#[derive(Debug)]
828pub struct RenderPipeline {
829 inner: Arc<PipelineInner>,
830 primitive: wgt::PrimitiveState,
831 vertex_buffers: Box<[Option<VertexBufferDesc>]>,
832 vertex_attributes: Box<[AttributeDesc]>,
833 color_targets: Box<[ColorTargetDesc]>,
834 depth: Option<DepthState>,
835 depth_bias: wgt::DepthBiasState,
836 stencil: Option<StencilState>,
837 alpha_to_coverage_enabled: bool,
838}
839
840impl crate::DynRenderPipeline for RenderPipeline {}
841
842#[cfg(send_sync)]
843static_assertions::assert_impl_all!(RenderPipeline: Send, Sync);
844
845#[derive(Debug)]
846pub struct ComputePipeline {
847 inner: Arc<PipelineInner>,
848}
849
850impl crate::DynComputePipeline for ComputePipeline {}
851
852#[derive(Debug)]
853pub struct RayTracingPipeline {}
854
855impl crate::DynRayTracingPipeline for RayTracingPipeline {}
856
857#[cfg(send_sync)]
858static_assertions::assert_impl_all!(ComputePipeline: Send, Sync);
859
860#[derive(Debug)]
861pub struct QuerySet {
862 queries: Box<[glow::Query]>,
863 target: BindTarget,
864}
865
866impl crate::DynQuerySet for QuerySet {}
867
868#[derive(Debug)]
869pub struct AccelerationStructure;
870
871impl crate::DynAccelerationStructure for AccelerationStructure {}
872
873#[derive(Debug)]
874pub struct PipelineCache;
875
876impl crate::DynPipelineCache for PipelineCache {}
877
878#[derive(Clone, Debug, PartialEq)]
879struct StencilOps {
880 pass: u32,
881 fail: u32,
882 depth_fail: u32,
883}
884
885impl Default for StencilOps {
886 fn default() -> Self {
887 Self {
888 pass: glow::KEEP,
889 fail: glow::KEEP,
890 depth_fail: glow::KEEP,
891 }
892 }
893}
894
895#[derive(Clone, Debug, PartialEq)]
896struct StencilSide {
897 function: u32,
898 mask_read: u32,
899 mask_write: u32,
900 reference: u32,
901 ops: StencilOps,
902}
903
904impl Default for StencilSide {
905 fn default() -> Self {
906 Self {
907 function: glow::ALWAYS,
908 mask_read: 0xFF,
909 mask_write: 0xFF,
910 reference: 0,
911 ops: StencilOps::default(),
912 }
913 }
914}
915
916#[derive(Debug, Clone, Default)]
917struct StencilState {
918 front: StencilSide,
919 back: StencilSide,
920}
921
922#[derive(Clone, Debug, Default, PartialEq)]
923struct PrimitiveState {
924 front_face: u32,
925 cull_face: u32,
926 unclipped_depth: bool,
927 polygon_mode: u32,
928}
929
930type InvalidatedAttachments = ArrayVec<u32, { crate::MAX_COLOR_ATTACHMENTS + 2 }>;
931
932#[derive(Debug)]
933struct ClearBufferOp {
934 dst: Buffer,
935 dst_target: BindTarget,
936 range: crate::MemoryRange,
937}
938
939#[derive(Debug)]
940struct BufferToBufferCopy {
941 src: Buffer,
942 src_target: BindTarget,
943 dst: Buffer,
944 dst_target: BindTarget,
945 copy: crate::BufferCopy,
946}
947
948#[cfg(webgl)]
949#[derive(Debug)]
950struct ExternalImageToTextureCopy {
951 src: wgt::CopyExternalImageSourceInfo,
952 dst: glow::Texture,
953 dst_target: BindTarget,
954 dst_format: wgt::TextureFormat,
955 dst_premultiplication: bool,
956 copy: crate::TextureCopy,
957}
958
959#[derive(Debug)]
960struct TextureToTextureCopy {
961 src: glow::Texture,
962 src_target: BindTarget,
963 dst: glow::Texture,
964 dst_target: BindTarget,
965 copy: crate::TextureCopy,
966}
967
968#[derive(Debug)]
969struct BufferToTextureCopy {
970 src: Buffer,
971 #[allow(unused)]
972 src_target: BindTarget,
973 dst: glow::Texture,
974 dst_target: BindTarget,
975 dst_format: wgt::TextureFormat,
976 copy: crate::BufferTextureCopy,
977}
978
979#[derive(Debug)]
980struct TextureToBufferCopy {
981 src: glow::Texture,
982 src_target: BindTarget,
983 src_format: wgt::TextureFormat,
984 dst: Buffer,
985 #[allow(unused)]
986 dst_target: BindTarget,
987 copy: crate::BufferTextureCopy,
988}
989
990#[derive(Debug)]
991struct QueryResultsCopy {
992 query_range: Range<u32>,
993 dst: Buffer,
994 dst_target: BindTarget,
995 dst_offset: wgt::BufferAddress,
996}
997
998#[derive(Debug)]
999struct AttachmentBinding {
1000 attachment: u32,
1001 view: TextureView,
1002 depth_slice: Option<u32>,
1003 sample_count: u32,
1004}
1005
1006#[derive(Debug)]
1007struct AttachmentResolve {
1008 attachment: u32,
1009 dst: TextureView,
1010 size: wgt::Extent3d,
1011}
1012
1013#[derive(Debug)]
1014enum Command {
1015 Draw {
1016 topology: u32,
1017 first_vertex: u32,
1018 vertex_count: u32,
1019 first_instance: u32,
1020 instance_count: u32,
1021 },
1022 DrawIndexed {
1023 topology: u32,
1024 index_type: u32,
1025 index_count: u32,
1026 index_offset: wgt::BufferAddress,
1027 base_vertex: i32,
1028 first_instance: u32,
1029 instance_count: u32,
1030 },
1031 DrawIndirect {
1032 topology: u32,
1033 indirect_buf: glow::Buffer,
1034 indirect_offset: wgt::BufferAddress,
1035 },
1036 DrawIndexedIndirect {
1037 topology: u32,
1038 index_type: u32,
1039 indirect_buf: glow::Buffer,
1040 indirect_offset: wgt::BufferAddress,
1041 },
1042 Dispatch([u32; 3]),
1043 DispatchIndirect {
1044 indirect_buf: glow::Buffer,
1045 indirect_offset: wgt::BufferAddress,
1046 },
1047 ClearBuffer(Box<ClearBufferOp>),
1048 CopyBufferToBuffer(Box<BufferToBufferCopy>),
1049 #[cfg(webgl)]
1050 CopyExternalImageToTexture(Box<ExternalImageToTextureCopy>),
1051 CopyTextureToTexture(Box<TextureToTextureCopy>),
1052 CopyBufferToTexture(Box<BufferToTextureCopy>),
1053 CopyTextureToBuffer(Box<TextureToBufferCopy>),
1054 SetIndexBuffer(glow::Buffer),
1055 BeginQuery(glow::Query, BindTarget),
1056 EndQuery(BindTarget),
1057 TimestampQuery(glow::Query),
1058 CopyQueryResults(Box<QueryResultsCopy>),
1059 ResetFramebuffer {
1060 is_default: bool,
1061 },
1062 BindAttachment(Box<AttachmentBinding>),
1063 ResolveAttachment(Box<AttachmentResolve>),
1064 InvalidateAttachments(InvalidatedAttachments),
1065 SetDrawColorBuffers(u8),
1066 ClearColorF {
1067 draw_buffer: u32,
1068 color: [f32; 4],
1069 is_srgb: bool,
1070 },
1071 ClearColorU(u32, [u32; 4]),
1072 ClearColorI(u32, [i32; 4]),
1073 ClearDepth(f32),
1074 ClearStencil(u32),
1075 ClearDepthAndStencil(f32, u32),
1080 BufferBarrier(glow::Buffer, wgt::BufferUses),
1081 TextureBarrier(wgt::TextureUses),
1082 SetViewport {
1083 rect: crate::Rect<i32>,
1084 depth: Range<f32>,
1085 },
1086 SetScissor(crate::Rect<i32>),
1087 SetStencilFunc {
1088 face: u32,
1089 function: u32,
1090 reference: u32,
1091 read_mask: u32,
1092 },
1093 SetStencilOps {
1094 face: u32,
1095 write_mask: u32,
1096 ops: StencilOps,
1097 },
1098 SetDepth(DepthState),
1099 SetDepthBias(wgt::DepthBiasState),
1100 ConfigureDepthStencil(crate::FormatAspects),
1101 SetAlphaToCoverage(bool),
1102 SetVertexAttribute {
1103 buffer: Option<glow::Buffer>,
1104 buffer_desc: VertexBufferDesc,
1105 attribute_desc: AttributeDesc,
1106 },
1107 UnsetVertexAttribute(u32),
1108 SetVertexBuffer {
1109 index: u32,
1110 buffer: BufferBinding,
1111 buffer_desc: VertexBufferDesc,
1112 },
1113 SetProgram(Arc<PipelineInner>),
1114 SetPrimitive(PrimitiveState),
1115 SetBlendConstant([f32; 4]),
1116 SetColorTarget {
1117 draw_buffer_index: Option<u32>,
1118 desc: ColorTargetDesc,
1119 },
1120 BindBuffer {
1121 target: BindTarget,
1122 slot: u32,
1123 buffer: glow::Buffer,
1124 offset: i32,
1125 size: i32,
1126 },
1127 BindSampler(u32, Option<glow::Sampler>),
1128 BindTexture {
1129 slot: u32,
1130 texture: glow::Texture,
1131 target: BindTarget,
1132 aspects: crate::FormatAspects,
1133 mip_levels: Range<u32>,
1134 },
1135 BindImage {
1136 slot: u32,
1137 binding: ImageBinding,
1138 },
1139 InsertDebugMarker(Range<u32>),
1140 PushDebugGroup(Range<u32>),
1141 PopDebugGroup,
1142 SetImmediates {
1143 data: Range<u32>,
1146 },
1147 SetClipDistances {
1148 old_count: u32,
1149 new_count: u32,
1150 },
1151}
1152
1153#[derive(Default)]
1154pub struct CommandBuffer {
1155 label: Option<String>,
1156 commands: Vec<Command>,
1157 data_bytes: Vec<u8>,
1158 queries: Vec<glow::Query>,
1159}
1160
1161impl crate::DynCommandBuffer for CommandBuffer {}
1162
1163impl fmt::Debug for CommandBuffer {
1164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1165 let mut builder = f.debug_struct("CommandBuffer");
1166 if let Some(ref label) = self.label {
1167 builder.field("label", label);
1168 }
1169 builder.finish()
1170 }
1171}
1172
1173#[cfg(send_sync)]
1174unsafe impl Sync for CommandBuffer {}
1175#[cfg(send_sync)]
1176unsafe impl Send for CommandBuffer {}
1177
1178pub struct CommandEncoder {
1183 cmd_buffer: CommandBuffer,
1184 state: command::State,
1185 private_caps: PrivateCapabilities,
1186 counters: Arc<wgt::HalCounters>,
1187}
1188
1189impl fmt::Debug for CommandEncoder {
1190 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1191 f.debug_struct("CommandEncoder")
1192 .field("cmd_buffer", &self.cmd_buffer)
1193 .finish()
1194 }
1195}
1196
1197#[cfg(send_sync)]
1198unsafe impl Sync for CommandEncoder {}
1199#[cfg(send_sync)]
1200unsafe impl Send for CommandEncoder {}
1201
1202#[cfg(not(webgl))]
1203fn gl_debug_message_callback(source: u32, gltype: u32, id: u32, severity: u32, message: &str) {
1204 let source_str = match source {
1205 glow::DEBUG_SOURCE_API => "API",
1206 glow::DEBUG_SOURCE_WINDOW_SYSTEM => "Window System",
1207 glow::DEBUG_SOURCE_SHADER_COMPILER => "ShaderCompiler",
1208 glow::DEBUG_SOURCE_THIRD_PARTY => "Third Party",
1209 glow::DEBUG_SOURCE_APPLICATION => "Application",
1210 glow::DEBUG_SOURCE_OTHER => "Other",
1211 _ => unreachable!(),
1212 };
1213
1214 let log_severity = match severity {
1215 glow::DEBUG_SEVERITY_HIGH => log::Level::Error,
1216 glow::DEBUG_SEVERITY_MEDIUM => log::Level::Warn,
1217 glow::DEBUG_SEVERITY_LOW => log::Level::Debug,
1218 glow::DEBUG_SEVERITY_NOTIFICATION => log::Level::Trace,
1219 _ => unreachable!(),
1220 };
1221
1222 let type_str = match gltype {
1223 glow::DEBUG_TYPE_DEPRECATED_BEHAVIOR => "Deprecated Behavior",
1224 glow::DEBUG_TYPE_ERROR => "Error",
1225 glow::DEBUG_TYPE_MARKER => "Marker",
1226 glow::DEBUG_TYPE_OTHER => "Other",
1227 glow::DEBUG_TYPE_PERFORMANCE => "Performance",
1228 glow::DEBUG_TYPE_POP_GROUP => "Pop Group",
1229 glow::DEBUG_TYPE_PORTABILITY => "Portability",
1230 glow::DEBUG_TYPE_PUSH_GROUP => "Push Group",
1231 glow::DEBUG_TYPE_UNDEFINED_BEHAVIOR => "Undefined Behavior",
1232 _ => unreachable!(),
1233 };
1234
1235 let _ = std::panic::catch_unwind(|| {
1236 log::log!(
1237 log_severity,
1238 "GLES: [{source_str}/{type_str}] ID {id} : {message}"
1239 );
1240 });
1241
1242 #[cfg(feature = "validation_canary")]
1243 if cfg!(debug_assertions) && log_severity == log::Level::Error {
1244 crate::VALIDATION_CANARY.add(message.to_string());
1246 }
1247}
1248
1249cfg_if::cfg_if! {
1251 if #[cfg(gles_with_std)] {
1252 type MaybeMutex<T> = std::sync::Mutex<T>;
1253
1254 fn lock<T>(mutex: &MaybeMutex<T>) -> std::sync::MutexGuard<'_, T> {
1255 mutex.lock().unwrap()
1256 }
1257 } else {
1258 #[cfg(all(send_sync, not(feature = "fragile-send-sync-non-atomic-wasm")))]
1262 compile_error!("cannot provide non-fragile Send+Sync without std");
1263
1264 type MaybeMutex<T> = core::cell::RefCell<T>;
1265
1266 fn lock<T>(mutex: &MaybeMutex<T>) -> core::cell::RefMut<'_, T> {
1267 mutex.borrow_mut()
1268 }
1269 }
1270}