Crate wgsl_bindgen

Source
Expand description

ยงwgsl_bindgen

๐Ÿš€ Generate typesafe Rust bindings from WGSL shaders for wgpu

wgsl_bindgen transforms your WGSL shader development workflow by automatically generating Rust types, constants, and boilerplate code that perfectly match your shaders. Powered by naga-oil, it integrates seamlessly into your build process to catch shader-related errors at compile time rather than runtime.

ยง๐ŸŽฏ Key Benefits

  • ๐Ÿ›ก๏ธ Type Safety: Catch shader binding mismatches at compile time
  • ๐Ÿ”„ Automatic Sync: Changes to WGSL automatically update Rust bindings
  • ๐Ÿ“ Reduced Boilerplate: Generate tedious wgpu setup code automatically
  • ๐ŸŽฎ Shader-First Workflow: Design in WGSL, get Rust bindings for free
  • ๐Ÿ”ง Flexible: Works with bytemuck, encase, serde, and custom types
  • โšก Fast: Build-time generation with intelligent caching

ยง๐Ÿš€ Quick Example

WGSL Shader (shaders/my_shader.wgsl):

struct Uniforms {
    transform: mat4x4<f32>,
    time: f32,
}

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var my_texture: texture_2d<f32>;
@group(0) @binding(2) var my_sampler: sampler;

Build Script (build.rs):

use wgsl_bindgen::{WgslBindgenOptionBuilder, WgslTypeSerializeStrategy, GlamWgslTypeMap};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    WgslBindgenOptionBuilder::default()
        .workspace_root("shaders")
        .add_entry_point("shaders/my_shader.wgsl")
        .serialization_strategy(WgslTypeSerializeStrategy::Bytemuck)
        .type_map(GlamWgslTypeMap)
        .output("src/shader_bindings.rs")
        .build()?
        .generate()?;
    Ok(())
}

Generated Rust Usage:

โ“˜
// Fully type-safe bindings generated from your WGSL!
let bind_group = my_shader::WgpuBindGroup0::from_bindings(
    device,
    my_shader::WgpuBindGroup0Entries::new(my_shader::WgpuBindGroup0EntriesParams {
        uniforms: uniform_buffer.as_entire_binding(),
        my_texture: &texture_view,  // Type-checked parameter names
        my_sampler: &sampler,       // Matches your WGSL exactly
    })
);
bind_group.set(&mut render_pass); // Simple, safe usage

ยง๐Ÿ“ฆ Generated Code Features

The code generated by wgsl_bindgen provides:

ยงType Safety & Validation

  • โœ… Compile-time struct layout validation when using bytemuck
  • โœ… Type-safe bind group creation with named parameters
  • โœ… Automatic vertex attribute setup with correct offsets and formats
  • โœ… Pipeline layout generation matching your shaderโ€™s resource bindings

ยงConvenience & Ergonomics

  • ๐Ÿ”ง Shader module creation with embedded or file-based sources
  • ๐Ÿ”ง Entry point helpers for vertex/fragment/compute stages
  • ๐Ÿ”ง Constructor functions for structs with proper padding
  • ๐Ÿ”ง Bind group helpers for setting individual or multiple groups

ยงFlexibility & Customization

  • ๐ŸŽ›๏ธ Multiple serialization strategies (bytemuck, encase)
  • ๐ŸŽ›๏ธ Custom type mapping (glam, nalgebra, custom types)
  • ๐ŸŽ›๏ธ Struct field overrides for specific use cases
  • ๐ŸŽ›๏ธ Import system support via naga-oil composer

ยง๐Ÿ› ๏ธ Configuration Options

ยงBasic Configuration

WgslBindgenOptionBuilder::default()
    .workspace_root("shaders")           // Shader directory
    .add_entry_point("shader.wgsl")      // Add shader files
    .output("src/bindings.rs")           // Output file
    .build()?
    .generate()?;

ยงAdvanced Configuration

WgslBindgenOptionBuilder::default()
    .workspace_root("shaders")
    .add_entry_point("pbr.wgsl")
    .add_entry_point("postfx.wgsl")
     
    // Serialization strategy
    .serialization_strategy(WgslTypeSerializeStrategy::Bytemuck)
     
    // Math library integration  
    .type_map(GlamWgslTypeMap)
     
    // Custom type overrides
    .override_struct_field_type(vec![
        ("MyStruct", "my_field", quote!(MyCustomType)).into()
    ])
     
    // Shader embedding options
    .shader_source_type(WgslShaderSourceType::EmbedSource)
     
    // Optional features
    .derive_serde(true)
    .short_constructor(2)
    .skip_hash_check(false)
     
    .output("src/shaders.rs")
    .build()?
    .generate()?;

ยง๐Ÿ” Error Handling

wgsl_bindgen provides detailed error reporting for common issues:

  • Shader compilation errors with source location information
  • Bind group validation (consecutive indices, no duplicates)
  • Type mapping failures with suggestions for fixes
  • Import resolution errors with detailed path resolution info

ยง๐Ÿ“š See Also

Modulesยง

bevy_util
qs
test_helper

Macrosยง

assert_rust_compilation
assert_tokens_snapshot

Structsยง

AdditionalScanDirectory
A struct representing a directory to scan for additional source files.
BindGroupLayoutGenerator
Represents a generator for creating WGSL bind group layout structures.
BindingGenerator
GlamWgslTypeMap
glam types like glam::Vec4 or glam::Mat4. Types not representable by glam like mat2x3<f32> will use the output from RustWgslTypeMap.
ImportPathPart
Import part path used in the import statement
NalgebraWgslTypeMap
nalgebra types like nalgebra::SVector<f64, 4> or nalgebra::SMatrix<f32, 2, 3>.
OverrideBindGroupEntryModulePath
Struct for overriding binding module path of bindgroup entry
OverrideSamplerType
Struct for overriding sampler types for specific bindings
OverrideStruct
This struct is used to create a custom mapping from the wgsl side to rust side, skipping generation of the struct and using the custom one instead. This also means skipping checks for alignment and size when using bytemuck for the struct. This is useful for core primitive types you would want to model in Rust side
OverrideStructAlignment
Struct for overriding alignment of specific structs.
OverrideStructFieldType
Struct for overriding the field type of specific structs.
OverrideTextureFilterability
Struct for overriding texture filterability for specific bindings
PipelineLayoutGenerator
Regex
A compiled regular expression for searching Unicode haystacks.
RustWgslTypeMap
Rust types like [f32; 4] or [[f32; 4]; 4].
SourceFileDir
SourceFilePath
SourceLocation
SourceModuleName
WGSLBindgen
WgpuGetBindingsGeneratorConfig
WgslBindgenOption
WgslBindgenOptionBuilder
Builder for WgslBindgenOption.
WgslMatTypeIter
An iterator over the variants of WgslMatType
WgslShaderIrCapabilities
Allowed IR capabilities.
WgslTypeInfo
Information about a WGSL type including its Rust representation, size, and alignment
WgslVecTypeIter
An iterator over the variants of WgslVecType

Enumsยง

BindResourceType
CreateModuleError
Errors while generating Rust source for a WGSl shader module.
SamplerType
Enum for sampler binding types
ShaderDefValue
WgslBindgenError
Enum representing the possible errors that can occur in the wgsl_bindgen process.
WgslBindgenOptionBuilderError
Error type for WgslBindgenOptionBuilder
WgslMatType
The WgslType enum represents various Wgsl matrices. See spec
WgslShaderSourceType
An enum representing the source type that will be generated for the output.
WgslType
The WgslType enum represents various WGSL types, such as vectors and matrices. See spec
WgslTypeSerializeStrategy
Enum representing the possible serialization strategies for WGSL types.
WgslTypeVisibility
An enum representing the visibility of the type generated in the output
WgslVecType
The WgslType enum represents various WGSL vectors. See spec

Traitsยง

GetBindingsGeneratorConfig
WgslTypeMapBuild
A trait for building WgslType to TokenStream map.

Functionsยง

pretty_print

Type Aliasesยง

FastIndexMap
Insertion-order-preserving hash map (IndexMap<K, V>), but with the same hasher as FastHashMap<K, V> (faster but not resilient to DoS attacks).
FxIndexMap
FxIndexSet
WgslTypeMap