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

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

material.h

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
#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 @   LOFU  阅读(18)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
点击右上角即可分享
微信分享提示