Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9bc44a08d5 | ||
|
|
3b4782565b | ||
|
|
fa3390f09e | ||
|
|
edd9ff70c6 | ||
|
|
071d1b6d63 | ||
|
|
fded9796fa |
Generated
+1
-1
@@ -320,7 +320,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "galdr"
|
name = "galdr"
|
||||||
version = "0.2.0"
|
version = "0.2.3"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"arc-swap",
|
"arc-swap",
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "galdr"
|
name = "galdr"
|
||||||
version = "0.2.0"
|
version = "0.2.3"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
description = "A terminal grid synthesizer: signal flows spatially through single-glyph unit generators, voiced by MIDI, rendered low-latency to PipeWire"
|
description = "A terminal grid synthesizer: signal flows spatially through single-glyph unit generators, voiced by MIDI, rendered low-latency to PipeWire"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
|
|||||||
@@ -59,7 +59,10 @@ galdr [--latency <frames>] [--poly <n>] [--rate <hz>] [--midi-name <s>]
|
|||||||
|
|
||||||
galdr creates a virtual MIDI input port named **galdr**; connect orca or any
|
galdr creates a virtual MIDI input port named **galdr**; connect orca or any
|
||||||
sequencer/DAW to it. `--midi-name` connects to an existing port instead.
|
sequencer/DAW to it. `--midi-name` connects to an existing port instead.
|
||||||
Cursor keys move; type a glyph to place it; Backspace clears; Esc quits.
|
|
||||||
|
Keys: cursor keys move; type a glyph to place it; Backspace clears; `?` toggles
|
||||||
|
help; Esc quits. Resize the grid with `(` / `)` (width) and `_` / `+` (height)
|
||||||
|
by one ruler division, or Ctrl+arrows by one cell (orca's bindings).
|
||||||
|
|
||||||
Runtime deps: PipeWire and ALSA (MIDI). Built in Rust; reuses the native
|
Runtime deps: PipeWire and ALSA (MIDI). Built in Rust; reuses the native
|
||||||
PipeWire path from spectrust.
|
PipeWire path from spectrust.
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
# Maintainer: Bendik Aagaard Lynghaug <bendik.lynghaug@gmail.com>
|
# Maintainer: Bendik Aagaard Lynghaug <bendik.lynghaug@gmail.com>
|
||||||
pkgname=galdr
|
pkgname=galdr
|
||||||
pkgver=0.2.0
|
pkgver=0.2.3
|
||||||
pkgrel=1
|
pkgrel=1
|
||||||
pkgdesc="Terminal grid synthesizer: signal flows through single-glyph unit generators, MIDI in, low-latency PipeWire out"
|
pkgdesc="Terminal grid synthesizer: signal flows through single-glyph unit generators, MIDI in, low-latency PipeWire out"
|
||||||
arch=('x86_64' 'aarch64')
|
arch=('x86_64' 'aarch64')
|
||||||
|
|||||||
+144
-8
@@ -9,7 +9,7 @@
|
|||||||
//! params, lowercase a-z read MIDI CC (a = CC 0). A neighbour to the left/right
|
//! params, lowercase a-z read MIDI CC (a = CC 0). A neighbour to the left/right
|
||||||
//! supplies a parameter; `M` instead reads the left cell as a second signal.
|
//! supplies a parameter; `M` instead reads the left cell as a second signal.
|
||||||
|
|
||||||
use crate::grid::{Grid, H, SLOTS, W};
|
use crate::grid::{Grid, MAX_W, SLOTS};
|
||||||
|
|
||||||
pub const MAX_STATE: usize = 4 * SLOTS;
|
pub const MAX_STATE: usize = 4 * SLOTS;
|
||||||
pub const TAU: f32 = std::f32::consts::TAU;
|
pub const TAU: f32 = std::f32::consts::TAU;
|
||||||
@@ -110,20 +110,23 @@ pub fn compile(grid: &Grid) -> Program {
|
|||||||
let mut nodes = Vec::new();
|
let mut nodes = Vec::new();
|
||||||
let mut st = 0usize;
|
let mut st = 0usize;
|
||||||
let mut has_env = false;
|
let mut has_env = false;
|
||||||
for row in 0..H {
|
for row in 0..grid.h {
|
||||||
for col in 0..W {
|
for col in 0..grid.w {
|
||||||
let Some((op, ssize)) = op_of(grid.get(col, row)) else { continue };
|
let Some((op, ssize)) = op_of(grid.get(col, row)) else { continue };
|
||||||
if matches!(op, Op::Env) {
|
if matches!(op, Op::Env) {
|
||||||
has_env = true;
|
has_env = true;
|
||||||
}
|
}
|
||||||
let input =
|
let input = if row > 0 && occupied(grid.get(col, row - 1)) {
|
||||||
if row > 0 && occupied(grid.get(col, row - 1)) { Some((row - 1) * W + col) } else { None };
|
Some((row - 1) * MAX_W + col)
|
||||||
let lsig = if col > 0 { Some(row * W + col - 1) } else { None };
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
let lsig = if col > 0 { Some(row * MAX_W + col - 1) } else { None };
|
||||||
let left = if col > 0 { param_of(grid.get(col - 1, row)) } else { Param::None };
|
let left = if col > 0 { param_of(grid.get(col - 1, row)) } else { Param::None };
|
||||||
let right = if col + 1 < W { param_of(grid.get(col + 1, row)) } else { Param::None };
|
let right = if col + 1 < grid.w { param_of(grid.get(col + 1, row)) } else { Param::None };
|
||||||
let this_st = st;
|
let this_st = st;
|
||||||
st = (st + ssize).min(MAX_STATE - 4);
|
st = (st + ssize).min(MAX_STATE - 4);
|
||||||
nodes.push(Node { op, out: row * W + col, input, lsig, left, right, st: this_st });
|
nodes.push(Node { op, out: row * MAX_W + col, input, lsig, left, right, st: this_st });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Program { nodes, has_env }
|
Program { nodes, has_env }
|
||||||
@@ -299,3 +302,136 @@ pub fn eval_voice(v: &mut Voice, p: &Program, regs: &[f32], sr: f32) -> f32 {
|
|||||||
v.env_level = env_max;
|
v.env_level = env_max;
|
||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::grid::Grid;
|
||||||
|
|
||||||
|
fn grid_from(src: &str) -> Grid {
|
||||||
|
let mut g = Grid::new();
|
||||||
|
for (r, line) in src.lines().enumerate() {
|
||||||
|
for (c, ch) in line.chars().enumerate() {
|
||||||
|
g.set(c, r, ch);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
g
|
||||||
|
}
|
||||||
|
|
||||||
|
fn voice(freq: f32, gate: f32, vel: f32) -> Voice {
|
||||||
|
let mut v = Voice::new();
|
||||||
|
v.active = true;
|
||||||
|
v.freq = freq;
|
||||||
|
v.gate = gate;
|
||||||
|
v.vel = vel;
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render(v: &mut Voice, p: &Program, n: usize) -> Vec<f32> {
|
||||||
|
let regs = [0.0f32; 128];
|
||||||
|
(0..n).map(|_| eval_voice(v, p, ®s, 48000.0)).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn compile_ignores_non_operators() {
|
||||||
|
// digits and dots are params/empty, not nodes
|
||||||
|
let p = compile(&grid_from("O5.\n!.."));
|
||||||
|
assert_eq!(p.nodes.len(), 2); // O and !
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn compile_wires_input_from_above() {
|
||||||
|
// O over ! -> the ! node's input is the O's slot
|
||||||
|
let p = compile(&grid_from("O\n!"));
|
||||||
|
let out_node = p.nodes.iter().find(|n| matches!(n.op, Op::Out)).unwrap();
|
||||||
|
assert!(out_node.input.is_some());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn compile_reads_left_param() {
|
||||||
|
// '5' left of L becomes a constant param
|
||||||
|
let p = compile(&grid_from("5L"));
|
||||||
|
let lp = p.nodes.iter().find(|n| matches!(n.op, Op::Low)).unwrap();
|
||||||
|
assert!(matches!(lp.left, Param::Const(x) if (x - 5.0).abs() < 1e-6));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn compile_lowercase_left_is_cc_reg() {
|
||||||
|
let p = compile(&grid_from("aG"));
|
||||||
|
let g = p.nodes.iter().find(|n| matches!(n.op, Op::Gain)).unwrap();
|
||||||
|
assert!(matches!(g.left, Param::Reg(0)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn compile_detects_envelope() {
|
||||||
|
assert!(compile(&grid_from("O\nE\n!")).has_env);
|
||||||
|
assert!(!compile(&grid_from("O\n!")).has_env);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn empty_grid_is_silent() {
|
||||||
|
let p = compile(&grid_from("...\n..."));
|
||||||
|
let mut v = voice(440.0, 1.0, 1.0);
|
||||||
|
assert!(render(&mut v, &p, 64).iter().all(|&y| y == 0.0));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sine_is_bounded_and_audible() {
|
||||||
|
let p = compile(&grid_from("O\n!"));
|
||||||
|
let mut v = voice(440.0, 1.0, 1.0);
|
||||||
|
let out = render(&mut v, &p, 2048);
|
||||||
|
assert!(out.iter().all(|&y| y.abs() <= 1.0 + 1e-6));
|
||||||
|
assert!(out.iter().cloned().fold(0.0, f32::max) > 0.5); // reaches amplitude
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn saw_first_sample_is_minus_one() {
|
||||||
|
// phase starts at 0 -> saw = 2*0-1 = -1
|
||||||
|
let p = compile(&grid_from("A\n!"));
|
||||||
|
let mut v = voice(440.0, 1.0, 1.0);
|
||||||
|
assert!((render(&mut v, &p, 1)[0] - (-1.0)).abs() < 1e-6);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn outputs_sum_across_columns() {
|
||||||
|
// two saw->out columns: first sample -1 + -1 = -2
|
||||||
|
let p = compile(&grid_from("A.A\n!.!"));
|
||||||
|
let mut v = voice(440.0, 1.0, 1.0);
|
||||||
|
assert!((render(&mut v, &p, 1)[0] - (-2.0)).abs() < 1e-6);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn no_envelope_is_gated_by_note() {
|
||||||
|
let p = compile(&grid_from("A\n!"));
|
||||||
|
let mut open = voice(440.0, 1.0, 1.0);
|
||||||
|
let mut shut = voice(440.0, 0.0, 1.0);
|
||||||
|
assert!(render(&mut open, &p, 1)[0].abs() > 0.5);
|
||||||
|
assert_eq!(render(&mut shut, &p, 1)[0], 0.0); // gate 0 -> silent
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn envelope_rises_then_releases() {
|
||||||
|
let p = compile(&grid_from("O\nE\n!"));
|
||||||
|
let mut v = voice(440.0, 1.0, 1.0);
|
||||||
|
render(&mut v, &p, 8000); // ~sustain reached
|
||||||
|
let peak = v.env_level;
|
||||||
|
assert!(peak > 0.9, "env should rise to sustain, got {peak}");
|
||||||
|
v.gate = 0.0;
|
||||||
|
render(&mut v, &p, 24000); // release (~0.5s >> 0.15s release)
|
||||||
|
assert!(v.env_level < 0.1, "env should decay after note off, got {}", v.env_level);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn mix_adds_left_cell() {
|
||||||
|
// (1,0)=A saw(-1); (1,1)=M reads above(empty=0) + left cell A(-1) = -1
|
||||||
|
let p = compile(&grid_from("A.\nAM\n.!"));
|
||||||
|
let mut v = voice(440.0, 1.0, 1.0);
|
||||||
|
assert!((render(&mut v, &p, 1)[0] - (-1.0)).abs() < 1e-6);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cutoff_hz_is_monotonic() {
|
||||||
|
assert!(cutoff_hz(0.0) < cutoff_hz(5.0));
|
||||||
|
assert!(cutoff_hz(5.0) < cutoff_hz(9.0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -91,3 +91,75 @@ impl Engine {
|
|||||||
(mix * 0.3).tanh()
|
(mix * 0.3).tanh()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::dsp::compile;
|
||||||
|
use crate::grid::Grid;
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
impl Engine {
|
||||||
|
fn first_freq(&self) -> Option<f32> {
|
||||||
|
self.voices.iter().find(|v| v.active).map(|v| v.freq)
|
||||||
|
}
|
||||||
|
fn reg(&self, i: usize) -> f32 {
|
||||||
|
self.regs[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn grid_from(src: &str) -> Grid {
|
||||||
|
let mut g = Grid::new();
|
||||||
|
for (r, line) in src.lines().enumerate() {
|
||||||
|
for (c, ch) in line.chars().enumerate() {
|
||||||
|
g.set(c, r, ch);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
g
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn noteon_maps_a4_to_440() {
|
||||||
|
let mut e = Engine::new(4, 48000.0);
|
||||||
|
e.apply(Event::NoteOn { note: 69, vel: 100 });
|
||||||
|
assert!((e.first_freq().unwrap() - 440.0).abs() < 0.01);
|
||||||
|
assert_eq!(e.active_voices(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn noteoff_reaps_gated_voice() {
|
||||||
|
let p = compile(&grid_from("A\n!")); // no envelope -> gate reaps immediately
|
||||||
|
let mut e = Engine::new(4, 48000.0);
|
||||||
|
e.apply(Event::NoteOn { note: 60, vel: 100 });
|
||||||
|
e.render(&p);
|
||||||
|
assert_eq!(e.active_voices(), 1);
|
||||||
|
e.apply(Event::NoteOff { note: 60 });
|
||||||
|
e.render(&p);
|
||||||
|
assert_eq!(e.active_voices(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn monophonic_steals_the_oldest_voice() {
|
||||||
|
let mut e = Engine::new(1, 48000.0);
|
||||||
|
e.apply(Event::NoteOn { note: 60, vel: 100 });
|
||||||
|
e.apply(Event::NoteOn { note: 72, vel: 100 });
|
||||||
|
assert_eq!(e.active_voices(), 1);
|
||||||
|
assert!((e.first_freq().unwrap() - 440.0 * 2f32.powf((72.0 - 69.0) / 12.0)).abs() < 0.01);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn cc_writes_register() {
|
||||||
|
let mut e = Engine::new(2, 48000.0);
|
||||||
|
e.apply(Event::Cc { idx: 0, val: 127 });
|
||||||
|
assert!((e.reg(0) - 1.0).abs() < 1e-6);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn master_output_is_limited() {
|
||||||
|
// many stacked saws would exceed 1.0 without the limiter
|
||||||
|
let p = compile(&grid_from("A.A.A.A\n!.!.!.!"));
|
||||||
|
let mut e = Engine::new(4, 48000.0);
|
||||||
|
e.apply(Event::NoteOn { note: 60, vel: 127 });
|
||||||
|
assert!(e.render(&p).abs() <= 1.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+75
-9
@@ -1,31 +1,97 @@
|
|||||||
//! The fixed-size character grid that is the editor surface.
|
//! The character grid — the editor surface. Logical size (`w`×`h`) is
|
||||||
|
//! resizable up to the max; cells are stored at a fixed `MAX_W` stride so a
|
||||||
|
//! resize never remaps existing content and compiled slot indices stay stable.
|
||||||
|
|
||||||
pub const W: usize = 24;
|
pub const MAX_W: usize = 40;
|
||||||
pub const H: usize = 16;
|
pub const MAX_H: usize = 24;
|
||||||
pub const SLOTS: usize = W * H;
|
pub const SLOTS: usize = MAX_W * MAX_H;
|
||||||
|
pub const DEFAULT_W: usize = 24;
|
||||||
|
pub const DEFAULT_H: usize = 16;
|
||||||
|
pub const RULER: usize = 8;
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct Grid {
|
pub struct Grid {
|
||||||
|
pub w: usize,
|
||||||
|
pub h: usize,
|
||||||
cells: Vec<char>,
|
cells: Vec<char>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Grid {
|
impl Grid {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Grid { cells: vec!['.'; SLOTS] }
|
Grid { w: DEFAULT_W, h: DEFAULT_H, cells: vec!['.'; SLOTS] }
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn get(&self, col: usize, row: usize) -> char {
|
pub fn get(&self, col: usize, row: usize) -> char {
|
||||||
if col < W && row < H {
|
if col < self.w && row < self.h {
|
||||||
self.cells[row * W + col]
|
self.cells[row * MAX_W + col]
|
||||||
} else {
|
} else {
|
||||||
'.'
|
'.'
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set(&mut self, col: usize, row: usize, c: char) {
|
pub fn set(&mut self, col: usize, row: usize, c: char) {
|
||||||
if col < W && row < H {
|
if col < self.w && row < self.h {
|
||||||
self.cells[row * W + col] = c;
|
self.cells[row * MAX_W + col] = c;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Resize to nh×nw, clamped to [1, MAX]. Content keeps its position.
|
||||||
|
pub fn resize(&mut self, nh: usize, nw: usize) {
|
||||||
|
self.h = nh.clamp(1, MAX_H);
|
||||||
|
self.w = nw.clamp(1, MAX_W);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// orca-c's ruler snap: resize by one ruler division, snapped to a
|
||||||
|
/// ruler-aligned size (1, 9, 17, ...) rather than a plain +/-1.
|
||||||
|
pub fn ruler_snap(size: usize, delta_rulers: isize) -> usize {
|
||||||
|
if size == 0 {
|
||||||
|
return if delta_rulers > 0 { RULER * delta_rulers as usize } else { 1 };
|
||||||
|
}
|
||||||
|
let size = if delta_rulers < 0 { size + RULER - 1 } else { size };
|
||||||
|
let n = ((size as isize - 1) / RULER as isize + delta_rulers).max(0);
|
||||||
|
(RULER as isize * n + 1) as usize
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ruler_snap_grows_and_shrinks() {
|
||||||
|
// ruler-aligned sizes are 1, 9, 17, ...
|
||||||
|
assert_eq!(ruler_snap(24, 1), 25);
|
||||||
|
assert_eq!(ruler_snap(24, -1), 17);
|
||||||
|
assert_eq!(ruler_snap(1, -1), 1); // cannot go below 1
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resize_clamps_to_bounds() {
|
||||||
|
let mut g = Grid::new();
|
||||||
|
g.resize(9999, 9999);
|
||||||
|
assert_eq!((g.h, g.w), (MAX_H, MAX_W));
|
||||||
|
g.resize(0, 0);
|
||||||
|
assert_eq!((g.h, g.w), (1, 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn get_out_of_bounds_is_empty() {
|
||||||
|
let g = Grid::new();
|
||||||
|
assert_eq!(g.get(MAX_W + 5, MAX_H + 5), '.');
|
||||||
|
assert_eq!(g.get(g.w, 0), '.'); // just past the right edge
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn set_get_roundtrip_and_resize_preserves() {
|
||||||
|
let mut g = Grid::new();
|
||||||
|
g.set(3, 2, 'O');
|
||||||
|
assert_eq!(g.get(3, 2), 'O');
|
||||||
|
g.resize(4, 4); // shrink below the cell? (3,2) still inside 4x4
|
||||||
|
assert_eq!(g.get(3, 2), 'O');
|
||||||
|
g.resize(2, 2); // now (3,2) is out of bounds -> hidden
|
||||||
|
assert_eq!(g.get(3, 2), '.');
|
||||||
|
g.resize(MAX_H, MAX_W); // grow back -> content returns (fixed stride)
|
||||||
|
assert_eq!(g.get(3, 2), 'O');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+223
-83
@@ -1,6 +1,8 @@
|
|||||||
//! Grid editor. crossterm renderer adapted from orca-rs's grid view (same
|
//! Grid editor. crossterm renderer adapted from orca-rs's grid view: a centered
|
||||||
//! centered-canvas + per-glyph colour approach); no embedded scope - run a
|
//! canvas with per-glyph colour, ruler marks, resize bindings, and a change-diff
|
||||||
//! spectrum analyzer (e.g. spectrust) on the side if you want one.
|
//! so only cells that actually change repaint (a full clear+redraw each frame
|
||||||
|
//! flickers over SSH on terminals that ignore synchronized-update). `?` toggles
|
||||||
|
//! a detailed help overlay; run a spectrum analyzer on the side if you want one.
|
||||||
|
|
||||||
use std::io::{self, Write};
|
use std::io::{self, Write};
|
||||||
use std::sync::atomic::{AtomicU32, Ordering};
|
use std::sync::atomic::{AtomicU32, Ordering};
|
||||||
@@ -12,30 +14,81 @@ use crossterm::cursor::{Hide, MoveTo, Show};
|
|||||||
use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
|
use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
|
||||||
use crossterm::style::{Attribute, Color, Print, SetAttribute, SetForegroundColor};
|
use crossterm::style::{Attribute, Color, Print, SetAttribute, SetForegroundColor};
|
||||||
use crossterm::terminal::{
|
use crossterm::terminal::{
|
||||||
disable_raw_mode, enable_raw_mode, BeginSynchronizedUpdate, Clear, ClearType,
|
disable_raw_mode, enable_raw_mode, Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen,
|
||||||
EndSynchronizedUpdate, EnterAlternateScreen, LeaveAlternateScreen,
|
|
||||||
};
|
};
|
||||||
use crossterm::{execute, queue, terminal};
|
use crossterm::{execute, queue, terminal};
|
||||||
|
|
||||||
use crate::dsp::{compile, Program};
|
use crate::dsp::{compile, Program};
|
||||||
use crate::grid::{Grid, H, W};
|
use crate::grid::{ruler_snap, Grid, RULER};
|
||||||
|
|
||||||
|
const HELP: &[&str] = &[
|
||||||
|
"galdr — grid synthesizer",
|
||||||
|
"",
|
||||||
|
"Signal flows DOWN: a cell's input is the cell above it. Operators are",
|
||||||
|
"UPPERCASE. A digit 0-9 to the left/right is a constant param; a lowercase",
|
||||||
|
"a-z reads MIDI CC (a = CC 0). Every note plays the whole grid; each ! sums",
|
||||||
|
"into the master, so parallel columns stack voices/timbres.",
|
||||||
|
"",
|
||||||
|
"SOURCES O sine A saw U pulse V triangle N noise",
|
||||||
|
" left param = pitch ratio (O/A) or pulse width (U)",
|
||||||
|
"FILTERS L lowpass H highpass B bandpass (state-variable)",
|
||||||
|
" left = cutoff, right = resonance (higher glyph = more)",
|
||||||
|
"SHAPERS S soft clip/tanh (left=drive) C hard clip (left=threshold)",
|
||||||
|
" F wavefolder (left=amount) D decimate/bitcrush (left=rate)",
|
||||||
|
"AMP/MOD E envelope, note-gated (left=attack, right=release)",
|
||||||
|
" G gain (left=amount) R ring modulator (left=ratio)",
|
||||||
|
"ROUTING M mix — adds the cell to its LEFT ! output to master",
|
||||||
|
"",
|
||||||
|
"KEYS arrows move · type a glyph to place · Backspace clears",
|
||||||
|
" ( ) width -/+ _ + height -/+ Ctrl+arrows resize by one",
|
||||||
|
" ? toggle this help · Esc quit",
|
||||||
|
];
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, PartialEq)]
|
||||||
|
enum Cs {
|
||||||
|
Fg(Color),
|
||||||
|
Cursor,
|
||||||
|
}
|
||||||
|
|
||||||
// Foreground colour by glyph category. (orca-rs uses one Normal colour; galdr
|
|
||||||
// tints by role so a patch reads at a glance.)
|
|
||||||
fn glyph_color(c: char) -> Color {
|
fn glyph_color(c: char) -> Color {
|
||||||
match c {
|
match c {
|
||||||
'O' | 'A' | 'U' | 'V' | 'N' => Color::Cyan, // sources
|
'O' | 'A' | 'U' | 'V' | 'N' => Color::Cyan,
|
||||||
'L' | 'H' | 'B' => Color::Blue, // filters
|
'L' | 'H' | 'B' => Color::Blue,
|
||||||
'S' | 'C' | 'F' | 'D' => Color::Yellow, // shapers
|
'S' | 'C' | 'F' | 'D' => Color::Yellow,
|
||||||
'E' | 'G' | 'R' | 'M' => Color::Green, // amp / mod
|
'E' | 'G' | 'R' | 'M' => Color::Green,
|
||||||
'!' => Color::Magenta, // output
|
'!' => Color::Magenta,
|
||||||
'0'..='9' => Color::Grey, // constants
|
'0'..='9' => Color::Grey,
|
||||||
'a'..='z' => Color::DarkYellow, // CC registers
|
'a'..='z' => Color::DarkYellow,
|
||||||
'.' => Color::DarkGrey, // empty
|
|
||||||
_ => Color::White,
|
_ => Color::White,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct Renderer {
|
||||||
|
cells: Vec<(char, Cs)>,
|
||||||
|
status: String,
|
||||||
|
tw: u16,
|
||||||
|
th: u16,
|
||||||
|
gw: usize,
|
||||||
|
gh: usize,
|
||||||
|
help: bool,
|
||||||
|
init: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Renderer {
|
||||||
|
fn new() -> Self {
|
||||||
|
Renderer {
|
||||||
|
cells: Vec::new(),
|
||||||
|
status: String::new(),
|
||||||
|
tw: 0,
|
||||||
|
th: 0,
|
||||||
|
gw: 0,
|
||||||
|
gh: 0,
|
||||||
|
help: false,
|
||||||
|
init: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn run(
|
pub fn run(
|
||||||
prog: Arc<ArcSwap<Program>>,
|
prog: Arc<ArcSwap<Program>>,
|
||||||
voices: Arc<AtomicU32>,
|
voices: Arc<AtomicU32>,
|
||||||
@@ -46,61 +99,96 @@ pub fn run(
|
|||||||
let mut out = io::stdout();
|
let mut out = io::stdout();
|
||||||
execute!(out, EnterAlternateScreen, Hide)?;
|
execute!(out, EnterAlternateScreen, Hide)?;
|
||||||
let (mut cx, mut cy) = (0usize, 0usize);
|
let (mut cx, mut cy) = (0usize, 0usize);
|
||||||
|
let mut help = false;
|
||||||
|
let mut r = Renderer::new();
|
||||||
|
|
||||||
let res = main_loop(&mut out, &prog, &voices, &mut grid, latency, &mut cx, &mut cy);
|
let res = (|| -> io::Result<()> {
|
||||||
|
loop {
|
||||||
|
draw(&mut out, &grid, cx, cy, voices.load(Ordering::Relaxed), latency, help, &mut r)?;
|
||||||
|
if !event::poll(Duration::from_millis(33))? {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Event::Key(k) = event::read()? else { continue };
|
||||||
|
if k.kind != KeyEventKind::Press {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);
|
||||||
|
let mut resized = false;
|
||||||
|
let mut edited = false;
|
||||||
|
match k.code {
|
||||||
|
KeyCode::Esc => {
|
||||||
|
if help {
|
||||||
|
help = false;
|
||||||
|
} else {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
KeyCode::Char('c') if ctrl => return Ok(()),
|
||||||
|
KeyCode::Char('?') => help = !help,
|
||||||
|
_ if help => {}
|
||||||
|
KeyCode::Char('(') => {
|
||||||
|
grid.resize(grid.h, ruler_snap(grid.w, -1));
|
||||||
|
resized = true;
|
||||||
|
}
|
||||||
|
KeyCode::Char(')') => {
|
||||||
|
grid.resize(grid.h, ruler_snap(grid.w, 1));
|
||||||
|
resized = true;
|
||||||
|
}
|
||||||
|
KeyCode::Char('_') => {
|
||||||
|
grid.resize(ruler_snap(grid.h, -1), grid.w);
|
||||||
|
resized = true;
|
||||||
|
}
|
||||||
|
KeyCode::Char('+') => {
|
||||||
|
grid.resize(ruler_snap(grid.h, 1), grid.w);
|
||||||
|
resized = true;
|
||||||
|
}
|
||||||
|
KeyCode::Left if ctrl => {
|
||||||
|
grid.resize(grid.h, grid.w.saturating_sub(1));
|
||||||
|
resized = true;
|
||||||
|
}
|
||||||
|
KeyCode::Right if ctrl => {
|
||||||
|
grid.resize(grid.h, grid.w + 1);
|
||||||
|
resized = true;
|
||||||
|
}
|
||||||
|
KeyCode::Up if ctrl => {
|
||||||
|
grid.resize(grid.h.saturating_sub(1), grid.w);
|
||||||
|
resized = true;
|
||||||
|
}
|
||||||
|
KeyCode::Down if ctrl => {
|
||||||
|
grid.resize(grid.h + 1, grid.w);
|
||||||
|
resized = true;
|
||||||
|
}
|
||||||
|
KeyCode::Left => cx = cx.saturating_sub(1),
|
||||||
|
KeyCode::Right => cx = (cx + 1).min(grid.w - 1),
|
||||||
|
KeyCode::Up => cy = cy.saturating_sub(1),
|
||||||
|
KeyCode::Down => cy = (cy + 1).min(grid.h - 1),
|
||||||
|
KeyCode::Backspace | KeyCode::Delete => {
|
||||||
|
grid.set(cx, cy, '.');
|
||||||
|
edited = true;
|
||||||
|
}
|
||||||
|
KeyCode::Char(c) => {
|
||||||
|
grid.set(cx, cy, if c == ' ' { '.' } else { c });
|
||||||
|
edited = true;
|
||||||
|
cx = (cx + 1).min(grid.w - 1);
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
if resized {
|
||||||
|
cx = cx.min(grid.w - 1);
|
||||||
|
cy = cy.min(grid.h - 1);
|
||||||
|
}
|
||||||
|
if resized || edited {
|
||||||
|
prog.store(Arc::new(compile(&grid)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
execute!(out, Show, LeaveAlternateScreen)?;
|
execute!(out, Show, LeaveAlternateScreen)?;
|
||||||
disable_raw_mode()?;
|
disable_raw_mode()?;
|
||||||
res
|
res
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main_loop(
|
#[allow(clippy::too_many_arguments)]
|
||||||
out: &mut io::Stdout,
|
|
||||||
prog: &Arc<ArcSwap<Program>>,
|
|
||||||
voices: &Arc<AtomicU32>,
|
|
||||||
grid: &mut Grid,
|
|
||||||
latency: u32,
|
|
||||||
cx: &mut usize,
|
|
||||||
cy: &mut usize,
|
|
||||||
) -> io::Result<()> {
|
|
||||||
loop {
|
|
||||||
draw(out, grid, *cx, *cy, voices.load(Ordering::Relaxed), latency)?;
|
|
||||||
|
|
||||||
if event::poll(Duration::from_millis(33))? {
|
|
||||||
if let Event::Key(k) = event::read()? {
|
|
||||||
if k.kind != KeyEventKind::Press {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if k.code == KeyCode::Esc
|
|
||||||
|| (k.code == KeyCode::Char('c') && k.modifiers.contains(KeyModifiers::CONTROL))
|
|
||||||
{
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
let mut changed = false;
|
|
||||||
match k.code {
|
|
||||||
KeyCode::Left => *cx = cx.saturating_sub(1),
|
|
||||||
KeyCode::Right => *cx = (*cx + 1).min(W - 1),
|
|
||||||
KeyCode::Up => *cy = cy.saturating_sub(1),
|
|
||||||
KeyCode::Down => *cy = (*cy + 1).min(H - 1),
|
|
||||||
KeyCode::Backspace | KeyCode::Delete => {
|
|
||||||
grid.set(*cx, *cy, '.');
|
|
||||||
changed = true;
|
|
||||||
}
|
|
||||||
KeyCode::Char(c) => {
|
|
||||||
grid.set(*cx, *cy, if c == ' ' { '.' } else { c });
|
|
||||||
changed = true;
|
|
||||||
*cx = (*cx + 1).min(W - 1);
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
if changed {
|
|
||||||
prog.store(Arc::new(compile(grid)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn draw(
|
fn draw(
|
||||||
out: &mut io::Stdout,
|
out: &mut io::Stdout,
|
||||||
grid: &Grid,
|
grid: &Grid,
|
||||||
@@ -108,38 +196,90 @@ fn draw(
|
|||||||
cy: usize,
|
cy: usize,
|
||||||
voices: u32,
|
voices: u32,
|
||||||
latency: u32,
|
latency: u32,
|
||||||
|
help: bool,
|
||||||
|
r: &mut Renderer,
|
||||||
) -> io::Result<()> {
|
) -> io::Result<()> {
|
||||||
let (tw, th) = terminal::size()?;
|
let (tw, th) = terminal::size()?;
|
||||||
let off_x = (tw as usize).saturating_sub(W) / 2;
|
|
||||||
let off_y = (th as usize).saturating_sub(H + 1) / 2;
|
|
||||||
|
|
||||||
queue!(out, BeginSynchronizedUpdate, Clear(ClearType::All))?;
|
let full = !r.init
|
||||||
for row in 0..H {
|
|| tw != r.tw
|
||||||
queue!(out, MoveTo(off_x as u16, (off_y + row) as u16))?;
|
|| th != r.th
|
||||||
for col in 0..W {
|
|| help != r.help
|
||||||
let c = grid.get(col, row);
|
|| grid.w != r.gw
|
||||||
queue!(out, SetAttribute(Attribute::Reset))?;
|
|| grid.h != r.gh;
|
||||||
if col == cx && row == cy {
|
if full {
|
||||||
queue!(out, SetAttribute(Attribute::Reverse))?;
|
queue!(out, Clear(ClearType::All))?;
|
||||||
|
r.cells = vec![('\0', Cs::Fg(Color::Reset)); grid.w * grid.h];
|
||||||
|
r.status.clear();
|
||||||
|
r.tw = tw;
|
||||||
|
r.th = th;
|
||||||
|
r.gw = grid.w;
|
||||||
|
r.gh = grid.h;
|
||||||
|
r.help = help;
|
||||||
|
r.init = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if help {
|
||||||
|
if full {
|
||||||
|
let oy = (th as usize).saturating_sub(HELP.len()) / 2;
|
||||||
|
let ox = (tw as usize).saturating_sub(74) / 2;
|
||||||
|
for (i, line) in HELP.iter().enumerate() {
|
||||||
|
queue!(
|
||||||
|
out,
|
||||||
|
MoveTo(ox as u16, (oy + i) as u16),
|
||||||
|
SetAttribute(Attribute::Reset),
|
||||||
|
SetForegroundColor(if i == 0 { Color::Magenta } else { Color::Grey }),
|
||||||
|
Print(line)
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
let off_x = (tw as usize).saturating_sub(grid.w) / 2;
|
||||||
|
let off_y = (th as usize).saturating_sub(grid.h + 1) / 2;
|
||||||
|
for row in 0..grid.h {
|
||||||
|
for col in 0..grid.w {
|
||||||
|
let raw = grid.get(col, row);
|
||||||
|
// ruler mark on empty intersections, for orientation while sizing
|
||||||
|
let disp = if raw == '.' {
|
||||||
|
if row % RULER == 0 && col % RULER == 0 { '+' } else { '.' }
|
||||||
} else {
|
} else {
|
||||||
queue!(out, SetForegroundColor(glyph_color(c)))?;
|
raw
|
||||||
|
};
|
||||||
|
let cs = if col == cx && row == cy {
|
||||||
|
Cs::Cursor
|
||||||
|
} else if raw == '.' {
|
||||||
|
Cs::Fg(Color::DarkGrey)
|
||||||
|
} else {
|
||||||
|
Cs::Fg(glyph_color(raw))
|
||||||
|
};
|
||||||
|
let idx = row * grid.w + col;
|
||||||
|
if r.cells[idx] == (disp, cs) {
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
queue!(out, Print(c))?;
|
r.cells[idx] = (disp, cs);
|
||||||
|
queue!(out, MoveTo((off_x + col) as u16, (off_y + row) as u16), SetAttribute(Attribute::Reset))?;
|
||||||
|
match cs {
|
||||||
|
Cs::Cursor => queue!(out, SetAttribute(Attribute::Reverse))?,
|
||||||
|
Cs::Fg(color) => queue!(out, SetForegroundColor(color))?,
|
||||||
|
}
|
||||||
|
queue!(out, Print(disp))?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Status line beneath the grid.
|
let status =
|
||||||
let status = format!(
|
format!("voices {voices} {}x{} latency {latency}f ? help Esc quit", grid.w, grid.h);
|
||||||
"voices {voices} latency {latency}f O~ A^ U pulse V tri N noise | L H B filt | S C F D shape | E env G gain R ring M mix | ! out Esc quit"
|
if status != r.status {
|
||||||
);
|
r.status = status.clone();
|
||||||
let s: String = status.chars().take(tw as usize).collect();
|
let pad: String = format!("{status:<width$}", width = tw as usize);
|
||||||
queue!(
|
queue!(
|
||||||
out,
|
out,
|
||||||
MoveTo(0, th.saturating_sub(1)),
|
MoveTo(0, th.saturating_sub(1)),
|
||||||
SetAttribute(Attribute::Reset),
|
SetAttribute(Attribute::Reset),
|
||||||
SetForegroundColor(Color::DarkGrey),
|
SetForegroundColor(Color::DarkGrey),
|
||||||
Print(s)
|
Print(pad.chars().take(tw as usize).collect::<String>())
|
||||||
)?;
|
)?;
|
||||||
queue!(out, EndSynchronizedUpdate)?;
|
}
|
||||||
out.flush()
|
out.flush()
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user