1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
use super::conv;
use crate::auxil::map_naga_stage;
use glow::HasContext;
use std::{
convert::TryInto,
ptr,
sync::{Arc, Mutex},
};
use arrayvec::ArrayVec;
#[cfg(not(target_arch = "wasm32"))]
use std::mem;
use std::sync::atomic::Ordering;
type ShaderStage<'a> = (
naga::ShaderStage,
&'a crate::ProgrammableStage<'a, super::Api>,
);
type NameBindingMap = fxhash::FxHashMap<String, (super::BindingRegister, u8)>;
struct CompilationContext<'a> {
layout: &'a super::PipelineLayout,
sampler_map: &'a mut super::SamplerBindMap,
name_binding_map: &'a mut NameBindingMap,
multiview: Option<std::num::NonZeroU32>,
}
impl CompilationContext<'_> {
fn consume_reflection(
self,
module: &naga::Module,
ep_info: &naga::valid::FunctionInfo,
reflection_info: naga::back::glsl::ReflectionInfo,
) {
for (handle, var) in module.global_variables.iter() {
if ep_info[handle].is_empty() {
continue;
}
let register = match var.space {
naga::AddressSpace::Uniform => super::BindingRegister::UniformBuffers,
naga::AddressSpace::Storage { .. } => super::BindingRegister::StorageBuffers,
_ => continue,
};
let br = var.binding.as_ref().unwrap();
let slot = self.layout.get_slot(br);
let name = match reflection_info.uniforms.get(&handle) {
Some(name) => name.clone(),
None => continue,
};
log::debug!(
"Rebind buffer: {:?} -> {}, register={:?}, slot={}",
var.name.as_ref(),
&name,
register,
slot
);
self.name_binding_map.insert(name, (register, slot));
}
for (name, mapping) in reflection_info.texture_mapping {
let var = &module.global_variables[mapping.texture];
let register = match module.types[var.ty].inner {
naga::TypeInner::Image {
class: naga::ImageClass::Storage { .. },
..
} => super::BindingRegister::Images,
_ => super::BindingRegister::Textures,
};
let tex_br = var.binding.as_ref().unwrap();
let texture_linear_index = self.layout.get_slot(tex_br);
self.name_binding_map
.insert(name, (register, texture_linear_index));
if let Some(sampler_handle) = mapping.sampler {
let sam_br = module.global_variables[sampler_handle]
.binding
.as_ref()
.unwrap();
let sampler_linear_index = self.layout.get_slot(sam_br);
self.sampler_map[texture_linear_index as usize] = Some(sampler_linear_index);
}
}
}
}
impl super::Device {
#[cfg(any(not(target_arch = "wasm32"), feature = "emscripten"))]
pub unsafe fn texture_from_raw(
&self,
name: std::num::NonZeroU32,
desc: &crate::TextureDescriptor,
drop_guard: Option<crate::DropGuard>,
) -> super::Texture {
let mut copy_size = crate::CopyExtent::map_extent_to_copy_size(&desc.size, desc.dimension);
let (target, _, is_cubemap) = super::Texture::get_info_from_desc(&mut copy_size, desc);
super::Texture {
inner: super::TextureInner::Texture {
raw: glow::NativeTexture(name),
target,
},
drop_guard,
mip_level_count: desc.mip_level_count,
array_layer_count: if desc.dimension == wgt::TextureDimension::D2 {
desc.size.depth_or_array_layers
} else {
1
},
format: desc.format,
format_desc: self.shared.describe_texture_format(desc.format),
copy_size,
is_cubemap,
}
}
#[cfg(any(not(target_arch = "wasm32"), feature = "emscripten"))]
pub unsafe fn texture_from_raw_renderbuffer(
&self,
name: std::num::NonZeroU32,
desc: &crate::TextureDescriptor,
drop_guard: Option<crate::DropGuard>,
) -> super::Texture {
let copy_size = crate::CopyExtent::map_extent_to_copy_size(&desc.size, desc.dimension);
super::Texture {
inner: super::TextureInner::Renderbuffer {
raw: glow::NativeRenderbuffer(name),
},
drop_guard,
mip_level_count: desc.mip_level_count,
array_layer_count: if desc.dimension == wgt::TextureDimension::D2 {
desc.size.depth_or_array_layers
} else {
1
},
format: desc.format,
format_desc: self.shared.describe_texture_format(desc.format),
copy_size,
is_cubemap: false,
}
}
unsafe fn compile_shader(
gl: &glow::Context,
shader: &str,
naga_stage: naga::ShaderStage,
#[cfg_attr(target_arch = "wasm32", allow(unused))] label: Option<&str>,
) -> Result<glow::Shader, crate::PipelineError> {
let target = match naga_stage {
naga::ShaderStage::Vertex => glow::VERTEX_SHADER,
naga::ShaderStage::Fragment => glow::FRAGMENT_SHADER,
naga::ShaderStage::Compute => glow::COMPUTE_SHADER,
};
let raw = unsafe { gl.create_shader(target) }.unwrap();
#[cfg(not(target_arch = "wasm32"))]
if gl.supports_debug() {
let name = unsafe { mem::transmute(raw) };
unsafe { gl.object_label(glow::SHADER, name, label) };
}
unsafe { gl.shader_source(raw, shader) };
unsafe { gl.compile_shader(raw) };
log::info!("\tCompiled shader {:?}", raw);
let compiled_ok = unsafe { gl.get_shader_compile_status(raw) };
let msg = unsafe { gl.get_shader_info_log(raw) };
if compiled_ok {
if !msg.is_empty() {
log::warn!("\tCompile: {}", msg);
}
Ok(raw)
} else {
Err(crate::PipelineError::Linkage(
map_naga_stage(naga_stage),
msg,
))
}
}
fn create_shader(
gl: &glow::Context,
naga_stage: naga::ShaderStage,
stage: &crate::ProgrammableStage<super::Api>,
context: CompilationContext,
) -> Result<glow::Shader, crate::PipelineError> {
use naga::back::glsl;
let pipeline_options = glsl::PipelineOptions {
shader_stage: naga_stage,
entry_point: stage.entry_point.to_string(),
multiview: context.multiview,
};
let shader = &stage.module.naga;
let entry_point_index = shader
.module
.entry_points
.iter()
.position(|ep| ep.name.as_str() == stage.entry_point)
.ok_or(crate::PipelineError::EntryPoint(naga_stage))?;
use naga::proc::BoundsCheckPolicy;
let version = gl.version();
let image_check = if !version.is_embedded && (version.major, version.minor) >= (1, 3) {
BoundsCheckPolicy::ReadZeroSkipWrite
} else {
BoundsCheckPolicy::Unchecked
};
let policies = naga::proc::BoundsCheckPolicies {
index: BoundsCheckPolicy::Unchecked,
buffer: BoundsCheckPolicy::Unchecked,
image: image_check,
binding_array: BoundsCheckPolicy::Unchecked,
};
let mut output = String::new();
let mut writer = glsl::Writer::new(
&mut output,
&shader.module,
&shader.info,
&context.layout.naga_options,
&pipeline_options,
policies,
)
.map_err(|e| {
let msg = format!("{}", e);
crate::PipelineError::Linkage(map_naga_stage(naga_stage), msg)
})?;
let reflection_info = writer.write().map_err(|e| {
let msg = format!("{}", e);
crate::PipelineError::Linkage(map_naga_stage(naga_stage), msg)
})?;
log::debug!("Naga generated shader:\n{}", output);
context.consume_reflection(
&shader.module,
shader.info.get_entry_point(entry_point_index),
reflection_info,
);
unsafe { Self::compile_shader(gl, &output, naga_stage, stage.module.label.as_deref()) }
}
unsafe fn create_pipeline<'a>(
&self,
gl: &glow::Context,
shaders: ArrayVec<ShaderStage<'a>, 3>,
layout: &super::PipelineLayout,
#[cfg_attr(target_arch = "wasm32", allow(unused))] label: Option<&str>,
multiview: Option<std::num::NonZeroU32>,
) -> Result<Arc<super::PipelineInner>, crate::PipelineError> {
let mut program_stages = ArrayVec::new();
let mut group_to_binding_to_slot = Vec::with_capacity(layout.group_infos.len());
for group in &*layout.group_infos {
group_to_binding_to_slot.push(group.binding_to_slot.clone());
}
for &(naga_stage, stage) in &shaders {
program_stages.push(super::ProgramStage {
naga_stage: naga_stage.to_owned(),
shader_id: stage.module.id,
entry_point: stage.entry_point.to_owned(),
});
}
let glsl_version = match self.shared.shading_language_version {
naga::back::glsl::Version::Embedded { version, .. } => version,
naga::back::glsl::Version::Desktop(_) => unreachable!(),
};
let mut guard = self
.shared
.program_cache
.try_lock()
.expect("Couldn't acquire program_cache lock");
let program = guard
.entry(super::ProgramCacheKey {
stages: program_stages,
group_to_binding_to_slot: group_to_binding_to_slot.into_boxed_slice(),
})
.or_insert_with(|| unsafe {
Self::create_program(
gl,
shaders,
layout,
label,
multiview,
glsl_version,
self.shared.private_caps,
)
})
.to_owned()?;
drop(guard);
Ok(program)
}
unsafe fn create_program<'a>(
gl: &glow::Context,
shaders: ArrayVec<ShaderStage<'a>, 3>,
layout: &super::PipelineLayout,
#[cfg_attr(target_arch = "wasm32", allow(unused))] label: Option<&str>,
multiview: Option<std::num::NonZeroU32>,
glsl_version: u16,
private_caps: super::PrivateCapabilities,
) -> Result<Arc<super::PipelineInner>, crate::PipelineError> {
let program = unsafe { gl.create_program() }.unwrap();
#[cfg(not(target_arch = "wasm32"))]
if let Some(label) = label {
if gl.supports_debug() {
let name = unsafe { mem::transmute(program) };
unsafe { gl.object_label(glow::PROGRAM, name, Some(label)) };
}
}
let mut name_binding_map = NameBindingMap::default();
let mut sampler_map = [None; super::MAX_TEXTURE_SLOTS];
let mut has_stages = wgt::ShaderStages::empty();
let mut shaders_to_delete = arrayvec::ArrayVec::<_, 3>::new();
for (naga_stage, stage) in shaders {
has_stages |= map_naga_stage(naga_stage);
let context = CompilationContext {
layout,
sampler_map: &mut sampler_map,
name_binding_map: &mut name_binding_map,
multiview,
};
let shader = Self::create_shader(gl, naga_stage, stage, context)?;
shaders_to_delete.push(shader);
}
if has_stages == wgt::ShaderStages::VERTEX {
let shader_src = format!("#version {} es \n void main(void) {{}}", glsl_version,);
log::info!("Only vertex shader is present. Creating an empty fragment shader",);
let shader = unsafe {
Self::compile_shader(
gl,
&shader_src,
naga::ShaderStage::Fragment,
Some("(wgpu internal) dummy fragment shader"),
)
}?;
shaders_to_delete.push(shader);
}
for &shader in shaders_to_delete.iter() {
unsafe { gl.attach_shader(program, shader) };
}
unsafe { gl.link_program(program) };
for shader in shaders_to_delete {
unsafe { gl.delete_shader(shader) };
}
log::info!("\tLinked program {:?}", program);
let linked_ok = unsafe { gl.get_program_link_status(program) };
let msg = unsafe { gl.get_program_info_log(program) };
if !linked_ok {
return Err(crate::PipelineError::Linkage(has_stages, msg));
}
if !msg.is_empty() {
log::warn!("\tLink: {}", msg);
}
if !private_caps.contains(super::PrivateCapabilities::SHADER_BINDING_LAYOUT) {
unsafe { gl.use_program(Some(program)) };
for (ref name, (register, slot)) in name_binding_map {
log::trace!("Get binding {:?} from program {:?}", name, program);
match register {
super::BindingRegister::UniformBuffers => {
let index = unsafe { gl.get_uniform_block_index(program, name) }.unwrap();
unsafe { gl.uniform_block_binding(program, index, slot as _) };
}
super::BindingRegister::StorageBuffers => {
let index =
unsafe { gl.get_shader_storage_block_index(program, name) }.unwrap();
log::error!(
"Unable to re-map shader storage block {} to {}",
name,
index
);
return Err(crate::DeviceError::Lost.into());
}
super::BindingRegister::Textures | super::BindingRegister::Images => {
let location = unsafe { gl.get_uniform_location(program, name) };
unsafe { gl.uniform_1_i32(location.as_ref(), slot as _) };
}
}
}
}
let mut uniforms: [super::UniformDesc; super::MAX_PUSH_CONSTANTS] =
[None; super::MAX_PUSH_CONSTANTS].map(|_: Option<()>| Default::default());
let count = unsafe { gl.get_active_uniforms(program) };
let mut offset = 0;
for uniform in 0..count {
let glow::ActiveUniform { utype, name, .. } =
unsafe { gl.get_active_uniform(program, uniform) }.unwrap();
if conv::is_opaque_type(utype) {
continue;
}
if let Some(location) = unsafe { gl.get_uniform_location(program, &name) } {
if uniforms[offset / 4].location.is_some() {
panic!("Offset already occupied")
}
let uniform_size = conv::uniform_byte_size(utype);
uniforms[offset / 4] = super::UniformDesc {
location: Some(location),
size: uniform_size,
utype,
};
offset += uniform_size as usize;
}
}
Ok(Arc::new(super::PipelineInner {
program,
sampler_map,
uniforms,
}))
}
}
impl crate::Device<super::Api> for super::Device {
unsafe fn exit(self, queue: super::Queue) {
let gl = &self.shared.context.lock();
unsafe { gl.delete_vertex_array(self.main_vao) };
unsafe { gl.delete_framebuffer(queue.draw_fbo) };
unsafe { gl.delete_framebuffer(queue.copy_fbo) };
unsafe { gl.delete_buffer(queue.zero_buffer) };
}
unsafe fn create_buffer(
&self,
desc: &crate::BufferDescriptor,
) -> Result<super::Buffer, crate::DeviceError> {
let target = if desc.usage.contains(crate::BufferUses::INDEX) {
glow::ELEMENT_ARRAY_BUFFER
} else {
glow::ARRAY_BUFFER
};
let emulate_map = self
.shared
.workarounds
.contains(super::Workarounds::EMULATE_BUFFER_MAP)
|| !self
.shared
.private_caps
.contains(super::PrivateCapabilities::BUFFER_ALLOCATION);
if emulate_map && desc.usage.intersects(crate::BufferUses::MAP_WRITE) {
return Ok(super::Buffer {
raw: None,
target,
size: desc.size,
map_flags: 0,
data: Some(Arc::new(Mutex::new(vec![0; desc.size as usize]))),
});
}
let gl = &self.shared.context.lock();
let target = if desc.usage.contains(crate::BufferUses::INDEX) {
glow::ELEMENT_ARRAY_BUFFER
} else {
glow::ARRAY_BUFFER
};
let is_host_visible = desc
.usage
.intersects(crate::BufferUses::MAP_READ | crate::BufferUses::MAP_WRITE);
let is_coherent = desc
.memory_flags
.contains(crate::MemoryFlags::PREFER_COHERENT);
let mut map_flags = 0;
if desc.usage.contains(crate::BufferUses::MAP_READ) {
map_flags |= glow::MAP_READ_BIT;
}
if desc.usage.contains(crate::BufferUses::MAP_WRITE) {
map_flags |= glow::MAP_WRITE_BIT;
}
let raw = Some(unsafe { gl.create_buffer() }.map_err(|_| crate::DeviceError::OutOfMemory)?);
unsafe { gl.bind_buffer(target, raw) };
let raw_size = desc
.size
.try_into()
.map_err(|_| crate::DeviceError::OutOfMemory)?;
if self
.shared
.private_caps
.contains(super::PrivateCapabilities::BUFFER_ALLOCATION)
{
if is_host_visible {
map_flags |= glow::MAP_PERSISTENT_BIT;
if is_coherent {
map_flags |= glow::MAP_COHERENT_BIT;
}
}
unsafe { gl.buffer_storage(target, raw_size, None, map_flags) };
} else {
assert!(!is_coherent);
let usage = if is_host_visible {
if desc.usage.contains(crate::BufferUses::MAP_READ) {
glow::STREAM_READ
} else {
glow::DYNAMIC_DRAW
}
} else {
glow::DYNAMIC_DRAW
};
unsafe { gl.buffer_data_size(target, raw_size, usage) };
}
unsafe { gl.bind_buffer(target, None) };
if !is_coherent && desc.usage.contains(crate::BufferUses::MAP_WRITE) {
map_flags |= glow::MAP_FLUSH_EXPLICIT_BIT;
}
#[cfg(not(target_arch = "wasm32"))]
if let Some(label) = desc.label {
if gl.supports_debug() {
let name = unsafe { mem::transmute(raw) };
unsafe { gl.object_label(glow::BUFFER, name, Some(label)) };
}
}
let data = if emulate_map && desc.usage.contains(crate::BufferUses::MAP_READ) {
Some(Arc::new(Mutex::new(vec![0; desc.size as usize])))
} else {
None
};
Ok(super::Buffer {
raw,
target,
size: desc.size,
map_flags,
data,
})
}
unsafe fn destroy_buffer(&self, buffer: super::Buffer) {
if let Some(raw) = buffer.raw {
let gl = &self.shared.context.lock();
unsafe { gl.delete_buffer(raw) };
}
}
unsafe fn map_buffer(
&self,
buffer: &super::Buffer,
range: crate::MemoryRange,
) -> Result<crate::BufferMapping, crate::DeviceError> {
let is_coherent = buffer.map_flags & glow::MAP_COHERENT_BIT != 0;
let ptr = match buffer.raw {
None => {
let mut vec = buffer.data.as_ref().unwrap().lock().unwrap();
let slice = &mut vec.as_mut_slice()[range.start as usize..range.end as usize];
slice.as_mut_ptr()
}
Some(raw) => {
let gl = &self.shared.context.lock();
unsafe { gl.bind_buffer(buffer.target, Some(raw)) };
let ptr = if let Some(ref map_read_allocation) = buffer.data {
let mut guard = map_read_allocation.lock().unwrap();
let slice = guard.as_mut_slice();
unsafe { self.shared.get_buffer_sub_data(gl, buffer.target, 0, slice) };
slice.as_mut_ptr()
} else {
unsafe {
gl.map_buffer_range(
buffer.target,
range.start as i32,
(range.end - range.start) as i32,
buffer.map_flags,
)
}
};
unsafe { gl.bind_buffer(buffer.target, None) };
ptr
}
};
Ok(crate::BufferMapping {
ptr: ptr::NonNull::new(ptr).ok_or(crate::DeviceError::Lost)?,
is_coherent,
})
}
unsafe fn unmap_buffer(&self, buffer: &super::Buffer) -> Result<(), crate::DeviceError> {
if let Some(raw) = buffer.raw {
if buffer.data.is_none() {
let gl = &self.shared.context.lock();
unsafe { gl.bind_buffer(buffer.target, Some(raw)) };
unsafe { gl.unmap_buffer(buffer.target) };
unsafe { gl.bind_buffer(buffer.target, None) };
}
}
Ok(())
}
unsafe fn flush_mapped_ranges<I>(&self, buffer: &super::Buffer, ranges: I)
where
I: Iterator<Item = crate::MemoryRange>,
{
if let Some(raw) = buffer.raw {
let gl = &self.shared.context.lock();
unsafe { gl.bind_buffer(buffer.target, Some(raw)) };
for range in ranges {
unsafe {
gl.flush_mapped_buffer_range(
buffer.target,
range.start as i32,
(range.end - range.start) as i32,
)
};
}
}
}
unsafe fn invalidate_mapped_ranges<I>(&self, _buffer: &super::Buffer, _ranges: I) {
}
unsafe fn create_texture(
&self,
desc: &crate::TextureDescriptor,
) -> Result<super::Texture, crate::DeviceError> {
let gl = &self.shared.context.lock();
let render_usage = crate::TextureUses::COLOR_TARGET
| crate::TextureUses::DEPTH_STENCIL_WRITE
| crate::TextureUses::DEPTH_STENCIL_READ;
let format_desc = self.shared.describe_texture_format(desc.format);
let mut copy_size = crate::CopyExtent {
width: desc.size.width,
height: desc.size.height,
depth: 1,
};
let (inner, is_cubemap) = if render_usage.contains(desc.usage)
&& desc.dimension == wgt::TextureDimension::D2
&& desc.size.depth_or_array_layers == 1
{
let raw = unsafe { gl.create_renderbuffer().unwrap() };
unsafe { gl.bind_renderbuffer(glow::RENDERBUFFER, Some(raw)) };
if desc.sample_count > 1 {
unsafe {
gl.renderbuffer_storage_multisample(
glow::RENDERBUFFER,
desc.sample_count as i32,
format_desc.internal,
desc.size.width as i32,
desc.size.height as i32,
)
};
} else {
unsafe {
gl.renderbuffer_storage(
glow::RENDERBUFFER,
format_desc.internal,
desc.size.width as i32,
desc.size.height as i32,
)
};
}
#[cfg(not(target_arch = "wasm32"))]
if let Some(label) = desc.label {
if gl.supports_debug() {
let name = unsafe { mem::transmute(raw) };
unsafe { gl.object_label(glow::RENDERBUFFER, name, Some(label)) };
}
}
unsafe { gl.bind_renderbuffer(glow::RENDERBUFFER, None) };
(super::TextureInner::Renderbuffer { raw }, false)
} else {
let raw = unsafe { gl.create_texture().unwrap() };
let (target, is_3d, is_cubemap) =
super::Texture::get_info_from_desc(&mut copy_size, desc);
unsafe { gl.bind_texture(target, Some(raw)) };
match desc.format.describe().sample_type {
wgt::TextureSampleType::Float { filterable: false }
| wgt::TextureSampleType::Uint
| wgt::TextureSampleType::Sint => {
unsafe {
gl.tex_parameter_i32(target, glow::TEXTURE_MIN_FILTER, glow::NEAREST as i32)
};
unsafe {
gl.tex_parameter_i32(target, glow::TEXTURE_MAG_FILTER, glow::NEAREST as i32)
};
}
wgt::TextureSampleType::Float { filterable: true }
| wgt::TextureSampleType::Depth => {}
}
if is_3d {
unsafe {
gl.tex_storage_3d(
target,
desc.mip_level_count as i32,
format_desc.internal,
desc.size.width as i32,
desc.size.height as i32,
desc.size.depth_or_array_layers as i32,
)
};
} else if desc.sample_count > 1 {
unsafe {
gl.tex_storage_2d_multisample(
target,
desc.sample_count as i32,
format_desc.internal,
desc.size.width as i32,
desc.size.height as i32,
true,
)
};
} else {
unsafe {
gl.tex_storage_2d(
target,
desc.mip_level_count as i32,
format_desc.internal,
desc.size.width as i32,
desc.size.height as i32,
)
};
}
#[cfg(not(target_arch = "wasm32"))]
if let Some(label) = desc.label {
if gl.supports_debug() {
let name = unsafe { mem::transmute(raw) };
unsafe { gl.object_label(glow::TEXTURE, name, Some(label)) };
}
}
unsafe { gl.bind_texture(target, None) };
(super::TextureInner::Texture { raw, target }, is_cubemap)
};
Ok(super::Texture {
inner,
drop_guard: None,
mip_level_count: desc.mip_level_count,
array_layer_count: if desc.dimension == wgt::TextureDimension::D2 {
desc.size.depth_or_array_layers
} else {
1
},
format: desc.format,
format_desc,
copy_size,
is_cubemap,
})
}
unsafe fn destroy_texture(&self, texture: super::Texture) {
if texture.drop_guard.is_none() {
let gl = &self.shared.context.lock();
match texture.inner {
super::TextureInner::Renderbuffer { raw, .. } => {
unsafe { gl.delete_renderbuffer(raw) };
}
super::TextureInner::DefaultRenderbuffer => {}
super::TextureInner::Texture { raw, .. } => {
unsafe { gl.delete_texture(raw) };
}
#[cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))]
super::TextureInner::ExternalFramebuffer { .. } => {}
}
}
drop(texture.drop_guard);
}
unsafe fn create_texture_view(
&self,
texture: &super::Texture,
desc: &crate::TextureViewDescriptor,
) -> Result<super::TextureView, crate::DeviceError> {
let end_array_layer = match desc.range.array_layer_count {
Some(count) => desc.range.base_array_layer + count.get(),
None => texture.array_layer_count,
};
let end_mip_level = match desc.range.mip_level_count {
Some(count) => desc.range.base_mip_level + count.get(),
None => texture.mip_level_count,
};
Ok(super::TextureView {
inner: texture.inner.clone(),
sample_type: texture.format.describe().sample_type,
aspects: crate::FormatAspects::from(texture.format)
& crate::FormatAspects::from(desc.range.aspect),
mip_levels: desc.range.base_mip_level..end_mip_level,
array_layers: desc.range.base_array_layer..end_array_layer,
format: texture.format,
})
}
unsafe fn destroy_texture_view(&self, _view: super::TextureView) {}
unsafe fn create_sampler(
&self,
desc: &crate::SamplerDescriptor,
) -> Result<super::Sampler, crate::DeviceError> {
let gl = &self.shared.context.lock();
let raw = unsafe { gl.create_sampler().unwrap() };
let (min, mag) =
conv::map_filter_modes(desc.min_filter, desc.mag_filter, desc.mipmap_filter);
unsafe { gl.sampler_parameter_i32(raw, glow::TEXTURE_MIN_FILTER, min as i32) };
unsafe { gl.sampler_parameter_i32(raw, glow::TEXTURE_MAG_FILTER, mag as i32) };
unsafe {
gl.sampler_parameter_i32(
raw,
glow::TEXTURE_WRAP_S,
conv::map_address_mode(desc.address_modes[0]) as i32,
)
};
unsafe {
gl.sampler_parameter_i32(
raw,
glow::TEXTURE_WRAP_T,
conv::map_address_mode(desc.address_modes[1]) as i32,
)
};
unsafe {
gl.sampler_parameter_i32(
raw,
glow::TEXTURE_WRAP_R,
conv::map_address_mode(desc.address_modes[2]) as i32,
)
};
if let Some(border_color) = desc.border_color {
let border = match border_color {
wgt::SamplerBorderColor::TransparentBlack | wgt::SamplerBorderColor::Zero => {
[0.0; 4]
}
wgt::SamplerBorderColor::OpaqueBlack => [0.0, 0.0, 0.0, 1.0],
wgt::SamplerBorderColor::OpaqueWhite => [1.0; 4],
};
unsafe { gl.sampler_parameter_f32_slice(raw, glow::TEXTURE_BORDER_COLOR, &border) };
}
if let Some(ref range) = desc.lod_clamp {
unsafe { gl.sampler_parameter_f32(raw, glow::TEXTURE_MIN_LOD, range.start) };
unsafe { gl.sampler_parameter_f32(raw, glow::TEXTURE_MAX_LOD, range.end) };
}
if let Some(anisotropy) = desc.anisotropy_clamp {
unsafe {
gl.sampler_parameter_i32(raw, glow::TEXTURE_MAX_ANISOTROPY, anisotropy.get() as i32)
};
}
if let Some(compare) = desc.compare {
unsafe {
gl.sampler_parameter_i32(
raw,
glow::TEXTURE_COMPARE_MODE,
glow::COMPARE_REF_TO_TEXTURE as i32,
)
};
unsafe {
gl.sampler_parameter_i32(
raw,
glow::TEXTURE_COMPARE_FUNC,
conv::map_compare_func(compare) as i32,
)
};
}
#[cfg(not(target_arch = "wasm32"))]
if let Some(label) = desc.label {
if gl.supports_debug() {
let name = unsafe { mem::transmute(raw) };
unsafe { gl.object_label(glow::SAMPLER, name, Some(label)) };
}
}
Ok(super::Sampler { raw })
}
unsafe fn destroy_sampler(&self, sampler: super::Sampler) {
let gl = &self.shared.context.lock();
unsafe { gl.delete_sampler(sampler.raw) };
}
unsafe fn create_command_encoder(
&self,
_desc: &crate::CommandEncoderDescriptor<super::Api>,
) -> Result<super::CommandEncoder, crate::DeviceError> {
Ok(super::CommandEncoder {
cmd_buffer: super::CommandBuffer::default(),
state: Default::default(),
private_caps: self.shared.private_caps,
})
}
unsafe fn destroy_command_encoder(&self, _encoder: super::CommandEncoder) {}
unsafe fn create_bind_group_layout(
&self,
desc: &crate::BindGroupLayoutDescriptor,
) -> Result<super::BindGroupLayout, crate::DeviceError> {
Ok(super::BindGroupLayout {
entries: Arc::from(desc.entries),
})
}
unsafe fn destroy_bind_group_layout(&self, _bg_layout: super::BindGroupLayout) {}
unsafe fn create_pipeline_layout(
&self,
desc: &crate::PipelineLayoutDescriptor<super::Api>,
) -> Result<super::PipelineLayout, crate::DeviceError> {
use naga::back::glsl;
let mut group_infos = Vec::with_capacity(desc.bind_group_layouts.len());
let mut num_samplers = 0u8;
let mut num_textures = 0u8;
let mut num_images = 0u8;
let mut num_uniform_buffers = 0u8;
let mut num_storage_buffers = 0u8;
let mut writer_flags = glsl::WriterFlags::ADJUST_COORDINATE_SPACE;
writer_flags.set(
glsl::WriterFlags::TEXTURE_SHADOW_LOD,
self.shared
.private_caps
.contains(super::PrivateCapabilities::SHADER_TEXTURE_SHADOW_LOD),
);
let mut binding_map = glsl::BindingMap::default();
for (group_index, bg_layout) in desc.bind_group_layouts.iter().enumerate() {
let mut binding_to_slot = vec![
!0;
bg_layout
.entries
.last()
.map_or(0, |b| b.binding as usize + 1)
]
.into_boxed_slice();
for entry in bg_layout.entries.iter() {
let counter = match entry.ty {
wgt::BindingType::Sampler { .. } => &mut num_samplers,
wgt::BindingType::Texture { .. } => &mut num_textures,
wgt::BindingType::StorageTexture { .. } => &mut num_images,
wgt::BindingType::Buffer {
ty: wgt::BufferBindingType::Uniform,
..
} => &mut num_uniform_buffers,
wgt::BindingType::Buffer {
ty: wgt::BufferBindingType::Storage { .. },
..
} => &mut num_storage_buffers,
};
binding_to_slot[entry.binding as usize] = *counter;
let br = naga::ResourceBinding {
group: group_index as u32,
binding: entry.binding,
};
binding_map.insert(br, *counter);
*counter += entry.count.map_or(1, |c| c.get() as u8);
}
group_infos.push(super::BindGroupLayoutInfo {
entries: Arc::clone(&bg_layout.entries),
binding_to_slot,
});
}
Ok(super::PipelineLayout {
group_infos: group_infos.into_boxed_slice(),
naga_options: glsl::Options {
version: self.shared.shading_language_version,
writer_flags,
binding_map,
zero_initialize_workgroup_memory: true,
},
})
}
unsafe fn destroy_pipeline_layout(&self, _pipeline_layout: super::PipelineLayout) {}
unsafe fn create_bind_group(
&self,
desc: &crate::BindGroupDescriptor<super::Api>,
) -> Result<super::BindGroup, crate::DeviceError> {
let mut contents = Vec::new();
for (entry, layout) in desc.entries.iter().zip(desc.layout.entries.iter()) {
let binding = match layout.ty {
wgt::BindingType::Buffer { .. } => {
let bb = &desc.buffers[entry.resource_index as usize];
super::RawBinding::Buffer {
raw: bb.buffer.raw.unwrap(),
offset: bb.offset as i32,
size: match bb.size {
Some(s) => s.get() as i32,
None => (bb.buffer.size - bb.offset) as i32,
},
}
}
wgt::BindingType::Sampler { .. } => {
let sampler = desc.samplers[entry.resource_index as usize];
super::RawBinding::Sampler(sampler.raw)
}
wgt::BindingType::Texture { .. } => {
let view = desc.textures[entry.resource_index as usize].view;
if view.mip_levels.start != 0 || view.array_layers.start != 0 {
log::error!("Unable to create a sampled texture binding for non-zero mipmap level or array layer.\n{}",
"This is an implementation problem of wgpu-hal/gles backend.")
}
let (raw, target) = view.inner.as_native();
super::RawBinding::Texture { raw, target }
}
wgt::BindingType::StorageTexture {
access,
format,
view_dimension,
} => {
let view = desc.textures[entry.resource_index as usize].view;
let format_desc = self.shared.describe_texture_format(format);
let (raw, _target) = view.inner.as_native();
super::RawBinding::Image(super::ImageBinding {
raw,
mip_level: view.mip_levels.start,
array_layer: match view_dimension {
wgt::TextureViewDimension::D2Array
| wgt::TextureViewDimension::CubeArray => None,
_ => Some(view.array_layers.start),
},
access: conv::map_storage_access(access),
format: format_desc.internal,
})
}
};
contents.push(binding);
}
Ok(super::BindGroup {
contents: contents.into_boxed_slice(),
})
}
unsafe fn destroy_bind_group(&self, _group: super::BindGroup) {}
unsafe fn create_shader_module(
&self,
desc: &crate::ShaderModuleDescriptor,
shader: crate::ShaderInput,
) -> Result<super::ShaderModule, crate::ShaderError> {
Ok(super::ShaderModule {
naga: match shader {
crate::ShaderInput::SpirV(_) => {
panic!("`Features::SPIRV_SHADER_PASSTHROUGH` is not enabled")
}
crate::ShaderInput::Naga(naga) => naga,
},
label: desc.label.map(|str| str.to_string()),
id: self.shared.next_shader_id.fetch_add(1, Ordering::Relaxed),
})
}
unsafe fn destroy_shader_module(&self, _module: super::ShaderModule) {}
unsafe fn create_render_pipeline(
&self,
desc: &crate::RenderPipelineDescriptor<super::Api>,
) -> Result<super::RenderPipeline, crate::PipelineError> {
let gl = &self.shared.context.lock();
let mut shaders = ArrayVec::new();
shaders.push((naga::ShaderStage::Vertex, &desc.vertex_stage));
if let Some(ref fs) = desc.fragment_stage {
shaders.push((naga::ShaderStage::Fragment, fs));
}
let inner =
unsafe { self.create_pipeline(gl, shaders, desc.layout, desc.label, desc.multiview) }?;
let (vertex_buffers, vertex_attributes) = {
let mut buffers = Vec::new();
let mut attributes = Vec::new();
for (index, vb_layout) in desc.vertex_buffers.iter().enumerate() {
buffers.push(super::VertexBufferDesc {
step: vb_layout.step_mode,
stride: vb_layout.array_stride as u32,
});
for vat in vb_layout.attributes.iter() {
let format_desc = conv::describe_vertex_format(vat.format);
attributes.push(super::AttributeDesc {
location: vat.shader_location,
offset: vat.offset as u32,
buffer_index: index as u32,
format_desc,
});
}
}
(buffers.into_boxed_slice(), attributes.into_boxed_slice())
};
let color_targets = {
let mut targets = Vec::new();
for ct in desc.color_targets.iter().filter_map(|at| at.as_ref()) {
targets.push(super::ColorTargetDesc {
mask: ct.write_mask,
blend: ct.blend.as_ref().map(conv::map_blend),
});
}
targets.into_boxed_slice()
};
Ok(super::RenderPipeline {
inner,
primitive: desc.primitive,
vertex_buffers,
vertex_attributes,
color_targets,
depth: desc.depth_stencil.as_ref().map(|ds| super::DepthState {
function: conv::map_compare_func(ds.depth_compare),
mask: ds.depth_write_enabled,
}),
depth_bias: desc
.depth_stencil
.as_ref()
.map(|ds| ds.bias)
.unwrap_or_default(),
stencil: desc
.depth_stencil
.as_ref()
.map(|ds| conv::map_stencil(&ds.stencil)),
alpha_to_coverage_enabled: desc.multisample.alpha_to_coverage_enabled,
})
}
unsafe fn destroy_render_pipeline(&self, pipeline: super::RenderPipeline) {
let mut program_cache = self.shared.program_cache.lock();
if Arc::strong_count(&pipeline.inner) == 2 {
program_cache.retain(|_, v| match *v {
Ok(ref p) => p.program != pipeline.inner.program,
Err(_) => false,
});
let gl = &self.shared.context.lock();
unsafe { gl.delete_program(pipeline.inner.program) };
}
}
unsafe fn create_compute_pipeline(
&self,
desc: &crate::ComputePipelineDescriptor<super::Api>,
) -> Result<super::ComputePipeline, crate::PipelineError> {
let gl = &self.shared.context.lock();
let mut shaders = ArrayVec::new();
shaders.push((naga::ShaderStage::Compute, &desc.stage));
let inner = unsafe { self.create_pipeline(gl, shaders, desc.layout, desc.label, None) }?;
Ok(super::ComputePipeline { inner })
}
unsafe fn destroy_compute_pipeline(&self, pipeline: super::ComputePipeline) {
let mut program_cache = self.shared.program_cache.lock();
if Arc::strong_count(&pipeline.inner) == 2 {
program_cache.retain(|_, v| match *v {
Ok(ref p) => p.program != pipeline.inner.program,
Err(_) => false,
});
let gl = &self.shared.context.lock();
unsafe { gl.delete_program(pipeline.inner.program) };
}
}
#[cfg_attr(target_arch = "wasm32", allow(unused))]
unsafe fn create_query_set(
&self,
desc: &wgt::QuerySetDescriptor<crate::Label>,
) -> Result<super::QuerySet, crate::DeviceError> {
let gl = &self.shared.context.lock();
let mut temp_string = String::new();
let mut queries = Vec::with_capacity(desc.count as usize);
for i in 0..desc.count {
let query =
unsafe { gl.create_query() }.map_err(|_| crate::DeviceError::OutOfMemory)?;
#[cfg(not(target_arch = "wasm32"))]
if gl.supports_debug() {
use std::fmt::Write;
if let Some(label) = desc.label {
temp_string.clear();
let _ = write!(temp_string, "{}[{}]", label, i);
let name = unsafe { mem::transmute(query) };
unsafe { gl.object_label(glow::QUERY, name, Some(&temp_string)) };
}
}
queries.push(query);
}
Ok(super::QuerySet {
queries: queries.into_boxed_slice(),
target: match desc.ty {
wgt::QueryType::Occlusion => glow::ANY_SAMPLES_PASSED,
_ => unimplemented!(),
},
})
}
unsafe fn destroy_query_set(&self, set: super::QuerySet) {
let gl = &self.shared.context.lock();
for &query in set.queries.iter() {
unsafe { gl.delete_query(query) };
}
}
unsafe fn create_fence(&self) -> Result<super::Fence, crate::DeviceError> {
Ok(super::Fence {
last_completed: 0,
pending: Vec::new(),
})
}
unsafe fn destroy_fence(&self, fence: super::Fence) {
let gl = &self.shared.context.lock();
for (_, sync) in fence.pending {
unsafe { gl.delete_sync(sync) };
}
}
unsafe fn get_fence_value(
&self,
fence: &super::Fence,
) -> Result<crate::FenceValue, crate::DeviceError> {
#[cfg_attr(target_arch = "wasm32", allow(clippy::needless_borrow))]
Ok(fence.get_latest(&self.shared.context.lock()))
}
unsafe fn wait(
&self,
fence: &super::Fence,
wait_value: crate::FenceValue,
timeout_ms: u32,
) -> Result<bool, crate::DeviceError> {
if fence.last_completed < wait_value {
let gl = &self.shared.context.lock();
let timeout_ns = if cfg!(target_arch = "wasm32") {
0
} else {
(timeout_ms as u64 * 1_000_000).min(!0u32 as u64)
};
let &(_, sync) = fence
.pending
.iter()
.find(|&&(value, _)| value >= wait_value)
.unwrap();
match unsafe {
gl.client_wait_sync(sync, glow::SYNC_FLUSH_COMMANDS_BIT, timeout_ns as i32)
} {
#[cfg(target_arch = "wasm32")]
glow::WAIT_FAILED => {
log::warn!("wait failed!");
Ok(false)
}
glow::TIMEOUT_EXPIRED => Ok(false),
glow::CONDITION_SATISFIED | glow::ALREADY_SIGNALED => Ok(true),
_ => Err(crate::DeviceError::Lost),
}
} else {
Ok(true)
}
}
unsafe fn start_capture(&self) -> bool {
#[cfg(feature = "renderdoc")]
return unsafe {
self.render_doc
.start_frame_capture(self.shared.context.raw_context(), ptr::null_mut())
};
#[allow(unreachable_code)]
false
}
unsafe fn stop_capture(&self) {
#[cfg(feature = "renderdoc")]
unsafe {
self.render_doc
.end_frame_capture(ptr::null_mut(), ptr::null_mut())
}
}
}
#[cfg(target_arch = "wasm32")]
unsafe impl Sync for super::Device {}
#[cfg(target_arch = "wasm32")]
unsafe impl Send for super::Device {}