wgsl_to_wgpu 0.17.1

Generate typesafe Rust bindings from WGSL shaders to wgpu
Documentation
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
use crate::{
    CreateModuleError, TypePath, indexed_name_to_ident, quote_shader_stages,
    wgsl::buffer_binding_type,
};
use proc_macro2::{Literal, Span, TokenStream};
use quote::quote;
use std::{collections::BTreeMap, num::NonZeroU32};
use syn::Ident;

pub struct GroupData<'a> {
    pub bindings: Vec<GroupBinding<'a>>,
}

pub struct GroupBinding<'a> {
    pub name: String,
    pub binding_index: u32,
    pub binding_type: &'a naga::Type,
    pub address_space: naga::AddressSpace,
    pub visibility: wgpu::ShaderStages,
}

pub fn bind_groups_module(
    module: &naga::Module,
    bind_group_data: &BTreeMap<u32, GroupData>,
) -> TokenStream {
    let bind_groups: Vec<_> = bind_group_data
        .iter()
        .map(|(group_no, group)| {
            let group_name = indexed_name_to_ident("BindGroup", *group_no);

            let layout = bind_group_layout(module, *group_no, group);
            let layout_descriptor = bind_group_layout_descriptor(module, *group_no, group);
            let group_impl = bind_group(module, *group_no, group);

            quote! {
                #[derive(Debug)]
                pub struct #group_name(wgpu::BindGroup);
                #layout
                #layout_descriptor
                #group_impl
            }
        })
        .collect();

    let bind_group_fields: Vec<_> = bind_group_data
        .keys()
        .map(|group_no| {
            let group_name = indexed_name_to_ident("BindGroup", *group_no);
            let field = indexed_name_to_ident("bind_group", *group_no);
            quote!(pub #field: &'a #group_name)
        })
        .collect();

    let group_parameters: Vec<_> = bind_group_data
        .keys()
        .map(|group_no| {
            let group = indexed_name_to_ident("bind_group", *group_no);
            let group_type = indexed_name_to_ident("BindGroup", *group_no);
            quote!(#group: &bind_groups::#group_type)
        })
        .collect();

    // The set function for each bind group already sets the index.
    let set_groups: Vec<_> = bind_group_data
        .keys()
        .map(|group_no| {
            let group = indexed_name_to_ident("bind_group", *group_no);
            quote!(#group.set(pass);)
        })
        .collect();

    let set_bind_groups = quote! {
        pub fn set_bind_groups<P: bind_groups::SetBindGroup>(
            pass: &mut P,
            #(#group_parameters),*
        ) {
            #(#set_groups)*
        }
    };

    if bind_groups.is_empty() {
        // Don't include empty modules.
        quote!()
    } else {
        // Create a module to avoid name conflicts with user structs.
        quote! {
            pub mod bind_groups {
                #(#bind_groups)*

                #[derive(Debug, Copy, Clone)]
                pub struct BindGroups<'a> {
                    #(#bind_group_fields),*
                }

                impl BindGroups<'_> {
                    pub fn set<P: SetBindGroup>(&self, pass: &mut P) {
                        #(self.#set_groups)*
                    }
                }

                // Support both compute and render passes.
                pub trait SetBindGroup {
                    fn set_bind_group(
                        &mut self,
                        index: u32,
                        bind_group: &wgpu::BindGroup,
                        offsets: &[wgpu::DynamicOffset],
                    );
                }
                impl SetBindGroup for wgpu::ComputePass<'_> {
                    fn set_bind_group(
                        &mut self,
                        index: u32,
                        bind_group: &wgpu::BindGroup,
                        offsets: &[wgpu::DynamicOffset],
                    ) {
                        self.set_bind_group(index, bind_group, offsets);
                    }
                }
                impl SetBindGroup for wgpu::RenderPass<'_> {
                    fn set_bind_group(
                        &mut self,
                        index: u32,
                        bind_group: &wgpu::BindGroup,
                        offsets: &[wgpu::DynamicOffset],
                    ) {
                        self.set_bind_group(index, bind_group, offsets);
                    }
                }
                impl SetBindGroup for wgpu::RenderBundleEncoder<'_> {
                    fn set_bind_group(
                        &mut self,
                        index: u32,
                        bind_group: &wgpu::BindGroup,
                        offsets: &[wgpu::DynamicOffset],
                    ) {
                        self.set_bind_group(index, bind_group, offsets);
                    }
                }
            }
            #set_bind_groups
        }
    }
}

fn bind_group_layout(module: &naga::Module, group_no: u32, group: &GroupData) -> TokenStream {
    let fields: Vec<_> = group
        .bindings
        .iter()
        .map(|binding| {
            let binding_name = &binding.name;
            let field_name = Ident::new(binding_name, Span::call_site());
            let field_type = binding_field_type(module, &binding.binding_type.inner, binding_name);
            quote!(pub #field_name: #field_type)
        })
        .collect();

    let name = indexed_name_to_ident("BindGroupLayout", group_no);
    quote! {
        #[derive(Debug)]
        pub struct #name<'a> {
            #(#fields),*
        }
    }
}

fn binding_field_type(
    module: &naga::Module,
    ty: &naga::TypeInner,
    binding_name: &String,
) -> TokenStream {
    match ty {
        naga::TypeInner::Struct { .. }
        | naga::TypeInner::Array { .. }
        | naga::TypeInner::Scalar { .. }
        | naga::TypeInner::Atomic { .. }
        | naga::TypeInner::Vector { .. }
        | naga::TypeInner::Matrix { .. } => quote!(wgpu::BufferBinding<'a>),
        naga::TypeInner::Image { .. } => quote!(&'a wgpu::TextureView),
        naga::TypeInner::Sampler { .. } => quote!(&'a wgpu::Sampler),
        naga::TypeInner::BindingArray {
            base,
            size: naga::ArraySize::Constant(size),
        } => {
            let base = binding_field_type(module, &module.types[*base].inner, binding_name);
            let count = Literal::usize_unsuffixed(size.get() as usize);
            quote!(&'a [#base; #count])
        }
        naga::TypeInner::AccelerationStructure { .. } => quote!(&'a wgpu::Tlas),
        ref inner => panic!("Unsupported type `{inner:?}` of '{binding_name}'."),
    }
}

fn bind_group_layout_descriptor(
    module: &naga::Module,
    group_no: u32,
    group: &GroupData,
) -> TokenStream {
    let entries: Vec<_> = group
        .bindings
        .iter()
        .map(|binding| bind_group_layout_entry(module, binding))
        .collect();

    let name = indexed_name_to_ident("LAYOUT_DESCRIPTOR", group_no);
    let label = format!("LayoutDescriptor{group_no}");
    quote! {
        const #name: wgpu::BindGroupLayoutDescriptor = wgpu::BindGroupLayoutDescriptor {
            label: Some(#label),
            entries: &[
                #(#entries),*
            ],
        };
    }
}

fn bind_group_layout_entry(module: &naga::Module, binding: &GroupBinding) -> TokenStream {
    let stages = quote_shader_stages(binding.visibility);

    let binding_index = Literal::usize_unsuffixed(binding.binding_index as usize);
    let buffer_binding_type = buffer_binding_type(binding.address_space);

    let (binding_type, count) = binding_ty_count(
        module,
        &binding.binding_type.inner,
        &binding_index,
        buffer_binding_type,
    );
    let count = count
        .map(|c| {
            // This is already a NonZeroU32, so we can unwrap here.
            let c = Literal::u32_unsuffixed(c.get());
            quote!(Some(std::num::NonZeroU32::new(#c).unwrap()))
        })
        .unwrap_or(quote!(None));

    quote! {
        wgpu::BindGroupLayoutEntry {
            binding: #binding_index,
            visibility: #stages,
            ty: #binding_type,
            count: #count,
        }
    }
}

fn binding_ty_count(
    module: &naga::Module,
    ty: &naga::TypeInner,
    binding_index: &Literal,
    buffer_binding_type: TokenStream,
) -> (TokenStream, Option<NonZeroU32>) {
    match ty {
        naga::TypeInner::Struct { .. }
        | naga::TypeInner::Array { .. }
        | naga::TypeInner::Scalar { .. }
        | naga::TypeInner::Atomic { .. }
        | naga::TypeInner::Vector { .. }
        | naga::TypeInner::Matrix { .. } => (
            quote!(wgpu::BindingType::Buffer {
                ty: #buffer_binding_type,
                has_dynamic_offset: false,
                min_binding_size: None,
            }),
            None,
        ),
        naga::TypeInner::Image {
            dim,
            arrayed,
            class,
            ..
        } => {
            let view_dim = match (dim, arrayed) {
                (naga::ImageDimension::D1, false) => quote!(wgpu::TextureViewDimension::D1),
                (naga::ImageDimension::D2, false) => quote!(wgpu::TextureViewDimension::D2),
                (naga::ImageDimension::D2, true) => quote!(wgpu::TextureViewDimension::D2Array),
                (naga::ImageDimension::D3, false) => quote!(wgpu::TextureViewDimension::D3),
                (naga::ImageDimension::Cube, false) => quote!(wgpu::TextureViewDimension::Cube),
                (naga::ImageDimension::Cube, true) => quote!(wgpu::TextureViewDimension::CubeArray),
                _ => panic!("Unsupported image dimension {dim:?}, arrayed = {arrayed}"),
            };

            match class {
                naga::ImageClass::Sampled { kind, multi } => {
                    let sample_type = match kind {
                        naga::ScalarKind::Sint => quote!(wgpu::TextureSampleType::Sint),
                        naga::ScalarKind::Uint => quote!(wgpu::TextureSampleType::Uint),
                        naga::ScalarKind::Float => {
                            // TODO: Don't assume all textures are filterable.
                            quote!(wgpu::TextureSampleType::Float { filterable: true })
                        }
                        _ => todo!(),
                    };
                    (
                        quote!(wgpu::BindingType::Texture {
                            sample_type: #sample_type,
                            view_dimension: #view_dim,
                            multisampled: #multi,
                        }),
                        None,
                    )
                }
                naga::ImageClass::Depth { multi } => (
                    quote!(wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Depth,
                        view_dimension: #view_dim,
                        multisampled: #multi,
                    }),
                    None,
                ),
                naga::ImageClass::Storage { format, access } => {
                    // TODO: Will the debug implementation always work with the macro?
                    // Assume texture format variants are the same as storage formats.
                    let format = syn::Ident::new(&format!("{format:?}"), Span::call_site());
                    let storage_access = storage_access(*access);

                    (
                        quote!(wgpu::BindingType::StorageTexture {
                            access: #storage_access,
                            format: wgpu::TextureFormat::#format,
                            view_dimension: #view_dim,
                        }),
                        None,
                    )
                }
                naga::ImageClass::External => {
                    unimplemented!()
                }
            }
        }
        naga::TypeInner::Sampler { comparison } => {
            let sampler_type = if *comparison {
                quote!(wgpu::SamplerBindingType::Comparison)
            } else {
                quote!(wgpu::SamplerBindingType::Filtering)
            };
            (quote!(wgpu::BindingType::Sampler(#sampler_type)), None)
        }
        naga::TypeInner::BindingArray {
            base,
            size: naga::ArraySize::Constant(size),
        } => {
            // Assume that counts for arrays aren't applied recursively.
            let (base, _) = binding_ty_count(
                module,
                &module.types[*base].inner,
                binding_index,
                buffer_binding_type,
            );
            (base, Some(*size))
        }
        naga::TypeInner::AccelerationStructure { vertex_return } => (
            quote!(wgpu::BindingType::AccelerationStructure { vertex_return: #vertex_return }),
            None,
        ),
        // TODO: Better error handling.
        ref inner => {
            panic!("Failed to generate BindingType for `{inner:?}` at index {binding_index}.")
        }
    }
}

fn storage_access(access: naga::StorageAccess) -> TokenStream {
    let is_read = access.contains(naga::StorageAccess::LOAD);
    let is_write = access.contains(naga::StorageAccess::STORE);
    match (is_read, is_write) {
        (true, true) => quote!(wgpu::StorageTextureAccess::ReadWrite),
        (true, false) => quote!(wgpu::StorageTextureAccess::ReadOnly),
        (false, true) => quote!(wgpu::StorageTextureAccess::WriteOnly),
        (false, false) => unreachable!(), // shouldn't be possible
    }
}

fn bind_group(module: &naga::Module, group_no: u32, group: &GroupData) -> TokenStream {
    let entries: Vec<_> = group
        .bindings
        .iter()
        .map(|binding| {
            let binding_index = Literal::usize_unsuffixed(binding.binding_index as usize);
            let binding_name = &binding.name;
            let field_name = Ident::new(&binding.name, Span::call_site());
            let resource_type =
                resource_ty(module, binding, &binding_index, binding_name, field_name);

            quote! {
                wgpu::BindGroupEntry {
                    binding: #binding_index,
                    resource: #resource_type,
                }
            }
        })
        .collect();

    let bind_group_name = indexed_name_to_ident("BindGroup", group_no);
    let bind_group_layout_name = indexed_name_to_ident("BindGroupLayout", group_no);

    let layout_descriptor_name = indexed_name_to_ident("LAYOUT_DESCRIPTOR", group_no);

    let label = format!("BindGroup{group_no}");

    let group_no = Literal::usize_unsuffixed(group_no as usize);

    quote! {
        impl #bind_group_name {
            pub fn get_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout {
                device.create_bind_group_layout(&#layout_descriptor_name)
            }

            pub fn from_bindings(device: &wgpu::Device, bindings: #bind_group_layout_name) -> Self {
                let bind_group_layout = device.create_bind_group_layout(&#layout_descriptor_name);
                let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
                    layout: &bind_group_layout,
                    entries: &[
                        #(#entries),*
                    ],
                    label: Some(#label),
                });
                Self(bind_group)
            }

            pub fn set<P: SetBindGroup>(&self, pass: &mut P) {
                pass.set_bind_group(#group_no, &self.0, &[]);
            }
        }
    }
}

fn resource_ty(
    module: &naga::Module,
    binding: &GroupBinding<'_>,
    binding_index: &Literal,
    binding_name: &String,
    field_name: Ident,
) -> TokenStream {
    match &binding.binding_type.inner {
        naga::TypeInner::Struct { .. }
        | naga::TypeInner::Array { .. }
        | naga::TypeInner::Scalar { .. }
        | naga::TypeInner::Atomic { .. }
        | naga::TypeInner::Vector { .. }
        | naga::TypeInner::Matrix { .. } => {
            quote!(wgpu::BindingResource::Buffer(bindings.#field_name))
        }
        naga::TypeInner::Image { .. } => {
            quote!(wgpu::BindingResource::TextureView(bindings.#field_name))
        }
        naga::TypeInner::Sampler { .. } => {
            quote!(wgpu::BindingResource::Sampler(bindings.#field_name))
        }
        naga::TypeInner::BindingArray { base, .. } => resource_array_ty(
            &module.types[*base].inner,
            binding_index,
            binding_name,
            field_name,
        ),
        naga::TypeInner::AccelerationStructure { .. } => {
            quote!(wgpu::BindingResource::AccelerationStructure(bindings.#field_name))
        }
        // TODO: Better error handling.
        inner => panic!(
            "Failed to generate BindingType for `{inner:?}` for '{binding_name}' at index {binding_index}.",
        ),
    }
}

fn resource_array_ty(
    ty: &naga::TypeInner,
    binding_index: &Literal,
    binding_name: &String,
    field_name: Ident,
) -> TokenStream {
    match ty {
        naga::TypeInner::Struct { .. }
        | naga::TypeInner::Array { .. }
        | naga::TypeInner::Scalar { .. }
        | naga::TypeInner::Vector { .. }
        | naga::TypeInner::Matrix { .. } => {
            quote!(wgpu::BindingResource::BufferArray(bindings.#field_name))
        }
        naga::TypeInner::Image { .. } => {
            quote!(wgpu::BindingResource::TextureViewArray(bindings.#field_name))
        }
        naga::TypeInner::Sampler { .. } => {
            quote!(wgpu::BindingResource::SamplerArray(bindings.#field_name))
        }
        // TODO: Better error handling.
        inner => panic!(
            "Failed to generate binding array type for `{inner:?}` for '{binding_name}' at index {binding_index}.",
        ),
    }
}

pub fn get_bind_group_data<'a, F>(
    module: &'a naga::Module,
    global_stages: &BTreeMap<String, wgpu::ShaderStages>,
    demangle: F,
) -> Result<BTreeMap<u32, GroupData<'a>>, CreateModuleError>
where
    F: Fn(&str) -> TypePath,
{
    // Use a BTree to sort type and field names by group index.
    // This isn't strictly necessary but makes the generated code cleaner.
    let mut groups = BTreeMap::new();

    for global_handle in module.global_variables.iter() {
        let global = &module.global_variables[global_handle.0];
        if let Some(binding) = &global.binding {
            let group = groups.entry(binding.group).or_insert(GroupData {
                bindings: Vec::new(),
            });
            let binding_type = &module.types[module.global_variables[global_handle.0].ty];

            let global_name = global.name.as_ref().unwrap();

            // Set visibility to all stages that access this binding.
            // This can avoid unneeded binding calls on some backends.
            let visibility = global_stages
                .get(global_name)
                .copied()
                .unwrap_or(wgpu::ShaderStages::NONE);

            let path = demangle(global_name);

            let group_binding = GroupBinding {
                name: path.name,
                binding_index: binding.binding,
                binding_type,
                address_space: global.space,
                visibility,
            };
            // Repeated bindings will probably cause a compile error.
            // We'll still check for it here just in case.
            if group
                .bindings
                .iter()
                .any(|g| g.binding_index == binding.binding)
            {
                return Err(CreateModuleError::DuplicateBinding {
                    binding: binding.binding,
                });
            }
            group.bindings.push(group_binding);
        }
    }

    // wgpu expects bind groups to be consecutive starting from 0.
    if groups.keys().map(|i| *i as usize).eq(0..groups.len()) {
        Ok(groups)
    } else {
        Err(CreateModuleError::NonConsecutiveBindGroups)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{assert_tokens_snapshot, demangle_identity, wgsl};
    use indoc::indoc;

    #[test]
    fn bind_group_data_consecutive_bind_groups() {
        let source = indoc! {r#"
            @group(0) @binding(0) var<uniform> a: vec4<f32>;
            @group(1) @binding(0) var<uniform> b: vec4<f32>;
            @group(2) @binding(0) var<uniform> c: vec4<f32>;

            @fragment
            fn main() {}
        "#};

        let module = naga::front::wgsl::parse_str(source).unwrap();
        let global_stages = wgsl::global_shader_stages(&module);
        assert_eq!(
            3,
            get_bind_group_data(&module, &global_stages, demangle_identity)
                .unwrap()
                .len()
        );
    }

    #[test]
    fn bind_group_data_first_group_not_zero() {
        let source = indoc! {r#"
            @group(1) @binding(0) var<uniform> a: vec4<f32>;

            @fragment
            fn main() {}
        "#};

        let module = naga::front::wgsl::parse_str(source).unwrap();
        let global_stages = wgsl::global_shader_stages(&module);

        assert!(matches!(
            get_bind_group_data(&module, &global_stages, demangle_identity),
            Err(CreateModuleError::NonConsecutiveBindGroups)
        ));
    }

    #[test]
    fn bind_group_data_non_consecutive_bind_groups() {
        let source = indoc! {r#"
            @group(0) @binding(0) var<uniform> a: vec4<f32>;
            @group(1) @binding(0) var<uniform> b: vec4<f32>;
            @group(3) @binding(0) var<uniform> c: vec4<f32>;

            @fragment
            fn main() {}
        "#};

        let module = naga::front::wgsl::parse_str(source).unwrap();
        let global_stages = wgsl::global_shader_stages(&module);

        assert!(matches!(
            get_bind_group_data(&module, &global_stages, demangle_identity),
            Err(CreateModuleError::NonConsecutiveBindGroups)
        ));
    }

    macro_rules! assert_bindgroups_snapshot {
        ($wgsl:expr) => {
            let wgsl = include_str!($wgsl);
            let module = naga::front::wgsl::parse_str(wgsl).unwrap();

            let global_stages = wgsl::global_shader_stages(&module);
            let bind_group_data =
                get_bind_group_data(&module, &global_stages, demangle_identity).unwrap();

            let actual = bind_groups_module(&module, &bind_group_data);
            assert_tokens_snapshot!(actual);
        };
    }

    #[test]
    fn bind_groups_module_compute() {
        assert_bindgroups_snapshot!("data/bindgroup/compute.wgsl");
    }

    #[test]
    fn bind_groups_module_vertex_fragment() {
        // Test different texture and sampler types.
        // TODO: Storage textures.
        assert_bindgroups_snapshot!("data/bindgroup/vertex_fragment.wgsl");
    }

    #[test]
    fn bind_groups_module_vertex() {
        // The actual content of the structs doesn't matter.
        // We only care about the groups and bindings.
        assert_bindgroups_snapshot!("data/bindgroup/vertex.wgsl");
    }

    #[test]
    fn bind_groups_module_fragment() {
        // The actual content of the structs doesn't matter.
        // We only care about the groups and bindings.
        assert_bindgroups_snapshot!("data/bindgroup/fragment.wgsl");
    }
}