Initial release: 8-bit sound synthesizer with LLM/MCP integration
Soundgen is a Rust workspace for generating 8-bit/chiptune sound effects, UI sounds, and ambient textures for game audio assets. It features JSON-first sound specs, an MCP server for LLM tool-use, an egui GUI editor, and a runtime library with NES-authentic DAC emulation. Features: - 6 voice types: pulse, triangle, noise, DPCM, wavetable, FM - Effects: ADSR envelope, frequency sweep, biquad filter, vibrato - 13 built-in presets (SFX/UI/ambient) as JSON data files - MCP server: list_presets, generate_sfx, render_sound tools - Pattern-based sequencer (JSON song format) - egui GUI: virtual keyboard, preset browser, channel editor, undo/redo - Runtime: NES nonlinear DAC + SoundBank for game embedding - 90 tests, 0 warnings Crates: - soundgen-core: synthesis engine (no I/O) - soundgen-fmt: SoundSpec JSON schema + PresetRegistry - soundgen-io: WAV writer + audio playback - soundgen-seq: sequencer (patterns, songs) - soundgen-cli: gen/render/render-song/list-presets - soundgen-mcp: MCP server for LLM integration - soundgen-gui: egui editor - soundgen-runtime: NES DAC + SoundBank
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "soundgen-gui"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "soundgen-gui"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
soundgen-core.workspace = true
|
||||
soundgen-fmt.workspace = true
|
||||
soundgen-io.workspace = true
|
||||
soundgen-seq.workspace = true
|
||||
eframe.workspace = true
|
||||
egui.workspace = true
|
||||
egui-file-dialog.workspace = true
|
||||
serde_json.workspace = true
|
||||
@@ -0,0 +1,912 @@
|
||||
//! Main Soundgen GUI application.
|
||||
//!
|
||||
//! Layout:
|
||||
//! - Top: menu bar (File / Edit)
|
||||
//! - Below: tab bar (SFX Editor / Sequencer) + transport (Play/Stop)
|
||||
//! - Left: preset browser
|
||||
//! - Center: editor content
|
||||
//! - Bottom: status bar + virtual keyboard
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use eframe::egui;
|
||||
use egui_file_dialog::FileDialog;
|
||||
use soundgen_fmt::{render_spec, ChannelSpec, PresetRegistry, SoundSpec};
|
||||
use soundgen_io::{play, write_wav};
|
||||
use soundgen_seq::{render_song, Song};
|
||||
|
||||
use crate::channel_panel::channel_panel;
|
||||
use crate::keyboard::Keyboard;
|
||||
use crate::preset_browser::PresetBrowser;
|
||||
use crate::waveform::waveform_display;
|
||||
|
||||
// ── Undo/Redo ────────────────────────────────────────────
|
||||
|
||||
struct UndoStack {
|
||||
undo: Vec<SoundSpec>,
|
||||
redo: Vec<SoundSpec>,
|
||||
last_save: Instant,
|
||||
}
|
||||
|
||||
impl UndoStack {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
undo: vec![],
|
||||
redo: vec![],
|
||||
last_save: Instant::now(),
|
||||
}
|
||||
}
|
||||
|
||||
fn push(&mut self, spec: &SoundSpec) {
|
||||
// Debounce: don't push more often than every 500ms
|
||||
if self.last_save.elapsed() < Duration::from_millis(500) {
|
||||
if let Some(last) = self.undo.last_mut() {
|
||||
*last = spec.clone();
|
||||
return;
|
||||
}
|
||||
}
|
||||
self.last_save = Instant::now();
|
||||
self.undo.push(spec.clone());
|
||||
self.redo.clear();
|
||||
if self.undo.len() > 50 {
|
||||
self.undo.remove(0);
|
||||
}
|
||||
}
|
||||
|
||||
fn undo(&mut self, current: &SoundSpec) -> Option<SoundSpec> {
|
||||
if let Some(prev) = self.undo.pop() {
|
||||
self.redo.push(current.clone());
|
||||
Some(prev)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn redo(&mut self, current: &SoundSpec) -> Option<SoundSpec> {
|
||||
if let Some(next) = self.redo.pop() {
|
||||
self.undo.push(current.clone());
|
||||
Some(next)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn can_undo(&self) -> bool {
|
||||
!self.undo.is_empty()
|
||||
}
|
||||
|
||||
fn can_redo(&self) -> bool {
|
||||
!self.redo.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
// ── App State ────────────────────────────────────────────
|
||||
|
||||
pub struct SoundgenApp {
|
||||
spec: SoundSpec,
|
||||
registry: PresetRegistry,
|
||||
browser: PresetBrowser,
|
||||
keyboard: Keyboard,
|
||||
song: Song,
|
||||
song_json: String,
|
||||
song_json_error: Option<String>,
|
||||
preview_samples: Vec<f32>,
|
||||
preview_dirty: bool,
|
||||
last_preview_update: Option<Instant>,
|
||||
status: String,
|
||||
status_time: Option<Instant>,
|
||||
playing: Option<Arc<Mutex<soundgen_io::PlaybackHandle>>>,
|
||||
tab: Tab,
|
||||
file_path: String,
|
||||
undo: UndoStack,
|
||||
file_dialog: FileDialog,
|
||||
export_dialog: FileDialog,
|
||||
open_dialog: FileDialog,
|
||||
last_keyboard_freq: f32,
|
||||
last_keyboard_vel: u8,
|
||||
}
|
||||
|
||||
#[derive(PartialEq)]
|
||||
enum Tab {
|
||||
SfxEditor,
|
||||
Sequencer,
|
||||
}
|
||||
|
||||
impl Default for SoundgenApp {
|
||||
fn default() -> Self {
|
||||
let registry =
|
||||
PresetRegistry::load_dir(std::path::Path::new("presets")).unwrap_or_else(|e| {
|
||||
eprintln!("Warning: could not load presets: {}", e);
|
||||
PresetRegistry::new()
|
||||
});
|
||||
|
||||
let spec = registry
|
||||
.get("jump")
|
||||
.map(|e| e.spec.clone())
|
||||
.unwrap_or(SoundSpec {
|
||||
name: "new_sound".to_string(),
|
||||
duration: 0.2,
|
||||
sample_rate: 44100,
|
||||
channels: vec![ChannelSpec::Pulse {
|
||||
duty: 50,
|
||||
frequency: soundgen_core::FrequencyAutomation::fixed(440.0),
|
||||
envelope: None,
|
||||
filter: None,
|
||||
volume: 0.5,
|
||||
pan: 0.0,
|
||||
}],
|
||||
});
|
||||
|
||||
let song = default_song();
|
||||
let song_json = serde_json::to_string_pretty(&song).unwrap_or_default();
|
||||
|
||||
Self {
|
||||
spec,
|
||||
registry,
|
||||
browser: PresetBrowser::new(),
|
||||
keyboard: Keyboard::new(60, 2),
|
||||
song,
|
||||
song_json,
|
||||
song_json_error: None,
|
||||
preview_samples: vec![],
|
||||
preview_dirty: true,
|
||||
last_preview_update: None,
|
||||
status: "Ready".to_string(),
|
||||
status_time: None,
|
||||
playing: None,
|
||||
tab: Tab::SfxEditor,
|
||||
file_path: "sound.json".to_string(),
|
||||
undo: UndoStack::new(),
|
||||
file_dialog: FileDialog::default(),
|
||||
export_dialog: FileDialog::default(),
|
||||
open_dialog: FileDialog::default(),
|
||||
last_keyboard_freq: 440.0,
|
||||
last_keyboard_vel: 100,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_song() -> Song {
|
||||
use soundgen_seq::{EnvelopeConfig, Note, Pattern, Row, TrackConfig, TrackVoice};
|
||||
Song {
|
||||
bpm: 120.0,
|
||||
rows_per_beat: 4,
|
||||
sample_rate: 44100,
|
||||
tracks: vec![
|
||||
TrackConfig {
|
||||
voice: TrackVoice::Pulse { duty: 50 },
|
||||
envelope: Some(EnvelopeConfig {
|
||||
attack: 0.005,
|
||||
decay: 0.03,
|
||||
sustain: 0.6,
|
||||
release: 0.05,
|
||||
}),
|
||||
volume: 0.35,
|
||||
pan: -0.2,
|
||||
},
|
||||
TrackConfig {
|
||||
voice: TrackVoice::Triangle,
|
||||
envelope: Some(EnvelopeConfig {
|
||||
attack: 0.01,
|
||||
decay: 0.05,
|
||||
sustain: 0.5,
|
||||
release: 0.08,
|
||||
}),
|
||||
volume: 0.4,
|
||||
pan: 0.3,
|
||||
},
|
||||
],
|
||||
patterns: vec![Pattern {
|
||||
rows: vec![
|
||||
Row {
|
||||
notes: vec![
|
||||
Some(Note::from_name("C4", 1.0).unwrap()),
|
||||
Some(Note::from_name("C2", 1.0).unwrap()),
|
||||
],
|
||||
},
|
||||
Row {
|
||||
notes: vec![None, None],
|
||||
},
|
||||
Row {
|
||||
notes: vec![Some(Note::from_name("E4", 1.0).unwrap()), None],
|
||||
},
|
||||
Row {
|
||||
notes: vec![None, None],
|
||||
},
|
||||
Row {
|
||||
notes: vec![
|
||||
Some(Note::from_name("G4", 1.0).unwrap()),
|
||||
Some(Note::from_name("G2", 1.0).unwrap()),
|
||||
],
|
||||
},
|
||||
Row {
|
||||
notes: vec![None, None],
|
||||
},
|
||||
Row {
|
||||
notes: vec![Some(Note::from_name("E4", 1.0).unwrap()), None],
|
||||
},
|
||||
Row {
|
||||
notes: vec![None, None],
|
||||
},
|
||||
],
|
||||
}],
|
||||
pattern_order: vec![0, 0],
|
||||
}
|
||||
}
|
||||
|
||||
impl eframe::App for SoundgenApp {
|
||||
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
// Handle hotkeys
|
||||
self.handle_hotkeys(ctx);
|
||||
|
||||
// Debounced preview update
|
||||
if self.preview_dirty {
|
||||
if let Some(last) = self.last_preview_update {
|
||||
if last.elapsed() >= Duration::from_millis(100) {
|
||||
self.update_preview();
|
||||
self.preview_dirty = false;
|
||||
self.last_preview_update = None;
|
||||
} else {
|
||||
ctx.request_repaint_after(Duration::from_millis(50));
|
||||
}
|
||||
} else {
|
||||
self.last_preview_update = Some(Instant::now());
|
||||
ctx.request_repaint_after(Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
|
||||
// Menu bar
|
||||
egui::TopBottomPanel::top("menu_bar").show(ctx, |ui| {
|
||||
egui::menu::bar(ui, |ui| {
|
||||
ui.menu_button("File", |ui| {
|
||||
if ui.button("Open... (Ctrl+O)").clicked() {
|
||||
self.open_dialog.select_file();
|
||||
ui.close_menu();
|
||||
}
|
||||
if ui.button("Save... (Ctrl+S)").clicked() {
|
||||
self.file_dialog.save_file();
|
||||
ui.close_menu();
|
||||
}
|
||||
if ui.button("Export WAV... (Ctrl+E)").clicked() {
|
||||
self.export_dialog.save_file();
|
||||
ui.close_menu();
|
||||
}
|
||||
if ui.button("New Sound").clicked() {
|
||||
self.new_sound();
|
||||
ui.close_menu();
|
||||
}
|
||||
});
|
||||
|
||||
ui.menu_button("Edit", |ui| {
|
||||
ui.add_enabled_ui(self.undo.can_undo(), |ui| {
|
||||
if ui.button("Undo (Ctrl+Z)").clicked() {
|
||||
self.do_undo();
|
||||
ui.close_menu();
|
||||
}
|
||||
});
|
||||
ui.add_enabled_ui(self.undo.can_redo(), |ui| {
|
||||
if ui.button("Redo (Ctrl+Shift+Z)").clicked() {
|
||||
self.do_redo();
|
||||
ui.close_menu();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
ui.menu_button("Add Channel", |ui| {
|
||||
if ui.button("Pulse").clicked() {
|
||||
self.add_channel(ChannelType::Pulse);
|
||||
ui.close_menu();
|
||||
}
|
||||
if ui.button("Triangle").clicked() {
|
||||
self.add_channel(ChannelType::Triangle);
|
||||
ui.close_menu();
|
||||
}
|
||||
if ui.button("Noise").clicked() {
|
||||
self.add_channel(ChannelType::Noise);
|
||||
ui.close_menu();
|
||||
}
|
||||
});
|
||||
|
||||
ui.separator();
|
||||
|
||||
ui.selectable_value(&mut self.tab, Tab::SfxEditor, "SFX Editor");
|
||||
ui.selectable_value(&mut self.tab, Tab::Sequencer, "Sequencer");
|
||||
|
||||
ui.separator();
|
||||
|
||||
// Transport
|
||||
let play_label = if self.playing.is_some() {
|
||||
"⏸ Stop"
|
||||
} else {
|
||||
"▶ Play"
|
||||
};
|
||||
if ui.button(play_label).clicked() {
|
||||
if self.playing.is_some() {
|
||||
self.stop_playback();
|
||||
self.set_status("Stopped".to_string());
|
||||
} else {
|
||||
self.play_current();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Status bar (above keyboard)
|
||||
egui::TopBottomPanel::bottom("status_bar").show(ctx, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
let status_color = if self.status.starts_with("Error") {
|
||||
egui::Color32::from_rgb(255, 100, 100)
|
||||
} else {
|
||||
egui::Color32::from_rgb(120, 180, 120)
|
||||
};
|
||||
ui.label(egui::RichText::new(&self.status).color(status_color));
|
||||
ui.separator();
|
||||
ui.label(
|
||||
egui::RichText::new(format!("{} Hz", self.spec.sample_rate))
|
||||
.small()
|
||||
.weak(),
|
||||
);
|
||||
if self.last_keyboard_freq > 0.0 {
|
||||
ui.label(
|
||||
egui::RichText::new(format!("Note: {:.0} Hz", self.last_keyboard_freq))
|
||||
.small()
|
||||
.weak(),
|
||||
);
|
||||
}
|
||||
ui.separator();
|
||||
ui.label(
|
||||
egui::RichText::new(format!("Channels: {}", self.spec.channels.len()))
|
||||
.small()
|
||||
.weak(),
|
||||
);
|
||||
if self.undo.can_undo() {
|
||||
ui.label(
|
||||
egui::RichText::new(format!("Undo: {}", self.undo.undo.len()))
|
||||
.small()
|
||||
.weak(),
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Keyboard panel
|
||||
egui::TopBottomPanel::bottom("keyboard_panel")
|
||||
.resizable(true)
|
||||
.default_height(140.0)
|
||||
.show(ctx, |ui| {
|
||||
let (presses, _releases, vel) = self.keyboard.show(ui);
|
||||
|
||||
for midi in &presses {
|
||||
let freq = crate::keyboard::midi_to_freq(*midi);
|
||||
self.last_keyboard_freq = freq;
|
||||
self.last_keyboard_vel = vel;
|
||||
// Set frequency on first channel
|
||||
if !self.spec.channels.is_empty() {
|
||||
self.spec.channels[0] =
|
||||
set_channel_freq(self.spec.channels[0].clone(), freq);
|
||||
// Set velocity as volume
|
||||
self.spec.channels[0] =
|
||||
set_channel_vol(self.spec.channels[0].clone(), vel as f32 / 127.0);
|
||||
}
|
||||
}
|
||||
|
||||
if !presses.is_empty() {
|
||||
self.play_current();
|
||||
}
|
||||
});
|
||||
|
||||
// Left panel: preset browser
|
||||
egui::SidePanel::left("browser")
|
||||
.resizable(true)
|
||||
.default_width(260.0)
|
||||
.show(ctx, |ui| {
|
||||
let to_play = self.browser.show(ui, &self.registry);
|
||||
if let Some(name) = to_play {
|
||||
if let Some(entry) = self.registry.get(&name) {
|
||||
self.undo.push(&self.spec);
|
||||
self.spec = entry.spec.clone();
|
||||
self.preview_dirty = true;
|
||||
self.status = format!("Loaded: {}", name);
|
||||
self.play_current();
|
||||
}
|
||||
}
|
||||
|
||||
ui.separator();
|
||||
|
||||
let selected_name = self.browser.selected.clone();
|
||||
if let Some(name) = &selected_name {
|
||||
let entry = self.registry.get(name).cloned();
|
||||
if let Some(entry) = entry {
|
||||
let spec = entry.spec.clone();
|
||||
let display_name = entry.name.clone();
|
||||
let dur = entry.spec.duration;
|
||||
let nch = entry.spec.channels.len();
|
||||
let sr = entry.spec.sample_rate;
|
||||
ui.group(|ui| {
|
||||
ui.heading(display_name);
|
||||
ui.label(format!("Duration: {:.2}s", dur));
|
||||
ui.label(format!("Channels: {}", nch));
|
||||
if ui.button("Load into editor").clicked() {
|
||||
self.undo.push(&self.spec);
|
||||
self.spec = spec.clone();
|
||||
self.preview_dirty = true;
|
||||
self.status = format!("Loaded: {}", name);
|
||||
}
|
||||
if ui.button("▶ Play preset").clicked() {
|
||||
let samples = render_spec(&spec);
|
||||
self.start_playback(samples, sr);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Central panel: editor
|
||||
egui::CentralPanel::default().show(ctx, |ui| match self.tab {
|
||||
Tab::SfxEditor => self.show_sfx_editor(ui),
|
||||
Tab::Sequencer => self.show_sequencer(ui),
|
||||
});
|
||||
|
||||
// Handle file dialogs
|
||||
self.handle_file_dialogs(ctx);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum ChannelType {
|
||||
Pulse,
|
||||
Triangle,
|
||||
Noise,
|
||||
}
|
||||
|
||||
impl SoundgenApp {
|
||||
fn handle_hotkeys(&mut self, ctx: &egui::Context) {
|
||||
let modifiers = ctx.input(|i| i.modifiers);
|
||||
let ctrl = modifiers.ctrl || modifiers.command;
|
||||
|
||||
// Space: play/stop
|
||||
if ctx.input(|i| i.key_pressed(egui::Key::Space)) {
|
||||
if self.playing.is_some() {
|
||||
self.stop_playback();
|
||||
self.set_status("Stopped".to_string());
|
||||
} else {
|
||||
self.play_current();
|
||||
}
|
||||
}
|
||||
|
||||
// Ctrl+S: save
|
||||
if ctrl && ctx.input(|i| i.key_pressed(egui::Key::S)) {
|
||||
self.file_dialog.save_file();
|
||||
}
|
||||
|
||||
// Ctrl+O: open
|
||||
if ctrl && ctx.input(|i| i.key_pressed(egui::Key::O)) {
|
||||
self.open_dialog.select_file();
|
||||
}
|
||||
|
||||
// Ctrl+E: export WAV
|
||||
if ctrl && ctx.input(|i| i.key_pressed(egui::Key::E)) {
|
||||
self.export_dialog.save_file();
|
||||
}
|
||||
|
||||
// Ctrl+Z: undo, Ctrl+Shift+Z: redo
|
||||
if ctrl && ctx.input(|i| i.key_pressed(egui::Key::Z)) {
|
||||
if modifiers.shift {
|
||||
self.do_redo();
|
||||
} else {
|
||||
self.do_undo();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_file_dialogs(&mut self, ctx: &egui::Context) {
|
||||
// Save dialog
|
||||
self.file_dialog.update(ctx);
|
||||
if let Some(path) = self.file_dialog.take_selected() {
|
||||
let json = serde_json::to_string_pretty(&self.spec).unwrap_or_default();
|
||||
match std::fs::write(&path, json) {
|
||||
Ok(()) => {
|
||||
self.file_path = path.display().to_string();
|
||||
self.set_status(format!("Saved to {}", path.display()));
|
||||
}
|
||||
Err(e) => self.set_status(format!("Save error: {}", e)),
|
||||
}
|
||||
}
|
||||
|
||||
// Open dialog
|
||||
self.open_dialog.update(ctx);
|
||||
if let Some(path) = self.open_dialog.take_selected() {
|
||||
match std::fs::read_to_string(&path) {
|
||||
Ok(content) => match serde_json::from_str::<SoundSpec>(&content) {
|
||||
Ok(spec) => {
|
||||
self.undo.push(&self.spec);
|
||||
self.spec = spec;
|
||||
self.file_path = path.display().to_string();
|
||||
self.preview_dirty = true;
|
||||
self.set_status(format!("Loaded from {}", path.display()));
|
||||
}
|
||||
Err(e) => self.set_status(format!("Parse error: {}", e)),
|
||||
},
|
||||
Err(e) => self.set_status(format!("Load error: {}", e)),
|
||||
}
|
||||
}
|
||||
|
||||
// Export dialog
|
||||
self.export_dialog.update(ctx);
|
||||
if let Some(path) = self.export_dialog.take_selected() {
|
||||
let samples = render_spec(&self.spec);
|
||||
match write_wav(&path, &samples, self.spec.sample_rate) {
|
||||
Ok(()) => self.set_status(format!("Exported to {}", path.display())),
|
||||
Err(e) => self.set_status(format!("Export error: {}", e)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn show_sfx_editor(&mut self, ui: &mut egui::Ui) {
|
||||
// Sound properties
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Name:");
|
||||
ui.text_edit_singleline(&mut self.spec.name);
|
||||
ui.separator();
|
||||
ui.label("Duration:");
|
||||
if ui
|
||||
.add(
|
||||
egui::Slider::new(&mut self.spec.duration, 0.01..=10.0)
|
||||
.suffix("s")
|
||||
.fixed_decimals(2),
|
||||
)
|
||||
.changed()
|
||||
{
|
||||
self.mark_dirty();
|
||||
}
|
||||
});
|
||||
|
||||
ui.separator();
|
||||
|
||||
// Channel controls
|
||||
let total = self.spec.channels.len();
|
||||
let mut to_remove: Option<usize> = None;
|
||||
let mut to_dup: Option<usize> = None;
|
||||
let mut to_move_up: Option<usize> = None;
|
||||
let mut to_move_down: Option<usize> = None;
|
||||
let mut any_changed = false;
|
||||
|
||||
for (i, channel) in self.spec.channels.iter_mut().enumerate() {
|
||||
let edit = channel_panel(ui, channel, i, total, "ch");
|
||||
if edit.changed {
|
||||
any_changed = true;
|
||||
}
|
||||
if edit.deleted {
|
||||
to_remove = Some(i);
|
||||
}
|
||||
if edit.duplicated {
|
||||
to_dup = Some(i);
|
||||
}
|
||||
if edit.moved_up {
|
||||
to_move_up = Some(i);
|
||||
}
|
||||
if edit.moved_down {
|
||||
to_move_down = Some(i);
|
||||
}
|
||||
}
|
||||
|
||||
if any_changed {
|
||||
self.mark_dirty();
|
||||
}
|
||||
|
||||
// Process channel edits
|
||||
if let Some(idx) = to_remove {
|
||||
self.undo.push(&self.spec);
|
||||
self.spec.channels.remove(idx);
|
||||
self.mark_dirty();
|
||||
}
|
||||
if let Some(idx) = to_dup {
|
||||
self.undo.push(&self.spec);
|
||||
let dup = self.spec.channels[idx].clone();
|
||||
// Adjust name if possible
|
||||
self.spec.channels.insert(idx + 1, dup);
|
||||
self.mark_dirty();
|
||||
}
|
||||
if let Some(idx) = to_move_up {
|
||||
if idx > 0 {
|
||||
self.undo.push(&self.spec);
|
||||
self.spec.channels.swap(idx, idx - 1);
|
||||
self.mark_dirty();
|
||||
}
|
||||
}
|
||||
if let Some(idx) = to_move_down {
|
||||
if idx < total - 1 {
|
||||
self.undo.push(&self.spec);
|
||||
self.spec.channels.swap(idx, idx + 1);
|
||||
self.mark_dirty();
|
||||
}
|
||||
}
|
||||
|
||||
ui.separator();
|
||||
|
||||
// Waveform preview
|
||||
ui.heading("Preview");
|
||||
let preview_dur = self.spec.duration;
|
||||
waveform_display(ui, &self.preview_samples, preview_dur, 80.0);
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("▶ Play").on_hover_text("Space").clicked() {
|
||||
self.play_current();
|
||||
}
|
||||
if ui
|
||||
.button("⟳ Refresh")
|
||||
.on_hover_text("Force re-render")
|
||||
.clicked()
|
||||
{
|
||||
self.update_preview();
|
||||
}
|
||||
if ui.button("Export WAV").on_hover_text("Ctrl+E").clicked() {
|
||||
self.export_dialog.save_file();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn show_sequencer(&mut self, ui: &mut egui::Ui) {
|
||||
ui.heading("Sequencer (Song)");
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("BPM:");
|
||||
ui.add(egui::Slider::new(&mut self.song.bpm, 60.0..=240.0));
|
||||
ui.separator();
|
||||
ui.label("Rows/beat:");
|
||||
ui.add(egui::Slider::new(&mut self.song.rows_per_beat, 1..=16));
|
||||
});
|
||||
|
||||
ui.separator();
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(format!(
|
||||
"Tracks: {} · Patterns: {} · Duration: {:.1}s",
|
||||
self.song.tracks.len(),
|
||||
self.song.patterns.len(),
|
||||
self.song.duration()
|
||||
));
|
||||
});
|
||||
|
||||
ui.separator();
|
||||
|
||||
// Action buttons
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("Format JSON").clicked() {
|
||||
self.song_json = serde_json::to_string_pretty(&self.song).unwrap_or_default();
|
||||
self.song_json_error = None;
|
||||
}
|
||||
if ui.button("Validate").clicked() {
|
||||
match serde_json::from_str::<Song>(&self.song_json) {
|
||||
Ok(_) => {
|
||||
self.song_json_error = None;
|
||||
self.set_status("JSON valid".to_string());
|
||||
}
|
||||
Err(e) => {
|
||||
self.song_json_error = Some(format!("{}", e));
|
||||
}
|
||||
}
|
||||
}
|
||||
if ui.button("New Song").clicked() {
|
||||
self.song = default_song();
|
||||
self.song_json = serde_json::to_string_pretty(&self.song).unwrap_or_default();
|
||||
self.song_json_error = None;
|
||||
}
|
||||
if ui.button("Apply JSON").clicked() {
|
||||
match serde_json::from_str::<Song>(&self.song_json) {
|
||||
Ok(song) => {
|
||||
self.song = song;
|
||||
self.song_json_error = None;
|
||||
self.set_status("Song updated".to_string());
|
||||
}
|
||||
Err(e) => {
|
||||
self.song_json_error = Some(format!("{}", e));
|
||||
}
|
||||
}
|
||||
}
|
||||
if ui.button("▶ Play Song").clicked() {
|
||||
let samples = render_song(&self.song);
|
||||
self.start_playback(samples, self.song.sample_rate);
|
||||
}
|
||||
if ui.button("Export Song WAV").clicked() {
|
||||
let samples = render_song(&self.song);
|
||||
let path = std::path::Path::new("song_export.wav");
|
||||
match write_wav(path, &samples, self.song.sample_rate) {
|
||||
Ok(()) => self.set_status(format!("Exported to {}", path.display())),
|
||||
Err(e) => self.set_status(format!("Export error: {}", e)),
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Show error
|
||||
if let Some(err) = &self.song_json_error {
|
||||
ui.colored_label(
|
||||
egui::Color32::from_rgb(255, 100, 100),
|
||||
format!("Error: {}", err),
|
||||
);
|
||||
}
|
||||
|
||||
ui.separator();
|
||||
|
||||
// JSON editor
|
||||
egui::ScrollArea::vertical()
|
||||
.id_source("song_json")
|
||||
.show(ui, |ui| {
|
||||
ui.add(
|
||||
egui::TextEdit::multiline(&mut self.song_json)
|
||||
.code_editor()
|
||||
.desired_width(f32::INFINITY)
|
||||
.desired_rows(20),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// ── Playback ──────────────────────────────────────────
|
||||
|
||||
fn play_current(&mut self) {
|
||||
let samples = render_spec(&self.spec);
|
||||
self.preview_samples = downsample_for_display(&samples);
|
||||
self.start_playback(samples, self.spec.sample_rate);
|
||||
}
|
||||
|
||||
fn start_playback(&mut self, samples: Vec<f32>, sample_rate: u32) {
|
||||
// Stop any previous playback first (prevents Drop from blocking)
|
||||
self.stop_playback();
|
||||
match play(&samples, sample_rate) {
|
||||
Ok(handle) => {
|
||||
self.playing = Some(Arc::new(Mutex::new(handle)));
|
||||
self.set_status(format!("Playing '{}'...", self.spec.name));
|
||||
}
|
||||
Err(e) => {
|
||||
self.set_status(format!("Playback error: {}", e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn stop_playback(&mut self) {
|
||||
if let Some(h) = self.playing.take() {
|
||||
if let Ok(mut guard) = h.lock() {
|
||||
guard.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Preview ───────────────────────────────────────────
|
||||
|
||||
fn mark_dirty(&mut self) {
|
||||
self.preview_dirty = true;
|
||||
}
|
||||
|
||||
fn update_preview(&mut self) {
|
||||
let samples = render_spec(&self.spec);
|
||||
self.preview_samples = downsample_for_display(&samples);
|
||||
}
|
||||
|
||||
// ── File operations ───────────────────────────────────
|
||||
|
||||
fn new_sound(&mut self) {
|
||||
self.undo.push(&self.spec);
|
||||
self.spec = SoundSpec {
|
||||
name: "new_sound".to_string(),
|
||||
duration: 0.2,
|
||||
sample_rate: 44100,
|
||||
channels: vec![ChannelSpec::Pulse {
|
||||
duty: 50,
|
||||
frequency: soundgen_core::FrequencyAutomation::fixed(440.0),
|
||||
envelope: None,
|
||||
filter: None,
|
||||
volume: 0.5,
|
||||
pan: 0.0,
|
||||
}],
|
||||
};
|
||||
self.mark_dirty();
|
||||
self.set_status("New sound".to_string());
|
||||
}
|
||||
|
||||
// ── Undo/Redo ─────────────────────────────────────────
|
||||
|
||||
fn do_undo(&mut self) {
|
||||
if let Some(prev) = self.undo.undo(&self.spec) {
|
||||
self.spec = prev;
|
||||
self.mark_dirty();
|
||||
self.set_status("Undo".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
fn do_redo(&mut self) {
|
||||
if let Some(next) = self.undo.redo(&self.spec) {
|
||||
self.spec = next;
|
||||
self.mark_dirty();
|
||||
self.set_status("Redo".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
// ── Channels ──────────────────────────────────────────
|
||||
|
||||
fn add_channel(&mut self, ch_type: ChannelType) {
|
||||
self.undo.push(&self.spec);
|
||||
match ch_type {
|
||||
ChannelType::Pulse => {
|
||||
self.spec.channels.push(ChannelSpec::Pulse {
|
||||
duty: 50,
|
||||
frequency: soundgen_core::FrequencyAutomation::fixed(440.0),
|
||||
envelope: None,
|
||||
filter: None,
|
||||
volume: 0.5,
|
||||
pan: 0.0,
|
||||
});
|
||||
}
|
||||
ChannelType::Triangle => {
|
||||
self.spec.channels.push(ChannelSpec::Triangle {
|
||||
frequency: soundgen_core::FrequencyAutomation::fixed(220.0),
|
||||
envelope: None,
|
||||
filter: None,
|
||||
volume: 0.4,
|
||||
pan: 0.0,
|
||||
});
|
||||
}
|
||||
ChannelType::Noise => {
|
||||
self.spec.channels.push(ChannelSpec::Noise {
|
||||
mode: "white".to_string(),
|
||||
frequency: 8000.0,
|
||||
envelope: None,
|
||||
filter: None,
|
||||
volume: 0.3,
|
||||
pan: 0.0,
|
||||
});
|
||||
}
|
||||
}
|
||||
self.mark_dirty();
|
||||
}
|
||||
|
||||
// ── Status ────────────────────────────────────────────
|
||||
|
||||
fn set_status(&mut self, msg: String) {
|
||||
self.status = msg;
|
||||
self.status_time = Some(Instant::now());
|
||||
}
|
||||
}
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────
|
||||
|
||||
fn set_channel_freq(mut ch: ChannelSpec, freq: f32) -> ChannelSpec {
|
||||
match &mut ch {
|
||||
ChannelSpec::Pulse { frequency, .. } => {
|
||||
frequency.start = freq;
|
||||
frequency.end = freq;
|
||||
}
|
||||
ChannelSpec::Triangle { frequency, .. } => {
|
||||
frequency.start = freq;
|
||||
frequency.end = freq;
|
||||
}
|
||||
ChannelSpec::Noise { .. } => {}
|
||||
}
|
||||
ch
|
||||
}
|
||||
|
||||
fn set_channel_vol(mut ch: ChannelSpec, vol: f32) -> ChannelSpec {
|
||||
match &mut ch {
|
||||
ChannelSpec::Pulse { volume, .. } => *volume = vol,
|
||||
ChannelSpec::Triangle { volume, .. } => *volume = vol,
|
||||
ChannelSpec::Noise { volume, .. } => *volume = vol,
|
||||
}
|
||||
ch
|
||||
}
|
||||
|
||||
fn downsample_for_display(samples: &[f32]) -> Vec<f32> {
|
||||
// Interleaved stereo → mono
|
||||
let mono: Vec<f32> = samples.iter().step_by(2).cloned().collect();
|
||||
let target_len = 1500usize;
|
||||
if mono.len() > target_len {
|
||||
let step = mono.len() / target_len;
|
||||
mono.iter()
|
||||
.step_by(step)
|
||||
.take(target_len)
|
||||
.cloned()
|
||||
.collect()
|
||||
} else {
|
||||
mono
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,480 @@
|
||||
//! Channel panel — controls for duty cycle, frequency, envelope, filter, volume, pan.
|
||||
//!
|
||||
//! Features:
|
||||
//! - Collapsible channels with color-coded headers
|
||||
//! - Compact ADSR with mini visual shape
|
||||
//! - Filter controls (type, cutoff, Q, sweep)
|
||||
//! - Move up/down, duplicate, delete buttons
|
||||
|
||||
use egui::{Color32, Ui};
|
||||
use soundgen_core::{FrequencyAutomation, SweepCurve};
|
||||
use soundgen_fmt::{ChannelSpec, CutoffAutomation, EnvelopeSpec, FilterKind, FilterSpec};
|
||||
|
||||
/// Channel type color for headers.
|
||||
pub fn channel_type_color(channel: &ChannelSpec) -> Color32 {
|
||||
match channel {
|
||||
ChannelSpec::Pulse { .. } => Color32::from_rgb(255, 200, 80), // amber
|
||||
ChannelSpec::Triangle { .. } => Color32::from_rgb(100, 255, 150), // green
|
||||
ChannelSpec::Noise { .. } => Color32::from_rgb(180, 180, 190), // gray
|
||||
}
|
||||
}
|
||||
|
||||
/// Channel type name.
|
||||
pub fn channel_type_name(channel: &ChannelSpec) -> &'static str {
|
||||
match channel {
|
||||
ChannelSpec::Pulse { .. } => "Pulse",
|
||||
ChannelSpec::Triangle { .. } => "Triangle",
|
||||
ChannelSpec::Noise { .. } => "Noise",
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw controls for a channel spec inside a collapsing header.
|
||||
/// Returns true if the spec was modified.
|
||||
pub fn channel_panel(
|
||||
ui: &mut Ui,
|
||||
channel: &mut ChannelSpec,
|
||||
index: usize,
|
||||
total: usize,
|
||||
id_source: &str,
|
||||
) -> ChannelEdit {
|
||||
let mut edit = ChannelEdit::default();
|
||||
let color = channel_type_color(channel);
|
||||
let name = channel_type_name(channel);
|
||||
|
||||
// Header with color bar + buttons
|
||||
ui.horizontal(|ui| {
|
||||
// Color indicator
|
||||
let (bar_rect, _) =
|
||||
ui.allocate_exact_size(egui::Vec2::new(4.0, 20.0), egui::Sense::hover());
|
||||
ui.painter().rect_filled(bar_rect, 2.0, color);
|
||||
|
||||
// Collapsing header
|
||||
let header_text = format!("Ch {} · {}", index + 1, name);
|
||||
let id = format!("{}_{}", id_source, index);
|
||||
egui::CollapsingHeader::new(header_text)
|
||||
.id_source(id)
|
||||
.default_open(true)
|
||||
.show(ui, |ui| {
|
||||
edit.changed = channel_controls(ui, channel, index);
|
||||
});
|
||||
|
||||
// Move/dup/delete buttons
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.button("×").on_hover_text("Delete channel").clicked() {
|
||||
edit.deleted = true;
|
||||
}
|
||||
if ui.button("⧉").on_hover_text("Duplicate channel").clicked() {
|
||||
edit.duplicated = true;
|
||||
}
|
||||
ui.add_enabled_ui(index > 0, |ui| {
|
||||
if ui.button("▲").on_hover_text("Move up").clicked() {
|
||||
edit.moved_up = true;
|
||||
}
|
||||
});
|
||||
ui.add_enabled_ui(index < total - 1, |ui| {
|
||||
if ui.button("▼").on_hover_text("Move down").clicked() {
|
||||
edit.moved_down = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
edit
|
||||
}
|
||||
|
||||
/// Actions from channel editing.
|
||||
#[derive(Default)]
|
||||
pub struct ChannelEdit {
|
||||
pub changed: bool,
|
||||
pub deleted: bool,
|
||||
pub duplicated: bool,
|
||||
pub moved_up: bool,
|
||||
pub moved_down: bool,
|
||||
}
|
||||
|
||||
fn channel_controls(ui: &mut Ui, channel: &mut ChannelSpec, _index: usize) -> bool {
|
||||
let mut changed = false;
|
||||
|
||||
match channel {
|
||||
ChannelSpec::Pulse {
|
||||
duty,
|
||||
frequency,
|
||||
envelope,
|
||||
filter,
|
||||
volume,
|
||||
pan,
|
||||
} => {
|
||||
// Duty cycle dropdown
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Duty:");
|
||||
let mut duty_val = *duty;
|
||||
let resp = egui::ComboBox::from_id_source("duty")
|
||||
.selected_text(format!("{}%", duty_val))
|
||||
.show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut duty_val, 12, "12.5%");
|
||||
ui.selectable_value(&mut duty_val, 25, "25%");
|
||||
ui.selectable_value(&mut duty_val, 50, "50%");
|
||||
ui.selectable_value(&mut duty_val, 75, "75%");
|
||||
});
|
||||
if resp.response.changed() {
|
||||
*duty = duty_val;
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
|
||||
changed |= freq_controls(ui, frequency);
|
||||
changed |= envelope_controls(ui, envelope);
|
||||
changed |= filter_controls(ui, filter);
|
||||
changed |= vol_pan_controls(ui, volume, pan);
|
||||
}
|
||||
ChannelSpec::Triangle {
|
||||
frequency,
|
||||
envelope,
|
||||
filter,
|
||||
volume,
|
||||
pan,
|
||||
} => {
|
||||
changed |= freq_controls(ui, frequency);
|
||||
changed |= envelope_controls(ui, envelope);
|
||||
changed |= filter_controls(ui, filter);
|
||||
changed |= vol_pan_controls(ui, volume, pan);
|
||||
}
|
||||
ChannelSpec::Noise {
|
||||
mode,
|
||||
frequency,
|
||||
envelope,
|
||||
filter,
|
||||
volume,
|
||||
pan,
|
||||
} => {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Mode:");
|
||||
let mut is_white = *mode == "white";
|
||||
if ui.radio_value(&mut is_white, true, "White").changed() {
|
||||
*mode = "white".to_string();
|
||||
changed = true;
|
||||
}
|
||||
if ui.radio_value(&mut is_white, false, "Periodic").changed() {
|
||||
*mode = "periodic".to_string();
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Clock:");
|
||||
if ui
|
||||
.add(
|
||||
egui::Slider::new(frequency, 100.0..=20000.0)
|
||||
.logarithmic(true)
|
||||
.suffix(" Hz"),
|
||||
)
|
||||
.changed()
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
changed |= envelope_controls(ui, envelope);
|
||||
changed |= filter_controls(ui, filter);
|
||||
changed |= vol_pan_controls(ui, volume, pan);
|
||||
}
|
||||
}
|
||||
|
||||
changed
|
||||
}
|
||||
|
||||
fn freq_controls(ui: &mut Ui, freq: &mut FrequencyAutomation) -> bool {
|
||||
let mut changed = false;
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Freq:");
|
||||
if ui
|
||||
.add(
|
||||
egui::Slider::new(&mut freq.start, 20.0..=8000.0)
|
||||
.logarithmic(true)
|
||||
.suffix(" Hz")
|
||||
.text("start"),
|
||||
)
|
||||
.on_hover_text("Starting frequency")
|
||||
.changed()
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
if ui
|
||||
.add(
|
||||
egui::Slider::new(&mut freq.end, 20.0..=8000.0)
|
||||
.logarithmic(true)
|
||||
.suffix(" Hz")
|
||||
.text("end"),
|
||||
)
|
||||
.on_hover_text("Ending frequency (sweep target)")
|
||||
.changed()
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Curve:");
|
||||
if ui
|
||||
.radio_value(&mut freq.curve, SweepCurve::Linear, "Linear")
|
||||
.changed()
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
if ui
|
||||
.radio_value(&mut freq.curve, SweepCurve::Exponential, "Exponential")
|
||||
.changed()
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
changed
|
||||
}
|
||||
|
||||
fn envelope_controls(ui: &mut Ui, envelope: &mut Option<EnvelopeSpec>) -> bool {
|
||||
let mut changed = false;
|
||||
|
||||
if envelope.is_none() {
|
||||
*envelope = Some(EnvelopeSpec::default());
|
||||
}
|
||||
|
||||
let env = envelope.as_mut().unwrap();
|
||||
|
||||
// ADSR visual + sliders in compact layout
|
||||
ui.horizontal(|ui| {
|
||||
// Mini ADSR visual
|
||||
crate::waveform::adsr_visual(ui, env.attack, env.decay, env.sustain, env.release, 1.0);
|
||||
|
||||
// Compact sliders in a grid
|
||||
ui.vertical(|ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("A:");
|
||||
if ui
|
||||
.add(
|
||||
egui::Slider::new(&mut env.attack, 0.0..=2.0)
|
||||
.suffix("s")
|
||||
.clamp_to_range(true)
|
||||
.fixed_decimals(3),
|
||||
)
|
||||
.on_hover_text("Attack time (seconds)")
|
||||
.changed()
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("D:");
|
||||
if ui
|
||||
.add(
|
||||
egui::Slider::new(&mut env.decay, 0.0..=2.0)
|
||||
.suffix("s")
|
||||
.clamp_to_range(true)
|
||||
.fixed_decimals(3),
|
||||
)
|
||||
.on_hover_text("Decay time (seconds)")
|
||||
.changed()
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("S:");
|
||||
if ui
|
||||
.add(
|
||||
egui::Slider::new(&mut env.sustain, 0.0..=1.0)
|
||||
.clamp_to_range(true)
|
||||
.fixed_decimals(2),
|
||||
)
|
||||
.on_hover_text("Sustain level (0-1)")
|
||||
.changed()
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
ui.label("R:");
|
||||
if ui
|
||||
.add(
|
||||
egui::Slider::new(&mut env.release, 0.0..=2.0)
|
||||
.suffix("s")
|
||||
.clamp_to_range(true)
|
||||
.fixed_decimals(3),
|
||||
)
|
||||
.on_hover_text("Release time (seconds)")
|
||||
.changed()
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
|
||||
changed
|
||||
}
|
||||
|
||||
fn filter_controls(ui: &mut Ui, filter: &mut Option<FilterSpec>) -> bool {
|
||||
let mut changed = false;
|
||||
|
||||
let has_filter = filter.is_some();
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
let mut enable = has_filter;
|
||||
if ui
|
||||
.checkbox(&mut enable, "Filter")
|
||||
.on_hover_text("Enable biquad filter")
|
||||
.changed()
|
||||
{
|
||||
if enable && filter.is_none() {
|
||||
*filter = Some(FilterSpec {
|
||||
kind: FilterKind::Lowpass,
|
||||
cutoff: 2000.0,
|
||||
cutoff_sweep: None,
|
||||
q: 0.707,
|
||||
});
|
||||
changed = true;
|
||||
} else if !enable && filter.is_some() {
|
||||
*filter = None;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if let Some(filt) = filter {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Type:");
|
||||
let mut kind = filt.kind;
|
||||
let resp = egui::ComboBox::from_id_source("filter_type")
|
||||
.selected_text(match kind {
|
||||
FilterKind::Lowpass => "Lowpass",
|
||||
FilterKind::Highpass => "Highpass",
|
||||
})
|
||||
.show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut kind, FilterKind::Lowpass, "Lowpass");
|
||||
ui.selectable_value(&mut kind, FilterKind::Highpass, "Highpass");
|
||||
});
|
||||
if resp.response.changed() {
|
||||
filt.kind = kind;
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Cutoff:");
|
||||
if ui
|
||||
.add(
|
||||
egui::Slider::new(&mut filt.cutoff, 20.0..=20000.0)
|
||||
.logarithmic(true)
|
||||
.suffix(" Hz"),
|
||||
)
|
||||
.on_hover_text("Filter cutoff frequency")
|
||||
.changed()
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Q:");
|
||||
if ui
|
||||
.add(
|
||||
egui::Slider::new(&mut filt.q, 0.1..=10.0)
|
||||
.fixed_decimals(2)
|
||||
.text("resonance"),
|
||||
)
|
||||
.on_hover_text("Filter resonance (higher = sharper)")
|
||||
.changed()
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
|
||||
// Cutoff sweep
|
||||
ui.horizontal(|ui| {
|
||||
let mut has_sweep = filt.cutoff_sweep.is_some();
|
||||
if ui
|
||||
.checkbox(&mut has_sweep, "Cutoff sweep")
|
||||
.on_hover_text("Automate cutoff over time")
|
||||
.changed()
|
||||
{
|
||||
if has_sweep {
|
||||
filt.cutoff_sweep = Some(CutoffAutomation {
|
||||
start: filt.cutoff,
|
||||
end: filt.cutoff * 0.1,
|
||||
curve: SweepCurve::Exponential,
|
||||
});
|
||||
changed = true;
|
||||
} else {
|
||||
filt.cutoff_sweep = None;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if let Some(sweep) = &mut filt.cutoff_sweep {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(" Start:");
|
||||
if ui
|
||||
.add(
|
||||
egui::Slider::new(&mut sweep.start, 20.0..=20000.0)
|
||||
.logarithmic(true)
|
||||
.suffix(" Hz"),
|
||||
)
|
||||
.changed()
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
ui.label("End:");
|
||||
if ui
|
||||
.add(
|
||||
egui::Slider::new(&mut sweep.end, 20.0..=20000.0)
|
||||
.logarithmic(true)
|
||||
.suffix(" Hz"),
|
||||
)
|
||||
.changed()
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(" Curve:");
|
||||
if ui
|
||||
.radio_value(&mut sweep.curve, SweepCurve::Linear, "Linear")
|
||||
.changed()
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
if ui
|
||||
.radio_value(&mut sweep.curve, SweepCurve::Exponential, "Exponential")
|
||||
.changed()
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
changed
|
||||
}
|
||||
|
||||
fn vol_pan_controls(ui: &mut Ui, volume: &mut f32, pan: &mut f32) -> bool {
|
||||
let mut changed = false;
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Vol:");
|
||||
if ui
|
||||
.add(egui::Slider::new(volume, 0.0..=1.0).fixed_decimals(2))
|
||||
.on_hover_text("Channel volume (0-1)")
|
||||
.changed()
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
ui.label("Pan:");
|
||||
if ui
|
||||
.add(
|
||||
egui::Slider::new(pan, -1.0..=1.0)
|
||||
.fixed_decimals(2)
|
||||
.text("L/R"),
|
||||
)
|
||||
.on_hover_text("Pan (-1=left, 0=center, 1=right)")
|
||||
.changed()
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
changed
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
//! Virtual piano keyboard widget for egui.
|
||||
//!
|
||||
//! Features:
|
||||
//! - Responsive key sizing (fits available width)
|
||||
//! - Octave shift (Z/X keys or ◀ ▶ buttons)
|
||||
//! - QWERTY letter labels on keys
|
||||
//! - Velocity slider
|
||||
//! - Mouse + keyboard input
|
||||
|
||||
use egui::{Color32, Pos2, Rect, Sense, Ui, Vec2};
|
||||
|
||||
/// Convert MIDI note number to frequency.
|
||||
pub fn midi_to_freq(midi: u8) -> f32 {
|
||||
440.0 * 2.0f32.powf((midi as f32 - 69.0) / 12.0)
|
||||
}
|
||||
|
||||
/// Is this MIDI note a black key?
|
||||
fn is_black_key(midi: u8) -> bool {
|
||||
let n = midi % 12;
|
||||
n == 1 || n == 3 || n == 6 || n == 8 || n == 10
|
||||
}
|
||||
|
||||
/// QWERTY-to-semitone mapping (relative to start_note).
|
||||
const QWERTY_MAP: &[(egui::Key, &str, u8)] = &[
|
||||
(egui::Key::A, "A", 0),
|
||||
(egui::Key::W, "W", 1),
|
||||
(egui::Key::S, "S", 2),
|
||||
(egui::Key::E, "E", 3),
|
||||
(egui::Key::D, "D", 4),
|
||||
(egui::Key::F, "F", 5),
|
||||
(egui::Key::T, "T", 6),
|
||||
(egui::Key::G, "G", 7),
|
||||
(egui::Key::Y, "Y", 8),
|
||||
(egui::Key::H, "H", 9),
|
||||
(egui::Key::U, "U", 10),
|
||||
(egui::Key::J, "J", 11),
|
||||
(egui::Key::K, "K", 12),
|
||||
(egui::Key::O, "O", 13),
|
||||
(egui::Key::L, "L", 14),
|
||||
];
|
||||
|
||||
/// Piano keyboard widget.
|
||||
pub struct Keyboard {
|
||||
/// Lowest MIDI note (changes with octave shift)
|
||||
pub start_note: u8,
|
||||
/// Number of octaves to display
|
||||
pub octaves: usize,
|
||||
/// Currently pressed notes (MIDI numbers)
|
||||
pub pressed: std::collections::HashSet<u8>,
|
||||
/// Velocity (0-127)
|
||||
pub velocity: u8,
|
||||
/// Responsive key width (computed each frame)
|
||||
key_w: f32,
|
||||
/// White key height
|
||||
key_h: f32,
|
||||
/// Black key width
|
||||
black_key_w: f32,
|
||||
/// Black key height
|
||||
black_key_h: f32,
|
||||
}
|
||||
|
||||
impl Keyboard {
|
||||
pub fn new(start_note: u8, octaves: usize) -> Self {
|
||||
Self {
|
||||
start_note,
|
||||
octaves,
|
||||
pressed: std::collections::HashSet::new(),
|
||||
velocity: 100,
|
||||
key_w: 28.0,
|
||||
key_h: 90.0,
|
||||
black_key_w: 18.0,
|
||||
black_key_h: 56.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Shift octave down.
|
||||
pub fn octave_down(&mut self) {
|
||||
if self.start_note >= 12 {
|
||||
self.start_note -= 12;
|
||||
}
|
||||
}
|
||||
|
||||
/// Shift octave up.
|
||||
pub fn octave_up(&mut self) {
|
||||
if self.start_note + 12 * self.octaves as u8 <= 120 {
|
||||
self.start_note += 12;
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the current octave range label (e.g., "C4–C6").
|
||||
pub fn range_label(&self) -> String {
|
||||
let bottom = self.start_note;
|
||||
let top = self.start_note + 12 * self.octaves as u8;
|
||||
format!("{}–{}", note_name(bottom), note_name(top))
|
||||
}
|
||||
|
||||
/// Draw the keyboard and handle input.
|
||||
/// Returns (newly_pressed, newly_released, velocity).
|
||||
pub fn show(&mut self, ui: &mut Ui) -> (Vec<u8>, Vec<u8>, u8) {
|
||||
let mut new_presses = Vec::new();
|
||||
let mut new_releases = Vec::new();
|
||||
|
||||
// Octave shift controls + velocity
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("◀").on_hover_text("Octave down (Z)").clicked() {
|
||||
self.octave_down();
|
||||
}
|
||||
ui.label(
|
||||
egui::RichText::new(self.range_label())
|
||||
.strong()
|
||||
.color(Color32::from_rgb(140, 180, 255)),
|
||||
);
|
||||
if ui.button("▶").on_hover_text("Octave up (X)").clicked() {
|
||||
self.octave_up();
|
||||
}
|
||||
ui.separator();
|
||||
ui.label("Vel:");
|
||||
ui.add(
|
||||
egui::Slider::new(&mut self.velocity, 1..=127)
|
||||
.clamp_to_range(true)
|
||||
.text(""),
|
||||
)
|
||||
.on_hover_text("Velocity (loudness)");
|
||||
});
|
||||
|
||||
// Compute responsive key width
|
||||
let num_white_keys = self.octaves * 7 + 1;
|
||||
let avail_w = ui.available_width().min(num_white_keys as f32 * 40.0);
|
||||
self.key_w = (avail_w / num_white_keys as f32).clamp(16.0, 40.0);
|
||||
self.black_key_w = self.key_w * 0.6;
|
||||
self.key_h = 90.0;
|
||||
self.black_key_h = 56.0;
|
||||
|
||||
let total_w = num_white_keys as f32 * self.key_w;
|
||||
let (rect, _) =
|
||||
ui.allocate_exact_size(Vec2::new(total_w, self.key_h), Sense::click_and_drag());
|
||||
|
||||
let painter = ui.painter_at(rect);
|
||||
|
||||
// Collect all notes to draw
|
||||
let mut notes: Vec<u8> = Vec::new();
|
||||
let mut white_count = 0u32;
|
||||
let mut midi = self.start_note;
|
||||
for _ in 0..(num_white_keys * 2) {
|
||||
if midi > 127 {
|
||||
break;
|
||||
}
|
||||
notes.push(midi);
|
||||
if !is_black_key(midi) {
|
||||
white_count += 1;
|
||||
}
|
||||
if white_count >= num_white_keys as u32 {
|
||||
break;
|
||||
}
|
||||
midi += 1;
|
||||
}
|
||||
|
||||
// Draw white keys
|
||||
let mut white_x = rect.left();
|
||||
let mut white_key_positions: Vec<(u8, Rect, &str)> = Vec::new();
|
||||
for ¬e in ¬es {
|
||||
if is_black_key(note) {
|
||||
continue;
|
||||
}
|
||||
let key_rect = Rect::from_min_size(
|
||||
Pos2::new(white_x, rect.top()),
|
||||
Vec2::new(self.key_w, self.key_h),
|
||||
);
|
||||
let is_pressed = self.pressed.contains(¬e);
|
||||
let color = if is_pressed {
|
||||
Color32::from_rgb(100, 160, 255)
|
||||
} else {
|
||||
Color32::from_rgb(235, 235, 240)
|
||||
};
|
||||
painter.rect_filled(key_rect, 3.0, color);
|
||||
painter.rect_stroke(key_rect, 3.0, (1.0, Color32::from_rgb(60, 60, 70)));
|
||||
|
||||
// C note labels
|
||||
if note % 12 == 0 {
|
||||
painter.text(
|
||||
Pos2::new(white_x + self.key_w * 0.5, rect.bottom() - 14.0),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
note_name(note),
|
||||
egui::FontId::proportional(11.0),
|
||||
Color32::from_rgb(100, 100, 120),
|
||||
);
|
||||
}
|
||||
|
||||
// QWERTY label
|
||||
if let Some(label) = qwerty_label_for_note(note, self.start_note) {
|
||||
painter.text(
|
||||
Pos2::new(white_x + self.key_w * 0.5, rect.bottom() - 28.0),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
label,
|
||||
egui::FontId::proportional(9.0),
|
||||
Color32::from_rgba_premultiplied(120, 120, 140, 100),
|
||||
);
|
||||
}
|
||||
|
||||
white_key_positions.push((note, key_rect, ""));
|
||||
white_x += self.key_w;
|
||||
}
|
||||
|
||||
// Draw black keys (on top)
|
||||
let mut white_x = rect.left();
|
||||
let mut black_key_positions: Vec<(u8, Rect)> = Vec::new();
|
||||
for ¬e in ¬es {
|
||||
if is_black_key(note) {
|
||||
let black_x = white_x - self.black_key_w * 0.5;
|
||||
let key_rect = Rect::from_min_size(
|
||||
Pos2::new(black_x, rect.top()),
|
||||
Vec2::new(self.black_key_w, self.black_key_h),
|
||||
);
|
||||
let is_pressed = self.pressed.contains(¬e);
|
||||
let color = if is_pressed {
|
||||
Color32::from_rgb(70, 100, 200)
|
||||
} else {
|
||||
Color32::from_rgb(35, 35, 42)
|
||||
};
|
||||
painter.rect_filled(key_rect, 2.0, color);
|
||||
painter.rect_stroke(key_rect, 2.0, (1.0, Color32::from_rgb(80, 80, 90)));
|
||||
|
||||
// QWERTY label on black key
|
||||
if let Some(label) = qwerty_label_for_note(note, self.start_note) {
|
||||
painter.text(
|
||||
Pos2::new(
|
||||
black_x + self.black_key_w * 0.5,
|
||||
rect.top() + self.black_key_h - 14.0,
|
||||
),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
label,
|
||||
egui::FontId::proportional(8.0),
|
||||
Color32::from_rgba_premultiplied(180, 180, 200, 120),
|
||||
);
|
||||
}
|
||||
|
||||
black_key_positions.push((note, key_rect));
|
||||
} else {
|
||||
white_x += self.key_w;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle mouse input
|
||||
let mouse_pos = ui.input(|i| i.pointer.hover_pos());
|
||||
let mouse_down = ui.input(|i| i.pointer.primary_down());
|
||||
let mouse_released = ui.input(|i| i.pointer.primary_released());
|
||||
|
||||
if let Some(pos) = mouse_pos {
|
||||
if mouse_down || mouse_released {
|
||||
// Check black keys first (on top)
|
||||
let mut hit_note: Option<u8> = None;
|
||||
for (note, kr) in &black_key_positions {
|
||||
if kr.contains(pos) {
|
||||
hit_note = Some(*note);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if hit_note.is_none() {
|
||||
for (note, kr, _) in &white_key_positions {
|
||||
if kr.contains(pos) {
|
||||
hit_note = Some(*note);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(note) = hit_note {
|
||||
if mouse_down && !self.pressed.contains(¬e) {
|
||||
self.pressed.insert(note);
|
||||
new_presses.push(note);
|
||||
}
|
||||
}
|
||||
|
||||
if mouse_released {
|
||||
let released: Vec<u8> = self.pressed.iter().copied().collect();
|
||||
for n in released {
|
||||
self.pressed.remove(&n);
|
||||
new_releases.push(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handle QWERTY keyboard input
|
||||
for (key, _label, semitone) in QWERTY_MAP {
|
||||
let midi = self.start_note + semitone;
|
||||
let pressed_now = ui.input(|i| i.key_down(*key));
|
||||
let was_pressed = self.pressed.contains(&midi);
|
||||
|
||||
if pressed_now && !was_pressed {
|
||||
self.pressed.insert(midi);
|
||||
new_presses.push(midi);
|
||||
} else if !pressed_now && was_pressed {
|
||||
self.pressed.remove(&midi);
|
||||
new_releases.push(midi);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle octave shift keys (Z / X)
|
||||
if ui.input(|i| i.key_pressed(egui::Key::Z)) {
|
||||
self.octave_down();
|
||||
}
|
||||
if ui.input(|i| i.key_pressed(egui::Key::X)) {
|
||||
self.octave_up();
|
||||
}
|
||||
|
||||
(new_presses, new_releases, self.velocity)
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the QWERTY letter label for a given MIDI note (if mapped).
|
||||
fn qwerty_label_for_note(note: u8, start_note: u8) -> Option<&'static str> {
|
||||
let semitone = note - start_note;
|
||||
QWERTY_MAP
|
||||
.iter()
|
||||
.find(|(_, _, s)| *s == semitone)
|
||||
.map(|(_, label, _)| *label)
|
||||
}
|
||||
|
||||
/// Get note name (e.g., "C4", "A#3").
|
||||
fn note_name(midi: u8) -> String {
|
||||
const NAMES: [&str; 12] = [
|
||||
"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B",
|
||||
];
|
||||
let octave = midi / 12 - 1;
|
||||
let note = midi % 12;
|
||||
format!("{}{}", NAMES[note as usize], octave)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
//! Soundgen GUI — egui-based 8-bit sound editor.
|
||||
//!
|
||||
//! Features:
|
||||
//! - Virtual piano keyboard (mouse + QWERTY, octave shift, velocity)
|
||||
//! - SFX editor with collapsible channels, ADSR visual, filter controls
|
||||
//! - Preset browser with click-to-play, color-coded categories
|
||||
//! - Sequencer with JSON editor
|
||||
//! - Undo/redo, hotkeys, file dialogs
|
||||
//! - Save/load projects (JSON), WAV export
|
||||
|
||||
mod app;
|
||||
mod channel_panel;
|
||||
mod keyboard;
|
||||
mod preset_browser;
|
||||
mod waveform;
|
||||
|
||||
fn main() -> eframe::Result<()> {
|
||||
let options = eframe::NativeOptions {
|
||||
viewport: egui::ViewportBuilder::default()
|
||||
.with_inner_size([1280.0, 820.0])
|
||||
.with_title("Soundgen — 8-bit Sound Synthesizer"),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
eframe::run_native(
|
||||
"Soundgen",
|
||||
options,
|
||||
Box::new(|cc| {
|
||||
setup_custom_theme(&cc.egui_ctx);
|
||||
Ok(Box::new(app::SoundgenApp::default()))
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
fn setup_custom_theme(ctx: &egui::Context) {
|
||||
let mut theme = egui::Visuals::dark();
|
||||
theme.panel_fill = egui::Color32::from_rgb(24, 24, 28);
|
||||
theme.window_fill = egui::Color32::from_rgb(32, 32, 38);
|
||||
theme.extreme_bg_color = egui::Color32::from_rgb(16, 16, 20);
|
||||
theme.faint_bg_color = egui::Color32::from_rgb(40, 40, 48);
|
||||
ctx.set_visuals(theme);
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
//! Preset browser — list, filter, and play presets with color-coded categories.
|
||||
|
||||
use egui::{Color32, RichText, Ui};
|
||||
use soundgen_fmt::{PresetCategory, PresetRegistry};
|
||||
|
||||
pub struct PresetBrowser {
|
||||
pub selected: Option<String>,
|
||||
pub filter: String,
|
||||
}
|
||||
|
||||
impl PresetBrowser {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
selected: None,
|
||||
filter: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw the browser. Returns the name of a preset to play (double-click or play button).
|
||||
pub fn show(&mut self, ui: &mut Ui, registry: &PresetRegistry) -> Option<String> {
|
||||
let mut to_play = None;
|
||||
|
||||
ui.heading("Presets");
|
||||
ui.horizontal(|ui| {
|
||||
ui.text_edit_singleline(&mut self.filter)
|
||||
.on_hover_text("Filter by name...");
|
||||
if !self.filter.is_empty() {
|
||||
if ui.button("✕").clicked() {
|
||||
self.filter.clear();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
egui::ScrollArea::vertical().show(ui, |ui| {
|
||||
let filter_lower = self.filter.to_lowercase();
|
||||
|
||||
for category in [
|
||||
PresetCategory::Sfx,
|
||||
PresetCategory::Ui,
|
||||
PresetCategory::Ambient,
|
||||
] {
|
||||
let presets: Vec<_> = registry
|
||||
.list(Some(category))
|
||||
.into_iter()
|
||||
.filter(|p| p.name.to_lowercase().contains(&filter_lower))
|
||||
.collect();
|
||||
|
||||
if presets.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let cat_color = category_color(category);
|
||||
let header = format!("{} ({})", category.as_str().to_uppercase(), presets.len());
|
||||
|
||||
ui.collapsing(header, |ui| {
|
||||
for entry in &presets {
|
||||
let is_selected = self.selected.as_deref() == Some(entry.name.as_str());
|
||||
|
||||
let bg = if is_selected {
|
||||
Color32::from_rgb(50, 70, 110)
|
||||
} else {
|
||||
Color32::from_rgb(35, 35, 42)
|
||||
};
|
||||
|
||||
let frame = egui::Frame::group(ui.style())
|
||||
.fill(bg)
|
||||
.stroke(egui::Stroke::new(
|
||||
if is_selected { 2.0 } else { 0.5 },
|
||||
if is_selected {
|
||||
cat_color
|
||||
} else {
|
||||
Color32::from_gray(60)
|
||||
},
|
||||
))
|
||||
.inner_margin(egui::Margin::symmetric(6.0, 4.0));
|
||||
|
||||
let response = frame.show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
// Category color dot
|
||||
let (dot_rect, _) = ui.allocate_exact_size(
|
||||
egui::Vec2::new(8.0, 8.0),
|
||||
egui::Sense::hover(),
|
||||
);
|
||||
ui.painter()
|
||||
.circle_filled(dot_rect.center(), 4.0, cat_color);
|
||||
|
||||
// Name
|
||||
ui.label(RichText::new(&entry.name).strong());
|
||||
|
||||
// Info
|
||||
ui.label(
|
||||
RichText::new(format!(
|
||||
"{:.2}s · {}ch",
|
||||
entry.spec.duration,
|
||||
entry.spec.channels.len()
|
||||
))
|
||||
.small()
|
||||
.weak(),
|
||||
);
|
||||
|
||||
ui.with_layout(
|
||||
egui::Layout::right_to_left(egui::Align::Center),
|
||||
|ui| {
|
||||
if ui.button("▶").on_hover_text("Play").clicked() {
|
||||
to_play = Some(entry.name.clone());
|
||||
self.selected = Some(entry.name.clone());
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
let resp = response.response.interact(egui::Sense::click());
|
||||
if resp.clicked() {
|
||||
self.selected = Some(entry.name.clone());
|
||||
}
|
||||
if resp.double_clicked() {
|
||||
to_play = Some(entry.name.clone());
|
||||
self.selected = Some(entry.name.clone());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
to_play
|
||||
}
|
||||
}
|
||||
|
||||
fn category_color(cat: PresetCategory) -> Color32 {
|
||||
match cat {
|
||||
PresetCategory::Sfx => Color32::from_rgb(255, 120, 80),
|
||||
PresetCategory::Ui => Color32::from_rgb(120, 200, 255),
|
||||
PresetCategory::Ambient => Color32::from_rgb(150, 255, 150),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
//! Waveform display widget with time grid, channel colors, and RMS meter.
|
||||
|
||||
use egui::{Color32, FontId, Pos2, Rect, Ui, Vec2};
|
||||
|
||||
/// Channel type colors for waveform display.
|
||||
#[allow(dead_code)]
|
||||
pub fn channel_color(index: usize) -> Color32 {
|
||||
match index % 6 {
|
||||
0 => Color32::from_rgb(100, 200, 255),
|
||||
1 => Color32::from_rgb(255, 200, 100),
|
||||
2 => Color32::from_rgb(150, 255, 150),
|
||||
3 => Color32::from_rgb(255, 150, 150),
|
||||
4 => Color32::from_rgb(200, 150, 255),
|
||||
_ => Color32::from_rgb(255, 255, 150),
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw a waveform preview with time grid and labels.
|
||||
///
|
||||
/// - `samples`: mono samples (downsampled for display)
|
||||
/// - `duration`: total duration in seconds
|
||||
/// - `height`: widget height in pixels
|
||||
pub fn waveform_display(ui: &mut Ui, samples: &[f32], duration: f32, height: f32) {
|
||||
let avail_w = ui.available_width();
|
||||
let size = Vec2::new(avail_w, height);
|
||||
let (rect, _) = ui.allocate_exact_size(size, egui::Sense::hover());
|
||||
let painter = ui.painter_at(rect);
|
||||
|
||||
// Inset: leave room for labels at bottom and RMS meter at right
|
||||
let label_h = 14.0;
|
||||
let meter_w = 8.0;
|
||||
let pad = 4.0;
|
||||
let wave_rect = Rect::from_min_max(
|
||||
Pos2::new(rect.left() + pad, rect.top() + pad),
|
||||
Pos2::new(rect.right() - meter_w - pad * 2.0, rect.bottom() - label_h),
|
||||
);
|
||||
|
||||
// Background
|
||||
painter.rect_filled(rect, 4.0, Color32::from_rgb(18, 18, 24));
|
||||
|
||||
if samples.len() < 2 {
|
||||
painter.text(
|
||||
rect.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
"No preview",
|
||||
FontId::proportional(14.0),
|
||||
Color32::from_rgb(80, 80, 100),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Time grid
|
||||
let grid_interval = if duration < 0.5 {
|
||||
0.05
|
||||
} else if duration < 2.0 {
|
||||
0.1
|
||||
} else if duration < 10.0 {
|
||||
0.5
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
let n_lines = (duration / grid_interval) as usize;
|
||||
for i in 0..=n_lines {
|
||||
let t = i as f32 * grid_interval;
|
||||
let x = wave_rect.left() + (t / duration) * wave_rect.width();
|
||||
let alpha = if i == 0 || i == n_lines { 50 } else { 25 };
|
||||
painter.line_segment(
|
||||
[
|
||||
Pos2::new(x, wave_rect.top()),
|
||||
Pos2::new(x, wave_rect.bottom()),
|
||||
],
|
||||
(1.0, Color32::from_rgba_premultiplied(80, 80, 100, alpha)),
|
||||
);
|
||||
if i > 0 && i < n_lines {
|
||||
painter.text(
|
||||
Pos2::new(x, wave_rect.bottom() + 2.0),
|
||||
egui::Align2::CENTER_TOP,
|
||||
if grid_interval < 1.0 {
|
||||
format!("{:.0}ms", t * 1000.0)
|
||||
} else {
|
||||
format!("{:.1}s", t)
|
||||
},
|
||||
FontId::proportional(8.0),
|
||||
Color32::from_rgb(70, 70, 90),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Center line
|
||||
let mid_y = wave_rect.center().y;
|
||||
painter.line_segment(
|
||||
[
|
||||
Pos2::new(wave_rect.left(), mid_y),
|
||||
Pos2::new(wave_rect.right(), mid_y),
|
||||
],
|
||||
(1.0, Color32::from_rgba_premultiplied(60, 60, 80, 60)),
|
||||
);
|
||||
|
||||
// Waveform line
|
||||
let amp = wave_rect.height() * 0.45;
|
||||
let color = Color32::from_rgb(100, 200, 255);
|
||||
let fill_color = Color32::from_rgba_premultiplied(100, 200, 255, 40);
|
||||
|
||||
let points: Vec<Pos2> = samples
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, &s)| {
|
||||
let x = wave_rect.left() + (i as f32 / samples.len() as f32) * wave_rect.width();
|
||||
let y = mid_y - s.clamp(-1.0, 1.0) * amp;
|
||||
Pos2::new(x, y)
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Fill under curve: draw vertical lines from each point to mid_y
|
||||
for p in &points {
|
||||
painter.line_segment([Pos2::new(p.x, mid_y), *p], (1.0, fill_color));
|
||||
}
|
||||
|
||||
// Waveform line on top
|
||||
painter.add(egui::Shape::line(points, (1.5, color)));
|
||||
|
||||
// RMS meter (right side, separate from waveform area)
|
||||
let rms = (samples.iter().map(|s| s * s).sum::<f32>() / samples.len() as f32).sqrt();
|
||||
let rms_db = 20.0 * rms.max(1e-6).log10();
|
||||
|
||||
let meter_rect = Rect::from_min_size(
|
||||
Pos2::new(rect.right() - meter_w - pad, wave_rect.top()),
|
||||
Vec2::new(meter_w, wave_rect.height()),
|
||||
);
|
||||
painter.rect_filled(meter_rect, 2.0, Color32::from_rgb(30, 30, 40));
|
||||
|
||||
let level = ((rms_db + 60.0) / 60.0).clamp(0.0, 1.0);
|
||||
let level_h = level * meter_rect.height();
|
||||
let level_color = if level > 0.85 {
|
||||
Color32::from_rgb(255, 80, 80)
|
||||
} else if level > 0.6 {
|
||||
Color32::from_rgb(255, 200, 80)
|
||||
} else {
|
||||
Color32::from_rgb(80, 200, 120)
|
||||
};
|
||||
painter.rect_filled(
|
||||
Rect::from_min_size(
|
||||
Pos2::new(meter_rect.left(), meter_rect.bottom() - level_h),
|
||||
Vec2::new(meter_w, level_h),
|
||||
),
|
||||
2.0,
|
||||
level_color,
|
||||
);
|
||||
|
||||
// Info text (top-left, inside wave rect)
|
||||
painter.text(
|
||||
Pos2::new(wave_rect.left() + 4.0, wave_rect.top() + 2.0),
|
||||
egui::Align2::LEFT_TOP,
|
||||
format!("{:.2}s · RMS {:.1} dB", duration, rms_db),
|
||||
FontId::proportional(10.0),
|
||||
Color32::from_rgb(120, 140, 160),
|
||||
);
|
||||
}
|
||||
|
||||
/// Draw a mini ADSR envelope shape.
|
||||
pub fn adsr_visual(
|
||||
ui: &mut Ui,
|
||||
attack: f32,
|
||||
decay: f32,
|
||||
sustain: f32,
|
||||
release: f32,
|
||||
_total_dur: f32,
|
||||
) {
|
||||
let width = 120.0;
|
||||
let height = 50.0;
|
||||
let (rect, _) = ui.allocate_exact_size(Vec2::new(width, height), egui::Sense::hover());
|
||||
let painter = ui.painter_at(rect);
|
||||
|
||||
// Background
|
||||
painter.rect_filled(rect, 3.0, Color32::from_rgb(20, 20, 28));
|
||||
|
||||
let pad = 3.0;
|
||||
let inner = Rect::from_min_max(
|
||||
Pos2::new(rect.left() + pad, rect.top() + pad),
|
||||
Pos2::new(rect.right() - pad, rect.bottom() - pad),
|
||||
);
|
||||
|
||||
// Calculate segment boundaries
|
||||
let total = attack + decay + 0.3 + release;
|
||||
let total = total.max(0.01);
|
||||
let atk_x = inner.left() + (attack / total) * inner.width();
|
||||
let dec_x = atk_x + (decay / total) * inner.width();
|
||||
let sus_end = inner.right() - (release / total) * inner.width();
|
||||
|
||||
let top = inner.top();
|
||||
let bottom = inner.bottom();
|
||||
let sustain_y = bottom - sustain * (bottom - top);
|
||||
|
||||
// Envelope points
|
||||
let points = vec![
|
||||
Pos2::new(inner.left(), bottom),
|
||||
Pos2::new(atk_x, top),
|
||||
Pos2::new(dec_x, sustain_y),
|
||||
Pos2::new(sus_end, sustain_y),
|
||||
Pos2::new(inner.right(), bottom),
|
||||
];
|
||||
|
||||
// Fill: draw as a series of triangles fan from bottom-left
|
||||
let fill_color = Color32::from_rgba_premultiplied(120, 180, 255, 30);
|
||||
for w in points.windows(2) {
|
||||
let tri = vec![Pos2::new(inner.left(), bottom), w[0], w[1]];
|
||||
painter.add(egui::Shape::convex_polygon(
|
||||
tri,
|
||||
fill_color,
|
||||
(0.0, Color32::TRANSPARENT),
|
||||
));
|
||||
}
|
||||
|
||||
// Envelope line
|
||||
let color = Color32::from_rgb(120, 180, 255);
|
||||
painter.add(egui::Shape::line(points, (2.0, color)));
|
||||
|
||||
// Segment labels
|
||||
let label_color = Color32::from_rgb(100, 120, 140);
|
||||
let font = FontId::proportional(8.0);
|
||||
painter.text(
|
||||
Pos2::new((inner.left() + atk_x) * 0.5, bottom + 1.0),
|
||||
egui::Align2::CENTER_TOP,
|
||||
"A",
|
||||
font.clone(),
|
||||
label_color,
|
||||
);
|
||||
painter.text(
|
||||
Pos2::new((atk_x + dec_x) * 0.5, bottom + 1.0),
|
||||
egui::Align2::CENTER_TOP,
|
||||
"D",
|
||||
font.clone(),
|
||||
label_color,
|
||||
);
|
||||
painter.text(
|
||||
Pos2::new((dec_x + sus_end) * 0.5, bottom + 1.0),
|
||||
egui::Align2::CENTER_TOP,
|
||||
"S",
|
||||
font.clone(),
|
||||
label_color,
|
||||
);
|
||||
painter.text(
|
||||
Pos2::new((sus_end + inner.right()) * 0.5, bottom + 1.0),
|
||||
egui::Align2::CENTER_TOP,
|
||||
"R",
|
||||
font,
|
||||
label_color,
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user