blue_engine_core/objects/
shader_builder.rs

1/// Configuration type for ShaderBuilder
2pub type ShaderConfigs = Vec<(String, Box<dyn Fn(Option<std::sync::Arc<str>>) -> String>)>;
3
4/// Helps with building and updating shader code
5pub struct ShaderBuilder {
6    /// the shader itself
7    pub shader: String,
8    /// Should the camera effect be applied
9    pub camera_effect: Option<std::sync::Arc<str>>,
10    /// configurations to be applied to the shader
11    pub configs: ShaderConfigs,
12}
13
14impl ShaderBuilder {
15    /// Creates a new shader builder
16    pub fn new(shader_source: String, camera_effect: Option<std::sync::Arc<str>>) -> Self {
17        let mut shader_builder = Self {
18            shader: shader_source,
19            camera_effect,
20            configs: vec![
21                (
22                    "//@CAMERA_STRUCT".to_string(),
23                    Box::new(|camera_effect| {
24                        if camera_effect.is_some() {
25                            r#"struct CameraUniforms {
26                            camera_matrix: mat4x4<f32>,
27                        };
28                        @group(1) @binding(0)
29                        var<uniform> camera_uniform: CameraUniforms;"#
30                                .to_string()
31                        } else {
32                            "".to_string()
33                        }
34                    }),
35                ),
36                (
37                    "//@CAMERA_VERTEX".to_string(),
38                    Box::new(|camera_effect| {
39                        if camera_effect.is_some() {
40                            r#"out.position = camera_uniform.camera_matrix * model_matrix * (transform_uniform.transform_matrix * vec4<f32>(input.position, 1.0));"#
41                        .to_string()
42                        } else {
43                            r#"out.position = model_matrix * (transform_uniform.transform_matrix * vec4<f32>(input.position, 1.0));"#.to_string()
44                        }
45                    }),
46                ),
47            ],
48        };
49        shader_builder.build();
50
51        shader_builder
52    }
53
54    /// Sets the new shader
55    pub fn set_shader(&mut self, new_shader: String) {
56        self.shader = new_shader;
57        self.build();
58    }
59
60    /// Builds the shader with the configuration defined
61    pub fn build(&mut self) {
62        for i in &self.configs {
63            self.shader = self.shader.replace(&i.0, &i.1(self.camera_effect.clone()));
64        }
65    }
66}