-
Notifications
You must be signed in to change notification settings - Fork 0
/
vector.go
71 lines (53 loc) · 1.21 KB
/
vector.go
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
package raytracing
import "math"
type Vector struct {
x float64
y float64
z float64
}
func NewVector(x, y, z float64) Vector {
return Vector{x: x, y: y, z: z}
}
func (v Vector) neg() Vector {
return NewVector(-v.x, -v.y, -v.z)
}
func (v Vector) add(w Vector) Vector {
return NewVector(v.x+w.x, v.y+w.y, v.z+w.z)
}
func (v Vector) sub(w Vector) Vector {
return NewVector(v.x-w.x, v.y-w.y, v.z-w.z)
}
func (v Vector) mul(t float64) Vector {
return NewVector(t*v.x, t*v.y, t*v.z)
}
func (v Vector) div(t float64) Vector {
return NewVector(v.x/t, v.y/t, v.z/t)
}
func (v Vector) dot(w Vector) float64 {
return v.x*w.x + v.y*w.y + v.z*w.z
}
func (v Vector) cross(w Vector) Vector {
return NewVector(v.y*w.z-v.z*w.y, v.z*w.x-v.x*w.z, v.x*w.y-v.y*w.x)
}
func (v Vector) norm() float64 {
return v.dot(v)
}
func (v Vector) length() float64 {
return math.Sqrt(v.norm())
}
func (v Vector) normalize() Vector {
return v.div(v.length())
}
type Point Vector
func NewPoint(x, y, z float64) Point {
return Point(NewVector(x, y, z))
}
func origin() Point {
return NewPoint(0, 0, 0)
}
func (p Point) to(q Point) Vector {
return NewVector(q.x-p.x, q.y-p.y, q.z-p.z)
}
func (v Vector) point() Point {
return Point(v)
}