Add presets and make graph follow selected layer/track

This commit is contained in:
Skyler Lehmkuhl
2025-10-25 05:31:18 -04:00
parent 16f4a2a359
commit 139946fb75
19 changed files with 2118 additions and 71 deletions
+80 -1
View File
@@ -722,7 +722,7 @@ impl Engine {
}
// Node graph commands
Command::GraphAddNode(track_id, node_type, _x, _y) => {
Command::GraphAddNode(track_id, node_type, x, y) => {
// Get MIDI track (graphs are only for MIDI tracks currently)
if let Some(TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
// Create graph if it doesn't exist
@@ -760,6 +760,9 @@ impl Engine {
let node_idx = graph.add_node(node);
let node_id = node_idx.index() as u32;
// Save position
graph.set_node_position(node_idx, x, y);
// Automatically set MIDI-receiving nodes as MIDI targets
if node_type == "MidiInput" || node_type == "VoiceAllocator" {
graph.set_midi_target(node_idx, true);
@@ -907,6 +910,72 @@ impl Engine {
}
}
}
Command::GraphSavePreset(track_id, preset_path, preset_name, description, tags) => {
if let Some(TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
if let Some(ref graph) = track.instrument_graph {
// Serialize the graph to a preset
let mut preset = graph.to_preset(&preset_name);
preset.metadata.description = description;
preset.metadata.tags = tags;
preset.metadata.author = String::from("User");
// Write to file
if let Ok(json) = preset.to_json() {
if let Err(e) = std::fs::write(&preset_path, json) {
let _ = self.event_tx.push(AudioEvent::GraphConnectionError(
track_id,
format!("Failed to save preset: {}", e)
));
}
} else {
let _ = self.event_tx.push(AudioEvent::GraphConnectionError(
track_id,
"Failed to serialize preset".to_string()
));
}
}
}
}
Command::GraphLoadPreset(track_id, preset_path) => {
// Read and deserialize the preset
match std::fs::read_to_string(&preset_path) {
Ok(json) => {
match crate::audio::node_graph::preset::GraphPreset::from_json(&json) {
Ok(preset) => {
match InstrumentGraph::from_preset(&preset, self.sample_rate, 8192) {
Ok(graph) => {
// Replace the track's graph
if let Some(TrackNode::Midi(track)) = self.project.get_track_mut(track_id) {
track.instrument_graph = Some(graph);
let _ = self.event_tx.push(AudioEvent::GraphStateChanged(track_id));
}
}
Err(e) => {
let _ = self.event_tx.push(AudioEvent::GraphConnectionError(
track_id,
format!("Failed to create graph from preset: {}", e)
));
}
}
}
Err(e) => {
let _ = self.event_tx.push(AudioEvent::GraphConnectionError(
track_id,
format!("Failed to parse preset: {}", e)
));
}
}
}
Err(e) => {
let _ = self.event_tx.push(AudioEvent::GraphConnectionError(
track_id,
format!("Failed to read preset file: {}", e)
));
}
}
}
}
}
@@ -1377,4 +1446,14 @@ impl EngineController {
pub fn graph_set_output_node(&mut self, track_id: TrackId, node_id: u32) {
let _ = self.command_tx.push(Command::GraphSetOutputNode(track_id, node_id));
}
/// Save the current graph as a preset
pub fn graph_save_preset(&mut self, track_id: TrackId, preset_path: String, preset_name: String, description: String, tags: Vec<String>) {
let _ = self.command_tx.push(Command::GraphSavePreset(track_id, preset_path, preset_name, description, tags));
}
/// Load a preset into a track's graph
pub fn graph_load_preset(&mut self, track_id: TrackId, preset_path: String) {
let _ = self.command_tx.push(Command::GraphLoadPreset(track_id, preset_path));
}
}
+164
View File
@@ -78,6 +78,9 @@ pub struct InstrumentGraph {
/// Temporary buffers for node MIDI inputs during processing
midi_input_buffers: Vec<Vec<MidiEvent>>,
/// UI positions for nodes (node_index -> (x, y))
node_positions: std::collections::HashMap<u32, (f32, f32)>,
}
impl InstrumentGraph {
@@ -94,6 +97,7 @@ impl InstrumentGraph {
input_buffers: vec![vec![0.0; buffer_size * 2]; 16],
// 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(),
}
}
@@ -103,6 +107,16 @@ impl InstrumentGraph {
self.graph.add_node(graph_node)
}
/// Set the UI position for a node
pub fn set_node_position(&mut self, node: NodeIndex, x: f32, y: f32) {
self.node_positions.insert(node.index() as u32, (x, y));
}
/// Get the UI position for a node
pub fn get_node_position(&self, node: NodeIndex) -> Option<(f32, f32)> {
self.node_positions.get(&(node.index() as u32)).copied()
}
/// Connect two nodes with type checking
pub fn connect(
&mut self,
@@ -543,4 +557,154 @@ impl InstrumentGraph {
new_graph
}
/// Serialize the graph to a preset
pub fn to_preset(&self, name: impl Into<String>) -> crate::audio::node_graph::preset::GraphPreset {
use crate::audio::node_graph::preset::{GraphPreset, SerializedConnection, SerializedNode};
use crate::audio::node_graph::nodes::VoiceAllocatorNode;
let mut preset = GraphPreset::new(name);
// Serialize all nodes
for node_idx in self.graph.node_indices() {
if let Some(graph_node) = self.graph.node_weight(node_idx) {
let node = &graph_node.node;
let node_id = node_idx.index() as u32;
let mut serialized = SerializedNode::new(node_id, node.node_type());
// Get all parameters
for param in node.parameters() {
let value = node.get_parameter(param.id);
serialized.set_parameter(param.id, value);
}
// For VoiceAllocator nodes, serialize the template graph
// We need to downcast to access template_graph()
// This is safe because we know the node type
if node.node_type() == "VoiceAllocator" {
// Use Any to downcast
let node_ptr = &**node as *const dyn crate::audio::node_graph::AudioNode;
let node_ptr = node_ptr as *const VoiceAllocatorNode;
unsafe {
let va_node = &*node_ptr;
let template_preset = va_node.template_graph().to_preset("template");
serialized.template_graph = Some(Box::new(template_preset));
}
}
// Save position if available
if let Some(pos) = self.get_node_position(node_idx) {
serialized.set_position(pos.0, pos.1);
}
preset.add_node(serialized);
}
}
// Serialize connections
for edge in self.graph.edge_references() {
let source = edge.source();
let target = edge.target();
let conn = edge.weight();
preset.add_connection(SerializedConnection {
from_node: source.index() as u32,
from_port: conn.from_port,
to_node: target.index() as u32,
to_port: conn.to_port,
});
}
// MIDI targets
preset.midi_targets = self.midi_targets.iter().map(|idx| idx.index() as u32).collect();
// Output node
preset.output_node = self.output_node.map(|idx| idx.index() as u32);
preset
}
/// Deserialize a preset into the graph
pub fn from_preset(preset: &crate::audio::node_graph::preset::GraphPreset, sample_rate: u32, buffer_size: usize) -> Result<Self, String> {
use crate::audio::node_graph::nodes::*;
use petgraph::stable_graph::NodeIndex;
use std::collections::HashMap;
let mut graph = Self::new(sample_rate, buffer_size);
let mut index_map: HashMap<u32, NodeIndex> = HashMap::new();
// Create all nodes
for serialized_node in &preset.nodes {
// Create the node based on type
let node: Box<dyn crate::audio::node_graph::AudioNode> = match serialized_node.node_type.as_str() {
"Oscillator" => Box::new(OscillatorNode::new("Oscillator")),
"Gain" => Box::new(GainNode::new("Gain")),
"Mixer" => Box::new(MixerNode::new("Mixer")),
"Filter" => Box::new(FilterNode::new("Filter")),
"ADSR" => Box::new(ADSRNode::new("ADSR")),
"MidiInput" => Box::new(MidiInputNode::new("MIDI Input")),
"MidiToCV" => Box::new(MidiToCVNode::new("MIDI→CV")),
"AudioToCV" => Box::new(AudioToCVNode::new("Audio→CV")),
"Oscilloscope" => Box::new(OscilloscopeNode::new("Oscilloscope")),
"TemplateInput" => Box::new(TemplateInputNode::new("Template Input")),
"TemplateOutput" => Box::new(TemplateOutputNode::new("Template Output")),
"VoiceAllocator" => {
let mut va = VoiceAllocatorNode::new("VoiceAllocator", sample_rate, buffer_size);
// If there's a template graph, deserialize and set it
if let Some(ref template_preset) = serialized_node.template_graph {
let template_graph = Self::from_preset(template_preset, sample_rate, buffer_size)?;
// Set the template graph (we'll need to add this method to VoiceAllocator)
*va.template_graph_mut() = template_graph;
va.rebuild_voices();
}
Box::new(va)
}
"AudioOutput" => Box::new(AudioOutputNode::new("Output")),
_ => return Err(format!("Unknown node type: {}", serialized_node.node_type)),
};
let node_idx = graph.add_node(node);
index_map.insert(serialized_node.id, node_idx);
// Set parameters
for (&param_id, &value) in &serialized_node.parameters {
if let Some(graph_node) = graph.graph.node_weight_mut(node_idx) {
graph_node.node.set_parameter(param_id, value);
}
}
// Restore position
graph.set_node_position(node_idx, serialized_node.position.0, serialized_node.position.1);
}
// Create connections
for conn in &preset.connections {
let from_idx = index_map.get(&conn.from_node)
.ok_or_else(|| format!("Connection from unknown node {}", conn.from_node))?;
let to_idx = index_map.get(&conn.to_node)
.ok_or_else(|| format!("Connection to unknown node {}", conn.to_node))?;
graph.connect(*from_idx, conn.from_port, *to_idx, conn.to_port)
.map_err(|e| format!("Failed to connect nodes: {:?}", e))?;
}
// Set MIDI targets
for &target_id in &preset.midi_targets {
if let Some(&target_idx) = index_map.get(&target_id) {
graph.set_midi_target(target_idx, true);
}
}
// Set output node
if let Some(output_id) = preset.output_node {
if let Some(&output_idx) = index_map.get(&output_id) {
graph.output_node = Some(output_idx);
}
}
Ok(graph)
}
}
+2
View File
@@ -2,7 +2,9 @@ mod graph;
mod node_trait;
mod types;
pub mod nodes;
pub mod preset;
pub use graph::{Connection, GraphNode, InstrumentGraph};
pub use node_trait::AudioNode;
pub use preset::{GraphPreset, PresetMetadata, SerializedConnection, SerializedNode};
pub use types::{ConnectionError, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
@@ -102,7 +102,7 @@ impl OscilloscopeNode {
];
let parameters = vec![
Parameter::new(PARAM_TIME_SCALE, "Time Scale", 10.0, 1000.0, 100.0, ParameterUnit::Milliseconds),
Parameter::new(PARAM_TIME_SCALE, "Time Scale", 10.0, 1000.0, 100.0, ParameterUnit::Time),
Parameter::new(PARAM_TRIGGER_MODE, "Trigger", 0.0, 2.0, 0.0, ParameterUnit::Generic),
Parameter::new(PARAM_TRIGGER_LEVEL, "Trigger Level", -1.0, 1.0, 0.0, ParameterUnit::Generic),
];
+147
View File
@@ -0,0 +1,147 @@
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// Serializable representation of a node graph preset
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GraphPreset {
/// Preset metadata
pub metadata: PresetMetadata,
/// Nodes in the graph
pub nodes: Vec<SerializedNode>,
/// Connections between nodes
pub connections: Vec<SerializedConnection>,
/// Which node indices are MIDI targets
pub midi_targets: Vec<u32>,
/// Which node index is the audio output (None if not set)
pub output_node: Option<u32>,
}
/// Metadata about the preset
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PresetMetadata {
/// Preset name
pub name: String,
/// Description of what the preset sounds like
#[serde(default)]
pub description: String,
/// Preset author
#[serde(default)]
pub author: String,
/// Preset version (for compatibility)
#[serde(default = "default_version")]
pub version: u32,
/// Tags for categorization (e.g., "bass", "lead", "pad")
#[serde(default)]
pub tags: Vec<String>,
}
fn default_version() -> u32 {
1
}
/// Serialized node representation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SerializedNode {
/// Unique ID (node index in the graph)
pub id: u32,
/// Node type (e.g., "Oscillator", "Filter", "ADSR")
pub node_type: String,
/// Parameter values (param_id -> value)
pub parameters: HashMap<u32, f32>,
/// UI position (for visual editor)
#[serde(default)]
pub position: (f32, f32),
/// For VoiceAllocator nodes: the nested template graph
#[serde(skip_serializing_if = "Option::is_none")]
pub template_graph: Option<Box<GraphPreset>>,
}
/// Serialized connection between nodes
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SerializedConnection {
/// Source node ID
pub from_node: u32,
/// Source port index
pub from_port: usize,
/// Destination node ID
pub to_node: u32,
/// Destination port index
pub to_port: usize,
}
impl GraphPreset {
/// Create a new preset with the given name
pub fn new(name: impl Into<String>) -> Self {
Self {
metadata: PresetMetadata {
name: name.into(),
description: String::new(),
author: String::new(),
version: 1,
tags: Vec::new(),
},
nodes: Vec::new(),
connections: Vec::new(),
midi_targets: Vec::new(),
output_node: None,
}
}
/// Serialize to JSON string
pub fn to_json(&self) -> Result<String, serde_json::Error> {
serde_json::to_string_pretty(self)
}
/// Deserialize from JSON string
pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
serde_json::from_str(json)
}
/// Add a node to the preset
pub fn add_node(&mut self, node: SerializedNode) {
self.nodes.push(node);
}
/// Add a connection to the preset
pub fn add_connection(&mut self, connection: SerializedConnection) {
self.connections.push(connection);
}
}
impl SerializedNode {
/// Create a new serialized node
pub fn new(id: u32, node_type: impl Into<String>) -> Self {
Self {
id,
node_type: node_type.into(),
parameters: HashMap::new(),
position: (0.0, 0.0),
template_graph: None,
}
}
/// Set a parameter value
pub fn set_parameter(&mut self, param_id: u32, value: f32) {
self.parameters.insert(param_id, value);
}
/// Set UI position
pub fn set_position(&mut self, x: f32, y: f32) {
self.position = (x, y);
}
}
+5
View File
@@ -137,6 +137,11 @@ pub enum Command {
GraphSetMidiTarget(TrackId, u32, bool),
/// Set which node is the audio output (track_id, node_index)
GraphSetOutputNode(TrackId, u32),
/// Save current graph as a preset (track_id, preset_path, preset_name, description, tags)
GraphSavePreset(TrackId, String, String, String, Vec<String>),
/// Load a preset into a track's graph (track_id, preset_path)
GraphLoadPreset(TrackId, String),
}
/// Events sent from audio thread back to UI/control thread
+1
View File
@@ -17,6 +17,7 @@ pub use audio::{
Metatrack, MidiClip, MidiClipId, MidiEvent, MidiTrack, ParameterId, PoolAudioFile, Project, RecordingState, RenderContext, Track, TrackId,
TrackNode,
};
pub use audio::node_graph::{GraphPreset, InstrumentGraph, PresetMetadata, SerializedConnection, SerializedNode};
pub use command::{AudioEvent, Command};
pub use effects::{Effect, GainEffect, PanEffect, SimpleEQ, SimpleSynth};
pub use io::{load_midi_file, AudioFile, WaveformPeak, WavWriter};