Skip to content

Commit

Permalink
feat(shader-ast-stdlib): add oscillator fns
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Aug 12, 2021
1 parent 2100e50 commit f14e8cb
Show file tree
Hide file tree
Showing 2 changed files with 88 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/shader-ast-stdlib/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export * from "./math/mincomp";
export * from "./math/mix-cubic";
export * from "./math/mix-quadratic";
export * from "./math/orthogonal";
export * from "./math/osc";
export * from "./math/polar";
export * from "./math/sincos";

Expand Down
87 changes: 87 additions & 0 deletions packages/shader-ast-stdlib/src/math/osc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import type { FnU } from "@thi.ng/api";
import {
abs,
float,
FLOAT0,
FLOAT05,
FLOAT1,
FLOAT2,
FloatTerm,
fract,
madd,
mul,
NumericF,
sin,
step,
sub,
TAU,
} from "@thi.ng/shader-ast";

const defOsc =
(fn: FnU<FloatTerm>) =>
(
phase: NumericF,
freq: NumericF,
amp: NumericF = FLOAT1,
dc: NumericF = FLOAT0
) =>
madd(fn(mul(float(phase), float(freq))), amp, dc);

/**
* Sine oscillator (ported from thi.ng/dsp)
*
* @param phase - normalized phase
* @param freq -
* @param amp -
* @param dc -
*/
export const sinOsc = defOsc((phase) => sin(mul(phase, TAU)));

/**
* Sawtooth oscillator (ported from thi.ng/dsp)
*
* @param phase - normalized phase
* @param freq -
* @param amp -
* @param dc -
*/
export const sawOsc = defOsc((phase) => sub(FLOAT1, mul(fract(phase), FLOAT2)));

/**
* Triangle oscillator (ported from thi.ng/dsp)
*
* @param phase - normalized phase
* @param freq -
* @param amp -
* @param dc -
*/
export const triOsc = defOsc((phase) =>
sub(abs(madd(fract(phase), 4, float(-2))), FLOAT1)
);

/**
* Rect oscillator w/ customizable duty cycle (default: 0.5) (ported from
* thi.ng/dsp)
*
* @param phase - normalized phase
* @param freq -
* @param amp -
* @param dc -
* @param duty -
*/
export const rectOsc = (
phase: NumericF,
freq: NumericF,
amp: NumericF = FLOAT1,
dc: NumericF = FLOAT0,
duty: NumericF = FLOAT05
) =>
madd(
madd(
step(float(duty), fract(mul(float(phase), float(freq)))),
FLOAT2,
float(-1)
),
amp,
dc
);

0 comments on commit f14e8cb

Please sign in to comment.