-
Notifications
You must be signed in to change notification settings - Fork 0
/
Vec.roc
118 lines (98 loc) · 1.94 KB
/
Vec.roc
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
interface Vec
exposes [
Vec,
zero,
one,
neg,
add,
sub,
mul,
div,
scale,
shrink,
dot,
cross,
unit,
length,
lengthSquared,
nearZero,
reflect,
refract,
]
imports [Math]
Vec : { x : F64, y : F64, z : F64 }
zero : Vec
zero = { x: 0, y: 0, z: 0 }
one : Vec
one = { x: 1, y: 1, z: 1 }
neg : Vec -> Vec
neg = \{ x, y, z } -> {
x: -x,
y: -y,
z: -z,
}
add : Vec, Vec -> Vec
add = \a, b -> {
x: a.x + b.x,
y: a.y + b.y,
z: a.z + b.z,
}
sub : Vec, Vec -> Vec
sub = \a, b -> {
x: a.x - b.x,
y: a.y - b.y,
z: a.z - b.z,
}
mul : Vec, Vec -> Vec
mul = \a, b -> {
x: a.x * b.x,
y: a.y * b.y,
z: a.z * b.z,
}
div : Vec, Vec -> Vec
div = \a, b -> {
x: a.x / b.x,
y: a.y / b.y,
z: a.z / b.z,
}
scale : Vec, F64 -> Vec
scale = \{ x, y, z }, t -> {
x: x * t,
y: y * t,
z: z * t,
}
shrink : Vec, F64 -> Vec
shrink = \v, t ->
scale v (1 / t)
dot : Vec, Vec -> F64
dot = \u, v ->
u.x * v.x + u.y * v.y + u.z * v.z
cross : Vec, Vec -> Vec
cross = \u, v -> {
x: u.y * v.z - u.z * v.y,
y: u.z * v.x - u.x * v.z,
z: u.x * v.y - u.y * v.x,
}
unit : Vec -> Vec
unit = \v ->
shrink v (length v)
length : Vec -> F64
length = \v ->
lengthSquared v |> Num.sqrt
lengthSquared : Vec -> F64
lengthSquared = \{ x, y, z } ->
x * x + y * y + z * z
nearZero : Vec -> Bool
nearZero = \{ x, y, z } ->
s = 1e-8
Num.abs x < s && Num.abs y < s && Num.abs z < s
reflect : Vec, Vec -> Vec
reflect = \v, n ->
Vec.sub v (Vec.scale n (2 * Vec.dot v n))
refract : Vec, Vec, F64 -> Vec
refract = \uv, n, etaiOverEtat ->
cosTheta = neg uv |> dot n |> Math.min 1
rOutPerp = scale n cosTheta |> add uv |> scale etaiOverEtat
s = Num.abs (1 - lengthSquared rOutPerp) |> Num.sqrt
rOutParallel = neg n |> scale s
add rOutPerp rOutParallel