1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
use super::types::*;
use std::io::Read;
use rin_util::{AutoLoader, Result, Error};
use std::fs;
use std::path::{Path, PathBuf};
use glin::{self, CreationContext, program::ShaderPrecision};
use super::CreationProxy;
use regex::Regex;

/// Program settings to be used by a glsl program autoloader
#[derive(Clone, Debug)]
pub struct ProgramSettings<P: AsRef<Path> + Clone>{
    /// glsl version, in desktop 330, 400, 420...
    /// in gles 2 or 3
    pub version: usize,
    /// precision of the shaders, by now applied
    /// to vertex and fragment
    pub precision: ShaderPrecision,
    /// enabled extensions by name
    pub extensions: Vec<String>,
    /// add or change defines in the shaders
    pub defines: Vec<(String, String)>,
    /// shader type / path pairs
    pub shaders: Vec<(GLenum, P)>,
    /// shader type / replacement pairs
    /// where replacement is two strings one for search and the second for replace by
    /// every time the shader is realoaded any replacements will be applied
    pub shader_replace: Vec<(GLenum, (String, String))>,
    /// search paths for includes.
    /// includes will be looked for in the same folder as the shader and if not found
    /// there in each of the paths in this vector until found
    pub includes_search_paths: Vec<P>,
    /// includes substitutions that don't come from files in the file system
    /// the key of this hashmap is the name of the include as found in the shaders
    /// the value is the source for the include
    pub includes_dictionary: glin::HashMap<String,String>,
}

impl<P: AsRef<Path> + Clone> ProgramSettings<P>{
    /// Converts this settings into glin::program::Settings by loading
    /// the shaders from the specified paths and turning them into
    /// a source `String`
    pub fn to_glin(&self) -> Result<glin::program::Settings<String>>{
        let mut errors = vec![];
        let mut includes = self.includes_dictionary.clone();
        let shaders = self.shaders.iter().filter_map(|&(ty, ref path)| {
            let shader_file = fs::File::open(path)
                .map_err(|err| format!("{}", err));
            if let Ok(mut shader_file) = shader_file{
                let mut shader_src = String::new();
                let read = shader_file.read_to_string(&mut shader_src)
                    .map_err(|err| format!("{}", err));
                if let Ok(_) = read{
                    shader_src = self.shader_replace.iter()
                        .filter(|(shader_ty, _)| *shader_ty == ty)
                        .fold(shader_src, |src, (_, (from, to))| src.replace(from, to));

                    for (include, path) in includes_paths(
                        path.as_ref().parent().unwrap(),
                        &self.includes_search_paths,
                        &self.includes_dictionary,
                        &shader_src)
                    {
                        let mut include_src = String::new();
                        if let Err(err) = fs::File::open(path)
                            .and_then( |mut file| file.read_to_string(&mut include_src))
                        {
                            errors.push(format!("{}", err))
                        }else{
                            include_src = self.shader_replace.iter()
                                .filter(|(shader_ty, _)| *shader_ty == ty)
                                .fold(include_src, |src, (_, (from, to))| src.replace(from, to));
                            includes.insert(include.to_str().unwrap().to_owned(), include_src);
                        }
                    }

                    Some((ty, shader_src))
                }else{
                    errors.push(read.unwrap_err());
                    None
                }
            }else{
                errors.push(shader_file.unwrap_err());
                None
            }
        }).collect::<Vec<_>>();

        if errors.is_empty(){
            Ok(glin::program::Settings{
                version: self.version,
                precision: self.precision,
                extensions: self.extensions.clone(),
                defines: self.defines.clone(),
                bindings: crate::default_attribute_bindings().clone(),
                shaders,
                includes,
                .. Default::default()
            })
        }else{
            Err(Error::new(&errors.join("\n\n")))
        }
    }
}

fn load_program<P: AsRef<Path> + Clone>(gl: &CreationProxy, settings: ProgramSettings<P>) -> Result<glin::Program>{
    let settings = settings.to_glin()?;
    gl.new_program().from_settings(settings)
        .map_err(|e| Error::with_cause("Program load error",e))
}

// Returns a vector of include paths as they are included and their corresponding absolute paths
fn includes_paths<P1,P2>(
    shader_path: P1,
    search_paths: &[P2],
    includes_dictionary: &glin::HashMap<String,String>,
    shader_src: &str) -> Vec<(PathBuf, PathBuf)>
where P1: AsRef<Path>,
      P2: AsRef<Path>
{
    let search = r"#include\s*".to_string() + "\"(.*)\"";
    let re = Regex::new(&search).unwrap();
    let shader_path = shader_path.as_ref().to_owned();
    re.captures_iter(shader_src).flat_map(move |captures|{
        if includes_dictionary.contains_key(&captures[1]) {
            vec![]
        }else{
            let include_path = Path::new(&captures[1]);
            let absolute_path = if include_path.is_absolute(){
                include_path.to_owned()
            }else{
                let mut path = shader_path.join(include_path);
                let mut search_paths = search_paths.iter();
                while !path.exists(){
                    if let Some(search_path) = search_paths.next(){
                        path = search_path.as_ref().join(include_path);
                    }else{
                        break;
                    }
                }

                path
            };

            if let Ok(mut include) = fs::File::open(&absolute_path){
                let mut include_src = String::new();
                include.read_to_string(&mut include_src).unwrap();
                let mut includes = includes_paths(
                    shader_path.clone(),
                    search_paths,
                    includes_dictionary,
                    &include_src);
                includes.push((include_path.to_owned(), absolute_path));
                includes
            }else{
                vec![(include_path.to_owned(), absolute_path)]
            }
        }
    }).collect()
}

pub(crate) fn new_program<P: AsRef<Path> + Clone + 'static>(gl: CreationProxy, settings: ProgramSettings<P>) -> AutoLoader<glin::Program>{
    let paths = {
        let includes = settings.shaders.iter()
            .filter_map(|(ty, path)|{
                if let Ok(mut shader) = fs::File::open(path.as_ref()){
                    let mut shader_src = String::new();
                    shader.read_to_string(&mut shader_src).unwrap();
                    shader_src = settings.shader_replace.iter()
                        .filter(|(shader_ty, _)| shader_ty == ty)
                        .fold(shader_src, |src, (_, (from, to))| src.replace(from, to));
                    Some(includes_paths(
                        path.as_ref().parent().unwrap(),
                        &settings.includes_search_paths,
                        &settings.includes_dictionary,
                        &shader_src))
                }else{
                    None
                }
            })
            .flat_map(|it| it);

        settings.shaders
            .iter()
            .map(|(_ty, path)| path.as_ref().to_owned())
            .chain(includes.map(|(_include, absolute)| absolute))
            .map(|path| path.to_str().unwrap().to_string())
            .collect::<Vec<_>>()
    };

    AutoLoader::new(
        paths,
        move || load_program(&gl, settings.clone())
    )
}