T4 Refraction (Milestone 2)

T4.1 Add refract() to calculate the refrac vector direction (vec3.h)

Add refract() in vec3.h to calculate the refrac vector direction

Add refract() at the end of vec3.h, outside the vec3 class.

inline vec3 refract(const vec3& uv, const vec3& n, double etai_over_etat) {
    auto cos_theta = std::fmin(dot(-uv, n), 1.0);
    vec3 r_out_perp =  etai_over_etat * (uv + cos_theta*n);
    vec3 r_out_parallel = -std::sqrt(std::fabs(1.0 - r_out_perp.length_squared())) * n;
    return r_out_perp + r_out_parallel;
}

T4.2 Add dielectric material (material.h)

Add class dielectric in material.h

dielectric inherits from material and implements its scatter method using refract()

class material {
//...
};

class lambertian : public material {
//...
};

class metal : public material {
//...
};

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
class dielectric : public material {
  private:
    // Refractive index in vacuum or air, or the ratio of the material's refractive index over
    // the refractive index of the enclosing media
    double refraction_index;

  public:
    dielectric(double refraction_index) : refraction_index(refraction_index) {}

    bool scatter(const ray& r_in, const hit_record& rec, color& attenuation, ray& scattered)
    const override {
        attenuation = color(1.0, 1.0, 1.0);
        double ri = rec.front_face ? (1.0/refraction_index) : refraction_index;

        vec3 unit_direction = unit_vector(r_in.direction());
        // refract vector
        vec3 refracted = refract(unit_direction, rec.normal, ri);

        scattered = ray(rec.p, refracted);
        return true;
    }
};
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

T4.3 Update the scene (main.cpp)

Change material left from metal to dielectric in main()

Build and Run Your Program

If building is successful, run your program in the terminal as follows using your executable name

It is slower then reflection as more refracted rays are involved.

If successful, you are going to see a lovely photo like the following

It is very interesting to notice that you see the sky colour through the bottom half of the glass sphere due to refraction.

T4.4 Add total internal reflection and Schlick Approximation in

Revise the satter() method in class dielectric to add total internal reflection, and schlick approximation for Fresnel effect.

Add new material in main() and add a hollow glass sphere

You are going to see output similar to the following:

Last updated