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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
use std::fs::File;
use std::io::Read;
use std::marker::PhantomData;
use std::mem;
use std::path::Path;
use std::str;

use crate::context::{Context, GLintptr, Program, Shader, UniformLocation};
use crate::resource::{GLPrimitive, GPUVec};

#[path = "../error.rs"]
mod error;

/// Structure encapsulating a program.
pub struct Effect {
    program: Program,
    vshader: Shader,
    fshader: Shader,
}

impl Effect {
    /// Creates a new shader program from two files containing the vertex and fragment shader.
    pub fn new(vshader_path: &Path, fshader_path: &Path) -> Option<Effect> {
        let mut vshader = String::new();
        let mut fshader = String::new();

        if File::open(vshader_path)
            .map(|mut v| v.read_to_string(&mut vshader))
            .is_err()
        {
            return None;
        }

        if File::open(fshader_path)
            .map(|mut f| f.read_to_string(&mut fshader))
            .is_err()
        {
            return None;
        }

        Some(Effect::new_from_str(&vshader[..], &fshader[..]))
    }

    /// Creates a new shader program from strings of the vertex and fragment shader.
    pub fn new_from_str(vshader: &str, fshader: &str) -> Effect {
        let (program, vshader, fshader) = load_shader_program(vshader, fshader);

        Effect {
            program,
            vshader,
            fshader,
        }
    }

    /// Gets a uniform variable from the shader program.
    pub fn get_uniform<T: GLPrimitive>(&self, name: &str) -> Option<ShaderUniform<T>> {
        let ctxt = Context::get();
        let location = ctxt.get_uniform_location(&self.program, name);

        if ctxt.get_error() == 0 {
            if let Some(id) = location {
                let data_type = PhantomData;
                return Some(ShaderUniform { id, data_type });
            }
        }

        None
    }

    /// Gets an attribute from the shader program.
    pub fn get_attrib<T: GLPrimitive>(&self, name: &str) -> Option<ShaderAttribute<T>> {
        let ctxt = Context::get();
        let location = ctxt.get_attrib_location(&self.program, name);

        if ctxt.get_error() == 0 && location != -1 {
            let id = location as u32;
            let data_type = PhantomData;
            return Some(ShaderAttribute { id, data_type });
        }

        None
    }

    /// Make this program active.
    pub fn use_program(&mut self) {
        verify!(Context::get().use_program(Some(&self.program)));
    }
}

impl Drop for Effect {
    fn drop(&mut self) {
        let ctxt = Context::get();
        if verify!(ctxt.is_program(Some(&self.program))) {
            verify!(ctxt.delete_program(Some(&self.program)));
        }
        if verify!(ctxt.is_shader(Some(&self.fshader))) {
            verify!(ctxt.delete_shader(Some(&self.fshader)));
        }
        if verify!(ctxt.is_shader(Some(&self.vshader))) {
            verify!(ctxt.delete_shader(Some(&self.vshader)));
        }
    }
}

/// Structure encapsulating an uniform variable.
pub struct ShaderUniform<T> {
    id: UniformLocation,
    data_type: PhantomData<T>,
}

impl<T: GLPrimitive> ShaderUniform<T> {
    /// Upload a value to this variable.
    pub fn upload(&mut self, value: &T) {
        value.upload(&self.id)
    }
}

/// Structure encapsulating an attribute.
pub struct ShaderAttribute<T> {
    id: u32,
    data_type: PhantomData<T>,
}

impl<T: GLPrimitive> ShaderAttribute<T> {
    /// Disable this attribute.
    pub fn disable(&mut self) {
        verify!(Context::get().disable_vertex_attrib_array(self.id));
    }

    /// Enable this attribute.
    pub fn enable(&mut self) {
        verify!(Context::get().enable_vertex_attrib_array(self.id));
    }

    /// Binds this attribute to a gpu vector.
    pub fn bind(&mut self, vector: &mut GPUVec<T>) {
        vector.bind();

        verify!(Context::get().vertex_attrib_pointer(
            self.id,
            T::size() as i32,
            T::GLTYPE,
            false,
            0,
            0
        ));
    }

    /// Binds this attribute to non contiguous parts of a gpu vector.
    pub fn bind_sub_buffer(&mut self, vector: &mut GPUVec<T>, strides: usize, start_index: usize) {
        unsafe { self.bind_sub_buffer_generic(vector, strides, start_index) }
    }

    /// Binds this attribute to non contiguous parts of a gpu vector.
    ///
    /// The type of the provided GPU buffer is not forced to match the type of this attribute.
    pub unsafe fn bind_sub_buffer_generic<T2: GLPrimitive>(
        &mut self,
        vector: &mut GPUVec<T2>,
        strides: usize,
        start_index: usize,
    ) {
        vector.bind();

        verify!(Context::get().vertex_attrib_pointer(
            self.id,
            T::size() as i32,
            T::GLTYPE,
            false,
            ((strides + 1) * mem::size_of::<T2>()) as i32,
            (start_index * mem::size_of::<T2>()) as GLintptr
        ));
    }
}

/// Loads a shader program using the given source codes for the vertex and fragment shader.
///
/// Fails after displaying opengl compilation errors if the shaders are invalid.
fn load_shader_program(vertex_shader: &str, fragment_shader: &str) -> (Program, Shader, Shader) {
    // Create and compile the vertex shader
    let ctxt = Context::get();
    let vshader = verify!(ctxt
        .create_shader(Context::VERTEX_SHADER)
        .expect("Could not create vertex shader."));

    verify!(ctxt.shader_source(&vshader, vertex_shader));
    verify!(ctxt.compile_shader(&vshader));
    check_shader_error(&vshader);

    // Create and compile the fragment shader
    let fshader = verify!(ctxt
        .create_shader(Context::FRAGMENT_SHADER)
        .expect("Could not create fragment shader."));
    verify!(ctxt.shader_source(&fshader, fragment_shader));
    verify!(ctxt.compile_shader(&fshader));
    check_shader_error(&fshader);

    // Link the vertex and fragment shader into a shader program
    let program = verify!(ctxt.create_program().expect("Could not create program."));
    verify!(ctxt.attach_shader(&program, &vshader));
    verify!(ctxt.attach_shader(&program, &fshader));
    verify!(ctxt.link_program(&program));
    (program, vshader, fshader)
}

/// Checks if a shader handle is valid.
///
/// If it is not valid, it fails with a descriptive error message.
fn check_shader_error(shader: &Shader) {
    let ctxt = Context::get();
    let compiles = ctxt.get_shader_parameter_int(shader, Context::COMPILE_STATUS);

    if compiles == Some(0) {
        if let Some(log) = ctxt.get_shader_info_log(shader) {
            panic!("Shader compilation failed: {}", log);
        } else {
            println!("Shader compilation failed.");
        }
    }
}