fyrox_impl/renderer/cache/
shader.rs

1// Copyright (c) 2019-present Dmitry Stepanov and Fyrox Engine contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in all
11// copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19// SOFTWARE.
20
21use crate::{
22    core::{log::Log, sstorage::ImmutableString},
23    material::shader::{Shader, ShaderResource},
24    renderer::{
25        cache::TemporaryCache,
26        framework::{
27            error::FrameworkError, gpu_program::GpuProgram, server::GraphicsServer, DrawParameters,
28        },
29    },
30};
31use fxhash::FxHashMap;
32
33pub struct RenderPassData {
34    pub program: Box<dyn GpuProgram>,
35    pub draw_params: DrawParameters,
36}
37
38pub struct ShaderSet {
39    pub render_passes: FxHashMap<ImmutableString, RenderPassData>,
40}
41
42impl ShaderSet {
43    pub fn new(server: &dyn GraphicsServer, shader: &Shader) -> Result<Self, FrameworkError> {
44        let mut map = FxHashMap::default();
45        for render_pass in shader.definition.passes.iter() {
46            let program_name = format!("{}_{}", shader.definition.name, render_pass.name);
47            match server.create_program_with_properties(
48                &program_name,
49                &render_pass.vertex_shader,
50                &render_pass.fragment_shader,
51                &shader.definition.resources,
52            ) {
53                Ok(gpu_program) => {
54                    map.insert(
55                        ImmutableString::new(&render_pass.name),
56                        RenderPassData {
57                            program: gpu_program,
58                            draw_params: render_pass.draw_parameters.clone(),
59                        },
60                    );
61                }
62                Err(e) => {
63                    return Err(FrameworkError::Custom(format!(
64                        "Failed to create {program_name} shader' GPU program. Reason: {e:?}"
65                    )));
66                }
67            };
68        }
69
70        Ok(Self { render_passes: map })
71    }
72}
73
74#[derive(Default)]
75pub struct ShaderCache {
76    pub(super) cache: TemporaryCache<ShaderSet>,
77}
78
79impl ShaderCache {
80    pub fn remove(&mut self, shader: &ShaderResource) {
81        let mut state = shader.state();
82        if let Some(shader_state) = state.data() {
83            self.cache.remove(&shader_state.cache_index);
84        }
85    }
86
87    pub fn get(
88        &mut self,
89        server: &dyn GraphicsServer,
90        shader: &ShaderResource,
91    ) -> Option<&ShaderSet> {
92        let mut shader_state = shader.state();
93
94        if let Some(shader_state) = shader_state.data() {
95            match self.cache.get_or_insert_with(
96                &shader_state.cache_index,
97                Default::default(),
98                || ShaderSet::new(server, shader_state),
99            ) {
100                Ok(shader_set) => Some(shader_set),
101                Err(error) => {
102                    Log::err(format!("{error}"));
103                    None
104                }
105            }
106        } else {
107            None
108        }
109    }
110
111    pub fn update(&mut self, dt: f32) {
112        self.cache.update(dt)
113    }
114
115    pub fn clear(&mut self) {
116        self.cache.clear();
117    }
118
119    pub fn alive_count(&self) -> usize {
120        self.cache.alive_count()
121    }
122}