This repository has been archived by the owner on Jun 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 186
/
lib.rs
2971 lines (2724 loc) · 104 KB
/
lib.rs
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
//! A cross-platform graphics and compute library based on [WebGPU](https://gpuweb.github.io/gpuweb/).
//!
//! To start using the API, create an [`Instance`].
#![doc(html_logo_url = "https://raw.githubusercontent.com/gfx-rs/wgpu-rs/master/logo.png")]
#![warn(missing_docs)]
mod backend;
pub mod util;
#[macro_use]
mod macros;
use std::{
borrow::Cow,
error,
fmt::{Debug, Display},
future::Future,
marker::PhantomData,
num::{NonZeroU32, NonZeroU8},
ops::{Bound, Range, RangeBounds},
sync::Arc,
thread,
};
use parking_lot::Mutex;
pub use wgt::{
AdapterInfo, AddressMode, Backend, BackendBit, BindGroupLayoutEntry, BindingType,
BlendComponent, BlendFactor, BlendOperation, BlendState, BufferAddress, BufferBindingType,
BufferSize, BufferUsage, Color, ColorTargetState, ColorWrite, CommandBufferDescriptor,
CompareFunction, DepthBiasState, DepthStencilState, DeviceType, DownlevelFlags,
DownlevelProperties, DynamicOffset, Extent3d, Face, Features, FilterMode, FrontFace,
ImageDataLayout, IndexFormat, InputStepMode, Limits, MultisampleState, Origin3d,
PipelineStatisticsTypes, PolygonMode, PowerPreference, PresentMode, PrimitiveState,
PrimitiveTopology, PushConstantRange, QuerySetDescriptor, QueryType, SamplerBorderColor,
ShaderFlags, ShaderLocation, ShaderModel, ShaderStage, StencilFaceState, StencilOperation,
StencilState, StorageTextureAccess, SwapChainDescriptor, SwapChainStatus, TextureAspect,
TextureDimension, TextureFormat, TextureFormatFeatureFlags, TextureFormatFeatures,
TextureSampleType, TextureUsage, TextureViewDimension, VertexAttribute, VertexFormat,
BIND_BUFFER_ALIGNMENT, COPY_BUFFER_ALIGNMENT, COPY_BYTES_PER_ROW_ALIGNMENT, MAP_ALIGNMENT,
PUSH_CONSTANT_ALIGNMENT, QUERY_SET_MAX_QUERIES, QUERY_SIZE, VERTEX_STRIDE_ALIGNMENT,
};
use backend::{BufferMappedRange, Context as C};
trait ComputePassInner<Ctx: Context> {
fn set_pipeline(&mut self, pipeline: &Ctx::ComputePipelineId);
fn set_bind_group(
&mut self,
index: u32,
bind_group: &Ctx::BindGroupId,
offsets: &[DynamicOffset],
);
fn set_push_constants(&mut self, offset: u32, data: &[u8]);
fn insert_debug_marker(&mut self, label: &str);
fn push_debug_group(&mut self, group_label: &str);
fn pop_debug_group(&mut self);
fn write_timestamp(&mut self, query_set: &Ctx::QuerySetId, query_index: u32);
fn begin_pipeline_statistics_query(&mut self, query_set: &Ctx::QuerySetId, query_index: u32);
fn end_pipeline_statistics_query(&mut self);
fn dispatch(&mut self, x: u32, y: u32, z: u32);
fn dispatch_indirect(
&mut self,
indirect_buffer: &Ctx::BufferId,
indirect_offset: BufferAddress,
);
}
trait RenderInner<Ctx: Context> {
fn set_pipeline(&mut self, pipeline: &Ctx::RenderPipelineId);
fn set_bind_group(
&mut self,
index: u32,
bind_group: &Ctx::BindGroupId,
offsets: &[DynamicOffset],
);
fn set_index_buffer(
&mut self,
buffer: &Ctx::BufferId,
index_format: IndexFormat,
offset: BufferAddress,
size: Option<BufferSize>,
);
fn set_vertex_buffer(
&mut self,
slot: u32,
buffer: &Ctx::BufferId,
offset: BufferAddress,
size: Option<BufferSize>,
);
fn set_push_constants(&mut self, stages: wgt::ShaderStage, offset: u32, data: &[u8]);
fn draw(&mut self, vertices: Range<u32>, instances: Range<u32>);
fn draw_indexed(&mut self, indices: Range<u32>, base_vertex: i32, instances: Range<u32>);
fn draw_indirect(&mut self, indirect_buffer: &Ctx::BufferId, indirect_offset: BufferAddress);
fn draw_indexed_indirect(
&mut self,
indirect_buffer: &Ctx::BufferId,
indirect_offset: BufferAddress,
);
fn multi_draw_indirect(
&mut self,
indirect_buffer: &Ctx::BufferId,
indirect_offset: BufferAddress,
count: u32,
);
fn multi_draw_indexed_indirect(
&mut self,
indirect_buffer: &Ctx::BufferId,
indirect_offset: BufferAddress,
count: u32,
);
fn multi_draw_indirect_count(
&mut self,
indirect_buffer: &Ctx::BufferId,
indirect_offset: BufferAddress,
count_buffer: &Ctx::BufferId,
count_buffer_offset: BufferAddress,
max_count: u32,
);
fn multi_draw_indexed_indirect_count(
&mut self,
indirect_buffer: &Ctx::BufferId,
indirect_offset: BufferAddress,
count_buffer: &Ctx::BufferId,
count_buffer_offset: BufferAddress,
max_count: u32,
);
}
trait RenderPassInner<Ctx: Context>: RenderInner<Ctx> {
fn set_blend_constant(&mut self, color: Color);
fn set_scissor_rect(&mut self, x: u32, y: u32, width: u32, height: u32);
fn set_viewport(
&mut self,
x: f32,
y: f32,
width: f32,
height: f32,
min_depth: f32,
max_depth: f32,
);
fn set_stencil_reference(&mut self, reference: u32);
fn insert_debug_marker(&mut self, label: &str);
fn push_debug_group(&mut self, group_label: &str);
fn pop_debug_group(&mut self);
fn write_timestamp(&mut self, query_set: &Ctx::QuerySetId, query_index: u32);
fn begin_pipeline_statistics_query(&mut self, query_set: &Ctx::QuerySetId, query_index: u32);
fn end_pipeline_statistics_query(&mut self);
fn execute_bundles<'a, I: Iterator<Item = &'a Ctx::RenderBundleId>>(
&mut self,
render_bundles: I,
);
}
trait Context: Debug + Send + Sized + Sync {
type AdapterId: Debug + Send + Sync + 'static;
type DeviceId: Debug + Send + Sync + 'static;
type QueueId: Debug + Send + Sync + 'static;
type ShaderModuleId: Debug + Send + Sync + 'static;
type BindGroupLayoutId: Debug + Send + Sync + 'static;
type BindGroupId: Debug + Send + Sync + 'static;
type TextureViewId: Debug + Send + Sync + 'static;
type SamplerId: Debug + Send + Sync + 'static;
type BufferId: Debug + Send + Sync + 'static;
type TextureId: Debug + Send + Sync + 'static;
type QuerySetId: Debug + Send + Sync + 'static;
type PipelineLayoutId: Debug + Send + Sync + 'static;
type RenderPipelineId: Debug + Send + Sync + 'static;
type ComputePipelineId: Debug + Send + Sync + 'static;
type CommandEncoderId: Debug;
type ComputePassId: Debug + ComputePassInner<Self>;
type RenderPassId: Debug + RenderPassInner<Self>;
type CommandBufferId: Debug + Send + Sync;
type RenderBundleEncoderId: Debug + RenderInner<Self>;
type RenderBundleId: Debug + Send + Sync + 'static;
type SurfaceId: Debug + Send + Sync + 'static;
type SwapChainId: Debug + Send + Sync + 'static;
type SwapChainOutputDetail: Send;
type RequestAdapterFuture: Future<Output = Option<Self::AdapterId>> + Send;
type RequestDeviceFuture: Future<Output = Result<(Self::DeviceId, Self::QueueId), RequestDeviceError>>
+ Send;
type MapAsyncFuture: Future<Output = Result<(), BufferAsyncError>> + Send;
fn init(backends: BackendBit) -> Self;
fn instance_create_surface(
&self,
handle: &impl raw_window_handle::HasRawWindowHandle,
) -> Self::SurfaceId;
fn instance_request_adapter(
&self,
options: &RequestAdapterOptions<'_>,
) -> Self::RequestAdapterFuture;
fn adapter_request_device(
&self,
adapter: &Self::AdapterId,
desc: &DeviceDescriptor,
trace_dir: Option<&std::path::Path>,
) -> Self::RequestDeviceFuture;
fn instance_poll_all_devices(&self, force_wait: bool);
fn adapter_get_swap_chain_preferred_format(
&self,
adapter: &Self::AdapterId,
surface: &Self::SurfaceId,
) -> Option<TextureFormat>;
fn adapter_features(&self, adapter: &Self::AdapterId) -> Features;
fn adapter_limits(&self, adapter: &Self::AdapterId) -> Limits;
fn adapter_downlevel_properties(&self, adapter: &Self::AdapterId) -> DownlevelProperties;
fn adapter_get_info(&self, adapter: &Self::AdapterId) -> AdapterInfo;
fn adapter_get_texture_format_features(
&self,
adapter: &Self::AdapterId,
format: wgt::TextureFormat,
) -> wgt::TextureFormatFeatures;
fn device_features(&self, device: &Self::DeviceId) -> Features;
fn device_limits(&self, device: &Self::DeviceId) -> Limits;
fn device_downlevel_properties(&self, device: &Self::DeviceId) -> DownlevelProperties;
fn device_create_swap_chain(
&self,
device: &Self::DeviceId,
surface: &Self::SurfaceId,
desc: &SwapChainDescriptor,
) -> Self::SwapChainId;
fn device_create_shader_module(
&self,
device: &Self::DeviceId,
desc: &ShaderModuleDescriptor,
) -> Self::ShaderModuleId;
fn device_create_bind_group_layout(
&self,
device: &Self::DeviceId,
desc: &BindGroupLayoutDescriptor,
) -> Self::BindGroupLayoutId;
fn device_create_bind_group(
&self,
device: &Self::DeviceId,
desc: &BindGroupDescriptor,
) -> Self::BindGroupId;
fn device_create_pipeline_layout(
&self,
device: &Self::DeviceId,
desc: &PipelineLayoutDescriptor,
) -> Self::PipelineLayoutId;
fn device_create_render_pipeline(
&self,
device: &Self::DeviceId,
desc: &RenderPipelineDescriptor,
) -> Self::RenderPipelineId;
fn device_create_compute_pipeline(
&self,
device: &Self::DeviceId,
desc: &ComputePipelineDescriptor,
) -> Self::ComputePipelineId;
fn device_create_buffer(
&self,
device: &Self::DeviceId,
desc: &BufferDescriptor,
) -> Self::BufferId;
fn device_create_texture(
&self,
device: &Self::DeviceId,
desc: &TextureDescriptor,
) -> Self::TextureId;
fn device_create_sampler(
&self,
device: &Self::DeviceId,
desc: &SamplerDescriptor,
) -> Self::SamplerId;
fn device_create_query_set(
&self,
device: &Self::DeviceId,
desc: &QuerySetDescriptor,
) -> Self::QuerySetId;
fn device_create_command_encoder(
&self,
device: &Self::DeviceId,
desc: &CommandEncoderDescriptor,
) -> Self::CommandEncoderId;
fn device_create_render_bundle_encoder(
&self,
device: &Self::DeviceId,
desc: &RenderBundleEncoderDescriptor,
) -> Self::RenderBundleEncoderId;
fn device_drop(&self, device: &Self::DeviceId);
fn device_poll(&self, device: &Self::DeviceId, maintain: Maintain);
fn device_on_uncaptured_error(
&self,
device: &Self::DeviceId,
handler: impl UncapturedErrorHandler,
);
fn buffer_map_async(
&self,
buffer: &Self::BufferId,
mode: MapMode,
range: Range<BufferAddress>,
) -> Self::MapAsyncFuture;
fn buffer_get_mapped_range(
&self,
buffer: &Self::BufferId,
sub_range: Range<BufferAddress>,
) -> BufferMappedRange;
fn buffer_unmap(&self, buffer: &Self::BufferId);
fn swap_chain_get_current_texture_view(
&self,
swap_chain: &Self::SwapChainId,
) -> (
Option<Self::TextureViewId>,
SwapChainStatus,
Self::SwapChainOutputDetail,
);
fn swap_chain_present(&self, view: &Self::TextureViewId, detail: &Self::SwapChainOutputDetail);
fn texture_create_view(
&self,
texture: &Self::TextureId,
desc: &TextureViewDescriptor,
) -> Self::TextureViewId;
fn surface_drop(&self, surface: &Self::SurfaceId);
fn adapter_drop(&self, adapter: &Self::AdapterId);
fn buffer_destroy(&self, buffer: &Self::BufferId);
fn buffer_drop(&self, buffer: &Self::BufferId);
fn texture_destroy(&self, buffer: &Self::TextureId);
fn texture_drop(&self, texture: &Self::TextureId);
fn texture_view_drop(&self, texture_view: &Self::TextureViewId);
fn sampler_drop(&self, sampler: &Self::SamplerId);
fn query_set_drop(&self, query_set: &Self::QuerySetId);
fn bind_group_drop(&self, bind_group: &Self::BindGroupId);
fn bind_group_layout_drop(&self, bind_group_layout: &Self::BindGroupLayoutId);
fn pipeline_layout_drop(&self, pipeline_layout: &Self::PipelineLayoutId);
fn shader_module_drop(&self, shader_module: &Self::ShaderModuleId);
fn command_encoder_drop(&self, command_encoder: &Self::CommandEncoderId);
fn command_buffer_drop(&self, command_buffer: &Self::CommandBufferId);
fn render_bundle_drop(&self, render_bundle: &Self::RenderBundleId);
fn compute_pipeline_drop(&self, pipeline: &Self::ComputePipelineId);
fn render_pipeline_drop(&self, pipeline: &Self::RenderPipelineId);
fn compute_pipeline_get_bind_group_layout(
&self,
pipeline: &Self::ComputePipelineId,
index: u32,
) -> Self::BindGroupLayoutId;
fn render_pipeline_get_bind_group_layout(
&self,
pipeline: &Self::RenderPipelineId,
index: u32,
) -> Self::BindGroupLayoutId;
fn command_encoder_copy_buffer_to_buffer(
&self,
encoder: &Self::CommandEncoderId,
source: &Self::BufferId,
source_offset: BufferAddress,
destination: &Self::BufferId,
destination_offset: BufferAddress,
copy_size: BufferAddress,
);
fn command_encoder_copy_buffer_to_texture(
&self,
encoder: &Self::CommandEncoderId,
source: ImageCopyBuffer,
destination: ImageCopyTexture,
copy_size: Extent3d,
);
fn command_encoder_copy_texture_to_buffer(
&self,
encoder: &Self::CommandEncoderId,
source: ImageCopyTexture,
destination: ImageCopyBuffer,
copy_size: Extent3d,
);
fn command_encoder_copy_texture_to_texture(
&self,
encoder: &Self::CommandEncoderId,
source: ImageCopyTexture,
destination: ImageCopyTexture,
copy_size: Extent3d,
);
fn command_encoder_begin_compute_pass(
&self,
encoder: &Self::CommandEncoderId,
desc: &ComputePassDescriptor,
) -> Self::ComputePassId;
fn command_encoder_end_compute_pass(
&self,
encoder: &Self::CommandEncoderId,
pass: &mut Self::ComputePassId,
);
fn command_encoder_begin_render_pass<'a>(
&self,
encoder: &Self::CommandEncoderId,
desc: &RenderPassDescriptor<'a, '_>,
) -> Self::RenderPassId;
fn command_encoder_end_render_pass(
&self,
encoder: &Self::CommandEncoderId,
pass: &mut Self::RenderPassId,
);
fn command_encoder_finish(&self, encoder: Self::CommandEncoderId) -> Self::CommandBufferId;
fn command_encoder_insert_debug_marker(&self, encoder: &Self::CommandEncoderId, label: &str);
fn command_encoder_push_debug_group(&self, encoder: &Self::CommandEncoderId, label: &str);
fn command_encoder_pop_debug_group(&self, encoder: &Self::CommandEncoderId);
fn command_encoder_write_timestamp(
&self,
encoder: &Self::CommandEncoderId,
query_set: &Self::QuerySetId,
query_index: u32,
);
fn command_encoder_resolve_query_set(
&self,
encoder: &Self::CommandEncoderId,
query_set: &Self::QuerySetId,
first_query: u32,
query_count: u32,
destination: &Self::BufferId,
destination_offset: BufferAddress,
);
fn render_bundle_encoder_finish(
&self,
encoder: Self::RenderBundleEncoderId,
desc: &RenderBundleDescriptor,
) -> Self::RenderBundleId;
fn queue_write_buffer(
&self,
queue: &Self::QueueId,
buffer: &Self::BufferId,
offset: BufferAddress,
data: &[u8],
);
fn queue_write_texture(
&self,
queue: &Self::QueueId,
texture: ImageCopyTexture,
data: &[u8],
data_layout: ImageDataLayout,
size: Extent3d,
);
fn queue_submit<I: Iterator<Item = Self::CommandBufferId>>(
&self,
queue: &Self::QueueId,
command_buffers: I,
);
fn queue_get_timestamp_period(&self, queue: &Self::QueueId) -> f32;
fn device_start_capture(&self, device: &Self::DeviceId);
fn device_stop_capture(&self, device: &Self::DeviceId);
}
/// Context for all other wgpu objects. Instance of wgpu.
///
/// This is the first thing you create when using wgpu.
/// Its primary use is to create [`Adapter`]s and [`Surface`]s.
///
/// Does not have to be kept alive.
#[derive(Debug)]
pub struct Instance {
context: Arc<C>,
}
/// Handle to a physical graphics and/or compute device.
///
/// Adapters can be used to open a connection to the corresponding [`Device`]
/// on the host system by using [`Adapter::request_device`].
///
/// Does not have to be kept alive.
#[derive(Debug)]
pub struct Adapter {
context: Arc<C>,
id: <C as Context>::AdapterId,
}
impl Drop for Adapter {
fn drop(&mut self) {
if !thread::panicking() {
self.context.adapter_drop(&self.id)
}
}
}
/// Open connection to a graphics and/or compute device.
///
/// Responsible for the creation of most rendering and compute resources.
/// These are then used in commands, which are submitted to a [`Queue`].
///
/// A device may be requested from an adapter with [`Adapter::request_device`].
#[derive(Debug)]
pub struct Device {
context: Arc<C>,
id: <C as Context>::DeviceId,
}
/// Passed to [`Device::poll`] to control if it should block or not. This has no effect on
/// the web.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Maintain {
/// Block
Wait,
/// Don't block
Poll,
}
/// The main purpose of this struct is to resolve mapped ranges (convert sizes
/// to end points), and to ensure that the sub-ranges don't intersect.
#[derive(Debug)]
struct MapContext {
total_size: BufferAddress,
initial_range: Range<BufferAddress>,
sub_ranges: Vec<Range<BufferAddress>>,
}
impl MapContext {
fn new(total_size: BufferAddress) -> Self {
MapContext {
total_size,
initial_range: 0..0,
sub_ranges: Vec::new(),
}
}
fn reset(&mut self) {
self.initial_range = 0..0;
assert!(
self.sub_ranges.is_empty(),
"You cannot unmap a buffer that still has accessible mapped views"
);
}
fn add(&mut self, offset: BufferAddress, size: Option<BufferSize>) -> BufferAddress {
let end = match size {
Some(s) => offset + s.get(),
None => self.initial_range.end,
};
assert!(self.initial_range.start <= offset && end <= self.initial_range.end);
for sub in self.sub_ranges.iter() {
assert!(
end <= sub.start || offset >= sub.end,
"Intersecting map range with {:?}",
sub
);
}
self.sub_ranges.push(offset..end);
end
}
fn remove(&mut self, offset: BufferAddress, size: Option<BufferSize>) {
let end = match size {
Some(s) => offset + s.get(),
None => self.initial_range.end,
};
let index = self
.sub_ranges
.iter()
.position(|r| *r == (offset..end))
.expect("unable to remove range from map context");
self.sub_ranges.swap_remove(index);
}
}
/// Handle to a GPU-accessible buffer.
///
/// Created with [`Device::create_buffer`] or [DeviceExt::create_buffer_init](util::DeviceExt::create_buffer_init)
#[derive(Debug)]
pub struct Buffer {
context: Arc<C>,
id: <C as Context>::BufferId,
map_context: Mutex<MapContext>,
usage: BufferUsage,
}
/// Slice into a [`Buffer`].
///
/// Created by calling [`Buffer::slice`]. To use the whole buffer, call with unbounded slice:
///
/// `buffer.slice(..)`
#[derive(Copy, Clone, Debug)]
pub struct BufferSlice<'a> {
buffer: &'a Buffer,
offset: BufferAddress,
size: Option<BufferSize>,
}
/// Handle to a texture on the GPU.
///
/// Created by calling [`Device::create_texture`]
#[derive(Debug)]
pub struct Texture {
context: Arc<C>,
id: <C as Context>::TextureId,
owned: bool,
}
/// Handle to a texture view.
///
/// A `TextureView` object describes a texture and associated metadata needed by a
/// [`RenderPipeline`] or [`BindGroup`].
#[derive(Debug)]
pub struct TextureView {
context: Arc<C>,
id: <C as Context>::TextureViewId,
owned: bool,
}
/// Handle to a sampler.
///
/// A `Sampler` object defines how a pipeline will sample from a [`TextureView`]. Samplers define
/// image filters (including anisotropy) and address (wrapping) modes, among other things. See
/// the documentation for [`SamplerDescriptor`] for more information.
#[derive(Debug)]
pub struct Sampler {
context: Arc<C>,
id: <C as Context>::SamplerId,
}
impl Drop for Sampler {
fn drop(&mut self) {
if !thread::panicking() {
self.context.sampler_drop(&self.id);
}
}
}
/// Handle to a presentable surface.
///
/// A `Surface` represents a platform-specific surface (e.g. a window) onto which rendered images may
/// be presented. A `Surface` may be created with the unsafe function [`Instance::create_surface`].
#[derive(Debug)]
pub struct Surface {
context: Arc<C>,
id: <C as Context>::SurfaceId,
}
impl Drop for Surface {
fn drop(&mut self) {
if !thread::panicking() {
self.context.surface_drop(&self.id)
}
}
}
/// Handle to a swap chain.
///
/// A `SwapChain` represents the image or series of images that will be presented to a [`Surface`].
/// A `SwapChain` may be created with [`Device::create_swap_chain`].
#[derive(Debug)]
pub struct SwapChain {
context: Arc<C>,
id: <C as Context>::SwapChainId,
}
/// Handle to a binding group layout.
///
/// A `BindGroupLayout` is a handle to the GPU-side layout of a binding group. It can be used to
/// create a [`BindGroupDescriptor`] object, which in turn can be used to create a [`BindGroup`]
/// object with [`Device::create_bind_group`]. A series of `BindGroupLayout`s can also be used to
/// create a [`PipelineLayoutDescriptor`], which can be used to create a [`PipelineLayout`].
#[derive(Debug)]
pub struct BindGroupLayout {
context: Arc<C>,
id: <C as Context>::BindGroupLayoutId,
}
impl Drop for BindGroupLayout {
fn drop(&mut self) {
if !thread::panicking() {
self.context.bind_group_layout_drop(&self.id);
}
}
}
/// Handle to a binding group.
///
/// A `BindGroup` represents the set of resources bound to the bindings described by a
/// [`BindGroupLayout`]. It can be created with [`Device::create_bind_group`]. A `BindGroup` can
/// be bound to a particular [`RenderPass`] with [`RenderPass::set_bind_group`], or to a
/// [`ComputePass`] with [`ComputePass::set_bind_group`].
#[derive(Debug)]
pub struct BindGroup {
context: Arc<C>,
id: <C as Context>::BindGroupId,
}
impl Drop for BindGroup {
fn drop(&mut self) {
if !thread::panicking() {
self.context.bind_group_drop(&self.id);
}
}
}
/// Handle to a compiled shader module.
///
/// A `ShaderModule` represents a compiled shader module on the GPU. It can be created by passing
/// valid SPIR-V source code to [`Device::create_shader_module`]. Shader modules are used to define
/// programmable stages of a pipeline.
#[derive(Debug)]
pub struct ShaderModule {
context: Arc<C>,
id: <C as Context>::ShaderModuleId,
}
impl Drop for ShaderModule {
fn drop(&mut self) {
if !thread::panicking() {
self.context.shader_module_drop(&self.id);
}
}
}
/// Source of a shader module.
pub enum ShaderSource<'a> {
/// SPIR-V module represented as a slice of words.
///
/// wgpu will attempt to parse and validate it, but the original binary
/// is passed to `gfx-rs` and `spirv_cross` for translation.
SpirV(Cow<'a, [u32]>),
/// WGSL module as a string slice.
///
/// wgpu-rs will parse it and use for validation. It will attempt
/// to build a SPIR-V module internally and panic otherwise.
///
/// Note: WGSL is not yet supported on the Web.
Wgsl(Cow<'a, str>),
}
/// Descriptor for a shader module.
pub struct ShaderModuleDescriptor<'a> {
/// Debug label of the shader module. This will show up in graphics debuggers for easy identification.
pub label: Label<'a>,
/// Source code for the shader.
pub source: ShaderSource<'a>,
/// Shader handling flags.
pub flags: ShaderFlags,
}
/// Handle to a pipeline layout.
///
/// A `PipelineLayout` object describes the available binding groups of a pipeline.
#[derive(Debug)]
pub struct PipelineLayout {
context: Arc<C>,
id: <C as Context>::PipelineLayoutId,
}
impl Drop for PipelineLayout {
fn drop(&mut self) {
if !thread::panicking() {
self.context.pipeline_layout_drop(&self.id);
}
}
}
/// Handle to a rendering (graphics) pipeline.
///
/// A `RenderPipeline` object represents a graphics pipeline and its stages, bindings, vertex
/// buffers and targets. A `RenderPipeline` may be created with [`Device::create_render_pipeline`].
#[derive(Debug)]
pub struct RenderPipeline {
context: Arc<C>,
id: <C as Context>::RenderPipelineId,
}
impl Drop for RenderPipeline {
fn drop(&mut self) {
if !thread::panicking() {
self.context.render_pipeline_drop(&self.id);
}
}
}
impl RenderPipeline {
/// Get an object representing the bind group layout at a given index.
pub fn get_bind_group_layout(&self, index: u32) -> BindGroupLayout {
let context = Arc::clone(&self.context);
BindGroupLayout {
context,
id: self
.context
.render_pipeline_get_bind_group_layout(&self.id, index),
}
}
}
/// Handle to a compute pipeline.
///
/// A `ComputePipeline` object represents a compute pipeline and its single shader stage.
/// A `ComputePipeline` may be created with [`Device::create_compute_pipeline`].
#[derive(Debug)]
pub struct ComputePipeline {
context: Arc<C>,
id: <C as Context>::ComputePipelineId,
}
impl Drop for ComputePipeline {
fn drop(&mut self) {
if !thread::panicking() {
self.context.compute_pipeline_drop(&self.id);
}
}
}
impl ComputePipeline {
/// Get an object representing the bind group layout at a given index.
pub fn get_bind_group_layout(&self, index: u32) -> BindGroupLayout {
let context = Arc::clone(&self.context);
BindGroupLayout {
context,
id: self
.context
.compute_pipeline_get_bind_group_layout(&self.id, index),
}
}
}
/// Handle to a command buffer on the GPU.
///
/// A `CommandBuffer` represents a complete sequence of commands that may be submitted to a command
/// queue with [`Queue::submit`]. A `CommandBuffer` is obtained by recording a series of commands to
/// a [`CommandEncoder`] and then calling [`CommandEncoder::finish`].
#[derive(Debug)]
pub struct CommandBuffer {
context: Arc<C>,
id: Option<<C as Context>::CommandBufferId>,
}
impl Drop for CommandBuffer {
fn drop(&mut self) {
if !thread::panicking() {
if let Some(ref id) = self.id {
self.context.command_buffer_drop(id);
}
}
}
}
/// Encodes a series of GPU operations.
///
/// A command encoder can record [`RenderPass`]es, [`ComputePass`]es,
/// and transfer operations between driver-managed resources like [`Buffer`]s and [`Texture`]s.
///
/// When finished recording, call [`CommandEncoder::finish`] to obtain a [`CommandBuffer`] which may
/// be submitted for execution.
#[derive(Debug)]
pub struct CommandEncoder {
context: Arc<C>,
id: Option<<C as Context>::CommandEncoderId>,
/// This type should be !Send !Sync, because it represents an allocation on this thread's
/// command buffer.
_p: PhantomData<*const u8>,
}
impl Drop for CommandEncoder {
fn drop(&mut self) {
if !thread::panicking() {
if let Some(id) = self.id.take() {
self.context.command_encoder_drop(&id);
}
}
}
}
/// In-progress recording of a render pass.
#[derive(Debug)]
pub struct RenderPass<'a> {
id: <C as Context>::RenderPassId,
parent: &'a mut CommandEncoder,
}
/// In-progress recording of a compute pass.
#[derive(Debug)]
pub struct ComputePass<'a> {
id: <C as Context>::ComputePassId,
parent: &'a mut CommandEncoder,
}
/// Encodes a series of GPU operations into a reusable "render bundle".
///
/// It only supports a handful of render commands, but it makes them reusable. [`RenderBundle`]s
/// can be executed onto a [`CommandEncoder`] using [`RenderPass::execute_bundles`].
///
/// Executing a [`RenderBundle`] is often more efficient then issuing the underlying commands manually.
#[derive(Debug)]
pub struct RenderBundleEncoder<'a> {
context: Arc<C>,
id: <C as Context>::RenderBundleEncoderId,
_parent: &'a Device,
/// This type should be !Send !Sync, because it represents an allocation on this thread's
/// command buffer.
_p: PhantomData<*const u8>,
}
/// Pre-prepared reusable bundle of GPU operations.
///
/// It only supports a handful of render commands, but it makes them reusable. [`RenderBundle`]s
/// can be executed onto a [`CommandEncoder`] using [`RenderPass::execute_bundles`].
///
/// Executing a [`RenderBundle`] is often more efficient then issuing the underlying commands manually.
#[derive(Debug)]
pub struct RenderBundle {
context: Arc<C>,
id: <C as Context>::RenderBundleId,
}
impl Drop for RenderBundle {
fn drop(&mut self) {
if !thread::panicking() {
self.context.render_bundle_drop(&self.id);
}
}
}
/// Handle to a query set.
pub struct QuerySet {
context: Arc<C>,
id: <C as Context>::QuerySetId,
}
impl Drop for QuerySet {
fn drop(&mut self) {
if !thread::panicking() {
self.context.query_set_drop(&self.id);
}
}
}
/// Handle to a command queue on a device.
///
/// A `Queue` executes recorded [`CommandBuffer`] objects and provides convenience methods
/// for writing to [buffers](Queue::write_buffer) and [textures](Queue::write_texture).
#[derive(Debug)]
pub struct Queue {
context: Arc<C>,
id: <C as Context>::QueueId,
}
/// Resource that can be bound to a pipeline.
#[non_exhaustive]
#[derive(Clone, Debug)]
pub enum BindingResource<'a> {
/// Binding is backed by a buffer.
///
/// Corresponds to [`wgt::BufferBindingType::Uniform`] and [`wgt::BufferBindingType::Storage`]
/// with [`BindGroupLayoutEntry::count`] set to None.
Buffer(BufferBinding<'a>),
/// Binding is backed by an array of buffers.
///
/// [`Features::BUFFER_BINDING_ARRAY`] must be supported to use this feature.
///
/// Corresponds to [`wgt::BufferBindingType::Uniform`] and [`wgt::BufferBindingType::Storage`]
/// with [`BindGroupLayoutEntry::count`] set to Some.
BufferArray(&'a [BufferBinding<'a>]),
/// Binding is a sampler.
///
/// Corresponds to [`wgt::BindingType::Sampler`] with [`BindGroupLayoutEntry::count`] set to None.
Sampler(&'a Sampler),
/// Binding is backed by a texture.
///
/// Corresponds to [`wgt::BindingType::Texture`] and [`wgt::BindingType::StorageTexture`] with
/// [`BindGroupLayoutEntry::count`] set to None.
TextureView(&'a TextureView),
/// Binding is backed by an array of textures.
///
/// [`Features::SAMPLED_TEXTURE_BINDING_ARRAY`] must be supported to use this feature.
///
/// Corresponds to [`wgt::BindingType::Texture`] and [`wgt::BindingType::StorageTexture`] with
/// [`BindGroupLayoutEntry::count`] set to Some.
TextureViewArray(&'a [&'a TextureView]),
}
/// Describes the segment of a buffer to bind.
#[derive(Clone, Debug)]
pub struct BufferBinding<'a> {
/// The buffer to bind.
pub buffer: &'a Buffer,
/// Base offset of the buffer. For bindings with `dynamic == true`, this offset
/// will be added to the dynamic offset provided in [`RenderPass::set_bind_group`].
///
/// The offset has to be aligned to [`BIND_BUFFER_ALIGNMENT`].
pub offset: BufferAddress,
/// Size of the binding, or `None` for using the rest of the buffer.
pub size: Option<BufferSize>,
}
/// Operation to perform to the output attachment at the start of a renderpass.
///
/// The render target must be cleared at least once before its content is loaded.
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
#[cfg_attr(feature = "trace", derive(serde::Serialize))]
#[cfg_attr(feature = "replay", derive(serde::Deserialize))]
pub enum LoadOp<V> {
/// Clear with a specified value.
Clear(V),
/// Load from memory.