Repository navigation
Expand file tree
/
Copy pathgfx.rs
More file actions
2367 lines (2190 loc) · 86.6 KB
/
Copy pathgfx.rs
File metadata and controls
2367 lines (2190 loc) · 86.6 KB
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 null / stubbed implementation
pub mod null;
/// Implemets this interface with a Direct3D12 backend.
#[cfg(target_os = "windows")]
pub mod d3d12;
/// Implemets this interface with a metal backend.
#[cfg(target_os = "macos")]
pub mod mtl;
use crate::os;
use std::any::Any;
use serde::{Deserialize, Serialize};
use std::hash::Hash;
use std::sync::{Arc, Mutex};
use maths_rs::max;
type Error = super::Error;
//
// Common types for deferred resource cleanup
//
/// A thread-safe free list for tracking available heap slot indices
pub struct FreeList {
pub list: Mutex<Vec<usize>>
}
/// Thread safe ref counted free-list that can be safely used in drop traits
pub type FreeListRef = Arc<FreeList>;
impl FreeList {
/// Create a new empty free list
pub fn new() -> FreeListRef {
Arc::new(FreeList {
list: Mutex::new(Vec::new())
})
}
/// Push an index back to the free list for reuse
pub fn push(&self, index: usize) {
let mut list = self.list.lock().unwrap();
list.push(index);
}
/// Pop an index from the free list, returns None if empty
pub fn pop(&self) -> Option<usize> {
let mut list = self.list.lock().unwrap();
list.pop()
}
/// Check if the free list is empty
pub fn is_empty(&self) -> bool {
let list = self.list.lock().unwrap();
list.is_empty()
}
}
impl Default for FreeList {
fn default() -> Self {
FreeList {
list: Mutex::new(Vec::new())
}
}
}
/// Structure to track resources and resource view allocations in `Drop` traits.
/// Generic over the resource type R (e.g. ID3D12Resource for D3D12)
pub struct DropResource<R> {
/// Resources to be dropped after waiting for GPU completion
pub resources: Vec<R>,
/// Frame number when the resource was dropped (0 = not yet initialised)
pub frame: usize,
/// Heap allocation indices to return to the free list
pub heap_allocs: Vec<usize>,
}
impl<R> DropResource<R> {
/// Create a new drop resource entry
pub fn new(resources: Vec<R>, heap_allocs: Vec<usize>) -> Self {
DropResource {
resources,
frame: 0,
heap_allocs,
}
}
}
/// A thread-safe drop list for deferred resource cleanup.
/// Generic over the resource type R.
pub struct DropList<R> {
pub list: Mutex<Vec<DropResource<R>>>
}
/// Thread safe ref counted drop-list that can be safely used in drop traits,
/// tracks the frame a resource was dropped on so it can be waited on
pub type DropListRef<R> = Arc<DropList<R>>;
impl<R> DropList<R> {
/// Create a new empty drop list
pub fn new() -> DropListRef<R> {
Arc::new(DropList {
list: Mutex::new(Vec::new())
})
}
/// Push a resource to the drop list for deferred cleanup
pub fn push(&self, resource: DropResource<R>) {
let mut list = self.list.lock().unwrap();
list.push(resource);
}
/// Cleanup resources that have been waiting long enough.
/// Returns heap allocations that should be returned to the free list.
/// `current_frame` is the current frame index
/// `num_bb` is the number of back buffers (resources must wait this many frames)
pub fn cleanup(&self, current_frame: usize, num_bb: usize, free_list: &FreeListRef) {
// Collect resources to drop OUTSIDE the mutex to avoid holding lock during deallocation
let to_drop: Vec<DropResource<R>> = {
let mut drop_list = self.list.lock().unwrap();
let initial_len = drop_list.len();
// Partition: extract items ready to drop, keep the rest
let mut ready_to_drop = Vec::new();
drop_list.retain_mut(|drop_res| {
if drop_res.frame == 0 {
drop_res.frame = current_frame;
true // keep - just tagged
} else {
let diff = current_frame.saturating_sub(drop_res.frame);
if diff > num_bb {
// Ready to drop - move heap allocs to free list
for alloc in &drop_res.heap_allocs {
free_list.push(*alloc);
}
// Take the resources out for deferred drop
ready_to_drop.push(DropResource {
resources: std::mem::take(&mut drop_res.resources),
frame: drop_res.frame,
heap_allocs: Vec::new(), // already processed
});
false // remove from list
} else {
true // keep - still waiting
}
}
});
if initial_len > 0 || ready_to_drop.len() > 0 {
println!("DropList cleanup: {} items, dropping {}, {} remaining",
initial_len, ready_to_drop.len(), drop_list.len());
}
ready_to_drop
};
// Resources drop here, OUTSIDE the mutex lock
drop(to_drop);
}
}
impl<R> Default for DropList<R> {
fn default() -> Self {
DropList {
list: Mutex::new(Vec::new())
}
}
}
/// Macro to pass data!\[expression\] or data!\[\] (None) to a create function, so you don't have to deduce a 'T'.
#[macro_export]
macro_rules! data {
() => {
None::<&[()]>
};
($input:expr) => {
Some($input)
}
}
/// Macro to inject debug names into gpu resources
#[cfg(target_os = "windows")]
#[macro_export]
macro_rules! gfx_debug_name {
($object:expr, $name:expr) => {
d3d12_debug_name($object, $name);
}
}
/// 3-Dimensional struct for compute shader thread count / thread group size.
#[derive(Copy, Clone)]
pub struct Size3 {
pub x: u32,
pub y: u32,
pub z: u32,
}
/// 3-Dimensional region used for copying resources
#[derive(Copy, Clone)]
pub struct Region {
pub left: u32,
pub top: u32,
pub front: u32,
pub right: u32,
pub bottom: u32,
pub back: u32
}
/// Structure to specify viewport coordinates on a `CmdBuf`.
#[derive(Copy, Clone)]
pub struct Viewport {
/// Top left x coordinate.
pub x: f32,
/// Top left y coordinate.
pub y: f32,
/// Width of the viewport rectangle.
pub width: f32,
/// Height of the viewport rectangle (Y is down).
pub height: f32,
/// Minimum depth of the viewport. Ranges between 0 and 1.
pub min_depth: f32,
/// Maximum depth of the viewport. Ranges between 0 and 1.
pub max_depth: f32,
}
/// Structure to specify scissor rect coordinates on a `CmdBuf`.
#[derive(Copy, Clone)]
pub struct ScissorRect {
// Left x coordinate.
pub left: i32,
// Top y coordinate.
pub top: i32,
/// Right x coordinate.
pub right: i32,
/// Bottom y coordinate.
pub bottom: i32,
}
/// Format for resource types (textures / buffers).
/// n = normalised unsigned integer,
/// u = unsigned integer,
/// i = signed integer,
/// f = float
#[derive(Copy, Clone, Serialize, Deserialize, Hash, PartialEq, Debug)]
pub enum Format {
Unknown,
R16n,
R16u,
R16i,
R16f,
R32u,
R32i,
R32f,
RG16f,
RG16u,
RG16i,
RG32u,
RG32i,
RG32f,
RGB32u,
RGB32i,
RGB32f,
RGBA8nSRGB,
RGBA8n,
RGBA8u,
RGBA8i,
BGRA8n,
BGRX8n,
BGRA8nSRGB,
BGRX8nSRGB,
RGBA16u,
RGBA16i,
RGBA16f,
RGBA32u,
RGBA32i,
RGBA32f,
D32fS8X24u,
D32f,
D24nS8u,
D16n,
BC1n,
BC1nSRGB,
BC2n,
BC2nSRGB,
BC3n,
BC3nSRGB,
BC4n,
BC5n,
}
/// Information to create a device, it contains default heaps for resource views
/// resources will be automatically allocated into these heaps, you can supply custom heaps if necessary.
#[derive(Default)]
pub struct DeviceInfo {
/// optional adapter to choose a specific adapter in the scenario of a multi-adapter system
/// if None is supplied the first non-software emulation adapter would be selected.
pub adapter_name: Option<String>,
/// space for shader resource views, constant buffers and unordered access views.
pub shader_heap_size: usize,
/// space for colour render targets.
pub render_target_heap_size: usize,
/// space for depth stencil targets.
pub depth_stencil_heap_size: usize,
}
/// Information returned from `Device::get_adapter_info`.
#[derive(Clone)]
pub struct AdapterInfo {
/// The chosen adapter a device was created with.
pub name: String,
/// Description of the device.
pub description: String,
/// Dedicated video memory in bytes.
pub dedicated_video_memory: usize,
/// Dedicated system memory in bytes.
pub dedicated_system_memory: usize,
/// Shared system memory in bytes.
pub shared_system_memory: usize,
/// List of available adapter descriptons.
pub available: Vec<String>,
}
/// Information to create a desciptor heap... `Device` will contain default heaps, but you can create your own if required.
pub struct HeapInfo {
/// ie: Shader, RenderTarget, DepthStencil, Sampler.
pub heap_type: HeapType,
/// Total size of the heap in number of resources.
pub num_descriptors: usize,
/// Optional debug name
pub debug_name: Option<String>
}
/// Options for heap types.
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum HeapType {
/// For shader resource view, constant buffer or unordered access.
Shader,
/// For render targets
RenderTarget,
/// For depth stencil targets
DepthStencil,
/// For sampler states
Sampler,
}
/// Allows user specified heaps to be used for creating views when creating textures through `create_texture_with_heap`
/// you can supply `None` for the heap types are not applicable and if a view is requested for a `None` heap the
/// default device heaps will be used instead
pub struct TextureHeapInfo<'stack, D: Device> {
/// Heap to allocate shader resource views and un-ordered access views
pub shader: Option<&'stack mut D::Heap>,
/// Heap to allocate render target views
pub render_target: Option<&'stack mut D::Heap>,
/// Heap to allocate depth stencil views
pub depth_stencil: Option<&'stack mut D::Heap>,
}
/// Information to create a query heap.
pub struct QueryHeapInfo {
/// ie: Timestamp, Occlusion, PipelineStatistics
pub heap_type: QueryType,
/// Total size of the heap in number of queries.
pub num_queries: usize,
}
/// Options for query heap types, and queries
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum QueryType {
/// Used for occlusion query heap or occlusion queries
Occlusion,
/// Can be used in the same heap as occlusion
BinaryOcclusion,
/// Create a heap to contain timestamp queries
Timestamp,
/// Create a heap to contain a structure of `PipelineStatistics`
PipelineStatistics,
/// Create video decoder statistics query and heap
VideoDecodeStatistics,
}
/// GPU pipeline statistics obtain by using a `PipelineStatistics` query
pub struct PipelineStatistics {
pub input_assembler_vertices: u64,
pub input_assembler_primitives: u64,
pub vertex_shader_invocations: u64,
pub pixel_shader_primitives: u64,
pub compute_shader_invocations: u64
}
/// Information to pass to `Device::create_swap_chain`.
pub struct SwapChainInfo {
/// Number of internal buffers to keep behind the scenes, which are swapped between each frame
/// to allow overlapped CPU/GPU command buffer producer / consumer
pub num_buffers: u32,
/// Must be BGRA8n, RGBA8n or RGBA16f.
pub format: Format,
/// Colour for clearing the window when using the backbuffer pass, use None to not clear.
pub clear_colour: Option<ClearColour>,
}
/// Information to create a buffer through `Device::create_buffer`.
#[derive(Copy, Clone)]
pub struct BufferInfo {
/// Indicates how the buffer will be used on the GPU.
pub usage: BufferUsage,
/// Used to indicate if we want to read or write from the CPU, use NONE if possible for best performance.
pub cpu_access: CpuAccessFlags,
/// Data format of the buffer this is is only required for index buffers and can be `gfx::Format::Unknown` otherwise
pub format: Format,
/// The stride of a vertex or structure in bytes.
pub stride: usize,
/// The number of array elements.
pub num_elements: usize,
/// Initial state to start image transition barriers before state
pub initial_state: ResourceState,
}
/// Information to create a shader through `Device::create_shader`.
pub struct ShaderInfo {
/// Type of the shader (Vertex, Fragment, Compute, etc...).
pub shader_type: ShaderType,
/// Optional info to compile from source, if this is none then
/// the shader will be treated as a precompiled byte code blob.
pub compile_info: Option<ShaderCompileInfo>,
}
/// Information required to compile a shader from source code.
pub struct ShaderCompileInfo {
/// The name of the entry point function in the shader to compile.
pub entry_point: String,
/// The target you wish to compile for, this is paltform specific.
/// hlsl: (vs_5_0, ps_5_0, vs_6_0, ps_6_0).
pub target: String,
/// Flags to pass to the compiler.
pub flags: ShaderCompileFlags,
}
/// The stage to which a shader will bind itself.
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub enum ShaderType {
Vertex,
Fragment,
Compute,
RayGen,
AnyHit,
ClosestHit,
Miss,
Intersection,
Callable,
Mesh,
Amplification
}
bitflags! {
/// Device feature flags.
pub struct DeviceFeatureFlags: u32 {
const NONE = 0;
const RAYTRACING = 1<<0;
const MESH_SAHDER = 1<<1;
}
/// Shader compilation flags.
pub struct ShaderCompileFlags: u32 {
/// No flags, default compilation.
const NONE = 0b00000000;
/// Generates shader with debug info
const DEBUG = 0b00000001;
/// Skips optimization for easier debuggability, deterministic results and faster compilation.
const SKIP_OPTIMIZATION = 0b00000010;
}
/// Render target write mask flags.
#[derive(Serialize, Deserialize)]
pub struct WriteMask : u8 {
// Write no colour channels
const NONE = 0;
/// Write the red colour channel
const RED = 1<<0;
/// Write the green colour channel
const GREEN = 1<<1;
/// Write the blue colour channel
const BLUE = 1<<2;
/// Write the alpha channel
const ALPHA = 1<<3;
/// Write (RED|GREEN|BLUE|ALPHA)
const ALL = (1<<4)-1;
}
/// CPU Access flags for buffers or textures.
pub struct CpuAccessFlags: u8 {
/// No CPUT access required, use this for best performance if you do not need to write data to a resource
const NONE = 1<<0;
/// CPU will read data from the resource
const READ = 1<<1;
/// CPU will write data to the resourc
const WRITE = 1<<2;
/// Must be used in conjunction with READ or WRITE, the resource will mapped once and never un-mapped
const PERSISTENTLY_MAPPED = 1<<3;
}
/// Textures can be used in one or more of the following ways
#[derive(Serialize, Deserialize)]
pub struct TextureUsage: u32 {
/// Texture will be only used for data storage and not used on any GPU pipeline stages
const NONE = 0;
/// Texture will be sampled in a shader
const SHADER_RESOURCE = (1 << 0);
/// Used as a read-writable resource in compute shaders
const UNORDERED_ACCESS = (1 << 1);
/// Used as a colour render target
const RENDER_TARGET = (1 << 2);
/// Used as a depth stencil buffer
const DEPTH_STENCIL = (1 << 3);
/// Used as a target for hardware assisted video decoding operations
const VIDEO_DECODE_TARGET = (1 << 4);
/// Indicates the texture will have mip-maps generated at run time
const GENERATE_MIP_MAPS = (1 << 5);
}
/// Describes how a buffer will be used on the GPU.
//#[derive(Copy, Clone, PartialEq)]
pub struct BufferUsage : u32 {
/// Used to simply store data (query results, copy buffers etc)
const NONE = 0;
/// Used as a Vertex buffer binding
const VERTEX = (1 << 0);
/// Used as a Vertex buffer binding
const INDEX = (1 << 1);
/// Used as constant buffer for shader data
const CONSTANT_BUFFER = (1 << 2);
/// Texture will be sampled in a shader
const SHADER_RESOURCE = (1 << 3);
/// Used as a read-writable resource in compute shaders
const UNORDERED_ACCESS = (1 << 4);
/// Used as indirect arguments for `execute_indirect`
const INDIRECT_ARGUMENT_BUFFER = (1 << 5);
/// Used in shader as `AppendStructuredBuffer` and contains a counter element
const APPEND_COUNTER = (1 << 6);
/// Upload only buffer, can be used for acceleration structure geometry or to copy data
const UPLOAD = (1 << 7);
/// Only create the buffer and no views
const BUFFER_ONLY = (1 << 8);
/// Used as acceleration
const ACCELERATION_STRUCTURE = (1 << 9);
}
/// Flags for raytracing geometry
pub struct RaytracingGeometryFlags : u8 {
/// No flags
const NONE = 0;
/// Specifies the implementation must only call the any-hit shader a single time for each primitive in this geometry
const NO_DUPLICATE_ANY_HIT = (1 << 0);
/// Opque Geometry specifies no anyhit shader is called
const OPAQUE = (1<<1);
}
// Flags for building ray tracing acelleration structures
pub struct AccelerationStructureBuildFlags : u8 {
const NONE = 0;
const ALLOW_COMPACTION = (1<<1);
const ALLOW_UPDATE = (1<<2);
const MINIMIZE_MEMORY = (1<<3);
const PERFORM_UPDATE = (1<<4);
const PREFER_FAST_BUILD = (1<<5);
const PREFER_FAST_TRACE = (1<<6);
}
}
/// `PipelineLayout` is required to create a pipeline it describes the layout of resources for access on the GPU.
#[derive(Default, Clone, Serialize, Deserialize)]
pub struct PipelineLayout {
/// Vector of `DescriptorBinding` which are arrays of textures, samplers or structured buffers, etc
pub bindings: Option<Vec<DescriptorBinding>>,
/// Small amounts of data that can be pushed into a command buffer and available as data in shaders
pub push_constants: Option<Vec<PushConstantInfo>>,
/// Static samplers that come along with the pipeline,
pub static_samplers: Option<Vec<SamplerBinding>>,
}
/// Describes the specific resource type for a descriptor binding (from shader reflection).
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum ResourceType {
/// 2D texture (Texture2D)
Texture2D,
/// 2D texture array (Texture2DArray)
Texture2DArray,
/// 3D volume texture (Texture3D)
Texture3D,
/// Cubemap texture (TextureCube)
TextureCube,
/// Multi-sampled 2D texture (Texture2DMS)
Texture2DMS,
/// Read-write 2D texture (RWTexture2D)
RWTexture2D,
/// Read-write 3D texture (RWTexture3D)
RWTexture3D,
/// Structured buffer (StructuredBuffer)
StructuredBuffer,
/// Read-write structured buffer (RWStructuredBuffer)
RWStructuredBuffer,
/// Append structured buffer (AppendStructuredBuffer)
AppendStructuredBuffer,
/// Consume structured buffer (ConsumeStructuredBuffer)
ConsumeStructuredBuffer,
/// Constant buffer (cbuffer/ConstantBuffer)
#[serde(alias = "cbuffer")]
ConstantBuffer,
/// Byte address buffer (ByteAddressBuffer)
ByteAddressBuffer,
/// Read-write byte address buffer (RWByteAddressBuffer)
RWByteAddressBuffer,
/// Generic buffer (Buffer)
Buffer,
/// Raytracing acceleration structure
RaytracingAccelerationStructure,
}
/// Describes a range of resources for access on the GPU.
#[derive(Clone, Serialize, Deserialize)]
pub struct DescriptorBinding {
/// The shader stage the resources will be accessible to.
pub visibility: ShaderVisibility,
/// Register index to bind to (supplied in shader).
pub shader_register: u32,
/// Register space to bind to (supplied in shader).
pub register_space: u32,
/// Type of resources in this descriptor binding.
pub binding_type: DescriptorType,
/// Number of descriptors in this table, use `None` for unbounded.
pub num_descriptors: Option<u32>,
/// Resource type from shader compiler (e.g. Texture2D, StructuredBuffer, etc.)
#[serde(default)]
pub resource_type: Option<ResourceType>,
}
/// Describes the type of descriptor binding to create.
#[derive(Clone, Copy, Serialize, Deserialize, Hash, PartialEq, Eq)]
pub enum DescriptorType {
/// Used for textures or structured buffers.
ShaderResource,
/// Used for cbuffers.
ConstantBuffer,
/// Used for read-write textures.
UnorderedAccess,
/// Used for texture samplers.
Sampler,
/// Used for push constants
PushConstants
}
/// Describes the visibility of which shader stages can access a descriptor.
#[derive(Copy, Clone, Hash, PartialEq, Eq, Serialize, Deserialize, Default, Debug)]
pub enum ShaderVisibility {
#[default]
All,
Vertex,
Fragment,
Compute,
Mesh,
Amplification,
}
/// View types for creating secondary views for resources
#[derive(Copy, Clone)]
pub enum ResourceView {
ShaderResource,
UnorderedAccess,
ConstantBuffer
}
pub struct ResourceViewInfo {
pub view_type: ResourceView,
pub format: Format,
pub first_element: usize,
pub structure_byte_size: usize,
pub num_elements: usize
}
/// Describes space in the shader to send data to via `CmdBuf::push_constants`.
#[derive(Clone, Serialize, Deserialize)]
pub struct PushConstantInfo {
/// The shader stage the constants will be accessible to.
pub visibility: ShaderVisibility,
/// Register index to bind to (supplied in shader).
pub shader_register: u32,
/// Register space to bind to (supplied in shader).
pub register_space: u32,
/// Number of 32-bit values to push.
pub num_values: u32,
}
/// You can request this based on resource type, register and space (as specified in shader)
#[derive(Clone)]
pub struct PipelineSlotInfo {
/// The slot in the pipeline layout to bind to
pub index: u32,
/// The number of descriptors or the number of 32-bit push constant values, if `None` the table is unbounded
pub count: Option<u32>,
}
/// Input layout describes the layout of vertex buffers bound to the input assembler.
pub type InputLayout = Vec<InputElementInfo>;
/// Describe a single element of an `InputLayoutInfo`.
#[derive(Clone, Serialize, Deserialize)]
pub struct InputElementInfo {
/// Element semantic ie. POSITION, TEXCOORD, COLOR etc.
pub semantic: String,
/// Index of the semantic ie. TEXCOORD0, TEXCOORD1 etc.
pub index: u32,
/// Format of the element size and width.
pub format: Format,
/// The vertex buffer slot this buffer will be bound to.
pub input_slot: u32,
/// Aligned byte offset of this element from the start of the struct.
pub aligned_byte_offset: u32,
/// Vertex or Instance stride.
pub input_slot_class: InputSlotClass,
/// Rate at which to step vertices.
pub step_rate: u32,
}
/// Describes the frequency of which elements are fetched from a vertex input element.
#[derive(Clone, Copy, Serialize, Deserialize)]
pub enum InputSlotClass {
PerVertex,
PerInstance,
}
/// Individual sampler state binding for use in static samplers in a `PipelineLayout`.
#[derive(Copy, Clone, Serialize, Deserialize)]
pub struct SamplerBinding {
/// The shader stage the sampler will be accessible to
pub visibility: ShaderVisibility,
/// Register index to bind to (supplied in shader)
pub shader_register: u32,
/// Register space to bind to (supplied in shader)
pub register_space: u32,
/// Sampler Info
pub sampler_info: SamplerInfo
}
/// Info to create a sampler state object to sample textures in shaders.
#[derive(Copy, Clone, Serialize, Deserialize)]
pub struct SamplerInfo {
pub filter: SamplerFilter,
pub address_u: SamplerAddressMode,
pub address_v: SamplerAddressMode,
pub address_w: SamplerAddressMode,
pub comparison: Option<ComparisonFunc>,
/// Colour is rgba8 packed into a u32
pub border_colour: Option<u32>,
pub mip_lod_bias: f32,
pub max_aniso: u32,
pub min_lod: f32,
pub max_lod: f32,
}
/// Filtering mode for the sampler (controls bilinear and trilinear interpolation).
#[derive(Copy, Clone, Serialize, Deserialize)]
pub enum SamplerFilter {
Point,
Linear,
Anisotropic,
}
/// Address mode for the sampler (controls wrapping and clamping).
#[derive(Copy, Clone, Serialize, Deserialize)]
pub enum SamplerAddressMode {
Wrap,
Mirror,
Clamp,
Border,
MirrorOnce,
}
/// Used for comparison ops in depth testing, samplers.
#[derive(Copy, Clone, Serialize, Deserialize)]
pub enum ComparisonFunc {
Never,
Less,
Equal,
LessEqual,
Greater,
NotEqual,
GreaterEqual,
Always,
}
/// Information to create a pipeline through `Device::create_render_pipeline`.
pub struct RenderPipelineInfo<'stack, D: Device> {
/// Vertex Shader
pub vs: Option<&'stack D::Shader>,
/// Fragment Shader
pub fs: Option<&'stack D::Shader>,
/// Vertex shader input layout
pub input_layout: InputLayout,
/// Layout of shader resources (constant buffers, structured buffers, textures, etc)
pub pipeline_layout: PipelineLayout,
/// Control rasterisation of primitives
pub raster_info: RasterInfo,
/// Control depth test and stencil oprations
pub depth_stencil_info: DepthStencilInfo,
/// Control blending settings for the output merge stage
pub blend_info: BlendInfo,
/// Primitive topolgy oof the input assembler
pub topology: Topology,
/// Only required for Topology::PatchList use 0 as default
pub patch_index: u32,
/// Sample mask for which MSAA samples to write
pub sample_mask: u32,
/// A valid render pass, you can share pipelines across passes providing the render target
/// formats and sample count are the same of the passes you wish to use the pipeline on
pub pass: Option<&'stack D::RenderPass>,
}
/// Indicates how the pipeline interprets vertex data at the input assembler stage
/// This will be also used to infer primitive topology types for geometry or hull shaders
#[derive(Copy, Clone, Serialize, Deserialize)]
pub enum Topology {
Undefined,
PointList,
LineList,
LineStrip,
TriangleList,
TriangleStrip,
LineListAdj,
LineStripAdj,
TriangleListAdj,
TriangleStripAdj,
PatchList,
}
/// Information to create a pipeline through `Device::create_mesh_pipeline`.
pub struct MeshPipelineInfo<'stack, D: Device> {
/// Mesh Shader
pub ms: Option<&'stack D::Shader>,
/// Amplification Shader
pub amps: Option<&'stack D::Shader>,
/// Fragment Shader
pub fs: Option<&'stack D::Shader>,
/// Layout of shader resources (constant buffers, structured buffers, textures, etc)
pub pipeline_layout: PipelineLayout,
/// Control rasterisation of primitives
pub raster_info: RasterInfo,
/// Control depth test and stencil oprations
pub depth_stencil_info: DepthStencilInfo,
/// Control blending settings for the output merge stage
pub blend_info: BlendInfo,
/// Topology of the mesh shader primitive
pub topology: PrimitiveTopology,
/// Sample mask for which MSAA samples to write
pub sample_mask: u32,
/// A valid render pass, you can share pipelines across passes providing the render target
/// formats and sample count are the same of the passes you wish to use the pipeline on
pub pass: Option<&'stack D::RenderPass>,
}
/// Primitive topology for mesh shader pipelines
#[derive(Copy, Clone, Serialize, Deserialize)]
pub enum PrimitiveTopology {
LineList,
TriangleList
}
/// Information to control the rasterisation mode of primitives when using a `RenderPipeline`
#[derive(Clone, Copy, Serialize, Deserialize)]
pub struct RasterInfo {
pub fill_mode: FillMode,
pub cull_mode: CullMode,
pub front_ccw: bool,
pub depth_bias: i32,
pub depth_bias_clamp: f32,
pub slope_scaled_depth_bias: f32,
pub depth_clip_enable: bool,
pub multisample_enable: bool,
pub antialiased_line_enable: bool,
pub forced_sample_count: u32,
pub conservative_raster_mode: bool,
}
/// Polygon fillmode
#[derive(Clone, Copy, Serialize, Deserialize)]
pub enum FillMode {
Wireframe,
Solid,
}
/// Polygon cull mode
#[derive(Clone, Copy, Serialize, Deserialize)]
pub enum CullMode {
None,
Front,
Back,
}
/// Information to control the depth and stencil testing of primitves when using a `RenderPipeline`
#[derive(Clone, Copy, Serialize, Deserialize)]
pub struct DepthStencilInfo {
/// Enable depth testing
pub depth_enabled: bool,
/// Choose to write or not write to the depth buffer
pub depth_write_mask: DepthWriteMask,
pub depth_func: ComparisonFunc,
/// Enable stencil testing
pub stencil_enabled: bool,
pub stencil_read_mask: u8,
pub stencil_write_mask: u8,
pub front_face: StencilInfo,
pub back_face: StencilInfo,
}
/// Write to the depth buffer, or omit writes and just perform depth testing
#[derive(Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum DepthWriteMask {
Zero,
All,
}
/// Stencil info for various outcomes of the depth stencil test
#[derive(Clone, Copy, Serialize, Deserialize)]
pub struct StencilInfo {
pub fail: StencilOp,
pub depth_fail: StencilOp,
pub pass: StencilOp,
pub func: ComparisonFunc,
}
/// Stencil operations
#[derive(Clone, Copy, Serialize, Deserialize)]
pub enum StencilOp {
Keep,
Zero,
Replace,
IncrSat,
DecrSat,
Invert,
Incr,
Decr,
}
/// Information to control blending operations on render targets
#[derive(Default)]
pub struct BlendInfo {
pub alpha_to_coverage_enabled: bool,
/// Separate blending on colour and alpha channels
pub independent_blend_enabled: bool,
/// Separate blend operations for each bout render targets
pub render_target: Vec<RenderTargetBlendInfo>,
}
/// Blending operations for a single render target
#[derive(Clone, Serialize, Deserialize)]
pub struct RenderTargetBlendInfo {
pub blend_enabled: bool,
pub logic_op_enabled: bool,
pub src_blend: BlendFactor,
pub dst_blend: BlendFactor,
pub blend_op: BlendOp,
pub src_blend_alpha: BlendFactor,
pub dst_blend_alpha: BlendFactor,
pub blend_op_alpha: BlendOp,
pub logic_op: LogicOp,
pub write_mask: WriteMask,
}
/// Controls how the source and destination terms in blend equation are derrived
#[derive(Clone, Copy, Serialize, Deserialize)]
pub enum BlendFactor {
Zero,
One,
SrcColour,
InvSrcColour,
SrcAlpha,
InvSrcAlpha,
DstAlpha,
InvDstAlpha,
DstColour,
InvDstColour,
SrcAlphaSat,
BlendFactor,
InvBlendFactor,
Src1Colour,
InvSrc1Colour,
Src1Alpha,
InvSrc1Alpha,
}
/// Controls how the source and destination terms are combined: final = src (op) dest
#[derive(Clone, Copy, Serialize, Deserialize)]
pub enum BlendOp {
Add,
Subtract,
RevSubtract,
Min,
Max,
}
/// The logical operation to configure for a render target blend with logic op enabled
#[derive(Clone, Copy, Serialize, Deserialize)]