summaryrefslogtreecommitdiff
path: root/klangfarbrs/src
diff options
context:
space:
mode:
authorGrant Shangreaux <grant@unabridgedsoftware.com>2021-11-01 19:45:51 -0500
committerGrant Shangreaux <grant@unabridgedsoftware.com>2021-11-01 19:45:51 -0500
commitc2ef13956710352267ae1583c11efbc745fecfd7 (patch)
tree01fc6ea2f5d7f6b9e4393716471d9161ae3d31fd /klangfarbrs/src
parente598f10e17b317386ae8681e664a0c250c7f2dbe (diff)
Add: triangle and sawtooth waveforms
Diffstat (limited to 'klangfarbrs/src')
-rw-r--r--klangfarbrs/src/lib.rs30
1 files changed, 26 insertions, 4 deletions
diff --git a/klangfarbrs/src/lib.rs b/klangfarbrs/src/lib.rs
index 7954eb2..059d59f 100644
--- a/klangfarbrs/src/lib.rs
+++ b/klangfarbrs/src/lib.rs
@@ -26,23 +26,35 @@ pub struct Osc {
pub enum Waveform {
Sine,
Square,
- // Triangle,
- // Saw,
+ Triangle,
+ Sawtooth,
// Noise,
}
/// Generates the next sample for an oscillator based on its waveform.
fn generate_sample(osc: &Osc) -> f32 {
+ let phase = osc.phase;
+
match osc.waveform {
Waveform::Sine => {
- (TAU * osc.phase).sin()
+ (TAU * phase).sin()
},
Waveform::Square => {
- if osc.phase < 0.5 {
+ if phase < 0.5 {
-1.0
} else {
1.0
}
+ },
+ Waveform::Triangle => {
+ if phase < 0.5 {
+ 4.0 * phase - 1.0
+ } else {
+ 4.0 * (1.0 - phase) - 1.0
+ }
+ },
+ Waveform::Sawtooth => {
+ 2.0 * phase - 1.0
}
}
}
@@ -96,6 +108,16 @@ impl Osc {
}
#[export]
+ fn triangle(&mut self, _owner: &Node) {
+ self.waveform = Waveform::Triangle
+ }
+
+ #[export]
+ fn sawtooth(&mut self, _owner: &Node) {
+ self.waveform = Waveform::Sawtooth
+ }
+
+ #[export]
pub fn set_sample_rate(&mut self, _owner: &Node, sample_rate: f32) {
self.sample_rate = sample_rate;
}