-
Notifications
You must be signed in to change notification settings - Fork 0
/
material.js
97 lines (83 loc) · 2.24 KB
/
material.js
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import { Ray } from "./ray";
import {
add,
dot,
mul,
random_in_unit_sphere,
random_unit_vector,
reflect,
refract,
unit_vector,
Color,
} from "./vec3";
export class Lambertian {
constructor(albedo) {
this.albedo = albedo;
this._type = 'Lambertian';
}
scatter(_, hit_record) {
let scatter_direction = add(hit_record.normal, random_unit_vector());
while (scatter_direction.near_zero()) {
scatter_direction = add(hit_record.normal, random_unit_vector());
}
return {
scattered: new Ray(hit_record.p, scatter_direction),
attenuation: this.albedo,
};
}
}
export class Metal {
constructor(a, f) {
this.albedo = a;
this.fuzz = f;
this._type = 'Metal';
}
scatter(r_in, hit_record) {
const reflected = reflect(unit_vector(r_in.direction), hit_record.normal);
const scattered = new Ray(
hit_record.p,
add(reflected, mul(this.fuzz, random_in_unit_sphere()))
);
const attenuation = this.albedo;
if (dot(scattered.direction, hit_record.normal) > 0) {
return { scattered, attenuation };
} else {
return null;
}
}
}
export class Dielectric {
constructor(index_of_refraction) {
this.ir = index_of_refraction;
this._type = 'Dielectric';
}
scatter(r_in, hit_record) {
const refraction_ratio = hit_record.front_face ? 1 / this.ir : this.ir;
const unit_direction = unit_vector(r_in.direction);
const cos_theta = Math.min(
dot(mul(-1, unit_direction), hit_record.normal),
1
);
const sin_theta = Math.sqrt(1 - cos_theta * cos_theta);
const cannot_refract = refraction_ratio * sin_theta > 1;
let direction;
if (
cannot_refract ||
Dielectric._reflectance(cos_theta, refraction_ratio) > Math.random()
) {
direction = reflect(unit_direction, hit_record.normal);
} else {
direction = refract(unit_direction, hit_record.normal, refraction_ratio);
}
return {
attenuation: new Color(1, 1, 1),
scattered: new Ray(hit_record.p, direction),
};
}
static _reflectance(cosine, ref_idx) {
// Use Schlick's approximation for reflectance.
let r0 = (1 - ref_idx) / (1 + ref_idx);
r0 = r0 * r0;
return r0 + (1 - r0) * Math.pow(1 - cosine, 5);
}
}