forked from antoniodgonzalez/md5mesh-viewer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvector.ts
38 lines (30 loc) · 1.1 KB
/
vector.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
export type Vector = ReadonlyArray<number>;
export const add = (a: Vector, b: Vector): Vector => [ a[0] + b[0], a[1] + b[1], a[2] + b[2] ];
export const sub = (a: Vector, b: Vector): Vector => [ a[0] - b[0], a[1] - b[1], a[2] - b[2] ];
export const mul = (a: Vector, b: number): Vector => [ a[0] * b, a[1] * b, a[2] * b ];
export const div = (a: Vector, b: number): Vector => [ a[0] / b, a[1] / b, a[2] / b ];
export const cross = (a: Vector, b: Vector): Vector => [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0]
];
export const normalize = (a: Vector): Vector => {
const s = a[0] * a[0] + a[1] * a[1] + a[2] * a[2];
return s <= 0 ? a : div(a, Math.sqrt(s));
};
export const flatten = (vectors: ReadonlyArray<Vector>): ReadonlyArray<number> => {
const a: number[] = [];
for (const b of vectors) {
a.push(...b);
}
return a;
};
export const sum = (vectors: ReadonlyArray<Vector>): Vector => {
const a = [0, 0, 0];
for (const b of vectors) {
a[0] += b[0];
a[1] += b[1];
a[2] += b[2];
}
return a;
};