Advertisement
jezzye13

Rust Rasterizer Hello Triangle

Feb 3rd, 2022
1,298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 2.24 KB | None | 0 0
  1. extern crate minifb;
  2. use glam::{Vec2};
  3.  
  4. use minifb::{Key, Window, WindowOptions};
  5.  
  6. const WIDTH: usize = 500;
  7. const HEIGHT: usize = 500;
  8.  
  9. //clockwise
  10. pub fn edge_function(v0: Vec2, v1: Vec2, p: Vec2) -> f32 {
  11.     (p.x - v0.x) * (v1.y - v0.y) - (p.y - v0.y) * (v1.x - v0.x)
  12. }
  13.  
  14. pub fn index_to_coords(p: usize, width: usize) -> (usize, usize) {
  15.     (p % width, p / width)
  16. }
  17.  
  18. pub fn to_arb8(a: u8, r: u8, g: u8, b: u8) -> u32 {
  19.     let mut argb: u32 = a as u32; //a
  20.     argb = (argb << 8) + r as u32; //r
  21.     argb = (argb << 8) + g as u32; //g
  22.     argb = (argb << 8) + b as u32; //b
  23.     argb
  24. }
  25.  
  26. fn main() {
  27.     let mut buffer: Vec<u32> = vec![0; WIDTH * HEIGHT];
  28.  
  29.     let mut window = Window::new(
  30.         "Hello triangle - ESC to exit",
  31.         WIDTH,
  32.         HEIGHT,
  33.         WindowOptions::default(),
  34.     )
  35.     .unwrap_or_else(|e| {
  36.         panic!("{}", e);
  37.     });
  38.  
  39.     let triangle = [
  40.         glam::vec2(100.0, 100.0),
  41.         glam::vec2(250.0, 400.0),
  42.         glam::vec2(400.0, 100.0),
  43.     ];
  44.  
  45.     let edge = (glam::vec2(0.0, 0.0), Vec2::new(WIDTH as f32, HEIGHT as f32));
  46.  
  47.     // Limit to max ~60 fps update rate
  48.     window.limit_update_rate(Some(std::time::Duration::from_micros(16600)));
  49.  
  50.     for i in 0..buffer.len() {
  51.         let coords = index_to_coords(i, WIDTH);
  52.         // shadow a varible
  53.         let coords = glam::vec2(coords.0 as f32, coords.1 as f32);
  54.         let m2 = edge_function(coords, triangle[0], triangle[1]);
  55.  
  56.         let m0 = edge_function(coords, triangle[1], triangle[2]);
  57.         let m1 = edge_function(coords, triangle[2], triangle[0]);
  58.         /*if m0 >= 0.0 && m1 >= 0.0 && m2 >= 0.0 {
  59.             buffer[i] = to_arb8(255, 0, 255, 0);
  60.         } else {
  61.             buffer[i] = to_arb8(255, 255, 0, 0);
  62.         }*/
  63.        
  64.         buffer[i] = to_arb8(
  65.             255,
  66.             (m2 * 255.0) as u8,
  67.             (m0 * 255.0) as u8,
  68.             (m1 * 255.0) as u8,
  69.         );
  70.     }
  71.  
  72.     while window.is_open() && !window.is_key_down(Key::Escape) {
  73.  
  74.         // We unwrap here as we want this code to exit if it fails. Real applications may want to handle this in a different way
  75.         window
  76.             .update_with_buffer(&buffer, WIDTH, HEIGHT)
  77.             .unwrap();
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement