Skip to content

Commit

Permalink
Add periodic functions
Browse files Browse the repository at this point in the history
  • Loading branch information
baku89 committed Feb 19, 2024
1 parent e73733f commit 6bed9b8
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
54 changes: 54 additions & 0 deletions src/scalar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,60 @@ export namespace scalar {
*/
export const invsqrt = inverseSqrt

/**
* Returns a sawtooth wave with the given period. Basically, the output will be the input value modulo `period`, but returns 1 when the phase is 1. The shape of the wave will be continous for the negative ranges, so when phase is negative integer, the output will be 0, else if phase is negative float, the output will be 1 - fractional part of phase.
* @see https://www.geogebra.org/calculator/d3grfqqe
*
* @param x the input value
* @param period the period of the wave
* @category Periodic Functions
*
* @shorthands
* - {@link ramp}
*
*/
export function sawtooth(x: number, period = 1): number {
x /= period

if (x === 1) return 1
if (x < 0) return (1 + (x % 1)) % 1
return x % 1
}

/**
* Alias for {@link sawtooth}
* @category Shorthands
*/
export const ramp = sawtooth

/**
* Returns a triangle wave with the given period. The output ranges from 0 to 1.
* @see https://www.geogebra.org/calculator/d3grfqqe
*
* @param x The input value
* @param period The period of the wave
* @category Periodic Functions
*/
export function triangle(x: number, period = 1): number {
x /= period

return 1 - Math.abs(1 - 2 * (Math.abs(x) % 1))
}

/**
* Returns a cosine wave with the given period. The output ranges from 0 to 1, and y = 0 when x = 0.
*
* @see https://www.geogebra.org/calculator/d3grfqqe
* @param v the input value
* @param period the period of the wave
* @category Periodic Functions
*/
export function coswave(v: number, period = 1): number {
v = (v * Math.PI * 2) / period
console.log({v})
return (-Math.cos(v) + 1) / 2
}

/**
* Returns whether or not the numbers have approximately the same.
*
Expand Down
1 change: 1 addition & 0 deletions typedoc.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"Constants",
"Generators",
"Functions",
"Periodic Functions",
"Shorthands"
],
"blockTags": ["@shorthands"]
Expand Down

0 comments on commit 6bed9b8

Please sign in to comment.