sable-gpu 0.1.0

GPU abstraction layer for Sable Engine - wgpu-based rendering primitives
Documentation
//! Shader loading and management.

use std::borrow::Cow;

use wgpu::{Device, ShaderModule, ShaderModuleDescriptor, ShaderSource};

/// A GPU shader module.
#[derive(Debug)]
pub struct Shader {
    module: ShaderModule,
}

impl Shader {
    /// Create a shader from WGSL source code.
    #[must_use]
    pub fn from_wgsl(device: &Device, source: &str, label: Option<&str>) -> Self {
        let module = device.create_shader_module(ShaderModuleDescriptor {
            label,
            source: ShaderSource::Wgsl(Cow::Borrowed(source)),
        });

        Self { module }
    }

    /// Create a shader from WGSL source code with an owned string.
    #[must_use]
    pub fn from_wgsl_owned(device: &Device, source: String, label: Option<&str>) -> Self {
        let module = device.create_shader_module(ShaderModuleDescriptor {
            label,
            source: ShaderSource::Wgsl(Cow::Owned(source)),
        });

        Self { module }
    }

    /// Get a reference to the underlying shader module.
    #[must_use]
    pub fn module(&self) -> &ShaderModule {
        &self.module
    }
}

/// Default triangle shader source.
pub const TRIANGLE_SHADER: &str = r"
struct VertexInput {
    @location(0) position: vec3<f32>,
    @location(1) color: vec3<f32>,
}

struct VertexOutput {
    @builtin(position) clip_position: vec4<f32>,
    @location(0) color: vec3<f32>,
}

@vertex
fn vs_main(in: VertexInput) -> VertexOutput {
    var out: VertexOutput;
    out.clip_position = vec4<f32>(in.position, 1.0);
    out.color = in.color;
    return out;
}

@fragment
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
    return vec4<f32>(in.color, 1.0);
}
";