| 1 |
import type {Quat, Rigid3d, Vec3} from "./types"; |
| 2 |
|
| 3 |
export function quatMultiply(a: Quat, b: Quat): Quat { |
| 4 |
return [ |
| 5 |
a[0] * b[0] - a[1] * b[1] - a[2] * b[2] - a[3] * b[3], |
| 6 |
a[0] * b[1] + a[1] * b[0] + a[2] * b[3] - a[3] * b[2], |
| 7 |
a[0] * b[2] - a[1] * b[3] + a[2] * b[0] + a[3] * b[1], |
| 8 |
a[0] * b[3] + a[1] * b[2] - a[2] * b[1] + a[3] * b[0], |
| 9 |
]; |
| 10 |
} |
| 11 |
|
| 12 |
export function quatRotate(q: Quat, v: Vec3): Vec3 { |
| 13 |
const [w, x, y, z] = q; |
| 14 |
const tx = 2 * (y * v[2] - z * v[1]); |
| 15 |
const ty = 2 * (z * v[0] - x * v[2]); |
| 16 |
const tz = 2 * (x * v[1] - y * v[0]); |
| 17 |
return [ |
| 18 |
v[0] + w * tx + y * tz - z * ty, |
| 19 |
v[1] + w * ty + z * tx - x * tz, |
| 20 |
v[2] + w * tz + x * ty - y * tx, |
| 21 |
]; |
| 22 |
} |
| 23 |
|
| 24 |
export function composeRigid(a: Rigid3d, b: Rigid3d): Rigid3d { |
| 25 |
const t = quatRotate(a.rotation, b.translation); |
| 26 |
return { |
| 27 |
rotation: quatMultiply(a.rotation, b.rotation), |
| 28 |
translation: [ |
| 29 |
t[0] + a.translation[0], |
| 30 |
t[1] + a.translation[1], |
| 31 |
t[2] + a.translation[2], |
| 32 |
], |
| 33 |
}; |
| 34 |
} |
| 35 |
|
| 36 |
export function transformPoint(transform: Rigid3d, point: Vec3): Vec3 { |
| 37 |
const rotated = quatRotate(transform.rotation, point); |
| 38 |
return [ |
| 39 |
rotated[0] + transform.translation[0], |
| 40 |
rotated[1] + transform.translation[1], |
| 41 |
rotated[2] + transform.translation[2], |
| 42 |
]; |
| 43 |
} |
| 44 |
|
| 45 |
export function projectionCenter(camFromWorld: Rigid3d): Vec3 { |
| 46 |
const [w, x, y, z] = camFromWorld.rotation; |
| 47 |
const rotated = quatRotate( |
| 48 |
[w, -x, -y, -z], |
| 49 |
camFromWorld.translation, |
| 50 |
); |
| 51 |
return [-rotated[0], -rotated[1], -rotated[2]]; |
| 52 |
} |
| 53 |
|
| 54 |
export function percentile(values: number[], q: number): number { |
| 55 |
if (values.length === 0) return 0; |
| 56 |
const sorted = [...values].sort((a, b) => a - b); |
| 57 |
const index = Math.min(sorted.length - 1, Math.max(0, q * (sorted.length - 1))); |
| 58 |
const left = Math.floor(index); |
| 59 |
const right = Math.ceil(index); |
| 60 |
if (left === right) return sorted[left] ?? 0; |
| 61 |
return (sorted[left] ?? 0) * (right - index) + (sorted[right] ?? 0) * (index - left); |
| 62 |
} |
| 63 |
|
| 64 |
export function median(values: number[]): number { |
| 65 |
if (values.length === 0) return 0; |
| 66 |
const sorted = [...values].sort((a, b) => a - b); |
| 67 |
const middle = Math.floor(sorted.length / 2); |
| 68 |
return sorted.length % 2 |
| 69 |
? (sorted[middle] ?? 0) |
| 70 |
: ((sorted[middle - 1] ?? 0) + (sorted[middle] ?? 0)) / 2; |
| 71 |
} |