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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! Exposes the OpenGL [`Shader`](struct.Shader.html) object and related types.

use std::marker::PhantomData;
use std::ptr;
use gl;
use gl::types::*;
use context::{AContext, BaseContext};
use types::{GLObject, GLError};

/// An OpenGL shader object.
///
/// A shader is a small program that runs on the GPU to compute a part of
/// the rendering pipeline. There are two shaders that are necessary for
/// rendering in OpenGL: the vertex shader and the fragment shader. The
/// vertex shader translates geometry from world space into screen space, and
/// the fragment shader determines the final color of each pixel (or
/// 'fragment'). In order to use a shader, it should be linked with
/// a [`Program`](../program/struct.Program.html) to be used for drawing.
///
/// A shader will automatically be deleted after going out of scope.
///
/// # See also
/// [`gl.build_fragment_shader`](trait.ContextShaderBuilderExt.html#tymethod.build_fragment_shader),
/// [`gl.build_vertex_shader`](trait.ContextShaderBuilderExt.html#tymethod.build_vertex_shader),
/// and [`gl.build_shader`](trait.ContextShaderBuilderExt.html#tymethod.build_shader):
/// Build and compile a new shader object.
///
/// [`gl.create_shader`](trait.ContextShaderExt.html#method.create_shader):
/// Create a new, empty shader object.
pub struct Shader {
    gl_id: GLuint,
    _phantom: PhantomData<*mut ()>
}

impl Drop for Shader {
    fn drop(&mut self) {
        unsafe {
            gl::DeleteShader(self.gl_id);
        }
    }
}

impl GLObject for Shader {
    type Id = GLuint;

    unsafe fn from_raw(id: Self::Id) -> Self {
        Shader {
            gl_id: id,
            _phantom: PhantomData
        }
    }

    fn id(&self) -> Self::Id {
        self.gl_id
    }
}



unsafe fn _get_shader_iv(shader: &Shader,
                         pname: GLenum,
                         params: *mut GLint)
{
    gl::GetShaderiv(shader.id(), pname, params);
    dbg_gl_sanity_check! {
        GLError::InvalidEnum => "`pname` is not an accepted value",
        GLError::InvalidValue => "`shader` is not a value generated by OpenGL",
        GLError::InvalidOperation => "`shader` is not a shader object, or `pname` is GL_COMPILE_STATUS, GL_INFO_LOG_LENGTH or GL_SHADER_SOURCE_LENGTH but a shader compiler is not supported",
        _ => "Unknown error"
    }
}

/// A safe interface for creating a shader with a source, and returning an error
/// or panicking if there is an error.
pub struct ShaderBuilder<'a, C: 'a>
    where C: AContext
{
    gl: &'a C,
    ty: ShaderType,
    source: &'a str
}

impl<'a, C: 'a> ShaderBuilder<'a, C>
    where C: AContext
{
    fn new(gl: &'a C, ty: ShaderType, source: &'a str)
        -> Self
    {
        ShaderBuilder { gl: gl, ty: ty, source: source }
    }

    /// Try to compile a shader with the provided options, or `Err` if
    /// a new shader object could not be created or if there was an error
    /// compiling the provided source.
    pub fn try_unwrap(self) -> Result<Shader, GLError> {
        unsafe {
            let mut shader = try! {
                self.gl.create_shader(self.ty).or_else(|_| {
                    let msg = "Error creating OpenGL shader";
                    Err(GLError::Message(msg.to_owned()))
                })
            };

            self.gl.shader_source(&mut shader, self.source);
            try!(self.gl.compile_shader(&mut shader));
            Ok(shader)
        }
    }

    /// Try to compile a shader with the provided options, panicking if
    /// a new shader object could not be created or if there was an error
    /// compiling the provided source.
    pub fn unwrap(self) -> Shader {
        self.try_unwrap().unwrap()
    }
}

/// An extension trait for [`ContextOf`](../context/struct.ContextOf.html) that
/// adds functions to build shaders using the [`ShaderBuilder`]
/// (struct.ShaderBuilder.html) interface.
pub trait ContextShaderBuilderExt: AContext + Sized {
    /// Build a new shader with the provided shader type and shader source.
    ///
    /// # Example
    /// ```no_run
    /// #[macro_use] extern crate glitter;
    /// use glitter::prelude::*;
    ///
    /// # fn main() {
    /// let vertex_source = r##"#version 100
    ///     attribute vec4 position;
    ///
    ///     void main() {
    ///         gl_Position = position;
    ///         _color = color;
    ///     }
    /// "##;
    ///
    /// let gl = unsafe { glitter::Context::current_context() };
    /// let shader = gl.build_shader(glitter::VERTEX_SHADER, vertex_source).unwrap();
    /// # }
    /// ```
    fn build_shader<'a>(&'a self, ty: ShaderType, source: &'a str)
        -> ShaderBuilder<'a, Self>;

    /// Build a new fragment shader with the provided shader source.
    ///
    /// # Example
    /// ```no_run
    /// #[macro_use] extern crate glitter;
    /// use glitter::prelude::*;
    ///
    /// # fn main() {
    /// let fragment_source = r##"#version 100
    ///     void main() {
    ///         gl_FragColor = vec4(1.0, 0.0, 0.0, 0.0);
    ///     }
    /// "##;
    ///
    /// let gl = unsafe { glitter::Context::current_context() };
    /// let shader = gl.build_fragment_shader(fragment_source).unwrap();
    /// # }
    /// ```
    fn build_fragment_shader<'a>(&'a self, source: &'a str)
        -> ShaderBuilder<'a, Self>
    {
        self.build_shader(ShaderType::FragmentShader, source)
    }

    /// Build a new vertex shader with the provided shader source.
    ///
    /// # Example
    /// ```no_run
    /// #[macro_use] extern crate glitter;
    /// use glitter::prelude::*;
    ///
    /// # fn main() {
    /// let vertex_source = r##"#version 100
    ///     attribute vec4 position;
    ///
    ///     void main() {
    ///         gl_Position = position;
    ///         _color = color;
    ///     }
    /// "##;
    ///
    /// let gl = unsafe { glitter::Context::current_context() };
    /// let shader = gl.build_vertex_shader(vertex_source).unwrap();
    /// # }
    /// ```
    fn build_vertex_shader<'a>(&'a self, source: &'a str)
        -> ShaderBuilder<'a, Self>
    {
        self.build_shader(ShaderType::VertexShader, source)
    }
}

impl<C: AContext> ContextShaderBuilderExt for C {
    fn build_shader<'a>(&'a self, ty: ShaderType, source: &'a str)
        -> ShaderBuilder<'a, C>
    {
        ShaderBuilder::new(self, ty, source)
    }
}

/// An extension trait that includes shader-related OpenGL methods.
pub trait ContextShaderExt: BaseContext {
    /// Create a new, uninitialized shader.
    ///
    /// # Safety
    /// Most OpenGL functions that take a shader expect the shader to have
    /// been setup and compiled already. Before using this shader,
    /// it must have its source set using [`gl.shader_source`]
    /// (trait.ContextShaderExt.html#method.shader_source) and compiled with
    /// [`gl.compile_shader`](trait.ContextShaderExt.html#method.compile_shader).
    /// Instead, consider using one of the shader builder functions, which
    /// handle proper setup and compilation automatically.
    ///
    /// # Example
    /// ```no_run
    /// #[macro_use] extern crate glitter;
    /// use glitter::prelude::*;
    ///
    /// # fn main() {
    /// let gl = unsafe { glitter::Context::current_context() };
    /// let vertex_source = r##"#version 100
    ///     attribute vec4 position;
    ///
    ///     void main() {
    ///         gl_Position = position;
    ///     }
    /// "##;
    ///
    /// let shader = unsafe {
    ///     let mut shader = gl.create_shader(glitter::VERTEX_SHADER).unwrap();
    ///     gl.shader_source(&mut shader, vertex_source);
    ///     gl.compile_shader(&mut shader).unwrap();
    ///
    ///     shader
    /// };
    /// # }
    /// ```
    ///
    /// # See also
    /// [`gl.build_shader`](trait.ContextShaderBuilderExt.html#tymethod.build_shader),
    /// [`gl.build_vertex_shader`](trait.ContextShaderBuilderExt.html#method.build_vertex_shader),
    /// and [`gl.build_fragment_shader`](trait.ContextShaderBuilderExt.html#method.build_fragment_shader):
    /// A safe interface for creating and building shaders, which automatically
    /// handle compilation and error checking.
    ///
    /// [`glCreateShader`](http://docs.gl/es2/glCreateShader) OpenGL docs
    unsafe fn create_shader(&self, shader_type: ShaderType)
        -> Result<Shader, ()>
    {
        let id = gl::CreateShader(shader_type.gl_enum());
        dbg_gl_sanity_check! {
            GLError::InvalidEnum => "`shaderType` is not an accepted value",
            _ => "Unknown error"
        }
        if id > 0 {
            Ok(Shader::from_raw(id))
        }
        else {
            Err(())
        }
    }

    /// Set or replace a shader object's source. The shader should be recompiled
    /// after calling this function by using the [`gl.compile_shader`]
    /// (trait.ContextShaderExt.html#method.compile_shader) function
    ///
    /// # See also
    /// [`gl.create_shader`](trait.ContextShaderExt.html#method.create_shader):
    /// A function to create a new, uninitialized shader. Includes an example
    /// of how to use `gl.shader_source`
    ///
    /// [`gl.build_shader`](trait.ContextShaderBuilderExt.html#tymethod.build_shader),
    /// [`gl.build_vertex_shader`](trait.ContextShaderBuilderExt.html#method.build_vertex_shader),
    /// and [`gl.build_fragment_shader`](trait.ContextShaderBuilderExt.html#method.build_fragment_shader):
    /// The preferred way to create and compile a shader object, which skips
    /// the need to directly call `gl.shader_source`.
    ///
    /// [`glShaderSource`](http://docs.gl/es2/glShaderSource) OpenGL docs
    fn shader_source(&self, shader: &mut Shader, source: &str) {
        unsafe {
            let source_ptr = source.as_ptr() as *const GLchar;
            let source_len = source.len() as GLint;

            gl::ShaderSource(shader.id(), 1,
                             &source_ptr as *const *const GLchar,
                             &source_len as *const GLint);
            dbg_gl_error! {
                GLError::InvalidOperation => "`shader` is not a shader object or shader compiler is not supported",
                GLError::InvalidValue => "`shader` is not a value generated by OpenGL or `count` < 0",
                _ => "Unknown error"
            }
        }
    }

    /// Compile the shader's associated source.
    ///
    /// # Panics
    /// This function will panic if an OpenGL error occurs while trying to
    /// compile the shader (determined by calling [`gl.get_error`]
    /// (../context/struct.ContextOf.html#method.get_error)). Note that this
    /// function ***does not*** panic if there was an error *within* the shader;
    /// this function should only panic if the shader is invalid or if
    /// shader compilation is unavailable with the current OpenGL context.
    ///
    /// # Failures
    /// If a compilation error occurs, an `Err` value will be returned
    /// with the compilation error messages (as determined by
    /// [`gl.get_shader_info_log`](trait.ContextShaderExt.html#method.get_shader_info_log)).
    ///
    /// # See also
    /// [`gl.create_shader`](trait.ContextShaderExt.html#method.create_shader):
    /// A function to create a new, uninitialized shader. Includes an example
    /// of how to use `gl.compile_shader`
    ///
    /// [`gl.build_shader`](trait.ContextShaderBuilderExt.html#tymethod.build_shader),
    /// [`gl.build_vertex_shader`](trait.ContextShaderBuilderExt.html#method.build_vertex_shader),
    /// and [`gl.build_fragment_shader`](trait.ContextShaderBuilderExt.html#method.build_fragment_shader):
    /// The preferred way to create and compile a shader object, which skips
    /// the need to directly call `gl.compile_shader`.
    ///
    /// [`glCompileShader`](http://docs.gl/es2/glCompileShader) OpenGL docs
    fn compile_shader(&self, shader: &mut Shader) -> Result<(), GLError> {
        let success = unsafe {
            gl::CompileShader(shader.id());
            dbg_gl_error! {
                GLError::InvalidOperation => "`shader` is not a shader object or shader compiler is not supported",
                GLError::InvalidValue => "`shader` is not a value generated by OpenGL",
                _ => "Unknown error"
            }

            let mut compile_status : GLint = 0;
            _get_shader_iv(shader,
                           gl::COMPILE_STATUS,
                           &mut compile_status as *mut GLint);

            compile_status == gl::TRUE as GLint
        };

        if success {
            Ok(())
        }
        else {
            let msg = match self.get_shader_info_log(&shader) {
                Some(s) => { s },
                None => { String::from("[Unknown shader error]") }
            };
            Err(GLError::Message(msg))
        }
    }

    /// Get the information log associated with a shader. This is used to
    /// get compilation errors, warnings, or other diagnostic information
    /// that may have occurred while trying to compile a shader. Returns `None`
    /// if no such diagnostic information was generated.
    ///
    /// # Example
    /// ```no_run
    /// #[macro_use] extern crate glitter;
    /// use glitter::prelude::*;
    ///
    /// # fn main() {
    /// let fragment_source = r##"#version 100
    ///     void main() {
    ///         float someValue = 1.0 * 2.0;
    ///         gl_FragColor = vec4(1.0, 0.0, 0.0, 0.0);
    ///     }
    /// "##;
    ///
    /// let gl = unsafe { glitter::Context::current_context() };
    /// let shader = gl.build_fragment_shader(fragment_source).unwrap();
    /// if let Some(info) = gl.get_shader_info_log(&shader) {
    ///     println!("Shader compilation info: {}", info);
    ///     // "Shader compilation info: unused variable `someValue` on line 3"
    ///     // (or whatever other diagnostics your graphics device
    ///     //  decides to output)
    /// }
    /// # }
    /// ```
    ///
    /// # See also
    /// [`glGetShaderInfoLog`](http://docs.gl/es2/glGetShaderInfoLog) OpenGL docs
    fn get_shader_info_log(&self, shader: &Shader) -> Option<String> {
        unsafe {
            let mut info_length : GLint = 0;
            _get_shader_iv(shader,
                           gl::INFO_LOG_LENGTH,
                           &mut info_length as *mut GLint);

            if info_length > 0 {
                let mut bytes = Vec::<u8>::with_capacity(info_length as usize);

                gl::GetShaderInfoLog(shader.id(),
                                     info_length,
                                     ptr::null_mut(),
                                     bytes.as_mut_ptr() as *mut GLchar);
                dbg_gl_sanity_check! {
                    GLError::InvalidValue => "`shader` is not a value generated by OpenGL, or `maxLength` < 0",
                    GLError::InvalidOperation => "`shader` is not a shader object",
                    _ => "Unknown error"
                }

                bytes.set_len((info_length - 1) as usize);

                String::from_utf8(bytes).ok()
            }
            else {
                None
            }
        }
    }
}

impl<C: BaseContext> ContextShaderExt for C {

}

gl_enum! {
    /// The possible types of shader objects.
    pub gl_enum ShaderType {
        /// A shader that is used for processing per-vertex data.
        pub const VertexShader as VERTEX_SHADER = gl::VERTEX_SHADER,

        /// A shader that is used for processing per-fragment (per-pixel)
        /// data.
        pub const FragmentShader as FRAGMENT_SHADER = gl::FRAGMENT_SHADER
    }
}