-
Notifications
You must be signed in to change notification settings - Fork 1
/
vec3.js
91 lines (91 loc) · 2.24 KB
/
vec3.js
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
// VExcess' vec3 library - optimized for performance rather than user friendliness
{
const sqrt = Math.sqrt; // caching for faster lookup
window.vec3 = function(x, y, z) {
return {
x: x,
y: y,
z: z ?? 0
};
};
vec3.fromArr = arr => ({
x: arr[0],
y: arr[1],
z: arr[2]
});
vec3.toArr = v => ([v.x, v.y, v.z]);
vec3.clone = v => ({
x: v.x,
y: v.y,
z: v.z
});
vec3.add = (v1, v2) => {
return typeof v2 === 'number' ? {
x: v1.x + v2,
y: v1.y + v2,
z: v1.z + v2
} : {
x: v1.x + v2.x,
y: v1.y + v2.y,
z: v1.z + v2.z
};
};
vec3.sub = (v1, v2) => {
return typeof v2 === 'number' ? {
x: v1.x - v2,
y: v1.y - v2,
z: v1.z - v2
} : {
x: v1.x - v2.x,
y: v1.y - v2.y,
z: v1.z - v2.z
};
};
vec3.mul = (v1, v2) => {
return typeof v2 === 'number' ? {
x: v1.x * v2,
y: v1.y * v2,
z: v1.z * v2
} : {
x: v1.x * v2.x,
y: v1.y * v2.y,
z: v1.z * v2.z
};
};
vec3.div = (v1, v2) => {
return typeof v2 === 'number' ? {
x: v1.x / v2,
y: v1.y / v2,
z: v1.z / v2
} : {
x: v1.x / v2.x,
y: v1.y / v2.y,
z: v1.z / v2.z
};
};
vec3.neg = v => ({
x: -v.x,
y: -v.y,
z: -v.z
});
vec3.mag = v1 => {
// benchmarks show that caching the values results in a 0.000008% performance boost
let x = v1.x, y = v1.y, z = v1.z;
return sqrt(x * x + y * y + z * z);
};
vec3.normalize = v1 => {
let x = v1.x, y = v1.y, z = v1.z;
let m = sqrt(x * x + y * y + z * z);
return m > 0 ? {
x: v1.x / m,
y: v1.y / m,
z: v1.z / m
} : v1;
};
vec3.dot = (v1, v2) => (v1.x * v2.x + v1.y * v2.y + v1.z * v2.z);
vec3.cross = (v1, v2) => ({
x: v1.y * v2.z - v1.z * v2.y,
y: v1.z * v2.x - v1.x * v2.z,
z: v1.x * v2.y - v1.y * v2.x
});
}