Skip to main content

strata_render/
custom_shader.rs

1//! Low-Level GPU Escape Hatch, Custom WGSL Shader Pipelines, and Compute/Fragment Execution.
2//!
3//! Provides direct access to raw WGSL shader compilation, uniform buffer bindings,
4//! and hardware render pass lifecycle hooks (`GpuRenderContext`).
5
6use crate::math3d::Mat4;
7use std::collections::BTreeMap;
8use std::sync::Arc;
9use strata_layout::Rect;
10
11/// Embedded Standard WGSL 3D Physically-Based Rendering Shader.
12pub const WGSL_PBR_3D_SHADER: &str = r#"
13struct CameraUniforms {
14    view_proj: mat4x4<f32>,
15    eye_pos: vec4<f32>,
16};
17
18struct LightUniforms {
19    dir_light_dir: vec4<f32>,
20    dir_light_color: vec4<f32>,
21    ambient_color: vec4<f32>,
22};
23
24struct MaterialUniforms {
25    base_color: vec4<f32>,
26    roughness: f32,
27    metalness: f32,
28    _padding: vec2<f32>,
29};
30
31@group(0) @binding(0) var<uniform> camera: CameraUniforms;
32@group(0) @binding(1) var<uniform> light: LightUniforms;
33@group(0) @binding(2) var<uniform> material: MaterialUniforms;
34
35struct VertexInput {
36    @location(0) position: vec3<f32>,
37    @location(1) normal: vec3<f32>,
38    @location(2) uv: vec2<f32>,
39};
40
41struct VertexOutput {
42    @builtin(position) clip_position: vec4<f32>,
43    @location(0) world_pos: vec3<f32>,
44    @location(1) world_normal: vec3<f32>,
45    @location(2) uv: vec2<f32>,
46};
47
48@vertex
49fn vs_main(model: VertexInput) -> VertexOutput {
50    var out: VertexOutput;
51    out.world_pos = model.position;
52    out.world_normal = model.normal;
53    out.uv = model.uv;
54    out.clip_position = camera.view_proj * vec4<f32>(model.position, 1.0);
55    return out;
56}
57
58@fragment
59fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
60    let N = normalize(in.world_normal);
61    let L = normalize(light.dir_light_dir.xyz);
62    let V = normalize(camera.eye_pos.xyz - in.world_pos);
63    let H = normalize(L + V);
64
65    let n_dot_l = max(dot(N, L), 0.0);
66    let n_dot_h = max(dot(N, H), 0.0);
67
68    // Blinn-Phong specular term modulated by roughness
69    let spec_power = (1.0 - material.roughness) * 64.0 + 1.0;
70    let specular = pow(n_dot_h, spec_power) * material.metalness;
71
72    let diffuse = light.dir_light_color.rgb * light.dir_light_color.w * n_dot_l;
73    let ambient = light.ambient_color.rgb * light.ambient_color.w;
74
75    let final_rgb = material.base_color.rgb * (ambient + diffuse) + specular;
76    return vec4<f32>(final_rgb, material.base_color.a);
77}
78"#;
79
80/// Embedded WGSL Compute Shader for Parallel Telemetry Signal Processing.
81pub const WGSL_COMPUTE_TELEMETRY_SHADER: &str = r#"
82@group(0) @binding(0) var<storage, read_write> telemetry_samples: array<f32>;
83
84@compute @workgroup_size(64)
85fn cs_main(@builtin(global_invocation_id) global_id: vec3<u32>) {
86    let index = global_id.x;
87    if (index >= arrayLength(&telemetry_samples)) {
88        return;
89    }
90    // High-frequency telemetry noise filtering
91    let val = telemetry_samples[index];
92    telemetry_samples[index] = val * 0.95 + sin(f32(index) * 0.1) * 0.05;
93}
94"#;
95
96/// WGSL Shader Definition.
97#[derive(Debug, Clone, PartialEq)]
98pub struct WgslShaderSource {
99    pub name: String,
100    pub source: String,
101    pub vertex_entry: String,
102    pub fragment_entry: String,
103    pub compute_entry: Option<String>,
104}
105
106impl WgslShaderSource {
107    pub fn pbr_3d() -> Self {
108        Self {
109            name: "strata_pbr_3d".to_string(),
110            source: WGSL_PBR_3D_SHADER.to_string(),
111            vertex_entry: "vs_main".to_string(),
112            fragment_entry: "fs_main".to_string(),
113            compute_entry: None,
114        }
115    }
116
117    pub fn compute_telemetry() -> Self {
118        Self {
119            name: "strata_compute_telemetry".to_string(),
120            source: WGSL_COMPUTE_TELEMETRY_SHADER.to_string(),
121            vertex_entry: String::new(),
122            fragment_entry: String::new(),
123            compute_entry: Some("cs_main".to_string()),
124        }
125    }
126
127    pub fn custom(name: &str, source: &str, vs: &str, fs: &str) -> Self {
128        Self {
129            name: name.to_string(),
130            source: source.to_string(),
131            vertex_entry: vs.to_string(),
132            fragment_entry: fs.to_string(),
133            compute_entry: None,
134        }
135    }
136}
137
138/// Primitive topology for vertex assembly.
139#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
140pub enum PrimitiveTopology {
141    #[default]
142    TriangleList,
143    TriangleStrip,
144    LineList,
145    LineStrip,
146    PointList,
147}
148
149/// Triangle face culling mode.
150#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
151pub enum FaceCullMode {
152    #[default]
153    Back,
154    Front,
155    None,
156}
157
158/// Low-Level Custom Hardware Shader Pipeline Descriptor and Execution State.
159#[derive(Debug, Clone, PartialEq)]
160pub struct CustomShaderPipeline {
161    pub shader: WgslShaderSource,
162    pub topology: PrimitiveTopology,
163    pub cull_mode: FaceCullMode,
164    pub depth_write_enabled: bool,
165    pub depth_compare: bool,
166    pub uniforms_f32: BTreeMap<String, f32>,
167    pub uniforms_vec4: BTreeMap<String, [f32; 4]>,
168    pub uniforms_mat4: BTreeMap<String, [f32; 16]>,
169}
170
171impl CustomShaderPipeline {
172    /// Creates a new custom shader pipeline wrapping the given WGSL source.
173    pub fn new(shader: WgslShaderSource) -> Self {
174        Self {
175            shader,
176            topology: PrimitiveTopology::TriangleList,
177            cull_mode: FaceCullMode::Back,
178            depth_write_enabled: true,
179            depth_compare: true,
180            uniforms_f32: BTreeMap::new(),
181            uniforms_vec4: BTreeMap::new(),
182            uniforms_mat4: BTreeMap::new(),
183        }
184    }
185
186    /// Sets a single scalar f32 uniform parameter.
187    pub fn set_uniform_f32(&mut self, name: &str, value: f32) {
188        self.uniforms_f32.insert(name.to_string(), value);
189    }
190
191    /// Sets a 4-component vector uniform parameter.
192    pub fn set_uniform_vec4(&mut self, name: &str, value: [f32; 4]) {
193        self.uniforms_vec4.insert(name.to_string(), value);
194    }
195
196    /// Sets a 4x4 matrix uniform parameter.
197    pub fn set_uniform_mat4(&mut self, name: &str, matrix: &Mat4) {
198        self.uniforms_mat4.insert(name.to_string(), matrix.m);
199    }
200
201    /// Validates that the shader source is non-empty and entry points are declared.
202    pub fn validate(&self) -> Result<(), String> {
203        if self.shader.source.trim().is_empty() {
204            return Err("WGSL shader source is empty".to_string());
205        }
206        if let Some(cs) = &self.shader.compute_entry {
207            if !self.shader.source.contains(cs) {
208                return Err(format!("Compute entry point '{}' not found in shader", cs));
209            }
210        } else {
211            if !self.shader.source.contains(&self.shader.vertex_entry) {
212                return Err(format!(
213                    "Vertex entry point '{}' not found in shader",
214                    self.shader.vertex_entry
215                ));
216            }
217            if !self.shader.source.contains(&self.shader.fragment_entry) {
218                return Err(format!(
219                    "Fragment entry point '{}' not found in shader",
220                    self.shader.fragment_entry
221                ));
222            }
223        }
224        Ok(())
225    }
226}
227
228/// Execution Context passed to raw GPU rendering hooks.
229pub struct GpuRenderContext<'a> {
230    pub viewport_bounds: Rect,
231    pub delta_time: f32,
232    pub frame_index: u64,
233    pub user_data: Option<&'a dyn std::any::Any>,
234}
235
236impl<'a> GpuRenderContext<'a> {
237    pub fn new(bounds: Rect, dt: f32, frame_index: u64) -> Self {
238        Self {
239            viewport_bounds: bounds,
240            delta_time: dt,
241            frame_index,
242            user_data: None,
243        }
244    }
245}
246
247/// Callback hook for direct raw GPU rendering.
248pub type GpuRenderCallback = Arc<dyn Fn(&mut GpuRenderContext) + Send + Sync>;
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253
254    #[test]
255    fn test_wgsl_pbr_shader_validation() {
256        let pbr_shader = WgslShaderSource::pbr_3d();
257        let pipeline = CustomShaderPipeline::new(pbr_shader);
258        assert!(pipeline.validate().is_ok());
259    }
260
261    #[test]
262    fn test_wgsl_compute_shader_validation() {
263        let compute_shader = WgslShaderSource::compute_telemetry();
264        let pipeline = CustomShaderPipeline::new(compute_shader);
265        assert!(pipeline.validate().is_ok());
266    }
267
268    #[test]
269    fn test_custom_shader_uniform_bindings() {
270        let mut pipeline = CustomShaderPipeline::new(WgslShaderSource::pbr_3d());
271        pipeline.set_uniform_f32("roughness", 0.35);
272        pipeline.set_uniform_vec4("color", [0.2, 0.4, 0.8, 1.0]);
273        pipeline.set_uniform_mat4("model", &Mat4::IDENTITY);
274
275        assert_eq!(*pipeline.uniforms_f32.get("roughness").unwrap(), 0.35);
276        assert_eq!(
277            *pipeline.uniforms_vec4.get("color").unwrap(),
278            [0.2, 0.4, 0.8, 1.0]
279        );
280        assert_eq!(
281            *pipeline.uniforms_mat4.get("model").unwrap(),
282            Mat4::IDENTITY.m
283        );
284    }
285}