Ray-Tracing In One Weekend Part4

参考博客:(27条消息) 【Ray-Tracing In One Weekend】第8章 金属材质_杨石兴的博客-CSDN博客

反射光的方向是 v+2b,n为单位向量,因此b的长度是n点乘v,b的方向和n这个法线方向相同,v的方向指向球内,b指向球外,因此需要相减

v3d.h

vec3 reflect(const vec3& v, const vec3& n) {
    return v - 2*dot(v,n)*n;
}

material.h

#ifndef MATERIAL_H
#define MATERIAL_H

#include "rtweekend.h"
#include "hittable.h"
struct hit_record;

class material {
public:
    virtual bool scatter(
        const ray& r_in, const hit_record& rec, color& attenuation, ray& scattered
    ) const = 0;
};
#endif
class lambertian :public material {
public:
    lambertian(const color& a) :albedo(a) {}
    virtual bool scatter(
        const ray& r_in, const hit_record& rec, color& attenuation, ray& scattered
    )const override {
        auto scatter_direction = rec.normal + random_unit_vector();
        // 如果最后的散射方向为0了,则不加那个随机
        if (scatter_direction.near_zero())
            scatter_direction = rec.normal;
        scattered = ray(rec.p, scatter_direction);
        attenuation = albedo;
        return true;
    }
public:
    color albedo;
};

class metal : public material {
public:
    //fuzz是metal材质的扰动
    metal(const color& a,double f) : albedo(a) ,fuzz(f<1?f:1){}

    virtual bool scatter(
        const ray& r_in, const hit_record& rec, color& attenuation, ray& scattered
    ) const override {
        vec3 reflected = reflect(unit_vector(r_in.direction()), rec.normal);
        scattered = ray(rec.p, reflected+fuzz*random_in_unit_sphere());
        attenuation = albedo;
        return (dot(scattered.direction(), rec.normal) > 0);
    }

public:
    color albedo;
    double fuzz;
};

  结果图:

 

 

 

 

 
posted @ 2022-10-31 10:34  LOFU  阅读(17)  评论(0编辑  收藏  举报