shdrlib 0.2.0

High-level shader compilation and rendering library built on wgpu and naga
Documentation
use crate::front::storage::ShaderObject;
use wgpu;

/// A wgpu shader module created from your Naga IR
pub struct WGPUShader {
    pub module: wgpu::ShaderModule,
    pub stage: naga::ShaderStage,
    pub entry_point: String,
}

impl WGPUShader {
    /// Create a wgpu ShaderModule from your ShaderObject
    pub fn from_shader_object(device: &wgpu::Device, shader_obj: &ShaderObject) -> Self {
        // Validate the Naga module first
        let info = naga::valid::Validator::new(
            naga::valid::ValidationFlags::all(),
            naga::valid::Capabilities::all(),
        )
        .validate(&shader_obj.ir.module)
        .expect("Shader validation failed");

        // Convert Naga IR to WGSL string for wgpu
        let wgsl_string = naga::back::wgsl::write_string(
            &shader_obj.ir.module,
            &info,
            naga::back::wgsl::WriterFlags::empty(),
        )
        .expect("Failed to convert Naga to WGSL");

        // Create shader module from WGSL
        let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("shdrlib shader"),
            source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Owned(wgsl_string)),
        });

        WGPUShader {
            module,
            stage: shader_obj.ir.metadata.stage,
            entry_point: shader_obj.ir.metadata.entry_point.clone(),
        }
    }

    /// Create from raw Naga module and metadata
    pub fn from_ir(
        device: &wgpu::Device,
        module: &naga::Module,
        stage: naga::ShaderStage,
        entry_point: String,
    ) -> Self {
        // Validate the Naga module
        let info = naga::valid::Validator::new(
            naga::valid::ValidationFlags::all(),
            naga::valid::Capabilities::all(),
        )
        .validate(module)
        .expect("Shader validation failed");

        // Convert to WGSL
        let wgsl_string = naga::back::wgsl::write_string(
            module,
            &info,
            naga::back::wgsl::WriterFlags::empty(),
        )
        .expect("Failed to convert Naga to WGSL");

        let shader_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("shdrlib shader"),
            source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Owned(wgsl_string)),
        });

        WGPUShader {
            module: shader_module,
            stage,
            entry_point,
        }
    }
}