-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsphere.rb
51 lines (39 loc) · 1.1 KB
/
sphere.rb
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
require_relative 'vector.rb'
require_relative 'intersection.rb'
class Sphere
attr_accessor :position, :radius, :material
def initialize(position, radius, material)
@position = position #center(c)
@radius = radius.to_f
@material = material
end
def intersection?(ray, t)
e = ray.position
d = ray.direction
e_c = e.minus(@position)
dd = d.num_product(2)
a = d.scalar_product(d)
b = dd.scalar_product(e_c)
c = e_c.scalar_product(e_c) - @radius ** 2
#puts "(A: #{a} , B: #{b} , C: #{c})"
discriminant = b**2-(4*a*c)
return Intersection.unsuccessful if (discriminant < 0.0)
t0 = ((b * -1) - Math.sqrt(discriminant))/(2 * a)
t1 = ((b * -1) + Math.sqrt(discriminant))/(2 * a)
success = false
if ((t0 > 0.0) && (t0 < t))
t = t0
success = true
end
if ((t1 > 0.0) && (t1 < t))
t = t1
success = true
end
return Intersection.new(t, success)
end
def normal(p)
c = @position#center
p_c = p.minus(c)#why? Ans: Book pag 77
return Vector.new(p_c.x/@radius,p_c.y/@radius,p_c.z/@radius)
end
end