docs/.vitepress/theme/math.ts
66 lines · 2138 bytes
1/**
2 * Copyright (c) 2024 taskylizard
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16// Thanks to @yellowsink for the original code!! <3
17// https://github.com/uwu/uwu.network/blob/master/src/components/sink/Takodachi.astro
18
19export type Vec2D = [number, number]
20
21// Mathmaticians hate him!!!
22/** Lenient square root */
23export const lSqrt = (n: number) => Math.sqrt(Math.abs(n))
24
25export const v2mag = (vec: Vec2D) =>
26 Math.sqrt(vec[0] * vec[0] + vec[1] * vec[1])
27
28export const v2add = (v1: Vec2D, v2: Vec2D): Vec2D => [
29 v1[0] + v2[0],
30 v1[1] + v2[1]
31]
32
33export const v2sub = (v1: Vec2D, v2: Vec2D): Vec2D => [
34 v1[0] - v2[0],
35 v1[1] - v2[1]
36]
37
38/** Multiplies a 2D vector by a scalar */
39export const v2smul = (vec: Vec2D, scalar: number): Vec2D => [
40 vec[0] * scalar,
41 vec[1] * scalar
42]
43
44export function v2norm(vec: Vec2D): Vec2D {
45 const l = v2mag(vec)
46 if (l === 0) return [Math.sqrt(2), Math.sqrt(2)]
47
48 return [vec[0] / l, vec[1] / l]
49}
50
51export const rad2deg = (n: number) => (n * 180) / Math.PI
52
53/** Calculates the gradient of a vector */
54export const v2grad = (vec: Vec2D) => vec[1] / vec[0]
55
56/** Calculates the angle of the vector against [1, 0] in radians */
57export const v2rad = (vec: Vec2D) => Math.atan(v2grad(vec))
58
59/** Calculates the angle of the vector against [1, 0] in degrees */
60export const v2deg = (vec: Vec2D) => rad2deg(v2rad(vec))
61
62/** Angle in degrees between two vec2ds in radians */
63export const v2radBtw = (v1: Vec2D, v2: Vec2D) => v2rad(v1) - v2rad(v2)
64
65/** Angle in degrees between two vec2ds in degrees */
66export const v2degBtw = (v1: Vec2D, v2: Vec2D) => rad2deg(v2radBtw(v1, v2))