Repository navigation
Expand file tree
/
Copy pathvector.js
More file actions
66 lines (53 loc) · 1.6 KB
/
Copy pathvector.js
File metadata and controls
66 lines (53 loc) · 1.6 KB
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
class Vec4 {
constructor(x, y, z, w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w ?? 0;
}
scaled(by) {
return new Vec4(this.x * by, this.y * by, this.z * by, this.w * by);
}
dot(other) {
return this.x * other.x +
this.y * other.y +
this.z * other.z +
this.w * other.w;
}
length() {
return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
}
norm() {
let len = this.length();
return new Vec4(this.x / len, this.y / len, this.z / len, this.w / len);
}
add(other) {
return new Vec4(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
}
sub(other) {
return this.add(other.scaled(-1));
}
cross(other) {
let x = this.y * other.z - this.z * other.y;
let y = this.z * other.x - this.x * other.z;
let z = this.x * other.y - this.y * other.x;
return new Vec4(x, y, z, 0);
}
/**
* Calculate the normal of the given triangle.
* For the resulting normal to point in the positive y direction, p0 to p1 should be to the
* left of p0 to p2
* @param {Vec4} p0
* @param {Vec4} p1
* @param {Vec4} p2
* @returns Vec4
*/
static normal_of_triangle(p0, p1, p2) {
let v0 = p1.sub(p0);
let v1 = p2.sub(p0);
return v0.cross(v1);
}
toString() {
return ['[', this.x, this.y, this.z, this.w, ']'].join(' ');
}
}