-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvector.go
76 lines (61 loc) · 1.58 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
72
73
74
75
76
package berlin
import "math"
// 3-component vector
type Vector [3]float64
// Returns a*v.
func (v Vector) Mul(a float64) Vector {
return Vector{a * v[0], a * v[1], a * v[2]}
}
// point-wise multiplication of components
func (v Vector) Mul3(a Vector) Vector {
return Vector{a[0] * v[0], a[1] * v[1], a[2] * v[2]}
}
func (v Vector) Abs() Vector {
return Vector{math.Abs(v[0]), math.Abs(v[1]), math.Abs(v[2])}
}
// Returns (1/a)*v.
func (v Vector) Div(a float64) Vector {
return v.Mul(1 / a)
}
// Returns a+b.
func (a Vector) Add(b Vector) Vector {
return Vector{a[0] + b[0], a[1] + b[1], a[2] + b[2]}
}
// Returns a+s*b.
func (a Vector) MAdd(s float64, b Vector) Vector {
return Vector{a[0] + s*b[0], a[1] + s*b[1], a[2] + s*b[2]}
}
// Returns a-b.
func (a Vector) Sub(b Vector) Vector {
return Vector{a[0] - b[0], a[1] - b[1], a[2] - b[2]}
}
// Returns the norm of v.
func (v Vector) Len() float64 {
return math.Sqrt(v[X]*v[X] + v[Y]*v[Y] + v[Z]*v[Z])
}
// Returns the norm squared
func (v Vector) Len2() float64 {
return v[X]*v[X] + v[Y]*v[Y] + v[Z]*v[Z]
}
//rescales norm of a vector to one
func norm(x Vector) {
magnitude := math.Sqrt(x[0]*x[0] + x[1]*x[1] + x[2]*x[2])
x = x.Mul(1. / magnitude)
}
// Returns the dot (inner) product a.b.
func (a Vector) Dot(b Vector) float64 {
return a[0]*b[0] + a[1]*b[1] + a[2]*b[2]
}
// Returns the cross (vector) product a x b
// in a right-handed coordinate system.
func (a Vector) Cross(b Vector) Vector {
x := a[1]*b[2] - a[2]*b[1]
y := a[2]*b[0] - a[0]*b[2]
z := a[0]*b[1] - a[1]*b[0]
return Vector{x, y, z}
}
const (
X = 0
Y = 1
Z = 2
)