softrender 0.1.0

Software Renderer in Rust
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
//! Rendering pipeline implementation

use std::sync::Arc;

use rayon::prelude::*;
use rayon::current_num_threads;

use nalgebra::coordinates::XYZW;

use ::utils::clamp;
use ::pixel::Pixel;
use ::mesh::{Mesh, Vertex};

use ::render::geometry::{FaceWinding, ClipVertex, ScreenVertex};
use ::render::framebuffer::FrameBuffer;
use ::render::uniform::Barycentric;

/// Starting point for the rendering pipeline.
///
/// By itself, it only holds the framebuffer and global uniforms,
/// but it spawns the first shader stage using those.
pub struct Pipeline<U, P> where P: Pixel, U: Send + Sync {
    framebuffer: FrameBuffer<P>,
    uniforms: U,
}

/// Vertex shader stage.
///
/// The vertex shader is responsible for transforming all mesh vertices into a form which can be presented on screen (more or less),
/// which usually involved transforming object-space coordinates to world-space, then to camera-space, then finally to projection/clip-space,
/// at which point it and any uniforms are passed back and sent to the fragment shader.
///
/// For a full example of how this works, see the documentation on the `run` method below.
///
/// The vertex shader holds a reference to the pipeline framebuffer and global uniforms,
/// and for the given mesh given to it when created.
/// These cannot be modified while the vertex shader exists.
pub struct VertexShader<'a, V, U: 'a, P: 'static> where V: Send + Sync,
                                                        U: Send + Sync,
                                                        P: Pixel {
    mesh: Arc<Mesh<V>>,
    uniforms: &'a U,
    framebuffer: &'a mut FrameBuffer<P>,
}

/// Fragment shader stage.
///
/// The fragment shader is responsible for determining the color of pixels where the underlying geometry has been projected onto.
/// Usually this is individual triangles that are rasterized and shaded by the fragment shader, but it also supports point-cloud, wireframe,
/// and lines (pairs of vertices considered as endpoints for lines).
///
/// The fragment shader runs several tests before executing the given shader program, including a depth test.
/// If the depth of the geometry (from the camera), is farther away than geometry that has already been rendered,
/// the shader program isn't run at all, since it wouldn't be visible anyway. Additionally,
/// if the geometry is nearer than an existing fragment, the existing fragment is overwritten.
///
/// Uniforms passed from the vertex shader are interpolating inside the triangles using Barycentric interpolation,
/// which is why it must satisfy the [`Barycentric`](../uniform/trait.Barycentric.html) trait, which can be automatically implemented for many types using the
/// `declare_uniforms!` macro. See the documentation on that for more information on how to use it.
pub struct FragmentShader<'a, V, U: 'a, K, P: 'static> where V: Send + Sync,
                                                             U: Send + Sync,
                                                             K: Send + Sync + Barycentric,
                                                             P: Pixel {
    mesh: Arc<Mesh<V>>,
    uniforms: &'a U,
    framebuffer: &'a mut FrameBuffer<P>,
    screen_vertices: Arc<Vec<ScreenVertex<K>>>,
    cull_faces: Option<FaceWinding>,
    blend_func: Arc<Box<Fn(P, P) -> P + Send + Sync>>,
}

///////////////////////

impl<U, P> Pipeline<U, P> where U: Send + Sync,
                                P: Pixel {
    /// Create a new rendering pipeline instance
    pub fn new(framebuffer: FrameBuffer<P>, uniforms: U) -> Pipeline<U, P> {
        assert!(framebuffer.width() > 0, "Framebuffer must have a non-zero width");
        assert!(framebuffer.height() > 0, "Framebuffer must have a non-zero height");

        Pipeline {
            framebuffer: framebuffer,
            uniforms: uniforms,
        }
    }

    /// Start the shading pipeline for a given mesh
    pub fn render_mesh<V>(&mut self, mesh: Arc<Mesh<V>>) -> VertexShader<V, U, P> where V: Send + Sync {
        VertexShader {
            mesh: mesh,
            uniforms: &self.uniforms,
            framebuffer: &mut self.framebuffer,
        }
    }

    /// Returns a reference to the uniforms value
    pub fn uniforms(&self) -> &U { &self.uniforms }
    /// Returns a mutable reference to the uniforms value
    pub fn uniforms_mut(&mut self) -> &mut U { &mut self.uniforms }

    /// Returns a reference to the framebuffer
    pub fn framebuffer(&self) -> &FrameBuffer<P> { &self.framebuffer }
    /// Returns a mutable reference to the framebuffer
    pub fn framebuffer_mut(&mut self) -> &mut FrameBuffer<P> { &mut self.framebuffer }
}

impl<'a, V, U: 'a, P: 'static> VertexShader<'a, V, U, P> where V: Send + Sync,
                                                               U: Send + Sync,
                                                               P: Pixel {
    /// Duplicates all references to internal state to return a cloned vertex shader,
    /// though since the vertex shader itself has very little internal state at this point,
    /// it's not that useful.
    pub fn duplicate<'b>(&'b mut self) -> VertexShader<'b, V, U, P> where 'a: 'b {
        VertexShader {
            mesh: self.mesh.clone(),
            uniforms: self.uniforms,
            framebuffer: self.framebuffer
        }
    }

    /// Executes the vertex shader on every vertex in the mesh,
    /// (hopefully) returning a `ClipVertex` with the transformed vertex in clip-space
    /// and any uniforms to be passed into the fragment shader.
    ///
    /// In case you don't want to research what clip-space is, it's basically the output of the projection transformation,
    /// so in your vertex shader you'd have something like:
    ///
    /// ```ignore
    /// let fragment_shader = vertex_shader.run(|vertex, global_uniforms| {
    ///     let GlobalUniforms { ref view, ref projection, ref model, ref model_inverse_transpose, .. } = *global_uniforms;
    ///     let VertexData { normal, uv } = vertex.vertex_data;
    ///
    ///     // Transform vertex position to world-space
    ///     let world_position = model * vertex.position.to_homogeneous();
    ///
    ///     // Transform normal to world-space
    ///     let normal = (model_inverse_transpose * normal.to_homogeneous()).normalize();
    ///
    ///     // Transform vertex position to clip-space (projection-space)
    ///     let clip_position = projection * view * world_position;
    ///
    ///     // Return the clip-space position and any uniforms to interpolate and pass into the fragment shader
    ///     ClipVertex::new(clip_position, Uniforms {
    ///         position: world_position,
    ///         normal: normal,
    ///         uv: uv,
    ///     })
    /// });
    /// ```
    ///
    /// where `GlobalUniforms`, `VertexData` and `Uniforms` are data structures defined by you.
    ///
    /// See the [`full_example`](https://github.com/novacrazy/rust-softrender/tree/master/full_example) project for this in action.
    pub fn run<S, K>(self, vertex_shader: S) -> FragmentShader<'a, V, U, K, P> where S: Fn(&Vertex<V>, &U) -> ClipVertex<K> + Sync,
                                                                                     K: Send + Sync + Barycentric {
        let VertexShader {
            mesh,
            uniforms,
            framebuffer
        } = self;

        let viewport = framebuffer.viewport();

        let vertices_per_thread = mesh.indices.len() / current_num_threads();

        let screen_vertices = mesh.vertices.par_iter()
                                           .with_min_len(vertices_per_thread)
                                           .map(|vertex| {
                                               vertex_shader(vertex, &*uniforms)
                                                   .normalize(viewport)
                                           }).collect();

        FragmentShader {
            mesh: mesh,
            uniforms: uniforms,
            framebuffer: framebuffer,
            screen_vertices: Arc::new(screen_vertices),
            cull_faces: None,
            // Use empty "normal" blend by default
            blend_func: Arc::new(Box::new(|s, _| s)),
        }
    }
}

/// Fragment returned by the fragment shader, which can either be a color
/// value for the pixel or a discard flag to skip that fragment altogether.
#[derive(Debug, Clone, Copy)]
pub enum Fragment<P> where P: Sized + Pixel {
    /// Discard the fragment altogether, as if it was never there.
    Discard,
    /// Desired color for the pixel
    Color(P)
}

/// Describes the style of lines to be drawn in wireframe rendering mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LineStyle {
    /// Thin, aliased lines drawn using Bresenham's algorithm
    Thin,
    /// Thin, antialiased line drawn using Xiaolin Wu's algorithm
    ThinAA,
}

impl Default for LineStyle {
    fn default() -> LineStyle { LineStyle::ThinAA }
}

impl<'a, V, U: 'a, K, P: 'static> FragmentShader<'a, V, U, K, P> where V: Send + Sync,
                                                                       U: Send + Sync,
                                                                       K: Send + Sync + Barycentric,
                                                                       P: Pixel {
    /// Duplicates all references to internal state to return a cloned fragment shader,
    /// which can be used to efficiently render the same geometry with different
    /// rasterization methods in quick succession.
    pub fn duplicate<'b>(&'b mut self) -> FragmentShader<'b, V, U, K, P> where 'a: 'b {
        FragmentShader {
            mesh: self.mesh.clone(),
            uniforms: self.uniforms,
            framebuffer: self.framebuffer,
            screen_vertices: self.screen_vertices.clone(),
            cull_faces: self.cull_faces.clone(),
            blend_func: self.blend_func.clone()
        }
    }

    /// Cull faces based on winding order. For more information on how and why this works,
    /// check out the documentation for the [`FaceWinding`](../geometry/enum.FaceWinding.html) enum.
    #[inline(always)]
    pub fn cull_faces(&mut self, cull: Option<FaceWinding>) {
        self.cull_faces = cull;
    }

    /// Sets the blend function for blending pixels together.
    ///
    /// The first parameter passed to the blend function is the output of the fragment shader, the source color.
    ///
    /// The second parameter passed to the blend function is the existing value in the framebuffer to blend over.
    ///
    /// You can use the tool [Here](http://www.andersriggelsen.dk/glblendfunc.php) to see how OpenGL does blending,
    /// and choose how you want to blend pixels.
    ///
    /// For a generic alpha-over blend function, check the Wikipedia article [Here](https://en.wikipedia.org/wiki/Alpha_compositing)
    /// for the *over* color function.
    #[inline(always)]
    pub fn set_blend_function<F>(&mut self, f: F) where F: Fn(P, P) -> P + Send + Sync + 'static {
        self.blend_func = Arc::new(Box::new(f));
    }

    /// Render the vertices as a point cloud. Shading is done per-vertex for a single pixel.
    pub fn points<S>(self, fragment_shader: S) where S: Fn(&ScreenVertex<K>, &U) -> Fragment<P> + Send + Sync {
        // Pull all variables out of self so we can borrow them individually.
        let FragmentShader {
            mesh,
            uniforms,
            framebuffer,
            screen_vertices,
            blend_func,
            ..
        } = self;

        let blend_func = &*blend_func;

        // template framebuffer for the render framebuffers, allowing the real framebuffer to be borrowed mutably later on.
        let empty_framebuffer = framebuffer.empty_clone();

        // Only allow as many new empty framebuffer clones as their are running threads, so one framebuffer per thread.
        // This has the benefit of running a large of number of triangles sequentially.
        let points_per_thread = mesh.indices.len() / current_num_threads();

        // Bounding box for points in framebuffer
        let bb = (framebuffer.width() as f32,
                  framebuffer.height() as f32);

        let partial_framebuffers = mesh.indices.par_iter().cloned().with_min_len(points_per_thread).fold(
            || { empty_framebuffer.empty_clone() }, |mut framebuffer: FrameBuffer<P>, index| {
                let ref vertex = screen_vertices[index as usize];

                let XYZW { x, y, z, .. } = *vertex.position;

                // don't render points "behind" or outside of the camera view
                if 0.0 <= x && x < bb.0 && 0.0 <= y && y < bb.1 && z > 0.0 {
                    let px = x as u32;
                    let py = y as u32;

                    if framebuffer.check_coordinate(px, py) {
                        let (fc, fd) = unsafe { framebuffer.pixel_depth_mut(px, py) };

                        if z < *fd {
                            match fragment_shader(vertex, &uniforms) {
                                Fragment::Color(c) => {
                                    *fc = (*blend_func)(c, *fc);
                                    *fd = z;
                                }
                                Fragment::Discard => ()
                            };
                        }
                    }
                }

                framebuffer
            });

        // Merge incoming partial framebuffers in parallel
        partial_framebuffers.reduce_with(|mut a, b| {
            b.merge_into(&mut a, &blend_func);
            a
        }).map(|final_framebuffer| {
            // Merge final framebuffer into external framebuffer
            final_framebuffer.merge_into(framebuffer, &blend_func);
        });
    }

    /// Vertices 0 and 1 are considered a line. Vertices 2 and 3 are considered a line. And so on.
    ///
    /// If the user specifies a non-even number of vertices, then the extra vertex is ignored.
    ///
    /// Equivalent to `GL_LINES` primitive
    pub fn lines<S>(self, fragment_shader: S, style: LineStyle) where S: Fn(&ScreenVertex<K>, &U) -> Fragment<P> + Send + Sync {
        // Pull all variables out of self so we can borrow them individually.
        let FragmentShader {
            mesh,
            uniforms,
            framebuffer,
            screen_vertices,
            blend_func,
            ..
        } = self;

        let blend_func = &*blend_func;

        // Bounding box for the entire view space
        let bb = (framebuffer.width() - 1,
                  framebuffer.height() - 1);

        // template framebuffer for the render framebuffers, allowing the real framebuffer to be borrowed mutably later on.
        let empty_framebuffer = framebuffer.empty_clone();

        // Only allow as many new empty framebuffer clones as their are running threads, so one framebuffer per thread.
        // This has the benefit of running a large of number of triangles sequentially.
        let lines_per_thread = mesh.indices.len() / (2 * current_num_threads());

        let partial_framebuffers = mesh.indices.par_chunks(2).with_min_len(lines_per_thread).filter(|line| line.len() == 2).fold(
            || { empty_framebuffer.empty_clone() }, |mut framebuffer: FrameBuffer<P>, line| {
                let ref a = screen_vertices[line[0] as usize];
                let ref b = screen_vertices[line[1] as usize];

                let (x1, y1) = (a.position.x, a.position.y);
                let (x2, y2) = (b.position.x, b.position.y);

                let d = (x1 - x2).hypot(y1 - y2);

                {
                    let plot_fragment = |x, y, alpha| {
                        if x >= 0 && y >= 0 {
                            let x = x as u32;
                            let y = y as u32;

                            if x <= bb.0 && y <= bb.1 {
                                let d1 = (x1 - x as f32).hypot(y1 - y as f32);

                                let t = d1 / d;

                                let position = a.position * (1.0 - t) + b.position * t;

                                // Don't render pixels "behind" the camera
                                if position.z > 0.0 {
                                    if framebuffer.check_coordinate(x, y) {
                                        let (fc, fd) = unsafe { framebuffer.pixel_depth_mut(x, y) };

                                        if position.z < *fd {
                                            // run fragment shader
                                            let fragment = fragment_shader(&ScreenVertex {
                                                position: position,
                                                uniforms: Barycentric::interpolate((1.0 - t), &a.uniforms,
                                                                                   t, &b.uniforms,
                                                                                   0.0, &b.uniforms),
                                            }, &uniforms);

                                            match fragment {
                                                Fragment::Color(c) => {
                                                    // blend pixels together and set the new depth value
                                                    *fc = (*blend_func)(c.mul_alpha(alpha as f32), *fc);
                                                    *fd = 0.0;
                                                }
                                                Fragment::Discard => ()
                                            };
                                        }
                                    }
                                }
                            }
                        }
                    };

                    match style {
                        LineStyle::Thin => {
                            ::render::line::draw_line_bresenham(x1 as i64, y1 as i64, x2 as i64, y2 as i64, plot_fragment);
                        }
                        LineStyle::ThinAA => {
                            ::render::line::draw_line_xiaolin_wu(x1 as f64, y1 as f64, x2 as f64, y2 as f64, plot_fragment);
                        }
                    }
                }

                framebuffer
            }
        );

        // Merge incoming partial framebuffers in parallel
        partial_framebuffers.reduce_with(|mut a, b| {
            b.merge_into(&mut a, &blend_func);
            a
        }).map(|final_framebuffer| {
            // Merge final framebuffer into external framebuffer
            final_framebuffer.merge_into(framebuffer, &blend_func);
        });
    }

    /// Render a wireframe for every triangle in the mesh. Shading it done along the lines using linear
    /// interpolation for uniforms in the connected vertices.
    pub fn wireframe<S>(self, fragment_shader: S, style: LineStyle) where S: Fn(&ScreenVertex<K>, &U) -> Fragment<P> + Send + Sync {
        // Pull all variables out of self so we can borrow them individually.
        let FragmentShader {
            mesh,
            uniforms,
            framebuffer,
            screen_vertices,
            blend_func,
            ..
        } = self;

        let blend_func = &*blend_func;

        // Bounding box for the entire view space
        let bb = (framebuffer.width() - 1,
                  framebuffer.height() - 1);

        // template framebuffer for the render framebuffers, allowing the real framebuffer to be borrowed mutably later on.
        let empty_framebuffer = framebuffer.empty_clone();

        // Only allow as many new empty framebuffer clones as their are running threads, so one framebuffer per thread.
        // This has the benefit of running a large of number of triangles sequentially.
        let triangles_per_thread = mesh.indices.len() / (3 * current_num_threads());

        let partial_framebuffers = mesh.indices.par_chunks(3).with_min_len(triangles_per_thread).filter(|triangle| triangle.len() == 3).fold(
            || { empty_framebuffer.empty_clone() }, |mut framebuffer: FrameBuffer<P>, triangle| {
                let ref a = screen_vertices[triangle[0] as usize];
                let ref b = screen_vertices[triangle[1] as usize];
                let ref c = screen_vertices[triangle[2] as usize];

                for &(a, b) in &[(a, b), (b, c), (c, a)] {
                    let (x1, y1) = (a.position.x, a.position.y);
                    let (x2, y2) = (b.position.x, b.position.y);

                    let d = (x1 - x2).hypot(y1 - y2);

                    let plot_fragment = |x, y, alpha| {
                        if x >= 0 && y >= 0 {
                            let x = x as u32;
                            let y = y as u32;

                            if x <= bb.0 && y <= bb.1 {
                                let d1 = (x1 - x as f32).hypot(y1 - y as f32);

                                let t = d1 / d;

                                let position = a.position * (1.0 - t) + b.position * t;

                                // Don't render pixels "behind" the camera
                                if position.z > 0.0 {
                                    if framebuffer.check_coordinate(x, y) {
                                        let (fc, fd) = unsafe { framebuffer.pixel_depth_mut(x, y) };

                                        if position.z < *fd {
                                            // run fragment shader
                                            let fragment = fragment_shader(&ScreenVertex {
                                                position: position,
                                                uniforms: Barycentric::interpolate((1.0 - t), &a.uniforms,
                                                                                   t, &b.uniforms,
                                                                                   0.0, &b.uniforms),
                                            }, &uniforms);

                                            match fragment {
                                                Fragment::Color(c) => {
                                                    // blend pixels together and set the new depth value
                                                    *fc = (*blend_func)(c.mul_alpha(alpha as f32), *fc);
                                                    *fd = 0.0;
                                                }
                                                Fragment::Discard => ()
                                            };
                                        }
                                    }
                                }
                            }
                        }
                    };

                    match style {
                        LineStyle::Thin => {
                            ::render::line::draw_line_bresenham(x1 as i64, y1 as i64, x2 as i64, y2 as i64, plot_fragment);
                        }
                        LineStyle::ThinAA => {
                            ::render::line::draw_line_xiaolin_wu(x1 as f64, y1 as f64, x2 as f64, y2 as f64, plot_fragment);
                        }
                    }
                }

                framebuffer
            });

        // Merge incoming partial framebuffers in parallel
        partial_framebuffers.reduce_with(|mut a, b| {
            b.merge_into(&mut a, &blend_func);
            a
        }).map(|final_framebuffer| {
            // Merge final framebuffer into external framebuffer
            final_framebuffer.merge_into(framebuffer, &blend_func);
        });
    }

    /// Rasterize the given vertices as triangles.
    ///
    /// Equivalent to `GL_TRIANGLES`
    pub fn triangles<S>(self, fragment_shader: S) where S: Fn(&ScreenVertex<K>, &U) -> Fragment<P> + Send + Sync {
        // Pull all variables out of self so we can borrow them individually.
        let FragmentShader {
            mesh,
            uniforms,
            framebuffer,
            screen_vertices,
            cull_faces,
            blend_func
        } = self;

        let blend_func = &*blend_func;

        // Bounding box for the entire view space
        let bb = (framebuffer.width() - 1,
                  framebuffer.height() - 1);

        // template framebuffer for the render framebuffers, allowing the real framebuffer to be borrowed mutably later on.
        let empty_framebuffer = framebuffer.empty_clone();

        // Only allow as many new empty framebuffer clones as their are running threads, so one framebuffer per thread.
        // This has the benefit of running a large of number of triangles sequentially.
        let triangles_per_thread = mesh.indices.len() / (3 * current_num_threads());

        let partial_framebuffers = mesh.indices.par_chunks(3).with_min_len(triangles_per_thread).filter(|triangle| {
            // if there are three points at all, go ahead
            if triangle.len() == 3 {
                //TODO: Check if triangle is on screen at all.

                // If there is a winding order for culling,
                // compare it to the triangle winding order,
                // otherwise go ahead
                if let Some(winding) = cull_faces {
                    let ref a = screen_vertices[triangle[0] as usize];
                    let ref b = screen_vertices[triangle[1] as usize];
                    let ref c = screen_vertices[triangle[2] as usize];

                    let (x1, y1) = (a.position.x, a.position.y);
                    let (x2, y2) = (b.position.x, b.position.y);
                    let (x3, y3) = (c.position.x, c.position.y);

                    let area2 = -x2 * y1 + 2.0 * x3 * y1 + x1 * y2 - x3 * y2 + 2.0 * x1 * y3 + x2 * y3;

                    // Check if the winding order matches the desired order
                    if winding == if area2.is_sign_negative() { FaceWinding::Clockwise } else { FaceWinding::CounterClockwise } {
                        true
                    } else {
                        false
                    }
                } else {
                    true
                }
            } else {
                false
            }
        }).fold(|| { empty_framebuffer.empty_clone() }, |mut framebuffer: FrameBuffer<P>, triangle| {
            let ref a = screen_vertices[triangle[0] as usize];
            let ref b = screen_vertices[triangle[1] as usize];
            let ref c = screen_vertices[triangle[2] as usize];

            let (x1, y1) = (a.position.x, a.position.y);
            let (x2, y2) = (b.position.x, b.position.y);
            let (x3, y3) = (c.position.x, c.position.y);

            // find x bounds for the bounding box
            let min_x: u32 = clamp(x1.min(x2).min(x3).floor() as u32, 0, bb.0);
            let max_x: u32 = clamp(x1.max(x2).max(x3).ceil() as u32, 0, bb.0);

            // find y bounds for the bounding box
            let min_y: u32 = clamp(y1.min(y2).min(y3).floor() as u32, 0, bb.1);
            let max_y: u32 = clamp(y1.max(y2).max(y3).ceil() as u32, 0, bb.1);

            let mut py = min_y;

            while py <= max_y {
                let mut px = min_x;

                while px <= max_x {
                    // Real screen position should be in the center of the pixel.
                    let (x, y) = (px as f32 + 0.5,
                                  py as f32 + 0.5);

                    // calculate determinant
                    let det = (y2 - y3) * (x1 - x3) + (x3 - x2) * (y1 - y3);

                    // calculate barycentric coordinates of the current point
                    let u = ((y2 - y3) * (x - x3) + (x3 - x2) * (y - y3)) / det;
                    let v = ((y3 - y1) * (x - x3) + (x1 - x3) * (y - y3)) / det;
                    let w = 1.0 - u - v;

                    // check if the point is inside the triangle at all
                    if u >= 0.0 && v >= 0.0 && w >= 0.0 {
                        // interpolate screen-space position
                        let position = a.position * u + b.position * v + c.position * w;

                        // don't render pixels "behind" the camera
                        if position.z > 0.0 {
                            let (fc, fd) = unsafe { framebuffer.pixel_depth_mut(px, py) };

                            // skip fragments that are behind over previous fragments
                            if position.z < *fd {
                                // run fragment shader
                                let fragment = fragment_shader(&ScreenVertex {
                                    position: position,
                                    // interpolate the uniforms
                                    uniforms: Barycentric::interpolate(u, &a.uniforms,
                                                                       v, &b.uniforms,
                                                                       w, &c.uniforms),
                                }, &uniforms);

                                match fragment {
                                    Fragment::Color(c) => {
                                        // blend pixels together and set the new depth value
                                        *fc = (*blend_func)(c, *fc);
                                        *fd = position.z;
                                    }
                                    Fragment::Discard => ()
                                };
                            }
                        }
                    }

                    px += 1;
                }

                py += 1;
            }

            framebuffer
        });

        // Merge incoming partial framebuffers in parallel
        partial_framebuffers.reduce_with(|mut a, b| {
            b.merge_into(&mut a, &blend_func);
            a
        }).map(|final_framebuffer| {
            // Merge final framebuffer into external framebuffer
            final_framebuffer.merge_into(framebuffer, &blend_func);
        });
    }
}