-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmath_utility.js
130 lines (116 loc) · 2.19 KB
/
math_utility.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
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
119
120
121
122
123
124
125
126
127
128
129
130
function Cross(a, b) {
return [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
];
}
function Times(a, v3) {
return [a * v3[0], a * v3[1], a * v3[2]];
}
function Dot(a, b) {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}
function Sub(a, b) {
return [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
}
function plzApplyManyMat4(vec3, ...trans) {
const e = multiplyManyMatrices(...trans);
const [x, y, z] = vec3;
const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
const tx = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
const ty = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
const tz = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
return [tx, ty, tz];
}
function multiplyTwoMatrices(A, B) {
const C = [];
for (let i = 0; i < 4; ++i) {
for (let j = 0; j < 4; ++j) {
let v = 0;
for (let k = 0; k < 4; ++k) {
v += A[j + 4 * k] * B[k + 4 * i];
}
C.push(v);
}
}
return C;
}
const plzMany = multiplyManyMatrices;
const plzIdentity = () => [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
function multiplyManyMatrices(...mtx) {
const identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
return mtx.reduce((prev, curr) => multiplyTwoMatrices(curr, prev), identity);
}
function plzTranslate(x, y, z) {
return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1];
}
function plzScale(x, y, z) {
return [x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1];
}
function Radians(angle) {
return (angle / 180) * Math.PI;
}
function plzRotateX(angle) {
const r = Radians(angle);
return [
1,
0,
0,
0,
0,
Math.cos(r),
Math.sin(r),
0,
0,
-Math.sin(r),
Math.cos(r),
0,
0,
0,
0,
1,
];
}
function plzRotateY(angle) {
const r = Radians(angle);
return [
Math.cos(r),
0,
-Math.sin(r),
0,
0,
1,
0,
0,
Math.sin(r),
0,
Math.cos(r),
0,
0,
0,
0,
1,
];
}
function plzRotateZ(angle) {
const r = Radians(angle);
return [
Math.cos(r),
Math.sin(r),
0,
0,
-Math.sin(r),
Math.cos(r),
0,
0,
0,
0,
1,
0,
0,
0,
0,
1,
];
}