Add automation and drag nodes into connections in the graph

This commit is contained in:
Skyler Lehmkuhl
2025-11-02 01:27:22 -05:00
parent 0ae168cbca
commit 988bbfd1a9
62 changed files with 2622 additions and 82 deletions
+23 -1
View File
@@ -81,6 +81,9 @@ pub struct InstrumentGraph {
/// UI positions for nodes (node_index -> (x, y))
node_positions: std::collections::HashMap<u32, (f32, f32)>,
/// Current playback time (for automation nodes)
playback_time: f64,
}
impl InstrumentGraph {
@@ -98,6 +101,7 @@ impl InstrumentGraph {
// Pre-allocate MIDI input buffers (max 128 events per port)
midi_input_buffers: (0..16).map(|_| Vec::with_capacity(128)).collect(),
node_positions: std::collections::HashMap::new(),
playback_time: 0.0,
}
}
@@ -319,7 +323,19 @@ impl InstrumentGraph {
}
/// Process the graph and produce audio output
pub fn process(&mut self, output_buffer: &mut [f32], midi_events: &[MidiEvent]) {
pub fn process(&mut self, output_buffer: &mut [f32], midi_events: &[MidiEvent], playback_time: f64) {
// Update playback time
self.playback_time = playback_time;
// Update playback time for all automation nodes before processing
use super::nodes::AutomationInputNode;
for node in self.graph.node_weights_mut() {
// Try to downcast to AutomationInputNode and update its playback time
if let Some(auto_node) = node.node.as_any_mut().downcast_mut::<AutomationInputNode>() {
auto_node.set_playback_time(playback_time);
}
}
// Use the requested output buffer size for processing
let process_size = output_buffer.len();
@@ -504,6 +520,11 @@ impl InstrumentGraph {
self.get_node(idx).and_then(|node| node.get_oscilloscope_cv_data(sample_count))
}
/// Get node by index (read-only)
pub fn get_graph_node(&self, idx: NodeIndex) -> Option<&GraphNode> {
self.graph.node_weight(idx)
}
/// Get node mutably by index
/// Note: Due to lifetime constraints with trait objects, this returns a mutable reference
/// to the GraphNode, from which you can access the node
@@ -816,6 +837,7 @@ impl InstrumentGraph {
"MidiInput" => Box::new(MidiInputNode::new("MIDI Input")),
"MidiToCV" => Box::new(MidiToCVNode::new("MIDI→CV")),
"AudioToCV" => Box::new(AudioToCVNode::new("Audio→CV")),
"AutomationInput" => Box::new(AutomationInputNode::new("Automation")),
"Oscilloscope" => Box::new(OscilloscopeNode::new("Oscilloscope")),
"TemplateInput" => Box::new(TemplateInputNode::new("Template Input")),
"TemplateOutput" => Box::new(TemplateOutputNode::new("Template Output")),
@@ -70,4 +70,10 @@ pub trait AudioNode: Send {
fn get_oscilloscope_cv_data(&self, _sample_count: usize) -> Option<Vec<f32>> {
None
}
/// Downcast to `&mut dyn Any` for type-specific operations
fn as_any_mut(&mut self) -> &mut dyn std::any::Any;
/// Downcast to `&dyn Any` for type-specific read-only operations
fn as_any(&self) -> &dyn std::any::Any;
}
+46
View File
@@ -0,0 +1,46 @@
#!/bin/bash
for file in *.rs; do
if [ "$file" = "mod.rs" ]; then
continue
fi
echo "Processing $file"
# Create a backup
cp "$file" "$file.bak"
# Add as_any() method right after as_any_mut()
awk '
{
lines[NR] = $0
if (/fn as_any_mut\(&mut self\)/) {
# Found as_any_mut, look for its closing brace
found_method = NR
}
if (found_method > 0 && /^ }$/ && !inserted) {
closing_brace = NR
inserted = 1
}
}
END {
for (i = 1; i <= NR; i++) {
print lines[i]
if (i == closing_brace) {
print ""
print " fn as_any(&self) -> &dyn std::any::Any {"
print " self"
print " }"
}
}
}
' "$file.bak" > "$file"
# Verify the change was made
if grep -q "fn as_any(&self)" "$file"; then
echo " ✓ Successfully added as_any() to $file"
rm "$file.bak"
else
echo " ✗ Failed to add as_any() to $file - restoring backup"
mv "$file.bak" "$file"
fi
done
@@ -212,4 +212,12 @@ impl AudioNode for ADSRNode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -148,4 +148,12 @@ impl AudioNode for AudioToCVNode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -0,0 +1,288 @@
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, SignalType};
use crate::audio::midi::MidiEvent;
use serde::{Deserialize, Serialize};
use std::sync::{Arc, RwLock};
/// Interpolation type for automation curves
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum InterpolationType {
Linear,
Bezier,
Step,
Hold,
}
/// A single keyframe in an automation curve
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutomationKeyframe {
/// Time in seconds (absolute project time)
pub time: f64,
/// CV output value
pub value: f32,
/// Interpolation type to next keyframe
pub interpolation: InterpolationType,
/// Bezier ease-out control point (for bezier interpolation)
pub ease_out: (f32, f32),
/// Bezier ease-in control point (for bezier interpolation)
pub ease_in: (f32, f32),
}
impl AutomationKeyframe {
pub fn new(time: f64, value: f32) -> Self {
Self {
time,
value,
interpolation: InterpolationType::Linear,
ease_out: (0.58, 1.0),
ease_in: (0.42, 0.0),
}
}
}
/// Automation Input Node - outputs CV signal controlled by timeline curves
pub struct AutomationInputNode {
name: String,
display_name: String, // User-editable name shown in UI
keyframes: Vec<AutomationKeyframe>,
outputs: Vec<NodePort>,
parameters: Vec<Parameter>,
/// Shared playback time (set by the graph before processing)
playback_time: Arc<RwLock<f64>>,
}
impl AutomationInputNode {
pub fn new(name: impl Into<String>) -> Self {
let name = name.into();
let outputs = vec![
NodePort::new("CV Out", SignalType::CV, 0),
];
Self {
name: name.clone(),
display_name: "Automation".to_string(),
keyframes: Vec::new(),
outputs,
parameters: Vec::new(),
playback_time: Arc::new(RwLock::new(0.0)),
}
}
/// Set the playback time (called by graph before processing)
pub fn set_playback_time(&mut self, time: f64) {
if let Ok(mut playback) = self.playback_time.write() {
*playback = time;
}
}
/// Get the display name (shown in UI)
pub fn display_name(&self) -> &str {
&self.display_name
}
/// Set the display name
pub fn set_display_name(&mut self, name: String) {
self.display_name = name;
}
/// Add a keyframe to the curve (maintains sorted order by time)
pub fn add_keyframe(&mut self, keyframe: AutomationKeyframe) {
// Find insertion position to maintain sorted order
let pos = self.keyframes.binary_search_by(|kf| {
kf.time.partial_cmp(&keyframe.time).unwrap_or(std::cmp::Ordering::Equal)
});
match pos {
Ok(idx) => {
// Replace existing keyframe at same time
self.keyframes[idx] = keyframe;
}
Err(idx) => {
// Insert at correct position
self.keyframes.insert(idx, keyframe);
}
}
}
/// Remove keyframe at specific time (with tolerance)
pub fn remove_keyframe_at_time(&mut self, time: f64, tolerance: f64) -> bool {
if let Some(idx) = self.keyframes.iter().position(|kf| (kf.time - time).abs() < tolerance) {
self.keyframes.remove(idx);
true
} else {
false
}
}
/// Update an existing keyframe
pub fn update_keyframe(&mut self, keyframe: AutomationKeyframe) {
// Remove old keyframe at this time, then add new one
self.remove_keyframe_at_time(keyframe.time, 0.001);
self.add_keyframe(keyframe);
}
/// Get all keyframes
pub fn keyframes(&self) -> &[AutomationKeyframe] {
&self.keyframes
}
/// Clear all keyframes
pub fn clear_keyframes(&mut self) {
self.keyframes.clear();
}
/// Evaluate curve at a specific time
fn evaluate_at_time(&self, time: f64) -> f32 {
if self.keyframes.is_empty() {
return 0.0;
}
// Before first keyframe
if time <= self.keyframes[0].time {
return self.keyframes[0].value;
}
// After last keyframe
let last_idx = self.keyframes.len() - 1;
if time >= self.keyframes[last_idx].time {
return self.keyframes[last_idx].value;
}
// Find bracketing keyframes
for i in 0..self.keyframes.len() - 1 {
let kf1 = &self.keyframes[i];
let kf2 = &self.keyframes[i + 1];
if time >= kf1.time && time <= kf2.time {
return self.interpolate(kf1, kf2, time);
}
}
0.0
}
/// Interpolate between two keyframes
fn interpolate(&self, kf1: &AutomationKeyframe, kf2: &AutomationKeyframe, time: f64) -> f32 {
// Calculate normalized position between keyframes (0.0 to 1.0)
let t = if kf2.time == kf1.time {
0.0
} else {
((time - kf1.time) / (kf2.time - kf1.time)) as f32
};
match kf1.interpolation {
InterpolationType::Linear => {
// Simple linear interpolation
kf1.value + (kf2.value - kf1.value) * t
}
InterpolationType::Bezier => {
// Cubic bezier interpolation using control points
let eased_t = self.cubic_bezier_ease(t, kf1.ease_out, kf2.ease_in);
kf1.value + (kf2.value - kf1.value) * eased_t
}
InterpolationType::Step | InterpolationType::Hold => {
// Hold value until next keyframe
kf1.value
}
}
}
/// Cubic bezier easing function
fn cubic_bezier_ease(&self, t: f32, ease_out: (f32, f32), ease_in: (f32, f32)) -> f32 {
// Simplified cubic bezier for 0,0 -> easeOut -> easeIn -> 1,1
let u = 1.0 - t;
3.0 * u * u * t * ease_out.1 +
3.0 * u * t * t * ease_in.1 +
t * t * t
}
}
impl AudioNode for AutomationInputNode {
fn category(&self) -> NodeCategory {
NodeCategory::Input
}
fn inputs(&self) -> &[NodePort] {
&[] // No inputs
}
fn outputs(&self) -> &[NodePort] {
&self.outputs
}
fn parameters(&self) -> &[Parameter] {
&self.parameters
}
fn set_parameter(&mut self, _id: u32, _value: f32) {
// No parameters
}
fn get_parameter(&self, _id: u32) -> f32 {
0.0
}
fn process(
&mut self,
_inputs: &[&[f32]],
outputs: &mut [&mut [f32]],
_midi_inputs: &[&[MidiEvent]],
_midi_outputs: &mut [&mut Vec<MidiEvent>],
sample_rate: u32,
) {
if outputs.is_empty() {
return;
}
let output = &mut outputs[0];
let length = output.len();
// Get the starting playback time
let playhead = if let Ok(playback) = self.playback_time.read() {
*playback
} else {
0.0
};
// Calculate time per sample
let sample_duration = 1.0 / sample_rate as f64;
// Evaluate curve for each sample
for i in 0..length {
let time = playhead + (i as f64 * sample_duration);
output[i] = self.evaluate_at_time(time);
}
}
fn reset(&mut self) {
// No state to reset
}
fn node_type(&self) -> &str {
"AutomationInput"
}
fn name(&self) -> &str {
&self.name
}
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self {
name: self.name.clone(),
display_name: self.display_name.clone(),
keyframes: self.keyframes.clone(),
outputs: self.outputs.clone(),
parameters: self.parameters.clone(),
playback_time: Arc::new(RwLock::new(0.0)),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -184,4 +184,12 @@ impl AudioNode for BitCrusherNode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -231,4 +231,12 @@ impl AudioNode for ChorusNode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -250,4 +250,12 @@ impl AudioNode for CompressorNode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -110,4 +110,12 @@ impl AudioNode for ConstantNode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -208,4 +208,12 @@ impl AudioNode for DelayNode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -254,4 +254,12 @@ impl AudioNode for DistortionNode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -155,4 +155,12 @@ impl AudioNode for EnvelopeFollowerNode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -256,4 +256,12 @@ impl AudioNode for EQNode {
node.update_filters();
Box::new(node)
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -198,4 +198,12 @@ impl AudioNode for FilterNode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -240,4 +240,12 @@ impl AudioNode for FlangerNode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -300,4 +300,12 @@ impl AudioNode for FMSynthNode {
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self::new(self.name.clone()))
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -127,4 +127,12 @@ impl AudioNode for GainNode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -219,4 +219,12 @@ impl AudioNode for LFONode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -212,4 +212,12 @@ impl AudioNode for LimiterNode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -161,4 +161,12 @@ impl AudioNode for MathNode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -102,4 +102,12 @@ impl AudioNode for MidiInputNode {
fn handle_midi(&mut self, event: &MidiEvent) {
self.pending_events.push(*event);
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -183,4 +183,12 @@ impl AudioNode for MidiToCVNode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -142,4 +142,12 @@ impl AudioNode for MixerNode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -1,5 +1,6 @@
mod adsr;
mod audio_to_cv;
mod automation_input;
mod bit_crusher;
mod chorus;
mod compressor;
@@ -39,6 +40,7 @@ mod wavetable_oscillator;
pub use adsr::ADSRNode;
pub use audio_to_cv::AudioToCVNode;
pub use automation_input::{AutomationInputNode, AutomationKeyframe, InterpolationType};
pub use bit_crusher::BitCrusherNode;
pub use chorus::ChorusNode;
pub use compressor::CompressorNode;
@@ -508,4 +508,12 @@ impl AudioNode for MultiSamplerNode {
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self::new(self.name.clone()))
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -194,4 +194,12 @@ impl AudioNode for NoiseGeneratorNode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -194,4 +194,12 @@ impl AudioNode for OscillatorNode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -299,4 +299,12 @@ impl AudioNode for OscilloscopeNode {
fn get_oscilloscope_cv_data(&self, sample_count: usize) -> Option<Vec<f32>> {
Some(self.read_cv_samples(sample_count))
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -93,4 +93,12 @@ impl AudioNode for AudioOutputNode {
outputs: self.outputs.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -165,4 +165,12 @@ impl AudioNode for PanNode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -286,4 +286,12 @@ impl AudioNode for PhaserNode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -221,4 +221,12 @@ impl AudioNode for QuantizerNode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -310,4 +310,12 @@ impl AudioNode for ReverbNode {
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self::new(self.name.clone()))
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -134,4 +134,12 @@ impl AudioNode for RingModulatorNode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -134,4 +134,12 @@ impl AudioNode for SampleHoldNode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -275,4 +275,12 @@ impl AudioNode for SimpleSamplerNode {
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self::new(self.name.clone()))
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -153,4 +153,12 @@ impl AudioNode for SlewLimiterNode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -101,4 +101,12 @@ impl AudioNode for SplitterNode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -85,6 +85,14 @@ impl AudioNode for TemplateInputNode {
fn handle_midi(&mut self, _event: &MidiEvent) {
// Pass through to connected nodes
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
/// Template Output node - represents the audio output from one voice in a VoiceAllocator
@@ -173,4 +181,12 @@ impl AudioNode for TemplateOutputNode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -359,4 +359,12 @@ impl AudioNode for VocoderNode {
node.setup_bands();
Box::new(node)
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -288,7 +288,8 @@ impl AudioNode for VoiceAllocatorNode {
mix_slice.fill(0.0);
// Process this voice's graph with its MIDI events
self.voice_instances[voice_idx].process(mix_slice, &midi_events);
// Note: playback_time is 0.0 since voice allocator doesn't track time
self.voice_instances[voice_idx].process(mix_slice, &midi_events, 0.0);
// Mix into output (accumulate)
for (i, sample) in mix_slice.iter().enumerate() {
@@ -341,4 +342,12 @@ impl AudioNode for VoiceAllocatorNode {
parameters: self.parameters.clone(),
})
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
@@ -283,4 +283,12 @@ impl AudioNode for WavetableOscillatorNode {
fn clone_node(&self) -> Box<dyn AudioNode> {
Box::new(Self::new(self.name.clone()))
}
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn as_any(&self) -> &dyn std::any::Any {
self
}
}