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
|
class Material
def initialize(albedo)
@albedo = albedo
end
def attenuation
@albedo
end
def scatter(ray, record)
nil
end
end
class Lambertian < Material
def scatter(ray, record)
scat = record.normal + Vec3.random_in_unit
scat = rec.normal if scat.near_zero?
Ray.new(record.point, scat)
end
end
class Metal < Material
def initialize(albedo, fuzz)
@fuzz = fuzz < 1 ? fuzz : 1
super(albedo)
end
def scatter(ray, record)
refl = ray.direction.reflect(record.normal)
refl = refl.unit + (Vec3.random_in_unit * @fuzz)
if refl.dot(record.normal) > 0
Ray.new(record.point, refl)
else
nil
end
end
end
class Dielectric < Material
def initialize(ref_index)
@ref_index = ref_index
super(Colour.new(1.0, 1.0, 1.0))
end
def scatter(ray, record)
ri = record.front_face ? (1.0 / @ref_index) : @ref_index
unit_dir = ray.direction.unit
costheta = [(-unit_dir).dot(record.normal), 1.0].min
sintheta = (1.0 - costheta ** 2) ** 0.5
cannot_refract = ri * sintheta > 1.0
maybe_reflect_anyway = Dielectric.reflectance(costheta, ri) > rand
refr = cannot_refract || maybe_reflect_anyway ?
unit_dir.reflect(record.normal) :
unit_dir.refract(record.normal, ri)
Ray.new(record.point, refr)
end
def self.reflectance(costheta, ri)
r0 = ((1.0 - ri) / (1.0 + ri)) ** 2
r0 + (1.0 - r0) * (1.0 - costheta) ** 5
end
end
|