summaryrefslogtreecommitdiff
path: root/src/material.rs
blob: a654f4dd7399d26227632d63b45439fe40e18a8a (plain)
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
use crate::calculus::calculus::{Ray, Vec3};
use crate::common::Color;
use crate::object::HitRecord;

#[derive(Clone)]
pub enum MaterialType {
    Diffuse,
    Metal(f32), // color fuzz
}

#[derive(Clone)]
pub struct Material {
    pub material_type: MaterialType,
    pub albedo: Color,
}

impl Material {
    pub fn new(albedo: Color, material_type: MaterialType) -> Self {
        let mut material_type = material_type;
        if let MaterialType::Metal(fuzz) = material_type {
            let fuzz = if fuzz <  1.0 { fuzz } else { fuzz };
            material_type = MaterialType::Metal(fuzz);
        }
        Self { albedo, material_type }
    }

    pub fn scatter(&self, r_in: &Ray, rec: &HitRecord, attenuation: &mut Color, scattered: &mut Ray) -> bool {
        scattered.direction = match self.material_type {
            MaterialType::Diffuse => {
                let  scatter_direction = rec.normal.add(&Vec3::random_unit());
                if scatter_direction.is_near_zero() {
                    rec.normal.clone()
                } else {
                    scatter_direction
                }
            }
            MaterialType::Metal(fuzz) => {
                let mut reflected = r_in.reflect(&rec.normal);
                reflected.unit().add(&Vec3::random_unit().scalar_mul(fuzz))

            }
        };
        scattered.origin = rec.position;
        attenuation.r = self.albedo.r;
        attenuation.g = self.albedo.g;
        attenuation.b = self.albedo.b;
        true
    }
}