-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tuple.ts
94 lines (73 loc) · 1.85 KB
/
Tuple.ts
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
import equal from './equal'
export class Tuple {
readonly #values: [number, number, number, number]
static point(x: number, y: number, z: number) {
return new Tuple(x, y, z, 1.0)
}
static vector(x: number, y: number, z: number) {
return new Tuple(x, y, z, 0.0)
}
constructor(x: number, y: number, z: number, w: number) {
this.#values = [x, y, z, w]
}
get x() {
return this.#values[0]
}
get y() {
return this.#values[1]
}
get z() {
return this.#values[2]
}
get w() {
return this.#values[3]
}
add(other: Tuple) {
return new Tuple(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w)
}
cross(other: Tuple) {
return Tuple.vector(
this.y * other.z - this.z * other.y,
this.z * other.x - this.x * other.z,
this.x * other.y - this.y * other.x
)
}
div(divisor: number) {
return this.mul(1 / divisor)
}
dot(other: Tuple) {
return this.x * other.x + this.y * other.y + this.z * other.z + this.w * other.w
}
equals(other: Tuple) {
return (
equal(this.x, other.x) &&
equal(this.y, other.y) &&
equal(this.z, other.z) &&
equal(this.w, other.w)
)
}
isPoint(): this is { w: 1.0 } {
return this.w === 1.0
}
isVector(): this is { w: 0.0 } {
return this.w === 0.0
}
magnitude() {
return Math.sqrt(this.x ** 2 + this.y ** 2 + this.z ** 2 + this.w ** 2)
}
mul(factor: number) {
return new Tuple(this.x * factor, this.y * factor, this.z * factor, this.w * factor)
}
negate() {
return new Tuple(0, 0, 0, 0).sub(this)
}
normalize() {
return this.div(this.magnitude())
}
sub(other: Tuple) {
return new Tuple(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w)
}
toString() {
return `Tuple(${this.#values.map((n) => n.toFixed(5)).join(', ')})`
}
}