Skip to content

armgit / nota

Public Imported from GitHub
0

Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.

Redesign of Forge

Egor Khindikaynen72e934cf0c03
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3bb82cc5..10286978 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -55,6 +55,74 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
level, the effective attack and release, look-ahead latency and how often it kicked in.
### Changed
+- **Nota Forge is redrawn, and every stage gets its own shape.** The card follows the new
+ mockup on the 700 × 260 frame, in the language of EQ-8:
+ - **Stages.** On the left the routing (Serial / Parallel / M/S / Multi) sits over the three
+ stages. Each stage shows its on dot, its type and the role it plays: in **M/S** stage 1
+ drives the Mid, stage 2 the Side and stage 3 the recombined signal; in **Multi** stage 1
+ takes the lows (below 180 Hz), stage 2 the mids and stage 3 the highs (above 2.4 kHz).
+ Drag a stage's output dB up or down to trim it. Drive and a teal Feedback sit under it.
+ Click a stage to select it.
+ - **Shape per stage.** The selected stage gets its type (Tube, Tape, Diode, Fuzz, Fold,
+ Digital) and three knobs: **Bias** (asymmetry, ±100 %), **Tone** (a ±12 dB tilt after the
+ stage) and **Width** (the stage's stereo image, 0 … 200 %). Before, Bias, Tone and Width
+ were shared by all stages.
+ - **Transfer and harmonics.** Amount, Wet and Out sit over the transfer curve. In M/S and
+ Multi the curve shows the selected stage. Every stage also shows faintly on its own, the
+ LFO-modulated curve is dashed teal, and a dot marks where the input sits now. Drag the
+ curve for Amount. Under it, harmonics 2 … 9 of a −6 dB sine show odd partials in brass,
+ even ones in ink, and the THD with its character (odd-heavy, even-heavy, mixed). The
+ curves and harmonics come from the engine's own shapers, so they match what you hear.
+ - **Modulation and quality.** LFO → Drive, Env → Tone and Rate, with a Sync switch. Sync
+ offers eight divisions from 2 bars to 1/64. Oversampling Off / 2× / 4× / 8×. A status strip
+ warns when Digital or Fold runs without oversampling. It also shows the sample rate,
+ oversampling, latency and CPU.
+ - **Compatibility.** The per-stage Bias / Tone / Width are appended and default to neutral.
+ The old shared Bias, Tone and Width stay as master offsets, so projects, racks and presets
+ saved before this sound the same. When a master offset is set, the status strip says so.
+ Mid/Side and Multiband now follow the stage roles above (Multiband crossovers moved from
+ 200 Hz / 2 kHz to 180 Hz / 2.4 kHz), so older projects that use these two routings sound
+ somewhat different.
+ - **32 factory presets**, up from six: warmth, drive, destruction, parallel, mid/side,
+ multiband and moving presets (Drum Glue, Warm Master, Wide Air, Low-End Only, Breathing
+ Drive …). The six earlier presets keep their names.
+ - **Automation** lists the stage params under Stage 1 / 2 / 3 and the LFO in its own group.
+ - **MCP: `read_forge`, `set_forge`, `set_forge_stage`.** `read_forge` reports the routing,
+ each stage with its role, THD and harmonics, the curve, the modulation, the meters and
+ the aliasing warning. `set_forge` and `set_forge_stage` edit Forge in dB, % and names.
+ `get_device_text` gives a summary, a live reading and a parameter guide, and
+ `device_action` 0 restarts the LFO and resets the meters.
+- **Nota Orbit is redrawn, and its LFO can follow the tempo.** The card follows the new mockup on
+ the 700 × 260 frame, laid out like Level and EQ-8:
+ - **LFO.** Pick the waveform and switch between **Hz** and **Sync**. The rate shows as a large
+ readout with its period in ms. Rate and Shape sit under it.
+ - **Sync.** The rate becomes a note value from 4/1 to 1/32, with dotted and triplet values.
+ While the transport plays, the LFO locks to the song position and restarts on the bar (a
+ 2/1 or 4/1 cycle restarts every 2 or 4 bars). When the transport stops, it keeps running
+ at the synced rate.
+ - **Glide on S&H.** On S&H, Shape becomes **Glide**, a slide from one random step to the
+ next. The right channel now plays the same steps as the left, one Phase later. At 0° the
+ steps move both channels together, as a random tremolo; at 180° they pan.
+ - **Gain graph.** Both channels' gain over two cycles (L brass, R teal), with the floor the
+ depth reaches in dB and a running head with the gain dots. Drag up / down for Amount and
+ left / right for Phase. Double-click resets both. Under the graph, a line shows where the
+ sound sits between left and right, and the swing it covers.
+ - **Motion.** Amount, Phase and Mix; **0° / 90° / 180°** buttons for the phase; the mode the
+ phase makes (tremolo, auto-pan or offset pan); and OUT L / OUT R meters with each
+ channel's gain. A status strip explains what you hear and shows the sample rate, tempo and
+ whether the LFO is free or synced.
+ - The channel gains now glide over about 1 ms, so Square and a jump in the transport no
+ longer click.
+ - **Compatibility.** Sync and Division are appended and default to Hz, so projects, racks
+ and presets saved before this open unchanged.
+ - **31 factory presets**, up from six: free and synced pans, tremolos (Chop Trem, Vintage Amp
+ Trem, Sidechain Pump, Helicopter), random steps and glides, and subtle motion. The six
+ earlier presets keep their names.
+ - **MCP: `read_orbit`.** It reports the settings, the rate and period, the mode, each
+ channel's gain now, the pan and its swing, whether the LFO is locked to the song, the
+ tempo and the levels. `get_device_text` gives a summary, a live reading and a parameter
+ guide with the Division table. `device_action` 0 restarts the LFO and 1 resets the
+ meters. Every parameter automates, MIDI-learns and saves in a preset.
- **Nota EQ-8 is redrawn with slopes, mid/side and global controls.** The card follows the new
mockup on the 700 × 260 frame, laid out like Dynamic EQ-8:
- **Band chips and graph.** A row of eight chips (number, type, channel, frequency) sits over
diff --git a/FEATURES.md b/FEATURES.md
index f8f7df9d..c87d90d0 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -401,8 +401,12 @@ and user presets, automation, persistence and cloning.
octaves, optionally narrowing with each repeat); Repeat (hold or Latch) and Mix. Timeline /
Slices / Filter graphs (drag the offset, the gate and the filter), a REPEAT column, a state
box and meters; 31 factory presets; MCP `read_beat_repeat`.
-- **Nota Orbit** (10, formerly Auto Pan) — auto-pan and tremolo, L/R phase (0° = tremolo …
- 180° = pan), 5 LFO shapes, Shape, Mix.
+- **Nota Orbit** (9, formerly Auto Pan) — auto-pan and tremolo on one LFO: L/R phase (0° =
+ tremolo … 180° = pan, with 0° / 90° / 180° buttons), Sine / Tri / Saw / Sqr / S&H, Shape
+ (Glide on S&H), Amount, Mix; rate free (0.01–40 Hz) or synced (4/1 … 1/32 with dotted and
+ triplet values, locked to the bar). A gain graph over two cycles (drag Amount and Phase),
+ the pan line with its swing, OUT L / R meters and a status strip; 31 factory presets; MCP
+ `read_orbit`.
- **Nota Crush** (12) — bit crusher: Bits (1–24), Rate (fractional sample and hold), Drive,
Wet; Digital / Analog / Fold modes; Anti-alias (4th order); GRIT (Dither / Jitter / Noise);
a post filter, output gain, Auto gain and a DC filter. Quantiser / Spectrum (engine FFT:
@@ -426,10 +430,13 @@ and user presets, automation, persistence and cloning.
- **Nota Strata** (15) — multi-layer overdub looper: layers with waveform, level and mute;
Record/Overdub/Play/Stop, Undo/Clear, Feedback, input gain, speed/reverse, quantize,
count-in, set-tempo, Export; audio layers persist into the project.
-- **Nota Forge** (17) — multi-stage saturator: 3 stages
- (Tube/Diode/Tape/Fuzz/Digital/Fold), Serial/Parallel/Mid-Side/Multiband routings,
- Amount/Tone/Wet, Bias/Width, LFO→Drive and Env→Tone; a transfer curve and a harmonics
- chart; **OVERSAMPLE** (Off/2×/4×/8×).
+- **Nota Forge** (17) — multi-stage saturator: 3 stages (Tube/Tape/Diode/Fuzz/Fold/Digital),
+ each with drive, output trim, feedback and its own Bias / Tone / Width; Serial / Parallel /
+ Mid-Side (Mid · Side · M+S) / Multiband (< 180 Hz · mids · > 2.4 kHz) routings; Amount /
+ Wet / Out; LFO→Drive (free or synced) and Env→Tone; a transfer curve (whole device or the
+ selected stage, each stage faint, the modulated curve, the live input) and harmonics 2–9
+ with THD from the engine; **OVERSAMPLE** (Off/2×/4×/8×) with an aliasing warning; 32 factory
+ presets; MCP `read_forge`, `set_forge`, `set_forge_stage`.
- **Nota EQ-3** (16) — three-band DJ isolator: Low / Mid / High faders (−24 … +6 dB, or the
Classic ±15 dB range) with a 0 dB detent and KILL buttons, two crossovers, 24 / 48 dB/oct
Linkwitz-Riley slopes (phase-aligned, flat at unity), output gain. A response graph with each
diff --git a/src/managed/Nota.App/ArrangementView.Automation.cs b/src/managed/Nota.App/ArrangementView.Automation.cs
index 3096f070..38486b99 100644
--- a/src/managed/Nota.App/ArrangementView.Automation.cs
+++ b/src/managed/Nota.App/ArrangementView.Automation.cs
@@ -395,10 +395,11 @@ public sealed partial class ArrangementView
// Nota Shutter its detector ("Det HP", "Det LP", "Det Filter"), Nota Auto Shift its
// scale notes, detector and MIDI target ("Note C#", "Det Low", "MIDI Glide" …) and Nota
// Beat Repeat its repeat filter ("Filter Freq", "Filter Type", "Filter Narrow" …), and
- // Nota EQ-8 and Nota Dynamic EQ-8 their eight bands ("3 Freq", "3 Slope" … under "Band 3"):
+ // Nota EQ-8 and Nota Dynamic EQ-8 their eight bands ("3 Freq", "3 Slope" … under "Band 3"),
+ // Nota Forge its three stages ("S2 Drive", "S2 Tone" … under "Stage 2") and its LFO:
// a word shared by two or more params becomes a submenu.
int bkind = e.TrackDeviceBuiltinKind(t.Id, d);
- bool grouped = bkind is 0 or 1 or 4 or 6 or 7 or 8 or 10 or 11 or 13 or 19 or 20 or 21 or 22;
+ bool grouped = bkind is 0 or 1 or 4 or 6 or 7 or 8 or 10 or 11 or 13 or 17 or 19 or 20 or 21 or 22;
var names = new string[builtinPc];
for (int p = 0; p < builtinPc; p++) names[p] = e.DeviceParamName(t.Id, d, p);
static string Head(string n) { int sp = n.IndexOf(' '); return sp > 0 ? n[..sp] : ""; }
@@ -413,7 +414,12 @@ public sealed partial class ArrangementView
if (!sub) { devMenu.Items.Add(leaf); continue; }
if (!groups.TryGetValue(head, out var g))
{
- g = new MenuItem { Header = bkind is 0 or 13 && int.TryParse(head, out _) ? "Band " + head : head };
+ g = new MenuItem
+ {
+ Header = bkind is 0 or 13 && int.TryParse(head, out _) ? "Band " + head
+ : bkind == 17 && head.Length == 2 && head[0] == 'S' && char.IsDigit(head[1]) ? "Stage " + head[1]
+ : head,
+ };
groups[head] = g; devMenu.Items.Add(g);
}
g.Items.Add(leaf);
diff --git a/src/managed/Nota.App/Controls/AutoPanViz.cs b/src/managed/Nota.App/Controls/AutoPanViz.cs
deleted file mode 100644
index 55391cc6..00000000
--- a/src/managed/Nota.App/Controls/AutoPanViz.cs
+++ /dev/null
@@ -1,105 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-only
-// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
-//
-// Nota Auto Pan viz: the per-channel amplitude curves over one LFO cycle — left
-// (amber) and right (teal), offset by Phase — so you see tremolo (curves overlap,
-// Phase 0°) vs auto-pan (curves opposite, Phase 180°). A live L—R bar with a moving
-// dot (fed by the device's published pan position) tracks the current stereo place.
-// Mirrors AutoPan.h's LFO/shape math so the picture matches the sound.
-
-using System;
-using System.Globalization;
-using Avalonia;
-using Avalonia.Controls;
-using Avalonia.Media;
-
-namespace Nota.App;
-
-internal sealed class AutoPanViz : Control
-{
- private static readonly IBrush Sunken = NotaPalette.BgSunken;
- private static readonly IBrush BorderDef = NotaPalette.BorderDefault;
- private static readonly IBrush AccentBright = NotaPalette.AccentBright;
- private static readonly IBrush Teal = NotaPalette.Teal;
- private static readonly IBrush TextTertiary = NotaPalette.TextTertiary;
- private static readonly IBrush Grid = NotaGraph.Grid;
- private static readonly Typeface Face = NotaFonts.Mono;
- private static readonly string[] WaveNames = { "SINE", "TRI", "SAW", "SQUARE", "S&H" };
-
- private int _wave;
- private float _amount = 0.7f, _shape, _phase = 0.5f, _pan = 0.5f;
-
- public AutoPanViz() { MinWidth = 150; MinHeight = 70; }
-
- public void Set(int wave, float amount, float shape, float phase, float pan)
- { _wave = Math.Clamp(wave, 0, 4); _amount = amount; _shape = shape; _phase = phase; _pan = pan; InvalidateVisual(); }
-
- private static double Frac(double x) => x - Math.Floor(x);
-
- // Mirrors AutoPan::lfo (S&H is shown as a flat mid-line — it has no fixed shape).
- private float Lfo(double ph)
- {
- double v = _wave switch
- {
- 1 => 4.0 * Math.Abs(ph - 0.5) - 1.0, // triangle
- 2 => 2.0 * ph - 1.0, // saw
- 3 => ph < 0.5 ? 1.0 : -1.0, // square
- 4 => 0.0, // S&H (random at runtime)
- _ => Math.Sin(2.0 * Math.PI * ph), // sine
- };
- if (_wave < 3 && _shape > 1e-3f)
- {
- double k = 1.0 + _shape * 12.0;
- double sharp = Math.Tanh(k * v) / Math.Tanh(k);
- v = v * (1.0 - _shape) + sharp * _shape;
- }
- return (float)v;
- }
-
- private float GainAt(double ph) => 1f - _amount * 0.5f * (1f - Lfo(ph));
-
- public override void Render(DrawingContext ctx)
- {
- double w = Bounds.Width, h = Bounds.Height;
- if (w <= 0 || h <= 0) return;
- NotaGraph.Window(ctx, new Rect(0, 0, w, h));
- double pad = 7, x0 = pad, x1 = w - pad, top = pad + 11, bot = h - pad - 15;
-
- var gridPen = new Pen(Grid, 1);
- for (int i = 1; i <= 3; i++) { double gy = top + (bot - top) * i / 4.0; ctx.DrawLine(gridPen, new Point(x0, gy), new Point(x1, gy)); }
-
- // Per-channel gain curves over one cycle (gain 1 at top, 0 at bottom).
- void Curve(double phOff, IBrush col)
- {
- var pen = new Pen(col, 1.6, lineCap: PenLineCap.Round, lineJoin: PenLineJoin.Round);
- var geo = new StreamGeometry();
- using (var gc = geo.Open())
- {
- int n = 96;
- for (int i = 0; i <= n; i++)
- {
- double t = (double)i / n;
- float g = GainAt(Frac(t + phOff));
- var pt = new Point(x0 + t * (x1 - x0), bot - g * (bot - top));
- if (i == 0) gc.BeginFigure(pt, false); else gc.LineTo(pt);
- }
- }
- ctx.DrawGeometry(null, pen, geo);
- }
- Curve(0.0, AccentBright); // L
- Curve(_phase, Teal); // R (phase-offset)
-
- // Live L—R position bar with a moving dot.
- double by = bot + 8, bh = 4;
- ctx.DrawRectangle(NotaPalette.Wash(NotaPalette.BorderStrong, 0x40), null, new Rect(x0, by, x1 - x0, bh), 2, 2);
- ctx.DrawLine(new Pen(Grid, 1), new Point((x0 + x1) / 2, by - 1), new Point((x0 + x1) / 2, by + bh + 1));
- double dotX = x0 + Math.Clamp(_pan, 0f, 1f) * (x1 - x0);
- ctx.DrawEllipse(AccentBright, null, new Point(dotX, by + bh / 2), 3, 3);
-
- ctx.DrawText(new FormattedText("L", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Face, 8, AccentBright), new Point(x0, pad - 2));
- var tR = new FormattedText("R", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Face, 8, Teal);
- ctx.DrawText(tR, new Point(x0 + 12, pad - 2));
- var tw = new FormattedText(WaveNames[_wave], CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Face, 8, TextTertiary);
- ctx.DrawText(tw, new Point(x1 - tw.Width, pad - 2));
- }
-}
diff --git a/src/managed/Nota.App/Controls/ForgeViews.cs b/src/managed/Nota.App/Controls/ForgeViews.cs
new file mode 100644
index 00000000..dd36d7ec
--- /dev/null
+++ b/src/managed/Nota.App/Controls/ForgeViews.cs
@@ -0,0 +1,199 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Forge (device kind 17) views, the "Nota Forge" mockup:
+// · FgTransferView — the transfer curve over input −1 … +1: the whole device in brass (in
+// Mid/Side and Multiband the selected stage, since each stage sees its own signal), every
+// stage alone as a faint curve, the LFO-modulated curve as teal dashes and a node where the
+// input sits on the curve now. Drag up / down for Amount; double-click resets it.
+// · FgHarmonicsView — harmonics 2 … 9 of a −6 dB test sine through that curve: odd partials in
+// brass, even ones in ink, with THD and its flavour.
+// The curves and the partials come from the engine (Forge.h scopeRead), computed by the same
+// shapers the audio runs, so the picture is what is heard.
+
+using System;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Media;
+
+namespace Nota.App;
+
+internal static class ForgeMath
+{
+ // Scope layout (Forge.h S_* / kTele / kHarm / kPts / kCurves).
+ public const int S_InPeak = 0, S_OutPeak = 1, S_InRms = 2, S_OutRms = 3, S_SampleRate = 4, S_Cpu = 5, S_Latency = 6,
+ S_OsFactor = 7, S_Lfo = 8, S_DriveMod = 9, S_Env = 10, S_ToneNow = 11, S_InLevel = 12, S_ThdChain = 13, S_ThdS1 = 14,
+ S_FlavorChain = 17, S_FlavorS1 = 18, S_Signal = 21, S_Alias = 22, S_Routing = 23, S_OnCount = 24, S_LfoHz = 25,
+ S_Bpm = 26, S_AmountDb = 27, S_OutputDb = 28;
+ public const int kTele = 32, kHarm = 8, kHarmOff = kTele, kPts = 129, kCurves = 8, kCurveOff = kHarmOff + kHarm * 4,
+ kScope = kCurveOff + kPts * kCurves;
+
+ public static readonly string[] AlgoNames = { "Tube", "Diode", "Tape", "Fuzz", "Digital", "Fold" };
+ // The type chips, in the mockup's order (soft → hard), and the algorithm each one picks.
+ public static readonly string[] ChipNames = { "Tube", "Tape", "Diode", "Fuzz", "Fold", "Dig" };
+ public static readonly int[] ChipAlgo = { 0, 2, 1, 3, 5, 4 };
+ public static readonly string[] Flavors = { "clean", "odd-heavy", "even-heavy", "mixed" };
+ public static readonly string[] DivNames = { "2/1", "1/1", "1/2", "1/4", "1/8", "1/16", "1/32", "1/64" };
+
+ /// <summary>The role word a stage plays in a routing (Mid/Side, Multiband), or "".</summary>
+ public static string Role(int routing, int stage) => routing switch
+ {
+ 2 => stage switch { 0 => "MID", 1 => "SIDE", _ => "M+S" },
+ 3 => stage switch { 0 => "LOW < 180", 1 => "MID", _ => "HIGH > 2.4k" },
+ 1 => "PAR",
+ _ => "",
+ };
+}
+
+internal sealed class FgTransferView : ShDragView
+{
+ public const int HAmount = 0;
+ private readonly float[] _main = new float[ForgeMath.kPts], _mod = new float[ForgeMath.kPts];
+ private readonly float[][] _stage = { new float[ForgeMath.kPts], new float[ForgeMath.kPts], new float[ForgeMath.kPts] };
+ private readonly bool[] _on = new bool[3];
+ private int _sel;
+ private bool _single, _active = true, _hasMod, _signal, _valid;
+ private double _in;
+ private string _label = "static";
+
+ /// <summary>Takes the curves from a scope read. `single` draws the selected stage as the main
+ /// curve (Mid/Side, Multiband); `hasMod` shows the LFO-modulated curve.</summary>
+ public void Set(float[] sc, int n, bool[] on, int sel, bool single, bool active, bool hasMod, string label)
+ {
+ _valid = n >= ForgeMath.kScope;
+ if (_valid)
+ {
+ int mi = single ? 2 + sel * 2 : 0;
+ Array.Copy(sc, ForgeMath.kCurveOff + mi * ForgeMath.kPts, _main, 0, ForgeMath.kPts);
+ Array.Copy(sc, ForgeMath.kCurveOff + (mi + 1) * ForgeMath.kPts, _mod, 0, ForgeMath.kPts);
+ for (int s = 0; s < 3; s++) Array.Copy(sc, ForgeMath.kCurveOff + (2 + s * 2) * ForgeMath.kPts, _stage[s], 0, ForgeMath.kPts);
+ _signal = sc[ForgeMath.S_Signal] > 0.5f;
+ _in = Math.Clamp(sc[ForgeMath.S_InLevel], 0, 1);
+ }
+ for (int s = 0; s < 3; s++) _on[s] = on[s];
+ _sel = sel; _single = single; _active = active; _hasMod = hasMod; _label = label;
+ InvalidateVisual();
+ }
+
+ protected override int Hit(Point p) => HAmount;
+ protected override double DragTo(int handle, Point start, Point p, double v0) => v0 + (start.Y - p.Y) / Math.Max(80, Bounds.Height * 1.4);
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+ var frame = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, frame);
+ double x0 = 1, x1 = w - 1, top = 1, bot = h - 1;
+ double X(double x) => x0 + (x + 1) / 2 * (x1 - x0);
+ double Y(double y) => top + (1 - (Math.Clamp(y, -1.25, 1.25) / 1.25 + 1) / 2) * (bot - top);
+
+ using (ctx.PushClip(new RoundedRect(frame.Deflate(1), NotaGraph.Radius)))
+ {
+ ctx.DrawLine(NotaGraph.GridPen, new Point(X(-0.5), top), new Point(X(-0.5), bot));
+ ctx.DrawLine(NotaGraph.GridPen, new Point(X(0.5), top), new Point(X(0.5), bot));
+ ctx.DrawLine(NotaGraph.GridPen, new Point(x0, Y(1)), new Point(x1, Y(1)));
+ ctx.DrawLine(NotaGraph.GridPen, new Point(x0, Y(-1)), new Point(x1, Y(-1)));
+ var axis = new Pen(NotaPalette.BorderDefault, 1);
+ ctx.DrawLine(axis, new Point(X(0), top), new Point(X(0), bot));
+ ctx.DrawLine(axis, new Point(x0, Y(0)), new Point(x1, Y(0)));
+ ctx.DrawLine(new Pen(NotaPalette.BorderDefault, 1, new DashStyle(new double[] { 3, 3 }, 0)), new Point(X(-1), Y(-1)), new Point(X(1), Y(1)));
+
+ if (_valid)
+ {
+ StreamGeometry Path(float[] ys)
+ {
+ var g = new StreamGeometry();
+ using var gc = g.Open();
+ for (int i = 0; i < ys.Length; i++)
+ {
+ double x = -1 + 2.0 * i / (ys.Length - 1);
+ var pt = new Point(X(x), Y(ys[i]));
+ if (i == 0) gc.BeginFigure(pt, false); else gc.LineTo(pt);
+ }
+ gc.EndFigure(false);
+ return g;
+ }
+ // Every stage alone, faint; the selected one lit. Hidden when the device is bypassed,
+ // and the selected one when it already is the main curve.
+ if (_active)
+ for (int s = 0; s < 3; s++)
+ {
+ bool isSel = s == _sel;
+ if (_single && isSel) continue;
+ double op = _on[s] ? (isSel ? 0.45 : 0.7) : 0.25;
+ var ink = isSel ? NotaPalette.AccentBright : NotaPalette.TextDisabled;
+ using (ctx.PushOpacity(op))
+ ctx.DrawGeometry(null, new Pen(ink, 1), Path(_stage[s]));
+ }
+ if (_active && _hasMod)
+ ctx.DrawGeometry(null, new Pen(NotaPalette.TealBright, 1.2, new DashStyle(new double[] { 4, 3 }, 0)), Path(_mod));
+ ctx.DrawGeometry(null, new Pen(_active ? NotaPalette.Accent : NotaPalette.TextDisabled, Dragging ? 2.2 : NotaGraph.PrimaryWidth,
+ lineJoin: PenLineJoin.Round), Path(_main));
+
+ // Where the input sits on the curve now.
+ if (_active && _signal && _in > 1e-4)
+ {
+ double fi = (_in + 1) / 2 * (ForgeMath.kPts - 1);
+ int i0 = Math.Clamp((int)Math.Floor(fi), 0, ForgeMath.kPts - 2);
+ double fr = fi - i0, y = _main[i0] + (_main[i0 + 1] - _main[i0]) * fr;
+ NotaGraph.Node(ctx, new Point(X(_in), Y(y)), true, NotaPalette.AccentBright);
+ }
+ }
+ }
+
+ NotaGraph.Title(ctx, frame, "Transfer");
+ if (_active && _hasMod)
+ NotaGraph.Legend(ctx, w - 6, 3, (_label, NotaPalette.AccentBright, NotaGraph.Mark.Line), ("modulated", NotaPalette.TealBright, NotaGraph.Mark.Dashed));
+ else
+ NotaGraph.Legend(ctx, w - 6, 3, (_active ? _label : "bypass", _active ? NotaPalette.AccentBright : NotaPalette.TextTertiary, NotaGraph.Mark.Line));
+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.BottomLeft, "in −1");
+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.BottomRight, "+1");
+ var o = NotaGraph.AxisText("out +1");
+ ctx.DrawText(o, new Point(X(0) + 3, Y(1) - o.Height / 2));
+ }
+}
+
+internal sealed class FgHarmonicsView : Control
+{
+ private readonly float[] _db = new float[ForgeMath.kHarm];
+ private string _label = "";
+ private bool _valid;
+
+ public FgHarmonicsView() { ClipToBounds = true; }
+
+ public void Set(float[] sc, int n, int set, string label)
+ {
+ _valid = n >= ForgeMath.kCurveOff;
+ if (_valid) Array.Copy(sc, ForgeMath.kHarmOff + set * ForgeMath.kHarm, _db, 0, ForgeMath.kHarm);
+ _label = label;
+ InvalidateVisual();
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+ var frame = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, frame);
+ NotaGraph.Title(ctx, frame, "Harmonics");
+ var lbl = NotaGraph.AxisText(_label, NotaPalette.TextSecondary);
+ ctx.DrawText(lbl, new Point(w - 6 - lbl.Width, 3));
+ if (!_valid) return;
+
+ double x0 = 8, x1 = w - 8, top = 15, bot = h - 10, gap = 6;
+ int n = ForgeMath.kHarm;
+ double bw = (x1 - x0 - gap * (n - 1)) / n;
+ for (int i = 0; i < n; i++)
+ {
+ int k = i + 2;
+ double hh = Math.Clamp((_db[i] + 72) / 72, 0, 1);
+ double x = x0 + i * (bw + gap);
+ IBrush ink = hh > 0.02 ? (k % 2 == 1 ? NotaPalette.Accent : NotaPalette.TextSecondary) : NotaPalette.SurfaceRaised;
+ double bh = Math.Max(1, hh * (bot - top));
+ ctx.DrawRectangle(ink, null, new RoundedRect(new Rect(x, bot - bh, bw, bh), 1, 1, 0, 0));
+ var kt = NotaGraph.AxisText(k.ToString(), NotaPalette.TextDisabled);
+ ctx.DrawText(kt, new Point(x + bw / 2 - kt.Width / 2, bot + 1));
+ }
+ }
+}
diff --git a/src/managed/Nota.App/Controls/ForgeViz.cs b/src/managed/Nota.App/Controls/ForgeViz.cs
deleted file mode 100644
index 470be495..00000000
--- a/src/managed/Nota.App/Controls/ForgeViz.cs
+++ /dev/null
@@ -1,246 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-only
-// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
-//
-// Nota Forge (device kind 17) visualisations, mockup 3m:
-// · ForgeTransferCurve — the multi-stage saturation transfer function. Two curves: the
-// static shape in brass, and the LFO→drive-modulated shape in teal dashes (it breathes
-// with the live LFO published by the DSP), so you see the range you sweep through.
-// · ForgeHarmonics — a bar chart of the harmonic spectrum produced by the current chain
-// (a test sine run through the replicated shapers, then FFT): odd partials full brass,
-// even ones dimmed, with a THD % / odd-vs-even readout.
-// Both replicate Forge.h's shape()/driveGain() exactly so the picture matches the sound.
-
-using System;
-using Avalonia;
-using Avalonia.Controls;
-using Avalonia.Media;
-using Nota.Application;
-
-namespace Nota.App;
-
-// Shared param snapshot + shaper maths, read straight off the device params.
-internal static class ForgeMath
-{
- public const int Amount = 0, Tone = 1, Wet = 2, Output = 3, Bias = 4, Width = 5, Routing = 6,
- LfoDrive = 7, EnvTone = 8, LfoRate = 9, LfoSync = 10,
- S1Type = 11, S1Drive = 12, S1Out = 13, S1FB = 14, S1On = 15;
- public const int Stages = 3, Algos = 6;
- public static readonly string[] AlgoNames = { "Tube", "Diode", "Tape", "Fuzz", "Digital", "Fold" };
-
- public static float Shape(int type, float x, float bias)
- {
- float b = bias * 0.6f;
- return type switch
- {
- 0 => MathF.Tanh(x + b) - MathF.Tanh(b),
- 1 => (x + b) >= 0 ? MathF.Tanh((x + b) * 1.3f) : MathF.Tanh((x + b) * 0.55f),
- 2 => MathF.Tanh(x + b * 0.4f),
- 3 => MathF.Tanh((x + b) / (1 + MathF.Abs(x + b)) * 3f),
- 4 => Math.Clamp(x + b, -1f, 1f),
- _ => MathF.Sin((x + b) * 0.9f),
- };
- }
- public static float DriveGain(float d) => 1 + d * d * 20f;
-
- // The full enabled-stage chain applied to one input sample (serial approximation for
- // the viz — feedback and inter-stage filters are omitted, the shape is what matters).
- public static float Chain(IAudioEngine e, int t, int d, float xin, float driveMod)
- {
- float P(int p) => e.DeviceGetParam(t, d, p);
- float amt = MathF.Pow(10, P(Amount) * 30f / 20f);
- float outGain = MathF.Pow(10, (P(Output) - 0.5f) * 48f / 20f);
- float bias = (P(Bias) - 0.5f) * 2f;
- float v = xin * amt;
- for (int s = 0; s < Stages; s++)
- {
- if (P(S1On + s * 5) < 0.5f) continue;
- int type = Math.Clamp((int)MathF.Round(P(S1Type + s * 5) * (Algos - 1)), 0, Algos - 1);
- float g = DriveGain(Math.Clamp(P(S1Drive + s * 5) + driveMod, 0f, 1f));
- float trim = MathF.Pow(10, (P(S1Out + s * 5) - 0.5f) * 24f / 20f);
- float y = Shape(type, v * g, bias) / MathF.Sqrt(g) * trim;
- v = y;
- }
- return Math.Clamp(v * outGain, -2f, 2f);
- }
-}
-
-internal sealed class ForgeTransferCurve : Control
-{
- private static readonly IBrush Bg = NotaPalette.BgSunken;
- private static readonly IBrush BorderB = NotaPalette.BorderDefault;
- private static readonly IPen Grid = NotaGraph.GridPen;
- private static readonly IPen Diag = new Pen(NotaPalette.Wash(NotaPalette.SurfaceRaised, 0x40), 1) { DashStyle = new DashStyle(new double[] { 3, 3 }, 0) };
- private static readonly IPen CurvePen = new Pen(NotaPalette.Accent, 1.8);
- private static readonly IBrush CurveFill = NotaPalette.Wash(NotaPalette.Accent, 0x14);
- private static readonly IPen ModPen = new Pen(NotaPalette.Teal, 1.3) { DashStyle = new DashStyle(new double[] { 4, 3 }, 0) };
- private static readonly IBrush AxisB = NotaPalette.TextTertiary;
- private static readonly IBrush Muted = NotaPalette.TextTertiary;
- private static readonly Typeface Face = NotaFonts.Mono;
-
- private readonly IAudioEngine _engine;
- private readonly int _track, _device;
- private float _lfoLive = 0.5f;
-
- public ForgeTransferCurve(IAudioEngine engine, int track, int device)
- {
- _engine = engine; _track = track; _device = device;
- MinHeight = 60; ClipToBounds = true;
- }
-
- public void Tick() { _lfoLive = Math.Clamp(_engine.DeviceGainReduction(_track, _device), 0, 1); InvalidateVisual(); }
- public void Sync() => InvalidateVisual();
-
- public override void Render(DrawingContext ctx)
- {
- double w = Bounds.Width, h = Bounds.Height;
- if (w <= 0 || h <= 0) return;
- NotaGraph.Window(ctx, new Rect(0, 0, w, h));
- double pad = 6, gx = pad, gy = 14, gw = w - pad * 2, gh = h - gy - 12;
- if (gw <= 0 || gh <= 0) return;
-
- // grid + identity diagonal
- ctx.DrawLine(Grid, new Point(gx, gy + gh / 2), new Point(gx + gw, gy + gh / 2));
- ctx.DrawLine(Grid, new Point(gx + gw / 2, gy), new Point(gx + gw / 2, gy + gh));
- ctx.DrawLine(Diag, new Point(gx, gy + gh), new Point(gx + gw, gy));
-
- Point Map(double xin, double yout) => new Point(gx + (xin * 0.5 + 0.5) * gw, gy + (1 - (yout * 0.5 + 0.5)) * gh);
-
- void Draw(float driveMod, IPen pen, bool fill)
- {
- int n = (int)Math.Clamp(gw, 48, 260);
- var pts = new Point[n];
- for (int i = 0; i < n; i++)
- {
- double xin = -1.0 + 2.0 * i / (n - 1);
- double y = ForgeMath.Chain(_engine, _track, _device, (float)xin, driveMod);
- pts[i] = Map(xin, Math.Clamp(y, -1, 1));
- }
- if (fill)
- {
- var geo = new StreamGeometry();
- using (var g = geo.Open())
- {
- g.BeginFigure(new Point(gx, gy + gh), true);
- foreach (var p in pts) g.LineTo(p);
- g.LineTo(new Point(gx + gw, gy + gh));
- g.EndFigure(true);
- }
- }
- for (int i = 1; i < n; i++) ctx.DrawLine(pen, pts[i - 1], pts[i]);
- }
-
- // modulated shape (behind), then static
- float depth = _engine.DeviceGetParam(_track, _device, ForgeMath.LfoDrive);
- float modAmt = depth * (_lfoLive - 0.5f) * 0.6f;
- if (depth > 0.01f) Draw(modAmt, ModPen, false);
- Draw(0f, CurvePen, true);
-
- void Lbl(string s, double x, double y, IBrush b) => ctx.DrawText(new FormattedText(s, System.Globalization.CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Face, 8, b), new Point(x, y));
- Lbl("TRANSFER", gx, 2, Muted);
- NotaGraph.Legend(ctx, gx + gw - 2, 2, ("static", NotaPalette.Accent, NotaGraph.Mark.Line), ("modulated", NotaPalette.Teal, NotaGraph.Mark.Dashed));
- Lbl("in −60", gx, gy + gh + 1, AxisB);
- Lbl("0\u2009dB", gx + gw - 22, gy + gh + 1, AxisB);
- }
-}
-
-internal sealed class ForgeHarmonics : Control
-{
- private const int N = 1024, Bars = 14;
- private static readonly IBrush Bg = NotaPalette.BgSunken;
- private static readonly IBrush BorderB = NotaPalette.BorderDefault;
- private static readonly IBrush OddB = NotaPalette.Accent;
- private static readonly IBrush EvenB = NotaPalette.Wash(NotaPalette.Accent, 0x73); // 45%
- private static readonly IBrush Muted = NotaPalette.TextTertiary;
- private static readonly IBrush LabelC = NotaPalette.TextSecondary;
- private static readonly Typeface Face = NotaFonts.Mono;
-
- private readonly IAudioEngine _engine;
- private readonly int _track, _device;
- private readonly double[] _re = new double[N], _im = new double[N];
- private readonly double[] _harm = new double[Bars + 2];
- private double _thd; private bool _oddHeavy = true;
-
- public ForgeHarmonics(IAudioEngine engine, int track, int device)
- {
- _engine = engine; _track = track; _device = device;
- MinHeight = 40; ClipToBounds = true;
- }
-
- public void Sync()
- {
- // Run a unit sine (a few periods) through the static chain, FFT, read partials.
- const int periods = 16;
- for (int i = 0; i < N; i++)
- {
- double ph = 2 * Math.PI * periods * i / N;
- double x = 0.7 * Math.Sin(ph);
- _re[i] = ForgeMath.Chain(_engine, _track, _device, (float)x, 0f);
- _im[i] = 0;
- }
- Fft(_re, _im);
- double fund = Mag(periods);
- if (fund < 1e-6) fund = 1e-6;
- double odd = 0, even = 0, dist = 0;
- for (int k = 1; k <= Bars; k++)
- {
- double m = Mag(periods * (k + 1)) / fund; // partials 2,3,4,...
- _harm[k] = m;
- if (k >= 1) { dist += m * m; if ((k + 1) % 2 == 1) odd += m; else even += m; }
- }
- _thd = Math.Sqrt(dist) * 100.0;
- _oddHeavy = odd >= even;
- InvalidateVisual();
- }
-
- private double Mag(int k) => k > 0 && k < N / 2 ? Math.Sqrt(_re[k] * _re[k] + _im[k] * _im[k]) : 0;
-
- public override void Render(DrawingContext ctx)
- {
- double w = Bounds.Width, h = Bounds.Height;
- if (w <= 0 || h <= 0) return;
- NotaGraph.Window(ctx, new Rect(0, 0, w, h));
- void Lbl(string s, double x, double y, IBrush b) => ctx.DrawText(new FormattedText(s, System.Globalization.CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Face, 8, b), new Point(x, y));
- Lbl("HARMONICS", 6, 3, Muted);
- Lbl($"THD {_thd:0}\u2009% · {(_oddHeavy ? "odd-heavy" : "even-heavy")}", w - 116, 3, LabelC);
-
- double gx = 6, gy = 15, gw = w - 12, gh = h - gy - 4;
- if (gh <= 0) return;
- double bw = gw / Bars;
- for (int k = 1; k <= Bars; k++)
- {
- double m = Math.Clamp(_harm[k] / 0.6, 0, 1); // 0..1 normalized for display
- double bh = m * gh;
- double x = gx + (k - 1) * bw;
- bool odd = (k + 1) % 2 == 1;
- ctx.FillRectangle(odd ? OddB : EvenB, new Rect(x + 1, gy + gh - bh, Math.Max(1, bw - 2), bh), 1);
- }
- }
-
- private static void Fft(double[] re, double[] im)
- {
- int n = re.Length;
- for (int i = 1, j = 0; i < n; i++)
- {
- int bit = n >> 1;
- for (; (j & bit) != 0; bit >>= 1) j ^= bit;
- j ^= bit;
- if (i < j) { (re[i], re[j]) = (re[j], re[i]); (im[i], im[j]) = (im[j], im[i]); }
- }
- for (int len = 2; len <= n; len <<= 1)
- {
- double ang = -2 * Math.PI / len, wr = Math.Cos(ang), wi = Math.Sin(ang);
- for (int i = 0; i < n; i += len)
- {
- double cr = 1, ci = 0;
- for (int k = 0; k < len / 2; k++)
- {
- int a = i + k, b = i + k + len / 2;
- double tr = re[b] * cr - im[b] * ci, ti = re[b] * ci + im[b] * cr;
- re[b] = re[a] - tr; im[b] = im[a] - ti;
- re[a] += tr; im[a] += ti;
- double ncr = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = ncr;
- }
- }
- }
- }
-}
diff --git a/src/managed/Nota.App/Controls/OrbitViews.cs b/src/managed/Nota.App/Controls/OrbitViews.cs
new file mode 100644
index 00000000..08bf89e1
--- /dev/null
+++ b/src/managed/Nota.App/Controls/OrbitViews.cs
@@ -0,0 +1,243 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Nota Orbit views (device kind 9) — the pictures on the Orbit card:
+// OrbitGainView — both channels' gain over two LFO cycles (L brass, R teal, R offset by Phase),
+// the floor the depth reaches, and a running head with the gain dots on it.
+// Drag up / down for Amount, left / right for Phase; double-click resets both.
+// OrbitPanBar — the stereo position now on an L—R line, over the swing the LFO covers.
+// OrbitMeter — a thin output meter in its channel's chroma.
+// OrbitMath mirrors AutoPan.h's LFO so the picture matches the sound; the S&H steps come from
+// the engine's telemetry (the four cycles around the window).
+
+using System;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Input;
+using Avalonia.Media;
+
+namespace Nota.App;
+
+internal static class OrbitMath
+{
+ public static readonly string[] Waves = { "Sine", "Tri", "Saw", "Sqr", "S&H" };
+ public static readonly string[] WaveNames = { "SINE", "TRIANGLE", "SAW", "SQUARE", "S&H" };
+ // Sync divisions, slowest → fastest (AutoPan::kDivBeats / kDivNames).
+ public static readonly double[] DivBeats = { 16, 8, 4, 3, 2, 4.0 / 3, 1.5, 1, 2.0 / 3, 0.75, 0.5, 1.0 / 3, 0.375, 0.25, 1.0 / 6, 0.125 };
+ public static readonly string[] DivNames = { "4/1", "2/1", "1/1", "1/2D", "1/2", "1/2T", "1/4D", "1/4", "1/4T", "1/8D", "1/8", "1/8T", "1/16D", "1/16", "1/16T", "1/32" };
+
+ public static int DivIndex(double v) => Math.Clamp((int)Math.Round(v * (DivBeats.Length - 1)), 0, DivBeats.Length - 1);
+ public static double DivNorm(int i) => (double)Math.Clamp(i, 0, DivBeats.Length - 1) / (DivBeats.Length - 1);
+ public static int WaveIndex(double v) => Math.Clamp((int)Math.Round(v * 4), 0, 4);
+ public static double FreeHz(double v) => 0.01 * Math.Pow(4000, Math.Clamp(v, 0, 1));
+
+ /// <summary>The LFO in [−1, 1] at window position <paramref name="p"/> (cycles, may run past 2);
+ /// <paramref name="sh"/> holds the S&amp;H steps of cycles −1, 0, 1, 2 of the window.</summary>
+ public static double Lfo(int wave, double shape, double p, ReadOnlySpan<float> sh)
+ {
+ int k = (int)Math.Floor(p);
+ double f = p - k, v;
+ switch (wave)
+ {
+ case 1: v = 4.0 * Math.Abs(f - 0.5) - 1.0; break;
+ case 2: v = 2.0 * f - 1.0; break;
+ case 3: return f < 0.5 ? 1 : -1;
+ case 4:
+ {
+ double a = Step(sh, k - 1), b = Step(sh, k);
+ double t = shape > 1e-3 ? Math.Min(1, f / shape) : 1;
+ t = t * t * (3 - 2 * t);
+ return a + (b - a) * t;
+ }
+ default: v = Math.Sin(2 * Math.PI * f); break;
+ }
+ if (shape > 1e-3)
+ {
+ double kk = 1 + shape * 12;
+ v = v * (1 - shape) + Math.Tanh(kk * v) / Math.Tanh(kk) * shape;
+ }
+ return v;
+ }
+
+ private static double Step(ReadOnlySpan<float> sh, int k) => sh.Length >= 4 ? sh[Math.Clamp(k + 1, 0, 3)] : 0;
+
+ /// <summary>A channel's gain for an LFO value (AutoPan.h: Mix blends toward 1).</summary>
+ public static double Gain(double lfo, double amount, double mix) => 1 - mix * amount * 0.5 * (1 - lfo);
+
+ public static string Db(double g) => g < 0.001 ? "−∞" : g >= 0.9995 ? "0.0" : NotaNum.F($"{20 * Math.Log10(g):0.0}");
+}
+
+internal sealed class OrbitGainView : Control
+{
+ private int _wave;
+ private double _shape, _amount = 0.7, _phase = 0.5, _mix = 1, _head, _gl = 1, _gr = 1, _periodMs = 690;
+ private bool _on = true, _drag;
+ private readonly float[] _sh = new float[4];
+ private Point _start;
+ private double _a0, _p0;
+
+ /// <summary>Amount and Phase (0..1) at the start of a drag.</summary>
+ public Func<(double Amount, double Phase)>? Value { get; set; }
+ public event Action? GestureBegin;
+ public event Action? GestureEnd;
+ public event Action<double, double>? Changed;
+ public event Action? ResetRequested;
+ public bool Dragging => _drag;
+
+ public OrbitGainView() { ClipToBounds = true; MinHeight = 40; Cursor = new Cursor(StandardCursorType.SizeAll); }
+
+ public void Set(int wave, double shape, double amount, double phase, double mix, double head, double gl, double gr,
+ ReadOnlySpan<float> sh, double periodMs, bool on)
+ {
+ _wave = wave; _shape = shape; _amount = amount; _phase = phase; _mix = mix; _head = head;
+ _gl = gl; _gr = gr; _periodMs = periodMs; _on = on;
+ for (int i = 0; i < 4; i++) _sh[i] = i < sh.Length ? sh[i] : 0f;
+ InvalidateVisual();
+ }
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ base.OnPointerPressed(e);
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
+ if (e.ClickCount == 2) { ResetRequested?.Invoke(); e.Handled = true; return; }
+ var v = Value?.Invoke() ?? (0.7, 0.5);
+ _a0 = v.Amount; _p0 = v.Phase; _start = e.GetPosition(this); _drag = true;
+ GestureBegin?.Invoke(); e.Pointer.Capture(this); e.Handled = true;
+ }
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ base.OnPointerMoved(e);
+ if (!_drag) return;
+ var p = e.GetPosition(this);
+ bool fine = (e.KeyModifiers & (KeyModifiers.Shift | KeyModifiers.Control | KeyModifiers.Meta)) != 0;
+ double k = fine ? 0.2 : 1;
+ // The depth follows the floor line: dragging down lowers the floor.
+ double a = Math.Clamp(_a0 + (p.Y - _start.Y) * k / Math.Max(60, Bounds.Height * 0.88), 0, 1);
+ // Phase: one window width = 360°.
+ double ph = Math.Clamp(_p0 + (p.X - _start.X) * k / Math.Max(120, Bounds.Width), 0, 1);
+ Changed?.Invoke(a, ph);
+ }
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ {
+ base.OnPointerReleased(e);
+ if (!_drag) return;
+ _drag = false; e.Pointer.Capture(null); GestureEnd?.Invoke(); InvalidateVisual();
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+ var frame = new Rect(0, 0, w, h);
+ NotaGraph.Window(ctx, frame);
+ double x0 = 1, x1 = w - 1, top = h * 0.06, bot = h * 0.94;
+ double X(double p) => x0 + p / 2 * (x1 - x0);
+ double Y(double g) => top + (1 - Math.Clamp(g, 0, 1)) * (bot - top);
+
+ for (int i = 1; i <= 3; i++)
+ {
+ double gy = Y(1 - i * 0.25);
+ ctx.DrawLine(NotaGraph.GridPen, new Point(x0, gy), new Point(x1, gy));
+ }
+ ctx.DrawLine(new Pen(NotaPalette.GraphBorder, 1, new DashStyle(new double[] { 2, 3 }, 0)), new Point(X(1), 0), new Point(X(1), h));
+
+ double floor = 1 - _amount * _mix;
+ double fy = Y(floor);
+ ctx.DrawLine(new Pen(NotaPalette.BorderStrong, 1, new DashStyle(new double[] { 4, 3 }, 0)), new Point(x0, fy), new Point(x1, fy));
+
+ // R first so L reads on top where they meet (tremolo).
+ IBrush inkL = _on ? NotaPalette.Accent : NotaPalette.TextAxis;
+ IBrush inkR = _on ? NotaPalette.TealBright : NotaPalette.TextAxis;
+ Curve(ctx, _phase, inkR);
+ Curve(ctx, 0, inkL);
+
+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.TopLeft, "0\u2009dB");
+ // The floor's level over its line; near the bottom it steps right of the 0° corner label.
+ var fl = NotaGraph.AxisText(OrbitMath.Db(floor) + "\u2009dB");
+ var zero = NotaGraph.AxisText("0°");
+ double flX = fy > h - 4 - zero.Height - fl.Height ? 4 + zero.Width + 8 : 4;
+ if (fy - fl.Height - 1 > fl.Height + 4) ctx.DrawText(fl, new Point(flX, fy - fl.Height - 1));
+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.BottomLeft, "0°");
+ var mid = NotaGraph.AxisText("360°");
+ ctx.DrawText(mid, new Point(X(1) - mid.Width / 2, h - 4 - mid.Height + 1));
+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.BottomRight, NotaNum.F($"{_periodMs * 2:0}\u2009ms"));
+
+ if (_on)
+ {
+ double hx = X(Math.Clamp(_head, 0, 2));
+ ctx.DrawLine(new Pen(NotaPalette.TextTertiary, 1), new Point(hx, 0), new Point(hx, h));
+ NotaGraph.Node(ctx, new Point(hx, Y(_gr)), true, NotaPalette.TealBright);
+ NotaGraph.Node(ctx, new Point(hx, Y(_gl)), true, NotaPalette.AccentBright);
+ }
+
+ void Curve(DrawingContext dc, double off, IBrush ink)
+ {
+ var geo = new StreamGeometry();
+ using (var g = geo.Open())
+ {
+ int n = Math.Max(64, (int)(x1 - x0));
+ for (int i = 0; i <= n; i++)
+ {
+ double p = 2.0 * i / n;
+ double gain = _on ? OrbitMath.Gain(OrbitMath.Lfo(_wave, _shape, p + off, _sh), _amount, _mix) : 1;
+ var pt = new Point(X(p), Y(gain));
+ if (i == 0) g.BeginFigure(pt, false); else g.LineTo(pt);
+ }
+ g.EndFigure(false);
+ }
+ dc.DrawGeometry(null, NotaGraph.SecondaryPen(ink, 1.6), geo);
+ }
+ }
+}
+
+internal sealed class OrbitPanBar : Control
+{
+ private double _pan, _min, _max;
+
+ public OrbitPanBar() { Height = 9; }
+
+ public void Set(double pan, double min, double max)
+ {
+ if (Math.Abs(pan - _pan) < 1e-4 && Math.Abs(min - _min) < 1e-4 && Math.Abs(max - _max) < 1e-4) return;
+ _pan = pan; _min = min; _max = max;
+ InvalidateVisual();
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 8) return;
+ double x0 = 4.5, x1 = w - 4.5, cy = h / 2;
+ double X(double v) => x0 + (Math.Clamp(v, -1, 1) + 1) / 2 * (x1 - x0);
+ ctx.DrawLine(new Pen(NotaPalette.BorderDefault, 1), new Point(0, cy), new Point(w, cy));
+ ctx.DrawLine(new Pen(NotaPalette.BorderStrong, 1), new Point(Math.Round(w / 2) + 0.5, cy - 3.5), new Point(Math.Round(w / 2) + 0.5, cy + 3.5));
+ if (_max > _min)
+ ctx.DrawRectangle(NotaPalette.TrackOff, null, new RoundedRect(new Rect(X(_min), cy - 1.5, Math.Max(1, X(_max) - X(_min)), 3), 1.5));
+ ctx.DrawEllipse(NotaPalette.TextPrimary, new Pen(NotaPalette.SurfaceCard, 2), new Point(X(_pan), cy), 3.5, 3.5);
+ }
+}
+
+internal sealed class OrbitMeter : Control
+{
+ private double _norm;
+ public IBrush Ink { get; set; } = NotaPalette.Accent;
+
+ public OrbitMeter() { Height = 4; }
+
+ public void Set(double norm)
+ {
+ norm = Math.Clamp(norm, 0, 1);
+ if (Math.Abs(norm - _norm) < 1e-4) return;
+ _norm = norm; InvalidateVisual();
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+ var r = new RoundedRect(new Rect(0, 0, w, h), h / 2);
+ ctx.DrawRectangle(NotaPalette.BgSunken, null, r);
+ if (_norm > 0)
+ using (ctx.PushClip(r)) ctx.DrawRectangle(Ink, null, new Rect(0, 0, w * _norm, h));
+ }
+}
diff --git a/src/managed/Nota.App/DeviceCards/Bodies/AutoPanDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/AutoPanDeviceBody.cs
index ed1181d5..52ce063f 100644
--- a/src/managed/Nota.App/DeviceCards/Bodies/AutoPanDeviceBody.cs
+++ b/src/managed/Nota.App/DeviceCards/Bodies/AutoPanDeviceBody.cs
@@ -1,13 +1,20 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Detail · Devices — built-in Nota Auto Pan (device kind 9) body: an LFO island
-// (waveform chips + Rate/Shape) and a MOTION island (Amount/Phase/Mix, Phase reading
-// tremolo↔pan in degrees) beside a live viz island (per-channel gain curves + a
-// moving L—R pan dot). All controls are the device's generic params → automation +
-// persist for free.
+// Detail · Devices — built-in Nota Orbit body (auto-pan / tremolo, device kind 9), a build of
+// the "Nota Orbit" mockup (700 × 260) in the Level / EQ-8 language: an LFO column (waveform,
+// Hz or Sync, the rate as a big readout with its period, Rate and Shape — Glide on S&H), a
+// centre panel with both channels' gain over two cycles, a running head with the gain dots and
+// the floor the depth reaches (drag: Amount up / down, Phase left / right), the stereo position
+// on an L—R line over the swing it covers, a MOTION column (Amount, Phase, Mix, the 0° / 90° /
+// 180° phase snaps and the output meters) with the mode it makes (tremolo, auto-pan, offset
+// pan), and a status strip. The live picture comes from the engine (AutoPan.h scopeRead). Every
+// control is a device param (normalized 0..1), so automation / MIDI learn / presets / A-B /
+// persistence come for free. FullBleed — the shared shell draws the header (name · preset ·
+// badge · bypass).
using System;
+using System.Collections.Generic;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
@@ -20,12 +27,14 @@ namespace Nota.App;
internal sealed class AutoPanDeviceBody : IDeviceBody
{
- // Param indices — must match AutoPan.h.
- private const int Rate = 0, Amount = 1, Waveform = 2, Shape = 3, Phase = 4, Mix = 5;
- private static readonly string[] Waves = { "Sine", "Tri", "Saw", "Sqr", "S&H" };
-
- public double Width => 700; // the almanac device format: 700 × 260; the viz column takes the slack
+ // ── Parameter indices (must match AutoPan.h) ─────────────────────────────
+ private const int Rate = 0, Amount = 1, Waveform = 2, Shape = 3, Phase = 4, Mix = 5, Sync = 6, Division = 7;
+ // Scope layout (AutoPan::S_* / kTele).
+ private const int S_InPeak = 0, S_OutPeakL = 1, S_OutPeakR = 2, S_GainL = 3, S_GainR = 4, S_Pan = 5, S_WinPhase = 6,
+ S_SampleRate = 11, S_Sh0 = 12, S_PanMin = 16, S_PanMax = 17, kTele = 32;
+ public double Width => 700;
+ public bool FullBleed => true;
public string? Subtitle => "PANNER"; // the processing type, shown as the header badge
public Control Build(DeviceCardContext ctx, int index)
@@ -33,100 +42,312 @@ internal sealed class AutoPanDeviceBody : IDeviceBody
var engine = ctx.Engine;
int track = ctx.TrackId, di = index;
float P(int p) => engine.DeviceGetParam(track, di, p);
- void SetP(int p, float v) => engine.DeviceSetParam(track, di, p, v);
void Begin(int p) => engine.BeginAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");
void End(int p) => engine.EndAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");
- static double Exp(double v, double lo, double hi) => lo * Math.Pow(hi / lo, Math.Clamp(v, 0, 1));
+ void Raw(int p, double v) => engine.DeviceSetParam(track, di, p, (float)Math.Clamp(v, 0, 1));
+ // A discrete edit (a click) is one automation gesture, so it records while the transport does.
+ void SetP(int p, double v) { Begin(p); Raw(p, v); End(p); }
+ void Reset(int p) { Begin(p); Raw(p, engine.DeviceParamDefault(track, di, p)); End(p); }
+ void Learn(Control c, int p) => MidiLearn.Bind(c, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
+
+ var readouts = new List<Action>();
+ void RefreshAll() { for (int i = 0; i < readouts.Count; i++) readouts[i](); }
+ var scope = new float[kTele];
+ int scN = 0;
+ double Sc(int i, double dflt = 0) => scN > i ? scope[i] : dflt;
- var viz = new AutoPanViz { VerticalAlignment = VerticalAlignment.Stretch, MinWidth = 200 };
- void SyncViz()
+ // ---- state and units (AutoPan.h) ---------------------------------------------------
+ bool On() => !engine.DeviceBypassed(track, di);
+ bool Synced() => P(Sync) >= 0.5f;
+ int WaveI() => OrbitMath.WaveIndex(P(Waveform));
+ int DivI() => OrbitMath.DivIndex(P(Division));
+ double Bpm() => engine.Bpm > 0 ? engine.Bpm : 120;
+ double RateHz() => Synced() ? Bpm() / 60 / OrbitMath.DivBeats[DivI()] : OrbitMath.FreeHz(P(Rate));
+ double PeriodMs() => 1000 / Math.Max(1e-3, RateHz());
+ double Deg() => P(Phase) * 360;
+ double Floor() => 1 - P(Amount) * P(Mix);
+ string Mode()
{
- int wv = Math.Clamp((int)Math.Round(P(Waveform) * 4), 0, 4);
- viz.Set(wv, P(Amount), P(Shape), P(Phase), engine.DeviceGainReduction(track, di));
+ if (!On()) return "bypass";
+ double d = Deg();
+ return d <= 15 || d >= 345 ? "tremolo" : Math.Abs(d - 180) <= 15 ? "auto-pan" : "offset pan";
}
- ctx.AddDeviceRefresher(SyncViz); // 60 Hz: also advances the live pan dot
- // ---- formatters ----
- static string PctF(double v) => $"{v * 100:0}\u2009%";
- string RateF(double v) => $"{Exp(v, 0.01, 40):0.00}\u2009Hz";
- static string DegF(double v) => $"{v * 360:0}°";
+ static string HzF(double hz) => hz >= 10 ? NotaNum.F($"{hz:0.0}") : NotaNum.F($"{hz:0.00}");
+ static string PctF(double v) => NotaNum.F($"{v * 100:0}\u2009%");
+ static string PanF(double pan) => Math.Abs(pan) < 0.02 ? "C" : (pan < 0 ? "L" : "R") + NotaNum.F($"{Math.Abs(pan) * 100:0}");
+ static string Ms(double ms) => NotaNum.F($"{ms:0}\u2009ms");
+
+ // ---- small builders ---------------------------------------------------------
+ static TextBlock Caps(string t, IBrush? c = null) => new()
+ { Text = t, FontSize = 7, FontWeight = FontWeight.Bold, Foreground = c ?? TextTertiary, LetterSpacing = 0.7, VerticalAlignment = VerticalAlignment.Center };
+ static TextBlock Mono(string t, double fs, IBrush c)
+ { var tb = new TextBlock { Text = t, FontSize = fs, Foreground = c, VerticalAlignment = VerticalAlignment.Center }; tb.BindResource(TextBlock.FontFamilyProperty, "Font.Mono"); return tb; }
+ static T Docked<T>(T c, Dock d) where T : Control { DockPanel.SetDock(c, d); return c; }
+ static T Col<T>(T c, int col) where T : Control { Grid.SetColumn(c, col); return c; }
+ static T GRow<T>(T c, int row) where T : Control { Grid.SetRow(c, row); return c; }
+
+ // Slider row: caps label · track · mono value. `label` is returned so a row can rename itself.
+ Grid Slider(string label, int p, Func<double, string> fmt, string tip, out TextBlock lbl, double labelW = 40, double valueW = 40,
+ bool modulation = false, Func<double, double>? snap = null)
+ {
+ var bar = DeviceCardKit.SliderRow("", () => P(p), v => { Raw(p, snap is null ? v : snap(v)); RefreshAll(); }, () => fmt(P(p)), out var sync,
+ begin: () => Begin(p), end: () => End(p), reset: () => Reset(p), valueWidth: valueW, modulation: modulation);
+ readouts.Add(sync);
+ Learn(bar, p);
+ ToolTip.SetTip(bar, tip);
+ lbl = Caps(label);
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions($"{labelW},*"), VerticalAlignment = VerticalAlignment.Center };
+ g.Children.Add(lbl);
+ g.Children.Add(Col(bar, 1));
+ return g;
+ }
- // ---- gauge-knob cell ----
- Control Cell(string name, int p, Func<double, string> fmt, IBrush? arc = null, double size = 40)
+ Border Island(Control head, Control body, double width = double.NaN)
{
- var value = new TextBlock { Text = fmt(P(p)), FontSize = 9, Foreground = TextPrimary };
- value.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");
- var knob = new Knob(P(p), 1.0) { Accent = true, ArcColor = arc, Default = engine.DeviceParamDefault(track, di, p), Width = size, Height = size };
- knob.ValueChanged += v => { SetP(p, (float)v); value.Text = fmt(v); SyncViz(); };
- knob.GestureBegin += () => Begin(p);
- knob.GestureEnd += () => End(p);
- MidiLearn.Bind(knob, MidiTarget.DeviceParam(track, di, p), name);
- ctx.AddDeviceRefresher(() => { if (!knob.Dragging) { float c = P(p); if (Math.Abs(c - knob.Value) > 1e-3) { knob.Value = c; value.Text = fmt(c); } } });
- return KnobCell(name, knob, value, size + 18);
+ var headBar = new Border
+ {
+ Height = 20, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 0, 0, 1), Padding = new Thickness(8, 0, 3, 0), Child = head,
+ };
+ return new Border
+ {
+ Width = width, Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile,
+ ClipToBounds = true, Child = new DockPanel { LastChildFill = true, Children = { Docked(headBar, Dock.Top), body } },
+ };
}
- static StackPanel KnobRow(params Control[] cs)
+ static Grid HeadRow(Control left, Control right)
{
- var sp = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 2, HorizontalAlignment = HorizontalAlignment.Center };
- foreach (var c in cs) sp.Children.Add(c);
- return sp;
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 6, VerticalAlignment = VerticalAlignment.Center };
+ g.Children.Add(left); g.Children.Add(Col(right, 1));
+ return g;
}
- Border Panel(Control body) => new()
+ // A legend sample: a drawn 8px stroke and its word (never a typed dash).
+ static Control LegendItem(string word, IBrush ink) => new StackPanel
+ {
+ Orientation = Orientation.Horizontal, Spacing = 3, VerticalAlignment = VerticalAlignment.Center,
+ Children = { new Border { Width = 8, Height = 1.5, Background = ink, VerticalAlignment = VerticalAlignment.Center }, Mono(word, 7, ink) },
+ };
+
+ // ======================================================================
+ // LEFT — LFO: waveform · Hz / Sync · the rate · Rate · Shape
+ // ======================================================================
+ var syncSeg = Segments(new[] { "Hz", "Sync" }, () => Synced() ? 1 : 0, i => { SetP(Sync, i); RefreshAll(); }, out var syncSync, fill: true, padX: 0);
+ syncSeg.Width = 76;
+ readouts.Add(syncSync);
+ Learn(syncSeg, Sync);
+ ToolTip.SetTip(syncSeg, "Hz runs the LFO free; Sync takes its rate from the tempo and locks it to the bar while the transport plays");
+
+ var waveSeg = Segments(OrbitMath.Waves, WaveI, i => { SetP(Waveform, i / 4.0); RefreshAll(); }, out var waveSync, fill: true, padX: 0);
+ readouts.Add(waveSync);
+ Learn(waveSeg, Waveform);
+ ToolTip.SetTip(waveSeg, "The LFO shape. S&H draws a random step every cycle; the right channel plays the same steps Phase later");
+
+ var big = Mono("", 26, AccentBright); big.FontWeight = FontWeight.Bold; big.LineHeight = 28;
+ var bigSub = new TextBlock { FontSize = 8, Foreground = TextSecondary };
+ var period = Mono("", 7, TextTertiary); period.Margin = new Thickness(0, 2, 0, 0);
+ readouts.Add(() =>
+ {
+ double hz = RateHz();
+ if (Synced())
+ {
+ big.Text = OrbitMath.DivNames[DivI()];
+ bigSub.Text = NotaNum.F($"note · {Bpm():0.##}\u2009BPM");
+ period.Text = HzF(hz) + "\u2009Hz · " + Ms(PeriodMs());
+ }
+ else
+ {
+ big.Text = HzF(hz);
+ bigSub.Text = "Hz · free";
+ period.Text = "period " + Ms(PeriodMs());
+ }
+ big.Foreground = On() ? AccentBright : NotaPalette.TextAxis;
+ });
+ var bigBlock = new StackPanel { Spacing = 1, VerticalAlignment = VerticalAlignment.Center, Children = { big, bigSub, period } };
+ ToolTip.SetTip(bigBlock, "The LFO rate: in Hz, or the note value it takes from the tempo");
+
+ var rateRow = Slider("RATE", Rate, v => HzF(OrbitMath.FreeHz(v)) + "\u2009Hz", "Rate — the free LFO rate, 0.01 … 40\u2009Hz", out _, 38, 46);
+ var divRow = Slider("RATE", Division, v => OrbitMath.DivNames[OrbitMath.DivIndex(v)],
+ "Rate — the note value of one LFO cycle, 4/1 … 1/32 with dotted (D) and triplet (T) values", out _, 38, 46,
+ snap: v => OrbitMath.DivNorm(OrbitMath.DivIndex(v)));
+ readouts.Add(() => { rateRow.IsVisible = !Synced(); divRow.IsVisible = Synced(); });
+ var shapeRow = Slider("SHAPE", Shape, v => PctF(v), "Shape — sharpens Sine, Tri and Saw toward a square; on S&H it is Glide, the slide from one step to the next", out var shapeLbl, 38, 46);
+ readouts.Add(() => shapeLbl.Text = WaveI() == 4 ? "GLIDE" : "SHAPE");
+
+ var leftBody = new Grid { RowDefinitions = new RowDefinitions("Auto,*,Auto,Auto"), RowSpacing = 6, Margin = new Thickness(8, 6) };
+ leftBody.Children.Add(waveSeg);
+ leftBody.Children.Add(GRow(bigBlock, 1));
+ leftBody.Children.Add(GRow(new Panel { Children = { rateRow, divRow } }, 2));
+ leftBody.Children.Add(GRow(shapeRow, 3));
+ var left = Island(HeadRow(Caps("LFO"), syncSeg), leftBody, 176);
+ DockPanel.SetDock(left, Dock.Left);
+
+ // ======================================================================
+ // CENTRE — GAIN · 2 CYCLES, and the pan line
+ // ======================================================================
+ var waveWord = Mono("", 7, TextTertiary);
+ readouts.Add(() => waveWord.Text = OrbitMath.WaveNames[WaveI()]);
+ var legend = new StackPanel
{
- Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1),
- CornerRadius = NotaRadius.Panel, Padding = new Thickness(9, 8), Child = body,
+ Orientation = Orientation.Horizontal, Spacing = 8, Margin = new Thickness(0, 0, 5, 0),
+ Children = { LegendItem("L", AccentBright), LegendItem("R", NotaPalette.TealBright), waveWord },
};
- static TextBlock Head(string t) => new() { Text = t, FontSize = 9, FontWeight = FontWeight.Bold, Foreground = TextTertiary, Margin = new Thickness(0, 0, 0, 7) };
+ var graph = new OrbitGainView { Value = () => (P(Amount), P(Phase)) };
+ graph.GestureBegin += () => { Begin(Amount); Begin(Phase); };
+ graph.GestureEnd += () => { End(Amount); End(Phase); };
+ graph.Changed += (a, ph) => { Raw(Amount, a); Raw(Phase, ph); RefreshAll(); };
+ graph.ResetRequested += () => { Reset(Amount); Reset(Phase); RefreshAll(); };
+ Learn(graph, Amount);
+ ToolTip.SetTip(graph, "Both channels' gain over two LFO cycles — L brass, R teal, Phase later — with the floor the depth reaches. Drag up / down for Amount, left / right for Phase; double-click resets both.");
+
+ var panBar = new OrbitPanBar { VerticalAlignment = VerticalAlignment.Center };
+ var panTxt = Mono("", 8, TextPrimary); panTxt.TextAlignment = TextAlignment.Right; panTxt.Width = 28;
+ var lTag = Mono("L", 7, AccentBright); lTag.FontWeight = FontWeight.Bold;
+ var rTag = Mono("R", 7, NotaPalette.TealBright); rTag.FontWeight = FontWeight.Bold;
+ var panRow = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto,Auto"), ColumnSpacing = 6, Height = 14, Margin = new Thickness(0, 4, 0, 0) };
+ panRow.Children.Add(lTag);
+ panRow.Children.Add(Col(panBar, 1));
+ panRow.Children.Add(Col(rTag, 2));
+ panRow.Children.Add(Col(panTxt, 3));
+ ToolTip.SetTip(panRow, "Where the sound sits now between left and right, over the swing the LFO covers");
+ var centreBody = new DockPanel { LastChildFill = true, Margin = new Thickness(5), Children = { Docked(panRow, Dock.Bottom), graph } };
+ var centre = Island(HeadRow(Caps("GAIN · 2 CYCLES"), legend), centreBody);
+ centre.Margin = new Thickness(5, 0);
+
+ // ======================================================================
+ // RIGHT — MOTION: Amount · Phase · Mix · phase snaps · output meters
+ // ======================================================================
+ var modeWord = Mono("", 7, TextSecondary);
+ modeWord.Margin = new Thickness(0, 0, 5, 0);
+ readouts.Add(() =>
+ {
+ string m = Mode();
+ modeWord.Text = m;
+ modeWord.Foreground = m == "auto-pan" ? AccentBright : m == "tremolo" ? NotaPalette.TealBright : TextSecondary;
+ });
+ ToolTip.SetTip(modeWord, "What the phase makes: tremolo near 0°, auto-pan near 180°, an offset pan between");
+
+ var amountRow = Slider("AMOUNT", Amount, v => PctF(v), "Amount — the depth: each channel dips to 1 − Amount at the LFO's low point", out _, 44, 36, modulation: true);
+ var phaseRow = Slider("PHASE", Phase, v => NotaNum.F($"{v * 360:0}°"), "Phase — the right LFO against the left: 0° tremolo, 90° a circling pan, 180° auto-pan", out _, 44, 36, modulation: true,
+ snap: v => Math.Round(v * 360) / 360);
+ var mixRow = Slider("MIX", Mix, v => PctF(v), "Mix — the moving signal against the dry one", out _, 44, 36);
- // ---- Waveform chips (live-synced) ----
- var chips = new Border[Waves.Length];
- void SyncWave() { int cur = Math.Clamp((int)Math.Round(P(Waveform) * 4), 0, 4); for (int i = 0; i < chips.Length; i++) { bool on = i == cur; chips[i].Background = on ? Brass : Card2; ((TextBlock)chips[i].Child!).Foreground = on ? OnAccent : TextSecondary; } }
- var waveRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 3 };
- for (int i = 0; i < Waves.Length; i++)
+ Border Snap(string text, double deg)
{
- int vi = i;
- var chip = new Border
+ var tb = Mono(text, 7, TextTertiary); tb.HorizontalAlignment = HorizontalAlignment.Center;
+ var b = new Border
{
- Background = Card2, BorderBrush = BorderStrong, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Control,
- Padding = new Thickness(7, 2), Cursor = new Cursor(StandardCursorType.Hand),
- Child = new TextBlock { Text = Waves[i], FontSize = 9, FontWeight = FontWeight.SemiBold, Foreground = TextSecondary },
+ BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Padding = new Thickness(0, 1),
+ Cursor = new Cursor(StandardCursorType.Hand), Child = tb,
};
- chip.PointerPressed += (_, e) => { e.Handled = true; SetP(Waveform, vi / 4f); SyncWave(); SyncViz(); };
- chips[i] = chip; waveRow.Children.Add(chip);
+ b.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return;
+ SetP(Phase, deg / 360); RefreshAll(); e.Handled = true;
+ };
+ readouts.Add(() =>
+ {
+ bool on = Math.Abs(Math.Round(Deg()) - deg) < 0.5;
+ b.Background = on ? NotaPalette.TrackOff : Brushes.Transparent;
+ tb.Foreground = on ? TextPrimary : TextTertiary;
+ });
+ Learn(b, Phase);
+ ToolTip.SetTip(b, deg == 0 ? "0° — tremolo: both channels together" : deg == 90 ? "90° — a quarter cycle apart: the sound circles" : "180° — auto-pan: one side up while the other is down");
+ return b;
+ }
+ var snaps = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,*"), ColumnSpacing = 1, Margin = new Thickness(44, 0, 0, 0) };
+ snaps.Children.Add(Snap("0°", 0));
+ snaps.Children.Add(Col(Snap("90°", 90), 1));
+ snaps.Children.Add(Col(Snap("180°", 180), 2));
+
+ Control MeterRow(string label, IBrush labelInk, IBrush ink, int peakSlot, int gainSlot)
+ {
+ var m = new OrbitMeter { Ink = ink, VerticalAlignment = VerticalAlignment.Center };
+ var v = Mono("", 8, TextPrimary); v.TextAlignment = TextAlignment.Right; v.Width = 36;
+ readouts.Add(() =>
+ {
+ double pk = Sc(peakSlot, -120);
+ m.Set(On() ? (pk + 60) / 60 : 0);
+ v.Text = On() ? OrbitMath.Db(Sc(gainSlot, 1)) : "0.0";
+ });
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("44,*,Auto"), ColumnSpacing = 0 };
+ g.Children.Add(Caps(label, labelInk));
+ g.Children.Add(Col(m, 1));
+ g.Children.Add(Col(new Border { Margin = new Thickness(6, 0, 0, 0), Child = v }, 2));
+ ToolTip.SetTip(g, "The channel's output peak, −60 … 0\u2009dBFS, and the gain the LFO gives it now, dB");
+ return g;
}
- SyncWave();
- ctx.AddDeviceRefresher(SyncWave);
- MidiLearn.Bind(waveRow, MidiTarget.DeviceParam(track, di, Waveform), engine.DeviceParamName(track, di, Waveform));
+ var meters = new Border
+ {
+ BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, 5, 0, 0),
+ Child = new StackPanel
+ {
+ Spacing = 5, Children =
+ {
+ MeterRow("OUT L", AccentBright, Brass, S_OutPeakL, S_GainL),
+ MeterRow("OUT R", NotaPalette.TealBright, NotaPalette.TealBright, S_OutPeakR, S_GainR),
+ },
+ },
+ };
- // ---- LFO island: waveform + Rate/Shape ----
- var lfoPanel = Panel(new StackPanel { Spacing = 8, VerticalAlignment = VerticalAlignment.Center, Children =
+ var rightBody = new Grid { RowDefinitions = new RowDefinitions("Auto,*,Auto,*,Auto,*,Auto,*,Auto"), Margin = new Thickness(8, 6) };
+ rightBody.Children.Add(amountRow);
+ rightBody.Children.Add(GRow(phaseRow, 2));
+ rightBody.Children.Add(GRow(mixRow, 4));
+ rightBody.Children.Add(GRow(snaps, 6));
+ rightBody.Children.Add(GRow(meters, 8));
+ var right = Island(HeadRow(Caps("MOTION"), modeWord), rightBody, 176);
+ DockPanel.SetDock(right, Dock.Right);
+
+ // ======================================================================
+ // Status strip
+ // ======================================================================
+ var statusLeft = new TextBlock { FontSize = 8, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
+ var statusRight = Mono("", 8, TextSecondary);
+ readouts.Add(() =>
{
- Head("LFO"),
- waveRow,
- KnobRow(Cell("Rate", Rate, RateF), Cell("Shape", Shape, PctF, Teal)),
- } });
-
- // ---- MOTION island: Amount/Phase/Mix (Phase caption tremolo↔pan) ----
- var phaseCap = new TextBlock { FontSize = 8, Foreground = TextTertiary, HorizontalAlignment = HorizontalAlignment.Center };
- void SyncPhaseCap() { float d = P(Phase); phaseCap.Text = d < 0.03f ? "tremolo" : d > 0.47f && d < 0.53f ? "auto-pan" : "offset"; }
- SyncPhaseCap();
- ctx.AddDeviceRefresher(SyncPhaseCap);
- var motionPanel = Panel(new StackPanel { Spacing = 6, VerticalAlignment = VerticalAlignment.Center, Children =
+ string m = Mode();
+ double hz = RateHz();
+ bool warn = false;
+ string foot;
+ if (!On()) foot = "Panner bypassed: the signal passes unchanged";
+ else if (P(Amount) < 0.01f || P(Mix) < 0.01f) { foot = "Amount or Mix at zero: nothing moves"; warn = true; }
+ else if (hz > 8) { foot = "Above 8\u2009Hz the movement reads as a flutter, not as panning"; warn = true; }
+ else if (m == "tremolo") foot = "Phase 0°: L and R move together, the level dips to " + OrbitMath.Db(Floor()) + "\u2009dB";
+ else if (m == "auto-pan")
+ {
+ double mn = Sc(S_PanMin), mx = Sc(S_PanMax);
+ foot = "Swing " + (mn < -0.02 ? PanF(mn) : "C") + " → " + (mx > 0.02 ? PanF(mx) : "C") + " · period " + Ms(PeriodMs());
+ }
+ else foot = NotaNum.F($"Phase {Deg():0}°: the channels are offset, the pan moves unevenly");
+ statusLeft.Text = foot;
+ statusLeft.Foreground = warn ? AccentBright : TextSecondary;
+ double sr = Sc(S_SampleRate);
+ statusRight.Text = (sr > 0 ? NotaNum.F($"{sr / 1000:0.#}\u2009kHz · ") : "") + NotaNum.F($"{Bpm():0.##}\u2009BPM · ") + (Synced() ? "retrig bar" : "free run");
+ });
+ var statusGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 8 };
+ statusGrid.Children.Add(statusLeft);
+ statusGrid.Children.Add(Col(statusRight, 1));
+ var status = new Border { Height = 18, Background = Sunken, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(8, 0), Child = statusGrid };
+ DockPanel.SetDock(status, Dock.Bottom);
+
+ // ---- assemble ---------------------------------------------------------------
+ var bodyRow = new DockPanel { LastChildFill = true, Margin = new Thickness(5), Children = { left, right, centre } };
+ var root = new DockPanel { LastChildFill = true, Background = NotaPalette.SurfaceInset, Children = { status, bodyRow } };
+
+ void Refresh()
{
- Head("MOTION"),
- KnobRow(Cell("Amount", Amount, PctF, Teal), Cell("Phase", Phase, DegF, Teal), Cell("Mix", Mix, PctF)),
- phaseCap,
- } });
-
- // ---- viz island ----
- var vizPanel = Panel(viz);
- vizPanel.VerticalAlignment = VerticalAlignment.Stretch;
-
- SyncViz();
-
- var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*"), ColumnSpacing = 6 };
- grid.Children.Add(lfoPanel);
- Grid.SetColumn(motionPanel, 1); grid.Children.Add(motionPanel);
- Grid.SetColumn(vizPanel, 2); grid.Children.Add(vizPanel);
- return grid;
+ scN = engine.DeviceScope(track, di, scope, kTele);
+ bool on = On();
+ double gl = Sc(S_GainL, 1), gr = Sc(S_GainR, 1);
+ graph.Set(WaveI(), P(Shape), P(Amount), P(Phase), P(Mix), Sc(S_WinPhase), gl, gr,
+ scN > S_Sh0 + 3 ? scope.AsSpan(S_Sh0, 4) : ReadOnlySpan<float>.Empty, PeriodMs(), on);
+ double pan = on ? Sc(S_Pan) : 0;
+ panBar.Set(pan, on ? Sc(S_PanMin) : 0, on ? Sc(S_PanMax) : 0);
+ panTxt.Text = PanF(pan);
+ RefreshAll();
+ }
+ ctx.AddDeviceRefresher(Refresh);
+ Refresh();
+ return root;
}
}
diff --git a/src/managed/Nota.App/DeviceCards/Bodies/ForgeDeviceBody.cs b/src/managed/Nota.App/DeviceCards/Bodies/ForgeDeviceBody.cs
index 55fa8471..1377ee13 100644
--- a/src/managed/Nota.App/DeviceCards/Bodies/ForgeDeviceBody.cs
+++ b/src/managed/Nota.App/DeviceCards/Bodies/ForgeDeviceBody.cs
@@ -1,17 +1,25 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Detail · Devices — built-in Nota Forge (device kind 17) body, built to mockup 3m: a
-// multi-stage saturator with every stage on screen. A LIVE strip (Amount / Tone / Wet +
-// four drawn routing choices) over a body of three columns: a STAGES chain (each stage a
-// row with an algorithm, drive, output trim and teal self-feedback that dims when off), a
-// TRANSFER curve + HARMONICS bar chart in the middle, and a SHAPE (Tone / Bias / Width) +
-// teal MODULATION (LFO→Drive · Env→Tone · rate/sync) rail on the right.
+// Detail · Devices — built-in Nota Forge body (multi-stage saturator, device kind 17), a build of
+// the "Nota Forge" mockup (700 × 260) in the EQ-8 language: on the left the routing (Serial /
+// Parallel / M/S / Multi) over the three stages — each with its on dot, its type and the role it
+// plays in the routing, a draggable output trim (drag the dB up / down), Drive and a teal
+// Feedback; a click selects the stage. In the centre Amount / Wet / Out over the transfer curve
+// (the whole device — the selected stage in M/S and Multi — every stage alone faintly, the
+// LFO-modulated curve dashed teal, a node where the input sits; drag it for Amount) and the
+// harmonics of a −6 dB sine with THD. On the right the selected stage's shape (type, Bias, Tone,
+// Width), the modulation (LFO → Drive, Env → Tone, Rate, Sync) and Oversampling; a status strip
+// under it all. Curves, harmonics and meters come from the engine (Forge.h scopeRead). Every
+// control is a device param (normalized 0..1), so automation / MIDI learn / presets / A-B /
+// persistence come for free. Double-click resets a control.
+// FullBleed — the shared shell draws the header (name · preset · badge · bypass).
using System;
using System.Collections.Generic;
using Avalonia;
using Avalonia.Controls;
+using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
@@ -22,249 +30,384 @@ namespace Nota.App;
internal sealed class ForgeDeviceBody : IDeviceBody
{
+ // ── Parameter indices (must match Forge.h) ───────────────────────────────
private const int Amount = 0, Tone = 1, Wet = 2, Output = 3, Bias = 4, WidthP = 5, Routing = 6,
- LfoDrive = 7, EnvTone = 8, LfoRate = 9, LfoSync = 10, S1Type = 11, S1On = 15, OS = 26;
+ LfoDrive = 7, EnvTone = 8, LfoRate = 9, LfoSync = 10, S1Type = 11, OS = 26, S1Bias = 27;
+ private static int TypeP(int s) => S1Type + s * 5;
+ private static int DriveP(int s) => S1Type + 1 + s * 5;
+ private static int OutP(int s) => S1Type + 2 + s * 5;
+ private static int FbP(int s) => S1Type + 3 + s * 5;
+ private static int OnP(int s) => S1Type + 4 + s * 5;
+ private static int BiasP(int s) => S1Bias + s * 3;
+ private static int ToneP(int s) => S1Bias + 1 + s * 3;
+ private static int WidthSP(int s) => S1Bias + 2 + s * 3;
- private static readonly string[] RouteNames = { "Serial", "Parallel", "Mid/Side", "Multiband" };
+ private static readonly string[] RouteNames = { "Serial", "Parallel", "M/S", "Multi" };
private static readonly string[] OsNames = { "Off", "2×", "4×", "8×" };
- private static readonly string[] DivNames = { "2/1", "1/1", "1/2", "1/4", "1/8", "1/16", "1/32", "1/64" };
-
- private static readonly IBrush HdrBg = NotaPalette.SurfaceCard;
- private static readonly IBrush RailBg = NotaPalette.SurfaceInset;
- private static readonly IBrush Border2 = NotaPalette.BorderDefault;
- private static readonly IBrush Inset = NotaPalette.BgSunken;
- private static readonly IBrush Amber = NotaPalette.Accent;
- private static readonly IBrush AmberLit = NotaPalette.AccentBright;
- private static readonly IBrush AmberSubtle = NotaPalette.Wash(NotaPalette.Accent, 0x28);
- private static readonly IBrush TealC = NotaPalette.Teal;
- private static readonly IBrush TealSubtle = NotaPalette.Wash(NotaPalette.Teal, 0x24);
- private static readonly IBrush TxtC = NotaPalette.TextPrimary;
- private static readonly IBrush MutedC = NotaPalette.TextTertiary;
- private static readonly IBrush LabelC = NotaPalette.TextSecondary;
- private static readonly IBrush Dim = NotaPalette.BorderStrong;
- private static readonly IBrush HandleC = NotaPalette.TextSecondary;
public double Width => 700;
-
- public string? Subtitle => "SATURATION"; // the processing type, shown as the header badge
public bool FullBleed => true;
+ public string? Subtitle => "SATURATION";
public Control Build(DeviceCardContext ctx, int index)
{
var engine = ctx.Engine;
int track = ctx.TrackId, di = index;
- float P(int p) => engine.DeviceGetParam(track, di, p);
- void SetP(int p, float v) => engine.DeviceSetParam(track, di, p, v);
+ int pc = engine.DeviceParamCount(track, di);
+ float P(int p) => p < pc ? engine.DeviceGetParam(track, di, p) : 0.5f;
void Begin(int p) => engine.BeginAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");
void End(int p) => engine.EndAutomationWrite(track, AutomationTarget.DeviceParam, di, p, "");
+ void Raw(int p, double v) { if (p < pc) engine.DeviceSetParam(track, di, p, (float)Math.Clamp(v, 0, 1)); }
+ // A discrete edit (a click) is one automation gesture, so it records while the transport does.
+ void SetP(int p, float v) { Begin(p); Raw(p, v); End(p); }
+ void Reset(int p) { Begin(p); Raw(p, engine.DeviceParamDefault(track, di, p)); End(p); }
+ double Def(int p) => engine.DeviceParamDefault(track, di, p);
+ bool On(int p) => P(p) >= 0.5f;
+ void Learn(Control c, int p) => MidiLearn.Bind(c, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
var readouts = new List<Action>();
- Control Cap(string t, IBrush? c = null, double w = 0) { var tb = new TextBlock { Text = t, FontSize = 8, FontWeight = FontWeight.Bold, Foreground = c ?? MutedC, VerticalAlignment = VerticalAlignment.Center }; if (w > 0) tb.Width = w; return tb; }
+ // MIDI learn on a control whose param follows the selected stage: rebinds when it moves.
+ void LearnFollow(Control c, Func<int> param)
+ {
+ int bound = param();
+ Learn(c, bound);
+ readouts.Add(() => { int p = param(); if (p != bound) { bound = p; Learn(c, p); } });
+ }
+ void RefreshAll() { for (int i = 0; i < readouts.Count; i++) readouts[i](); }
+ var scope = new float[ForgeMath.kScope];
+ int scN = 0;
+ double Sc(int i) => scN > i ? scope[i] : 0;
- // ---- viz ----
- var transfer = new ForgeTransferCurve(engine, track, di) { VerticalAlignment = VerticalAlignment.Stretch };
- var harm = new ForgeHarmonics(engine, track, di) { Height = 52 };
- void SyncViz() { transfer.Sync(); harm.Sync(); }
- ctx.AddDeviceRefresher(transfer.Tick);
+ int sel = 0; // the stage the SHAPE panel edits (UI state)
+ Action refreshNow = () => { };
+ void Refresh() => refreshNow();
+ int RouteI() => Math.Clamp((int)Math.Round(P(Routing) * 3), 0, 3);
+ int TypeI(int s) => Math.Clamp((int)Math.Round(P(TypeP(s)) * 5), 0, 5);
+ bool Single() => RouteI() >= 2;
+ bool Active() => !engine.DeviceBypassed(track, di);
+ int OsI() => Math.Clamp((int)Math.Round(P(OS) * 3), 0, 3);
- // ---- formatters ----
- static string AmtF(double v) => $"+{v * 30:0.0}\u2009dB";
- static string ToneF(double v) => $"{(v - 0.5) * 24:+0.0;−0.0;0.0}\u2009dB";
- static string WetF(double v) => $"{v * 100:0}\u2009%";
- static string BiasF(double v) => $"{(v - 0.5) * 200:+0;−0;0}\u2009%";
- static string WidthF(double v) => $"{v * 200:0}\u2009%";
- static string OutF(double v) => $"{(v - 0.5) * 24:+0.0;−0.0;0.0}";
- static string PctF(double v) => $"{v * 100:0}\u2009%";
- static string FbF(double v) => v < 0.005 ? "—" : $"{v * 100:0}\u2009%";
- string RateF(double v) => P(LfoSync) >= 0.5f ? DivNames[Math.Clamp((int)Math.Round(v * 7), 0, 7)] + " sync" : $"{0.05 * Math.Pow(20 / 0.05, v):0.0}\u2009Hz";
+ // ---- units (Forge.h) ----------------------------------------------------------------
+ static string Sgn(double v) => NotaNum.F($"{v:+0.0;−0.0;0.0}");
+ static string SgnI(double v) => NotaNum.F($"{v:+0;−0;0}");
+ static string AmtF(double v) => Sgn(v * 30) + " dB";
+ static string OutF(double v) => Sgn((v - 0.5) * 48) + " dB";
+ static string TrimF(double v) => Sgn((v - 0.5) * 24) + " dB";
+ static string PctF(double v) => NotaNum.F($"{v * 100:0} %");
+ static string FbF(double v) => v < 0.005 ? "—" : PctF(v);
+ static string BiasF(double v) => SgnI((v - 0.5) * 200) + " %";
+ static string ToneF(double v) => Sgn((v - 0.5) * 24) + " dB";
+ static string WidthF(double v) => NotaNum.F($"{v * 200:0} %");
+ string RateF(double v) => On(LfoSync) ? ForgeMath.DivNames[Math.Clamp((int)Math.Round(v * 7), 0, 7)] + " sync"
+ : NotaNum.F($"{0.05 * Math.Pow(400, v):0.00} Hz");
- // ---- horizontal slider (label | slot | value) ----
- Control HRow(int p, string label, Func<double, string> fmt, double labW, double valW, bool teal = false, bool bipolar = false)
+ // ---- small builders -----------------------------------------------------------------
+ static TextBlock Caps(string t, IBrush? c = null, double fs = 7) => new()
+ { Text = t, FontSize = fs, FontWeight = FontWeight.Bold, Foreground = c ?? TextTertiary, LetterSpacing = 0.8, VerticalAlignment = VerticalAlignment.Center };
+ static TextBlock Mono(string t, double fs, IBrush c)
+ { var tb = new TextBlock { Text = t, FontSize = fs, Foreground = c, VerticalAlignment = VerticalAlignment.Center }; tb.BindResource(TextBlock.FontFamilyProperty, "Font.Mono"); return tb; }
+ static T Docked<T>(T c, Dock d) where T : Control { DockPanel.SetDock(c, d); return c; }
+ static T Col<T>(T c, int col) where T : Control { Grid.SetColumn(c, col); return c; }
+ static T GRow<T>(T c, int row) where T : Control { Grid.SetRow(c, row); return c; }
+ static Border Island(Control child, double width = double.NaN) => new()
{
- var accent = teal ? TealC : Amber;
- var fill = new Border { Height = 3, Background = accent, CornerRadius = NotaRadius.Clip, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center };
- var track2 = new Border { Height = 3, Background = Inset, CornerRadius = NotaRadius.Clip, VerticalAlignment = VerticalAlignment.Center };
- var center = bipolar ? new Border { Width = 1, Background = Dim, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Stretch, Margin = new Thickness(0, 1) } : null;
- var handle = new Border { Width = 8, Height = 9, Background = HandleC, CornerRadius = NotaRadius.Clip, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center };
- var slot = new Panel { Height = 11, MinWidth = 30 }; slot.Children.Add(track2); if (center != null) slot.Children.Add(center); slot.Children.Add(fill); slot.Children.Add(handle);
- var val = new TextBlock { Text = fmt(P(p)), FontSize = 9, Foreground = TxtC, VerticalAlignment = VerticalAlignment.Center }; val.BindResource(TextBlock.FontFamilyProperty, "Font.Mono"); if (valW > 0) { val.Width = valW; val.TextAlignment = TextAlignment.Right; }
- bool drag = false;
- void Upd() { double v = P(p), W = slot.Bounds.Width, hx = v * W; handle.Margin = new Thickness(Math.Clamp(hx - 4, 0, Math.Max(0, W - 8)), 0, 0, 0); if (bipolar) { double c = W * 0.5, a = Math.Min(c, hx), b = Math.Max(c, hx); fill.Margin = new Thickness(a, 0, 0, 0); fill.Width = Math.Max(0, b - a); } else fill.Width = hx; val.Text = fmt(v); }
- void SetX(double x) { SetP(p, (float)Math.Clamp(x / Math.Max(1, slot.Bounds.Width), 0, 1)); SyncViz(); Upd(); }
- slot.PointerPressed += (_, e) => { drag = true; e.Pointer.Capture(slot); Begin(p); SetX(e.GetPosition(slot).X); };
- slot.PointerMoved += (_, e) => { if (drag) SetX(e.GetPosition(slot).X); };
- slot.PointerReleased += (_, e) => { if (drag) { drag = false; e.Pointer.Capture(null); End(p); } };
- MidiLearn.Bind(slot, MidiTarget.DeviceParam(track, di, p), label);
- readouts.Add(() => { if (!drag) Upd(); });
- var g = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = 5, VerticalAlignment = VerticalAlignment.Center };
- if (labW > 0) { var l = Cap(label, teal ? TealC : MutedC, labW); g.Children.Add(l); }
- Grid.SetColumn(slot, 1); g.Children.Add(slot); Grid.SetColumn(val, 2); g.Children.Add(val);
- return g;
- }
+ Width = width, Background = Card2, BorderBrush = BorderDef, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile,
+ ClipToBounds = true, Child = child,
+ };
+ static Border Bar(Control child, Thickness pad) => new()
+ { Height = 20, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 0, 0, 1), Padding = pad, Child = child };
- // ---- routing icon chips ----
- Control RoutingChips()
+ // Slider row, as the mockup draws it inside the card: caps 7 label · 3px track · mono 8 value
+ // (brass-light once moved off its default). The param is chosen at paint time — the selected
+ // stage's, or a fixed one. Double-click resets.
+ Control Slider(string label, Func<int> param, Func<double, string> fmt, string tip, double labelW, double valueW,
+ bool teal = false, bool bipolar = false)
{
- var cells = new Border[4]; var icons = new RoutingIcon[4]; var texts = new TextBlock[4];
- void Sync() { int cur = Math.Clamp((int)Math.Round(P(Routing) * 3), 0, 3); for (int i = 0; i < 4; i++) { bool on = i == cur; cells[i].Background = on ? Amber : Brushes.Transparent; cells[i].BorderBrush = on ? Amber : Dim; icons[i].Color = on ? NotaPalette.TextOnAccent : LabelC; texts[i].Foreground = on ? NotaPalette.TextOnAccent : LabelC; } }
- var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 2, VerticalAlignment = VerticalAlignment.Center };
- for (int i = 0; i < 4; i++) { int iv = i; var ic = new RoutingIcon(i) { Width = 18, Height = 13, VerticalAlignment = VerticalAlignment.Center }; var tb = new TextBlock { Text = RouteNames[i], FontSize = 9, Foreground = LabelC, VerticalAlignment = VerticalAlignment.Center }; var c = new Border { Height = 22, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Control, Padding = new Thickness(5, 0), Cursor = new Cursor(StandardCursorType.Hand), Child = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, VerticalAlignment = VerticalAlignment.Center, Children = { ic, tb } } }; c.PointerPressed += (_, e) => { e.Handled = true; SetP(Routing, iv / 3f); SyncViz(); Sync(); }; cells[i] = c; icons[i] = ic; texts[i] = tb; row.Children.Add(c); }
- readouts.Add(Sync);
- MidiLearn.Bind(row, MidiTarget.DeviceParam(track, di, Routing), engine.DeviceParamName(track, di, Routing));
- return row;
+ var lbl = Caps(label, teal ? Teal : TextTertiary);
+ lbl.TextTrimming = TextTrimming.None;
+ var track = new SliderTrack { Bipolar = bipolar, Modulation = teal, Reset = () => { Reset(param()); Refresh(); }, VerticalAlignment = VerticalAlignment.Center };
+ track.Changed += v => { Raw(param(), v); Refresh(); };
+ track.GestureBegin += () => Begin(param());
+ track.GestureEnd += () => End(param());
+ var val = Mono("", 8, TextPrimary);
+ val.TextAlignment = TextAlignment.Right;
+ val.HorizontalAlignment = HorizontalAlignment.Right;
+ static ColumnDefinition Fixed(double w) => new(w > 0 ? new GridLength(w) : GridLength.Auto);
+ var g = new Grid { ColumnSpacing = 5, VerticalAlignment = VerticalAlignment.Center, Background = Brushes.Transparent };
+ g.ColumnDefinitions.Add(Fixed(labelW));
+ g.ColumnDefinitions.Add(new ColumnDefinition(1, GridUnitType.Star));
+ g.ColumnDefinitions.Add(Fixed(valueW));
+ g.Children.Add(lbl); g.Children.Add(Col(track, 1)); g.Children.Add(Col(val, 2));
+ readouts.Add(() =>
+ {
+ int p = param();
+ if (!track.Dragging) track.Norm = P(p);
+ val.Text = fmt(P(p));
+ val.Foreground = Math.Abs(P(p) - Def(p)) > 0.003 ? AccentBright : TextPrimary;
+ });
+ LearnFollow(g, param);
+ ToolTip.SetTip(g, tip);
+ return g;
}
- // ---- oversampling quality selector (Off / 2× / 4× / 8×) ----
- Control OsChips()
- {
- var seg = DeviceCardKit.Segments(OsNames, () => Math.Clamp((int)Math.Round(P(OS) * 3), 0, 3), i => { Begin(OS); SetP(OS, i / 3f); End(OS); }, out var sync, minSegWidth: 30);
- readouts.Add(sync);
- MidiLearn.Bind(seg, MidiTarget.DeviceParam(track, di, OS), engine.DeviceParamName(track, di, OS));
- return seg;
- }
+ // ======================================================================
+ // LEFT — routing + the three stages
+ // ======================================================================
+ var routeSeg = Segments(RouteNames, RouteI, i => { SetP(Routing, i / 3f); Refresh(); }, out var routeSync, fill: true, padX: 2);
+ readouts.Add(routeSync);
+ Learn(routeSeg, Routing);
+ ToolTip.SetTip(routeSeg, "Routing — Serial: 1 → 2 → 3. Parallel: all three from the same input, averaged. M/S: stage 1 drives the Mid, stage 2 the Side, stage 3 the recombined stereo. Multi: stage 1 the lows (< 180 Hz), 2 the mids, 3 the highs (> 2.4 kHz)");
- // ---- one stage row ----
- Control StageRow(int s)
+ Control StageTile(int s)
{
- int baseP = S1Type + s * 5, typeP = baseP, driveP = baseP + 1, outP = baseP + 2, fbP = baseP + 3, onP = baseP + 4;
- var dot = new Border { Width = 6, Height = 6, CornerRadius = NotaRadius.Badge, VerticalAlignment = VerticalAlignment.Center, Cursor = new Cursor(StandardCursorType.Hand) };
- var idx = new TextBlock { Text = (s + 1).ToString(), FontSize = 9, Foreground = MutedC, VerticalAlignment = VerticalAlignment.Center }; idx.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");
- var name = new TextBlock { FontSize = 9, FontWeight = FontWeight.SemiBold, VerticalAlignment = VerticalAlignment.Center, Cursor = new Cursor(StandardCursorType.Hand) };
- var outVal = new TextBlock { FontSize = 9, Foreground = LabelC, VerticalAlignment = VerticalAlignment.Center, TextAlignment = TextAlignment.Right, Width = 34 }; outVal.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");
- var fbVal = new TextBlock { FontSize = 8, Foreground = LabelC, VerticalAlignment = VerticalAlignment.Center, TextAlignment = TextAlignment.Right, Width = 26 }; fbVal.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");
-
- var head = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center, Children = { dot, idx, name } };
- var headRow = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
- headRow.Children.Add(head); Grid.SetColumn(outVal, 1); headRow.Children.Add(outVal);
-
- var line2 = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Children = {
- Cap("DRIVE", MutedC, 30),
- new Border { Child = HRow(driveP, "", PctF, 0, 0), Width = 58, VerticalAlignment = VerticalAlignment.Center },
- Cap("FEEDBACK", TealC, 42),
- new Border { Child = HRow(fbP, "", FbF, 0, 0, teal: true), Width = 32, VerticalAlignment = VerticalAlignment.Center },
- fbVal } };
+ var dot = new Border { Width = 7, Height = 7, CornerRadius = NotaRadius.Pill, VerticalAlignment = VerticalAlignment.Center, Cursor = new Cursor(StandardCursorType.Hand) };
+ var num = Mono((s + 1).ToString(), 8, TextSecondary); num.FontWeight = FontWeight.Bold;
+ var name = new TextBlock { FontSize = 9, FontWeight = FontWeight.SemiBold, VerticalAlignment = VerticalAlignment.Center };
+ var role = new TextBlock { FontSize = 7, FontWeight = FontWeight.Bold, LetterSpacing = 0.5, VerticalAlignment = VerticalAlignment.Center };
+ var outTxt = Mono("", 8, TextSecondary);
+ var outBox = new Border
+ {
+ Background = Sunken, CornerRadius = NotaRadius.Clip, Padding = new Thickness(2, 0), VerticalAlignment = VerticalAlignment.Center,
+ Cursor = new Cursor(StandardCursorType.SizeNorthSouth), Child = outTxt,
+ };
+ var head = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto,*,Auto"), ColumnSpacing = 5 };
+ head.Children.Add(dot); head.Children.Add(Col(num, 1)); head.Children.Add(Col(name, 2)); head.Children.Add(Col(role, 3)); head.Children.Add(Col(outBox, 4));
- var border = new Border { BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile, Padding = new Thickness(7, 4), Background = RailBg, BorderBrush = Border2,
- Child = new StackPanel { Spacing = 3, VerticalAlignment = VerticalAlignment.Center, Children = { headRow, line2 } } };
+ bool Lit() => On(OnP(s)) && Active();
+ var drive = Slider("DRIVE", () => DriveP(s), PctF, $"Stage {s + 1} drive — how hard the stage is pushed (gain 1 … ×21, the level made up)", 42, 32);
+ var fb = Slider("FEEDBACK", () => FbP(s), FbF, $"Stage {s + 1} feedback — its output back into its input (0 … 85 %): thicker, and on the edge of ringing with Fold / Fuzz", 44, 30, teal: true);
+ var rows = new StackPanel { Spacing = 1, Children = { drive, fb } };
+ var body = new DockPanel { Children = { Docked(head, Dock.Top), new Border { VerticalAlignment = VerticalAlignment.Bottom, Child = rows } } };
+ var tile = new Border
+ {
+ BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Padding = new Thickness(6, 3), Background = Sunken,
+ Cursor = new Cursor(StandardCursorType.Hand), Child = body,
+ };
- // out trim: drag on the out value (vertical) — quick, keeps line1 compact.
- bool od = false; double oy = 0;
- outVal.Cursor = new Cursor(StandardCursorType.SizeNorthSouth);
- outVal.PointerPressed += (_, e) => { od = true; oy = e.GetPosition(outVal).Y; Begin(outP); e.Pointer.Capture(outVal); e.Handled = true; };
- outVal.PointerMoved += (_, e) => { if (od) { double dy = oy - e.GetPosition(outVal).Y; oy = e.GetPosition(outVal).Y; SetP(outP, (float)Math.Clamp(P(outP) + dy * 0.01, 0, 1)); SyncViz(); outVal.Text = OutF(P(outP)) + "\u2009dB"; } };
- outVal.PointerReleased += (_, e) => { if (od) { od = false; End(outP); e.Pointer.Capture(null); } };
+ tile.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(tile).Properties.IsLeftButtonPressed) return;
+ if (sel != s) { sel = s; Refresh(); }
+ };
+ dot.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(dot).Properties.IsLeftButtonPressed) return;
+ SetP(OnP(s), On(OnP(s)) ? 0f : 1f); Refresh(); e.Handled = true;
+ };
+ Learn(dot, OnP(s));
+ ToolTip.SetTip(dot, $"Stage {s + 1} on / off");
- dot.PointerPressed += (_, e) => { e.Handled = true; Begin(onP); SetP(onP, P(onP) >= 0.5f ? 0f : 1f); End(onP); SyncViz(); };
- name.PointerPressed += (_, e) => { e.Handled = true; int t = (int)Math.Round(P(typeP) * (ForgeMath.Algos - 1)); t = (t + 1) % ForgeMath.Algos; SetP(typeP, t / (float)(ForgeMath.Algos - 1)); SyncViz(); };
+ // Output trim: drag the dB up / down; double-click resets.
+ bool od = false; double oy = 0, ov = 0;
+ outBox.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(outBox).Properties.IsLeftButtonPressed) return;
+ sel = s;
+ if (e.ClickCount == 2) { Reset(OutP(s)); Refresh(); e.Handled = true; return; }
+ od = true; oy = e.GetPosition(outBox).Y; ov = P(OutP(s)); Begin(OutP(s)); e.Pointer.Capture(outBox); e.Handled = true; Refresh();
+ };
+ outBox.PointerMoved += (_, e) =>
+ {
+ if (!od) return;
+ Raw(OutP(s), ov + (oy - e.GetPosition(outBox).Y) / 120.0); Refresh();
+ };
+ outBox.PointerReleased += (_, e) => { if (od) { od = false; End(OutP(s)); e.Pointer.Capture(null); } };
+ Learn(outBox, OutP(s));
+ ToolTip.SetTip(outBox, $"Stage {s + 1} output, −12 … +12 dB — drag up / down, double-click resets");
readouts.Add(() =>
{
- bool on = P(onP) >= 0.5f;
- dot.Background = on ? Amber : Dim;
- Inactive.Set(border, !on, interactive: true);
- int t = Math.Clamp((int)Math.Round(P(typeP) * (ForgeMath.Algos - 1)), 0, ForgeMath.Algos - 1);
- name.Text = ForgeMath.AlgoNames[t]; name.Foreground = on ? TxtC : MutedC;
- outVal.Text = OutF(P(outP)) + "\u2009dB";
- fbVal.Text = FbF(P(fbP));
+ bool lit = Lit(), isSel = s == sel;
+ dot.Background = lit ? Brass : BorderStrong;
+ num.Foreground = lit ? TextSecondary : TextDisabled;
+ name.Text = ForgeMath.AlgoNames[TypeI(s)];
+ name.Foreground = lit ? (isSel ? AccentBright : TextPrimary) : TextTertiary;
+ role.Text = ForgeMath.Role(RouteI(), s);
+ role.Foreground = lit ? NotaPalette.TealBright : TextDisabled;
+ double trim = (P(OutP(s)) - 0.5) * 24;
+ outTxt.Text = TrimF(P(OutP(s)));
+ outTxt.Foreground = Math.Abs(trim) > 0.05 ? AccentBright : lit ? TextSecondary : TextDisabled;
+ tile.BorderBrush = isSel ? Brass : NotaPalette.GraphBorder;
+ tile.Background = isSel ? Raised : Sunken;
+ rows.Opacity = lit ? 1 : 0.45;
});
- // Stage algorithm (click the name to cycle) and on/off dot are discrete params too.
- MidiLearn.Bind(name, MidiTarget.DeviceParam(track, di, typeP), engine.DeviceParamName(track, di, typeP));
- MidiLearn.Bind(dot, MidiTarget.DeviceParam(track, di, onP), engine.DeviceParamName(track, di, onP));
- return border;
+ return tile;
}
+ var stageGrid = new Grid { RowDefinitions = new RowDefinitions("*,*,*"), RowSpacing = 4, Margin = new Thickness(4) };
+ for (int s = 0; s < 3; s++) stageGrid.Children.Add(GRow(StageTile(s), s));
+ var left = Island(new DockPanel { Children = { Docked(Bar(routeSeg, new Thickness(3, 0)), Dock.Top), stageGrid } }, 186);
+ DockPanel.SetDock(left, Dock.Left);
- Control MiniToggle(int p, string label)
- {
- var host = Switch(label, () => P(p) >= 0.5f, () => SetP(p, P(p) >= 0.5f ? 0f : 1f), out var sync);
- readouts.Add(sync);
- MidiLearn.Bind(host, MidiTarget.DeviceParam(track, di, p), engine.DeviceParamName(track, di, p));
- return host;
- }
+ // ======================================================================
+ // CENTRE — Amount / Wet / Out over the transfer curve and the harmonics
+ // ======================================================================
+ var macros = new Grid { ColumnDefinitions = new ColumnDefinitions("13*,10*,10*"), ColumnSpacing = 8, VerticalAlignment = VerticalAlignment.Center };
+ macros.Children.Add(Slider("AMOUNT", () => Amount, AmtF, "Amount — 0 … +30 dB into the stages. Drag the curve up / down for the same", 0, 0));
+ macros.Children.Add(Col(Slider("WET", () => Wet, PctF, "Wet — the forged signal against the dry one", 0, 0), 1));
+ macros.Children.Add(Col(Slider("OUT", () => Output, OutF, "Output, −24 … +24 dB", 0, 0, bipolar: true), 2));
- // ================= LIVE strip =================
- var live = new Border { Height = 34, Background = HdrBg, BorderBrush = Border2, BorderThickness = new Thickness(0, 0, 0, 1),
- Child = new DockPanel { LastChildFill = false, Margin = new Thickness(9, 0), Children = {
- WithDock(new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10, VerticalAlignment = VerticalAlignment.Center, Children = {
- Cap("LIVE"),
- new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Width = 150, Children = { Cap("AMOUNT", MutedC, 46), new Border { Child = HRow(Amount, "", AmtF, 0, 52), Width = 100 } } },
- new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Width = 118, Children = { Cap("TONE", MutedC, 30), new Border { Child = HRow(Tone, "", ToneF, 0, 46, bipolar: true), Width = 76 } } },
- new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Width = 96, Children = { Cap("WET", MutedC, 24), new Border { Child = HRow(Wet, "", WetF, 0, 36), Width = 62 } } } } }, Dock.Left),
- WithDock(RoutingChips(), Dock.Right) } } };
+ var transfer = new FgTransferView { Value = _ => P(Amount) };
+ transfer.GestureBegin += _ => Begin(Amount);
+ transfer.GestureEnd += _ => End(Amount);
+ transfer.Changed += (_, v) => { Raw(Amount, v); Refresh(); };
+ transfer.ResetRequested += _ => { Reset(Amount); Refresh(); };
+ Learn(transfer, Amount);
+ ToolTip.SetTip(transfer, "Input → output through the device (in M/S and Multi through the selected stage): each stage alone faint, the LFO-modulated curve dashed teal, the node where the input sits now. Drag up / down for Amount; double-click resets.");
+ var harm = new FgHarmonicsView { Height = 50 };
+ ToolTip.SetTip(harm, "Harmonics 2 … 9 of a −6 dB sine through the curve: odd partials in brass (hard, buzzy), even ones in ink (warm, round), and the total harmonic distortion");
+ var graphs = new DockPanel
+ {
+ Margin = new Thickness(5), LastChildFill = true,
+ Children = { Docked(new Border { Margin = new Thickness(0, 4, 0, 0), Child = harm }, Dock.Bottom), transfer },
+ };
+ var centre = Island(new DockPanel { Children = { Docked(Bar(macros, new Thickness(6, 0)), Dock.Top), graphs } });
+ centre.Margin = new Thickness(5, 0);
- // ================= STAGES column =================
- var stagesHdr = new Grid { Height = 10, ColumnDefinitions = new ColumnDefinitions("Auto,*") };
- stagesHdr.Children.Add(Cap("STAGES"));
- var sub = new TextBlock { Text = "drive · out · feedback", FontSize = 8, Foreground = MutedC, HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center }; Grid.SetColumn(sub, 1); stagesHdr.Children.Add(sub);
- var stages = new DockPanel { LastChildFill = true, Margin = new Thickness(8, 7) };
- DockPanel.SetDock(stagesHdr, Dock.Top); stages.Children.Add(stagesHdr);
- var stageStack = new Grid { RowDefinitions = new RowDefinitions("*,4,*,4,*"), Margin = new Thickness(0, 4, 0, 0) };
- for (int s = 0; s < 3; s++) { var row = StageRow(s); Grid.SetRow(row, s * 2); stageStack.Children.Add(row); }
- stages.Children.Add(stageStack);
- var stagesPanel = new Border { Width = 288, Child = stages };
+ // ======================================================================
+ // RIGHT — the selected stage's shape, modulation, oversampling
+ // ======================================================================
+ var badgeTxt = Mono("", 8, OnAccent); badgeTxt.FontWeight = FontWeight.Bold; badgeTxt.HorizontalAlignment = HorizontalAlignment.Center;
+ var badge = new Border { Width = 13, Height = 13, CornerRadius = NotaRadius.Pill, VerticalAlignment = VerticalAlignment.Center, Child = badgeTxt };
+ var stName = new TextBlock { FontSize = 9, FontWeight = FontWeight.SemiBold, VerticalAlignment = VerticalAlignment.Center };
+ var shapeHead = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = 6 };
+ shapeHead.Children.Add(badge); shapeHead.Children.Add(Col(stName, 1)); shapeHead.Children.Add(Col(Caps("SHAPE"), 2));
+ readouts.Add(() =>
+ {
+ bool lit = On(OnP(sel));
+ badgeTxt.Text = (sel + 1).ToString();
+ badge.Background = lit ? AccentBright : TextDisabled;
+ stName.Text = ForgeMath.AlgoNames[TypeI(sel)].ToUpperInvariant();
+ stName.Foreground = lit ? AccentBright : TextTertiary;
+ });
- // ================= middle: transfer + harmonics =================
- var mid = new DockPanel { LastChildFill = true, Margin = new Thickness(0, 7, 0, 7) };
- mid.Children.Add(new Border { Height = 52, Child = harm, Margin = new Thickness(0, 4, 0, 0), [DockPanel.DockProperty] = Dock.Bottom });
- mid.Children.Add(new Border { Child = transfer });
+ var typeSeg = Segments(ForgeMath.ChipNames, () => Array.IndexOf(ForgeMath.ChipAlgo, TypeI(sel)),
+ i => { SetP(TypeP(sel), ForgeMath.ChipAlgo[i] / 5f); Refresh(); }, out var typeSync, fill: true, padX: 1);
+ readouts.Add(typeSync);
+ ToolTip.SetTip(typeSeg, "The selected stage's type — Tube: soft, asymmetric, warm; Tape: soft and even; Diode: hard on one side; Fuzz: squared-off, dense; Fold: folds the peaks back, bright and metallic; Digital: a hard clip");
- // ================= right rail: SHAPE + MODULATION =================
- var shape = new StackPanel { Spacing = 4, Children = {
- Cap("SHAPE", MutedC),
- HRow(Tone, "TONE", ToneF, 34, 44, bipolar: true),
- HRow(Bias, "BIAS", BiasF, 34, 44, bipolar: true),
- HRow(WidthP, "WIDTH", WidthF, 34, 44) } };
- var mod = new Border { BorderBrush = TealC, BorderThickness = new Thickness(2, 0, 0, 0), Padding = new Thickness(6, 0, 0, 0), Margin = new Thickness(0, 2, 0, 0),
- Child = new StackPanel { Spacing = 4, Children = {
- Cap("MODULATION", TealC),
- HRow(LfoDrive, "LFO → DRIVE", PctF, 60, 32, teal: true),
- HRow(EnvTone, "ENV → TONE", PctF, 60, 32, teal: true),
- HRow(LfoRate, "RATE", RateF, 34, 52, teal: true),
- MiniToggle(LfoSync, "SYNC") } } };
- var quality = new StackPanel { Spacing = 4, Children = {
- Cap("QUALITY", MutedC),
- new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center, Children = { Cap("OVERSAMPLE", MutedC), OsChips() } } } };
- var divider1 = new Border { Height = 1, Background = NotaPalette.SurfaceRaised };
- var divider2 = new Border { Height = 1, Background = NotaPalette.SurfaceRaised };
- var rail = new Border { Width = 176, Background = RailBg, BorderBrush = Border2, BorderThickness = new Thickness(1, 0, 0, 0), Padding = new Thickness(8, 7),
- Child = new StackPanel { Spacing = 5, Children = { shape, divider1, mod, divider2, quality } } };
+ // Gauge knob on the selected stage's param.
+ Control StageKnob(Func<int> param, string label, Func<double, string> fmt, string tip)
+ {
+ var val = Mono(fmt(P(param())), 7, TextPrimary);
+ var knob = new Knob(P(param()), 1.0) { Accent = true, Default = Def(param()), Width = 30, Height = 30 };
+ knob.ValueChanged += v => { Raw(param(), v); val.Text = fmt(P(param())); Refresh(); };
+ knob.GestureBegin += () => Begin(param());
+ knob.GestureEnd += () => End(param());
+ LearnFollow(knob, param);
+ ToolTip.SetTip(knob, tip);
+ readouts.Add(() =>
+ {
+ if (!knob.Dragging) { double c = P(param()); if (Math.Abs(c - knob.Value) > 1e-4) knob.Value = c; }
+ val.Text = fmt(P(param()));
+ val.Foreground = Math.Abs(P(param()) - Def(param())) > 0.003 ? AccentBright : TextPrimary;
+ });
+ return KnobCell(label, knob, val, 46);
+ }
+ var knobs = new UniformGrid
+ {
+ Rows = 1,
+ Children =
+ {
+ StageKnob(() => BiasP(sel), "BIAS", BiasF, "Bias — the stage's asymmetry, −100 … +100 %: pushes the curve off-centre, adding even harmonics"),
+ StageKnob(() => ToneP(sel), "TONE", ToneF, "Tone — a tilt after the stage, −12 … +12 dB around 800 Hz: darker or brighter distortion"),
+ StageKnob(() => WidthSP(sel), "WIDTH", WidthF, "Width — the stage's stereo image, 0 … 200 % (in M/S, stage 2's width scales the side)"),
+ },
+ };
- // ================= assemble =================
- DockPanel.SetDock(stagesPanel, Dock.Left); DockPanel.SetDock(rail, Dock.Right);
- var body = new DockPanel { LastChildFill = true, Children = { stagesPanel, rail, mid } };
- DockPanel.SetDock(live, Dock.Top);
- var root = new DockPanel { LastChildFill = true, Background = NotaPalette.BgApp, Children = { live, body } };
+ var syncSw = Switch("Sync", () => On(LfoSync), () => { SetP(LfoSync, On(LfoSync) ? 0f : 1f); Refresh(); }, out var syncSync);
+ readouts.Add(syncSync);
+ Learn(syncSw, LfoSync);
+ ToolTip.SetTip(syncSw, "Sync — the LFO rate as a note division locked to the song, or free in Hz");
+ var modHead = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
+ modHead.Children.Add(Caps("MODULATION", Teal)); modHead.Children.Add(Col(syncSw, 1));
+ var mods = new StackPanel
+ {
+ Spacing = 2,
+ Children =
+ {
+ Slider("LFO → DRIVE", () => LfoDrive, PctF, "LFO → Drive — the LFO sweeps every stage's drive, up to ±30 %", 50, 40, teal: true),
+ Slider("ENV → TONE", () => EnvTone, PctF, "Env → Tone — loud parts push the tone brighter", 50, 40, teal: true),
+ Slider("RATE", () => LfoRate, RateF, "LFO rate — free 0.05 … 20 Hz, or with Sync a division from 2 bars to 1/64", 50, 40, teal: true),
+ },
+ };
+ var osSeg = Segments(OsNames, OsI, i => { SetP(OS, i / 3f); Refresh(); }, out var osSync, fill: true, padX: 2);
+ readouts.Add(osSync);
+ Learn(osSeg, OS);
+ ToolTip.SetTip(osSeg, "Oversampling — runs the stages at 2 / 4 / 8 × the rate so the harmonics above Nyquist don't fold back (minimum phase, no latency)");
+ var osRow = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), ColumnSpacing = 6 };
+ osRow.Children.Add(Caps("OVERSAMPLE")); osRow.Children.Add(Col(osSeg, 1));
+ static Control Rule(Control c) => new Border { BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, 4, 0, 0), Child = c };
- void RefreshAll() { foreach (var a in readouts) a(); }
- SyncViz();
- ctx.AddDeviceRefresher(() => { RefreshAll(); harm.Sync(); });
- RefreshAll();
- return root;
- }
+ var rightBody = new Grid { RowDefinitions = new RowDefinitions("Auto,*,Auto,*,Auto,Auto,*,Auto"), Margin = new Thickness(8, 6) };
+ rightBody.Children.Add(GRow(typeSeg, 0));
+ rightBody.Children.Add(GRow(knobs, 2));
+ rightBody.Children.Add(GRow(Rule(modHead), 4));
+ rightBody.Children.Add(GRow(new Border { Margin = new Thickness(0, 3, 0, 0), Child = mods }, 5));
+ rightBody.Children.Add(GRow(Rule(osRow), 7));
+ var right = Island(new DockPanel { Children = { Docked(Bar(shapeHead, new Thickness(8, 0)), Dock.Top), rightBody } }, 184);
+ DockPanel.SetDock(right, Dock.Right);
- private static Control WithDock(Control c, Dock d) { DockPanel.SetDock(c, d); return c; }
-}
+ // ======================================================================
+ // Status strip
+ // ======================================================================
+ var statusLeft = new TextBlock { FontSize = 8, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
+ var statusRight = Mono("", 8, TextSecondary);
+ string StatusText()
+ {
+ if (Sc(ForgeMath.S_Alias) > 0.5) return "Digital / Fold without oversampling alias: switch on 2× or more";
+ int on = 0; for (int s = 0; s < 3; s++) if (On(OnP(s))) on++;
+ var parts = new List<string>
+ {
+ $"{on} of 3 stages",
+ new[] { "serial", "parallel", "mid/side", "multiband" }[RouteI()],
+ $"S{sel + 1} {ForgeMath.AlgoNames[TypeI(sel)]} {PctF(P(DriveP(sel)))}",
+ };
+ if (P(LfoDrive) > 0.005f) parts.Add($"LFO {PctF(P(LfoDrive))} {RateF(P(LfoRate))}");
+ if (P(EnvTone) > 0.005f) parts.Add($"env → tone {PctF(P(EnvTone))}");
+ // The master offsets have no knob on the card (their per-stage successors do) — say so when set.
+ if (Math.Abs(P(Tone) - 0.5f) > 0.002f) parts.Add("master tone " + SgnI((P(Tone) - 0.5) * 200) + " %");
+ if (Math.Abs(P(Bias) - 0.5f) > 0.002f) parts.Add("master bias " + BiasF(P(Bias)));
+ if (Math.Abs(P(WidthP) - 0.5f) > 0.002f) parts.Add("master width " + WidthF(P(WidthP)));
+ return string.Join(" · ", parts);
+ }
+ readouts.Add(() =>
+ {
+ bool alias = Sc(ForgeMath.S_Alias) > 0.5;
+ statusLeft.Text = StatusText();
+ statusLeft.Foreground = alias ? AccentBright : TextSecondary;
+ double sr = Sc(ForgeMath.S_SampleRate);
+ statusRight.Text = sr > 0
+ ? NotaNum.F($"{sr / 1000:0.#} kHz · OS {(OsI() == 0 ? "off" : OsNames[OsI()])} · latency {Sc(ForgeMath.S_Latency):0} smp · CPU {Sc(ForgeMath.S_Cpu) * 100:0.0} %")
+ : "";
+ });
+ ToolTip.SetTip(statusLeft, "What the device is doing; the master Tone / Bias / Width offsets of older projects show here when set");
+ var statusGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 8 };
+ statusGrid.Children.Add(statusLeft);
+ statusGrid.Children.Add(Col(statusRight, 1));
+ var status = new Border { Height = 18, Background = Sunken, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(8, 0), Child = statusGrid };
+ DockPanel.SetDock(status, Dock.Bottom);
-// Four routing-topology icons (mockup 3m): two-line diagrams picked by picture.
-internal sealed class RoutingIcon : Control
-{
- private readonly int _kind;
- private IBrush _color = NotaPalette.TextTertiary;
- public IBrush Color { get => _color; set { _color = value; InvalidateVisual(); } }
- public RoutingIcon(int kind) { _kind = kind; }
+ // ---- assemble ---------------------------------------------------------------
+ var bodyRow = new DockPanel { LastChildFill = true, Margin = new Thickness(5), Children = { left, right, centre } };
+ var root = new DockPanel { LastChildFill = true, Background = NotaPalette.SurfaceInset, Children = { status, bodyRow } };
- public override void Render(DrawingContext ctx)
- {
- double w = Bounds.Width, h = Bounds.Height;
- if (w <= 0 || h <= 0) return;
- var pen = new Pen(_color, 1.4) { LineCap = PenLineCap.Round };
- double sx = w / 21.0, sy = h / 16.0;
- void L(double x1, double y1, double x2, double y2) => ctx.DrawLine(pen, new Point(x1 * sx, y1 * sy), new Point(x2 * sx, y2 * sy));
- switch (_kind)
+ var onArr = new bool[3];
+ refreshNow = () =>
{
- case 0: L(2, 8, 8, 8); L(13, 8, 19, 8); break; // Serial
- case 1: L(2, 4, 19, 4); L(2, 12, 19, 12); break; // Parallel
- case 2: L(2, 4, 19, 4); L(2, 12, 10, 12); break; // Mid/Side
- default: L(2, 3, 19, 3); L(2, 8, 19, 8); L(2, 13, 19, 13); break; // Multiband
- }
+ scN = engine.DeviceScope(track, di, scope, ForgeMath.kScope);
+ for (int s = 0; s < 3; s++) onArr[s] = On(OnP(s));
+ bool single = Single(), active = Active();
+ string mainLbl = single ? $"stage {sel + 1} · {ForgeMath.Role(RouteI(), sel).Split(' ')[0].ToLowerInvariant()}" : "static";
+ transfer.Set(scope, scN, onArr, sel, single, active, P(LfoDrive) > 0.005f, mainLbl);
+ int set = single ? sel + 1 : 0;
+ int thdSlot = single ? ForgeMath.S_ThdS1 + sel : ForgeMath.S_ThdChain;
+ int flSlot = single ? ForgeMath.S_FlavorS1 + sel : ForgeMath.S_FlavorChain;
+ harm.Set(scope, scN, set, !active ? "bypass"
+ : NotaNum.F($"THD {Sc(thdSlot):0.0} % · {ForgeMath.Flavors[Math.Clamp((int)Sc(flSlot), 0, 3)]}"));
+ RefreshAll();
+ };
+ ctx.AddDeviceRefresher(Refresh);
+ Refresh();
+ return root;
}
}
diff --git a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
index cc0c5d9c..989b8297 100644
--- a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
@@ -994,15 +994,51 @@ public sealed class FactoryPresetCatalog : IFactoryPresets
Eq3("Megaphone", ("Mid", 0.9333f), ("High", 0.0f), ("Low Kill", 1f), ("Low Freq", 0.6736f), ("High Freq", 0.4491f), ("Slope", 1f), ("Gain", 0.4583f));
Fx("eq3", 16, "Classic Flat", ("Range", 0f), ("Low", 0.5f), ("Mid", 0.5f), ("High", 0.5f));
- // ---- Nota Forge (kind 17) — multi-stage saturation, all params normalized 0..1.
- // Stage type: 0 Tube/0.2 Diode/0.4 Tape/0.6 Fuzz/0.8 Digital/1 Fold; gains/bias
- // bipolar (0.5 = neutral); Routing 0 Serial/0.33 Par/0.67 M-S/1 Multiband.
- Fx("forge", 17, "Cabinet Heat", ("Amount", 0.42f), ("Tone", 0.6f), ("Bias", 0.6f), ("S1 Type", 0f), ("S1 Drive", 0.5f), ("S1 On", 1f), ("S2 On", 0f), ("S3 On", 0f));
- Fx("forge", 17, "Diode Crunch", ("Amount", 0.5f), ("S1 Type", 0.2f), ("S1 Drive", 0.68f), ("S1 On", 1f), ("S2 Type", 0.6f), ("S2 Drive", 0.4f), ("S2 On", 1f), ("S3 On", 0f));
- Fx("forge", 17, "Tape Glue", ("Amount", 0.3f), ("Wet", 0.85f), ("S1 Type", 0.4f), ("S1 Drive", 0.32f), ("S1 On", 1f), ("S2 On", 0f), ("S3 On", 0f));
- Fx("forge", 17, "Fuzz Wall", ("Amount", 0.62f), ("S1 Type", 0.6f), ("S1 Drive", 0.85f), ("S1 FB", 0.3f), ("S1 On", 1f), ("S2 Type", 0.2f), ("S2 Drive", 0.5f), ("S2 On", 1f), ("S3 On", 0f));
- Fx("forge", 17, "Parallel Warmth", ("Routing", 0.333f), ("Amount", 0.4f), ("S1 Type", 0f), ("S1 Drive", 0.5f), ("S1 On", 1f), ("S2 Type", 0.4f), ("S2 Drive", 0.35f), ("S2 On", 1f), ("S3 On", 0f));
- Fx("forge", 17, "Multiband Drive", ("Routing", 1f), ("Amount", 0.45f), ("S1 Type", 0f), ("S1 Drive", 0.45f), ("S1 On", 1f), ("S2 Type", 0.4f), ("S2 Drive", 0.4f), ("S2 On", 1f), ("S3 Type", 0.8f), ("S3 Drive", 0.3f), ("S3 On", 1f), ("LFO Drive", 0.3f));
+ // ---- Nota Forge (kind 17) — multi-stage saturation. Written in units through Forge(…):
+ // FgG = the globals (Amount dB, routing 0 Serial / 1 Parallel / 2 M-S / 3 Multi, wet %,
+ // output dB, LFO → drive %, env → tone %, sync division 0 2/1 … 3 1/4 … 7 1/64 or a free
+ // rate in Hz, oversampling 0 Off … 3 8×); FgS = a stage (1..3, type, drive %, out dB,
+ // feedback %, bias %, tone dB, width %). Stages not named are off.
+ Forge("Init", FgG(10.5f), FgS(1, FTube, 40));
+ // Warmth
+ Forge("Cabinet Heat", FgG(12.6f), FgS(1, FTube, 50, bias: 20, tone: 2.4f));
+ Forge("Tape Glue", FgG(9f, wet: 85), FgS(1, FTape, 32));
+ Forge("Tube Warmth", FgG(6f), FgS(1, FTube, 35, bias: 15, tone: -1));
+ Forge("Console Bus", FgG(4.5f), FgS(1, FTape, 25), FgS(2, FTube, 20, bias: 10));
+ Forge("Vocal Silk", FgG(6f, wet: 70), FgS(1, FTube, 30, bias: 25, tone: 1.5f));
+ Forge("Bass Weight", FgG(9f), FgS(1, FTape, 45, tone: -3), FgS(2, FTube, 30, bias: 20));
+ // Drive
+ Forge("Diode Crunch", FgG(15f), FgS(1, FDiode, 68), FgS(2, FFuzz, 40));
+ Forge("Amp Stack", FgG(18f, outDb: -3), FgS(1, FTube, 60, bias: 20), FgS(2, FDiode, 50, tone: -2), FgS(3, FTape, 30));
+ Forge("Guitar Edge", FgG(16.5f, outDb: -3), FgS(1, FDiode, 55, bias: 30, tone: 3));
+ Forge("Snare Crack", FgG(12f, wet: 75, os: 1), FgS(1, FDiode, 50, tone: 4), FgS(2, FDigital, 25));
+ // Destroy
+ Forge("Fuzz Wall", FgG(18.6f, outDb: -3), FgS(1, FFuzz, 85, fb: 30), FgS(2, FDiode, 50));
+ Forge("Fold Bells", FgG(6f, os: 2), FgS(1, FFold, 45, tone: 3));
+ Forge("Digital Hard Clip", FgG(12f, os: 1), FgS(1, FDigital, 60));
+ Forge("Broken Speaker", FgG(21f, outDb: -6, os: 1), FgS(1, FFuzz, 70, bias: 60, tone: -6, width: 60), FgS(2, FFold, 40, fb: 20));
+ Forge("Feedback Scream", FgG(15f, outDb: -4.5f), FgS(1, FTube, 70, fb: 70), FgS(2, FFuzz, 60, fb: 40, tone: -3));
+ Forge("Wavefolder Synth", FgG(9f, outDb: -3, os: 2), FgS(1, FFold, 60, bias: 20, fb: 15), FgS(2, FTape, 30, tone: -2));
+ // Parallel
+ Forge("Parallel Warmth", FgG(12f, routing: 1), FgS(1, FTube, 50), FgS(2, FTape, 35));
+ Forge("Drum Glue", FgG(6f, routing: 1, wet: 60, outDb: -1.5f, lfo: 35, env: 20, div: 2, os: 1),
+ FgS(1, FTube, 55, fb: 10, bias: 15), FgS(2, FTape, 45, tone: -3), FgS(3, FDiode, 30, outDb: -3, bias: -20));
+ Forge("NY Drums", FgG(12f, routing: 1, wet: 45), FgS(1, FDiode, 70), FgS(2, FFuzz, 50, outDb: -3));
+ Forge("Bass Parallel Grit", FgG(9f, routing: 1, wet: 50), FgS(1, FFuzz, 60, tone: -4), FgS(2, FTube, 40));
+ // Mid / Side
+ Forge("Wide Air", FgG(6f, routing: 2), FgS(1, FTube, 20), FgS(2, FTape, 50, tone: 3, width: 140));
+ Forge("Mono Grit Core", FgG(12f, routing: 2), FgS(1, FDiode, 60), FgS(2, FTape, 15));
+ Forge("Side Sizzle", FgG(9f, routing: 2, os: 1), FgS(2, FDigital, 45, tone: 4, width: 130));
+ // Multiband
+ Forge("Multiband Drive", FgG(13.5f, routing: 3, lfo: 30, os: 1), FgS(1, FTube, 45), FgS(2, FTape, 40), FgS(3, FDigital, 30));
+ Forge("Warm Master", FgG(3f, routing: 3, os: 2), FgS(1, FTape, 35, tone: 1), FgS(2, FTube, 25, bias: 10), FgS(3, FDigital, 15, tone: -4, width: 120));
+ Forge("Low-End Only", FgG(12f, routing: 3), FgS(1, FTube, 60, bias: 15));
+ Forge("Presence Lift", FgG(9f, routing: 3), FgS(2, FTube, 40, tone: 2), FgS(3, FTape, 35, width: 120));
+ // Motion
+ Forge("Breathing Drive", FgG(12f, lfo: 50, div: 2), FgS(1, FTube, 50));
+ Forge("Wobble Crunch", FgG(15f, lfo: 70, div: 4, os: 1), FgS(1, FDiode, 55), FgS(2, FFold, 25));
+ Forge("Envelope Bite", FgG(9f, env: 60), FgS(1, FTape, 45));
+ Forge("Slow Tide", FgG(9f, lfo: 40, freeHz: 0.2f), FgS(1, FTape, 50), FgS(2, FTube, 30, width: 130));
// ---- Nota AutoGain (kind 18) — loudness matching, all params normalized 0..1.
// Target 0..1 → −36..0 LUFS; Scale 0 Mom/0.5 Short/1 Integ; Response 0 Fast/1 Slow.
@@ -1542,14 +1578,49 @@ public sealed class FactoryPresetCatalog : IFactoryPresets
Fx("vintage", 8, "Neutral Saturator", ("Character", 0f), ("Drive", 0.50f), ("Tone Model", 0.5f), ("Wow", 0f), ("Flutter", 0f), ("Noise", 0f), ("Crackle", 0f), ("Wear", 0f), ("Auto Comp", 1f), ("Oversampling", 0.667f));
Fx("vintage", 8, "Gated Dust", ("Character", 0f), ("Drive", 0f), ("Wow", 0f), ("Flutter", 0f), ("Noise", 0.35f), ("Hiss HP", 0.5f), ("Crackle", 0.30f), ("Wear", 0.20f), ("Wear Follow", 1f), ("Output", 0.42f));
- // ---- Nota Auto Pan (kind 9) — all params normalized 0..1. Waveform 0 Sine/.25 Tri/
- // .5 Saw/.75 Sqr/1 S&H; Phase 0.5 = 180° (pan), 0 = tremolo; Rate exp 0.01..40 Hz.
- Fx("autopan", 9, "Classic Pan", ("Rate", 0.60f), ("Amount", 0.80f), ("Waveform", 0f), ("Shape", 0f), ("Phase", 0.5f), ("Mix", 1f));
- Fx("autopan", 9, "Tremolo", ("Rate", 0.70f), ("Amount", 0.70f), ("Waveform", 0f), ("Shape", 0f), ("Phase", 0f), ("Mix", 1f));
- Fx("autopan", 9, "Chop Gate", ("Rate", 0.72f), ("Amount", 1.0f), ("Waveform", 0.75f), ("Shape", 0f), ("Phase", 0f), ("Mix", 1f));
- Fx("autopan", 9, "Slow Sweep", ("Rate", 0.40f), ("Amount", 0.90f), ("Waveform", 0f), ("Shape", 0f), ("Phase", 0.5f), ("Mix", 1f));
- Fx("autopan", 9, "Random Space", ("Rate", 0.62f), ("Amount", 0.75f), ("Waveform", 1f), ("Shape", 0f), ("Phase", 0.5f), ("Mix", 0.85f));
- Fx("autopan", 9, "Hard Square", ("Rate", 0.66f), ("Amount", 0.85f), ("Waveform", 0f), ("Shape", 0.9f), ("Phase", 0.5f), ("Mix", 1f));
+ // ---- Nota Orbit (kind 9, formerly Auto Pan) — all params normalized 0..1 (unnamed ones reset
+ // to their defaults). Waveform 0 Sine/.25 Tri/.5 Saw/.75 Sqr/1 S&H; Shape sharpens the
+ // smooth waves, on S&H it is the glide; Phase 0..1 = 0..360° (0 tremolo, .25 = 90°, .5 =
+ // 180° pan); Rate exp 0.01*4000^v Hz (.278 = 0.1, .361 = 0.2, .472 = 0.5, .555 = 1, .6 =
+ // 1.45, .639 = 2, .749 = 5, .771 = 6, .855 = 12 Hz); Sync 1 = Division sets the rate: round(15v)
+ // of 4/1, 2/1, 1/1, 1/2D, 1/2, 1/2T, 1/4D, 1/4, 1/4T, 1/8D, 1/8, 1/8T, 1/16D, 1/16, 1/16T, 1/32
+ // (.133 = 1/1, .267 = 1/2, .4 = 1/4D, .467 = 1/4, .6 = 1/8D, .667 = 1/8, .733 = 1/8T, .867 = 1/16).
+ Fx("autopan", 9, "Init", ("Rate", 0.60f), ("Amount", 0.70f), ("Waveform", 0f), ("Shape", 0f), ("Phase", 0.5f), ("Mix", 1f), ("Sync", 0f), ("Division", 0.667f));
+ // Pan — free
+ Fx("autopan", 9, "Classic Pan", ("Rate", 0.60f), ("Amount", 0.80f), ("Waveform", 0f), ("Shape", 0f), ("Phase", 0.5f), ("Mix", 1f));
+ Fx("autopan", 9, "Slow Sweep", ("Rate", 0.40f), ("Amount", 0.90f), ("Waveform", 0f), ("Shape", 0f), ("Phase", 0.5f), ("Mix", 1f));
+ Fx("autopan", 9, "Hard Square", ("Rate", 0.66f), ("Amount", 0.85f), ("Waveform", 0f), ("Shape", 0.9f), ("Phase", 0.5f), ("Mix", 1f));
+ Fx("autopan", 9, "Wide Drift", ("Rate", 0.278f), ("Amount", 0.90f), ("Phase", 0.5f));
+ Fx("autopan", 9, "Gentle Sway", ("Rate", 0.472f), ("Amount", 0.45f), ("Phase", 0.5f));
+ Fx("autopan", 9, "Quarter Circle", ("Rate", 0.555f), ("Amount", 0.80f), ("Phase", 0.25f));
+ Fx("autopan", 9, "Ping Pong", ("Rate", 0.639f), ("Amount", 0.90f), ("Waveform", 0.75f), ("Phase", 0.5f));
+ // Pan — synced
+ Fx("autopan", 9, "Eighth Swirl", ("Sync", 1f), ("Division", 0.667f), ("Waveform", 0.25f), ("Shape", 0.45f), ("Amount", 1f), ("Phase", 0.5f));
+ Fx("autopan", 9, "Bar Sweep", ("Sync", 1f), ("Division", 0.133f), ("Amount", 0.85f), ("Phase", 0.5f));
+ Fx("autopan", 9, "Two-Bar Drift", ("Sync", 1f), ("Division", 0.067f), ("Amount", 0.80f), ("Phase", 0.5f));
+ Fx("autopan", 9, "Quarter Pan", ("Sync", 1f), ("Division", 0.467f), ("Amount", 0.70f), ("Phase", 0.5f));
+ Fx("autopan", 9, "Dotted Bounce", ("Sync", 1f), ("Division", 0.6f), ("Waveform", 0.25f), ("Amount", 0.80f), ("Phase", 0.5f));
+ Fx("autopan", 9, "Triplet Roll", ("Sync", 1f), ("Division", 0.733f), ("Amount", 0.60f), ("Phase", 0.5f));
+ Fx("autopan", 9, "Saw Rotor", ("Sync", 1f), ("Division", 0.467f), ("Waveform", 0.5f), ("Shape", 0.2f), ("Amount", 0.70f), ("Phase", 0.5f));
+ // Tremolo
+ Fx("autopan", 9, "Tremolo", ("Rate", 0.70f), ("Amount", 0.70f), ("Waveform", 0f), ("Shape", 0f), ("Phase", 0f), ("Mix", 1f));
+ Fx("autopan", 9, "Chop Gate", ("Rate", 0.72f), ("Amount", 1.0f), ("Waveform", 0.75f), ("Shape", 0f), ("Phase", 0f), ("Mix", 1f));
+ Fx("autopan", 9, "Chop Trem", ("Sync", 1f), ("Division", 0.867f), ("Waveform", 0.75f), ("Amount", 0.60f), ("Phase", 0f), ("Mix", 0.85f));
+ Fx("autopan", 9, "Vintage Amp Trem", ("Rate", 0.749f), ("Amount", 0.55f), ("Shape", 0.15f), ("Phase", 0f));
+ Fx("autopan", 9, "Deep Throb", ("Sync", 1f), ("Division", 0.467f), ("Shape", 0.3f), ("Amount", 0.90f), ("Phase", 0f));
+ Fx("autopan", 9, "Helicopter", ("Rate", 0.855f), ("Amount", 0.85f), ("Waveform", 0.75f), ("Phase", 0f));
+ Fx("autopan", 9, "Sidechain Pump", ("Sync", 1f), ("Division", 0.467f), ("Waveform", 0.5f), ("Amount", 0.80f), ("Phase", 0f));
+ Fx("autopan", 9, "Stutter 32", ("Sync", 1f), ("Division", 1f), ("Waveform", 0.75f), ("Amount", 1f), ("Phase", 0f));
+ // Random
+ Fx("autopan", 9, "Random Space", ("Rate", 0.62f), ("Amount", 0.75f), ("Waveform", 1f), ("Shape", 0f), ("Phase", 0.5f), ("Mix", 0.85f));
+ Fx("autopan", 9, "Random Steps", ("Sync", 1f), ("Division", 0.667f), ("Waveform", 1f), ("Amount", 0.80f), ("Phase", 0.5f));
+ Fx("autopan", 9, "Drifting Cloud", ("Rate", 0.40f), ("Waveform", 1f), ("Shape", 1f), ("Amount", 0.70f), ("Phase", 0.5f));
+ Fx("autopan", 9, "Glitch Gate", ("Sync", 1f), ("Division", 0.867f), ("Waveform", 1f), ("Amount", 1f), ("Phase", 0f));
+ Fx("autopan", 9, "Wander", ("Sync", 1f), ("Division", 0.267f), ("Waveform", 1f), ("Shape", 0.8f), ("Amount", 0.60f), ("Phase", 0.25f));
+ // Subtle
+ Fx("autopan", 9, "Stereo Breath", ("Rate", 0.361f), ("Amount", 0.25f), ("Phase", 0.5f));
+ Fx("autopan", 9, "Mix Motion", ("Sync", 1f), ("Division", 0.267f), ("Waveform", 0.25f), ("Amount", 0.35f), ("Phase", 0.5f), ("Mix", 0.6f));
+ Fx("autopan", 9, "Offset Swirl", ("Sync", 1f), ("Division", 0.4f), ("Amount", 0.60f), ("Phase", 0.375f));
// ---- Nota Auto Shift (kind 10) — pitch correction, all params normalized 0..1 (unnamed ones
// reset to their defaults). Key round(11v) (0 C, .182 D, .364 E, .455 F, .636 G, .818 A);
@@ -1921,6 +1992,46 @@ public sealed class FactoryPresetCatalog : IFactoryPresets
private void Fx(string group, int kind, string name, params (string Name, float Value)[] ps)
=> Add(group, name, "builtin-effect", kind, isInstrument: false, isMidi: false, ps);
+ // Nota Forge stage types (the S* Type step, × 1/5).
+ private const int FTube = 0, FDiode = 1, FTape = 2, FFuzz = 3, FDigital = 4, FFold = 5;
+
+ // Nota Forge globals in units → normalized pairs (see the Forge block above).
+ private static (string Name, float Value)[] FgG(float amountDb, int routing = 0, float wet = 100, float outDb = 0, float lfo = 0,
+ float env = 0, int div = 3, float freeHz = 0, int os = 0)
+ {
+ var ps = new List<(string, float)>
+ {
+ ("Amount", amountDb / 30f), ("Routing", routing / 3f), ("Wet", wet / 100f), ("Output", 0.5f + outDb / 48f),
+ ("LFO Drive", lfo / 100f), ("Env Tone", env / 100f), ("Oversampling", os / 3f),
+ ("Tone", 0.5f), ("Bias", 0.5f), ("Width", 0.5f),
+ };
+ if (freeHz > 0) { ps.Add(("LFO Sync", 0f)); ps.Add(("LFO Rate", MathF.Log(freeHz / 0.05f) / MathF.Log(400f))); }
+ else { ps.Add(("LFO Sync", 1f)); ps.Add(("LFO Rate", div / 7f)); }
+ return ps.ToArray();
+ }
+
+ // A Nota Forge stage for Forge(…): number 1..3, type, drive %, out dB, feedback %, bias %, tone dB, width %.
+ private static (int N, int Type, float Drive, float OutDb, float Fb, float Bias, float Tone, float Width) FgS(int n, int type, float drive,
+ float outDb = 0, float fb = 0, float bias = 0, float tone = 0, float width = 100) => (n, type, drive, outDb, fb, bias, tone, width);
+
+ // Every stage is spelled out: the ones named are on as given, the rest are off — so a preset
+ // never inherits the default stages.
+ private void Forge(string name, (string Name, float Value)[] globals, params (int N, int Type, float Drive, float OutDb, float Fb, float Bias, float Tone, float Width)[] stages)
+ {
+ var ps = new List<(string, float)>(globals);
+ var used = new bool[4];
+ foreach (var st in stages)
+ {
+ used[st.N] = true;
+ string p = "S" + st.N + " ";
+ ps.Add((p + "On", 1f)); ps.Add((p + "Type", st.Type / 5f)); ps.Add((p + "Drive", st.Drive / 100f));
+ ps.Add((p + "Out", 0.5f + st.OutDb / 24f)); ps.Add((p + "FB", st.Fb / 100f)); ps.Add((p + "Bias", 0.5f + st.Bias / 200f));
+ ps.Add((p + "Tone", 0.5f + st.Tone / 24f)); ps.Add((p + "Width", st.Width / 200f));
+ }
+ for (int n = 1; n <= 3; n++) if (!used[n]) ps.Add(("S" + n + " On", 0f));
+ Fx("forge", 17, name, ps.ToArray());
+ }
+
// Nota EQ-3 in the Isolator law — names Range, so it isn't read as a pre-Range preset.
private void Eq3(string name, params (string Name, float Value)[] ps)
=> Fx("eq3", 16, name, [("Range", 1f), .. ps]);
diff --git a/src/managed/Nota.Mcp/Tools/DeviceTools.cs b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
index 21ac56c1..a3af6b95 100644
--- a/src/managed/Nota.Mcp/Tools/DeviceTools.cs
+++ b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
@@ -67,10 +67,10 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
[McpServerTool(Name = "load_device_file"), Description("Load an audio file into a device that takes one — Nota Chamber: a user impulse response (WAV / FLAC / MP3; mono, stereo or 4-channel true stereo), which also selects it. Returns true on success.")]
public Task<bool> LoadDeviceFile(int trackId, int deviceIndex, [Description("Absolute path to the audio file")] string path) => Mutate(() => E.DeviceLoadFile(trackId, deviceIndex, path));
- [McpServerTool(Name = "get_device_text"), Description("Read a device's resource text. Nota Chamber: id 0 = current IR name, 1 = its category, 2 = the loaded user IR's name, 10 = the built-in IR list (name, category, seconds per line; the IR param selects entry round(v × 16), 1.0 = the user IR). Nota Lens: id 0 = the analysis summary, 1 = the third-octave band table, 2 = the scope measurements, 3 = the strongest spectral peaks, 4 = the A/B cursor measurements — or use read_analyzer, which returns all of it parsed. Delay (kind 3): id 0 = a one-line summary of what it is doing now (sync division or free times, ping-pong, feedback, mix, or that it is frozen). Reverb (kind 2): id 0 = a one-line summary (algorithm, RT60, pre-delay, diffusion, mix, early reflections / vintage, or that the tail is frozen). Compressor (kind 1): id 0 = a one-line summary (character, threshold, ratio, knee, attack / release, detector, range, mix, the reduction right now, external key / unlinked / Listen) — or use read_dynamics for the numbers. Auto Filter (kind 7): id 0 = a one-line summary (type, slope, cutoff, Q, what the envelope and LFO drive and by how much, drive, mix, sidechain key), 1 = the live reading (modulated cutoff with its note, resonance, envelope level, LFO value and phase, onsets counted), 2 = a guide to what each 0..1 parameter value means — or use read_filter_motion for the numbers. Nota Vintage (kind 8): id 0 = a one-line summary (character, drive, tone model and shelves, wow / flutter with their rates, noise, crackle, wear, stage, mix, output, oversampling, auto-comp), 1 = the live reading (in / out peaks, THD with the 2nd and 3rd harmonics, asymmetry, wow and flutter in cents, band-limit, hiss level, auto-comp gain), 2 = a guide to what each 0..1 parameter value means — or use read_vintage for the numbers. Nota Valve (kind 6): id 0 = a one-line summary (model, gain, the tone stack with the middle's frequency, bright / deep, even-only, cabinet with mic, distance, axis and position, low / high cut, gate, mix, output, oversampling, auto-comp), 1 = the live reading (in / out peaks, THD with the 2nd and 3rd harmonics, estimated aliasing, drive, gate open / closed, auto-comp gain, the cab's loss at 4 kHz vs on-axis), 2 = a guide to the parameter values and units — or use read_valve for the numbers. Nota Utility (kind 4): id 0 = a one-line summary (channel mode, width and its L/R or M/S law, mono below with its slope, balance, phase, mute, gain, auto match and its reference, true-peak limit), 1 = the live reading (in / out LUFS-S, peak and RMS, true peak, the delta in the meter's unit, correlation, width, energy balance, auto-match gain, limiter reduction), 2 = a guide to the parameter values and units — or use read_utility for the numbers. Nota Shutter (kind 19): id 0 = a one-line summary (Gate / Duck, threshold, return, shape with attack / hold / release, floor, lookahead, retrigger, internal / external key, the key filter band, peak hold, Listen), 1 = the live reading (state, gain, reduction now and peak, in / out / detector levels, the share of the window it was open, openings in the last bar and since reset, key level, latency), 2 = a guide to what each 0..1 parameter value means — or use read_shutter for the numbers. Nota Auto Shift (kind 10): id 0 = a one-line summary (key and scale or the MIDI target settings, key source, amount, speed, range, human, shift and fine, formant preserve and shift, mix, detection range and sensitivity, skip sibilants, follow), 1 = the live reading (detected note and cents, frequency, clarity, target and correction, ratio, input level, MIDI note held, share sung in scale, the best and runner-up key, Learn running, latency), 2 = a guide to what each 0..1 parameter value means — or use read_auto_shift for the numbers. Nota Beat Repeat (kind 11): id 0 = a one-line summary (mode, interval, grid, offset, gate, chance, variation, pitch and pitch decay, decay, volume, the repeat filter with its type, band and narrowing, mix, Repeat held, latch), 1 = the live reading (idle / capturing / repeating, the pass of how many, the slice in ms and beats, the repeat's gain, pitch and filter, in / repeat / out levels, bar and beat, bursts and skipped intervals since reset), 2 = a guide to what each 0..1 parameter value means — or use read_beat_repeat for the numbers. Nota Dynamic EQ-8 (kind 13): id 0 = a one-line summary (bands on and dynamic, the Dynamic switch, each band on with its type, frequency, gain, Q and — for a dynamic band — mode, threshold, range, attack / release and key, solo, output, whether a key track is routed), 1 = the live reading (in / out peaks, whether a key arrives, each band's detector level and — for a dynamic band — its threshold and the gain it has now of its range, CPU), 2 = a guide to the parameter layout and units — or use read_dynamic_eq for the numbers and set_dynamic_eq_band to edit a band. Nota Ceiling (kind 14): id 0 = a one-line summary (character, gain, ceiling and whether it is true-peak, release or auto, look-ahead, stereo link, key high-pass, key track, the loudness target, Delta), 1 = the live reading (gain reduction now, its mean and deepest over the last 4 s and since reset, in / out peaks and their holds, true peak, the share of time over the ceiling, the release in use and its range, transients that reached the clip, LUFS M / S / I and the distance to the target, LRA, PLR, latency), 2 = a guide to the parameter values and units — or use read_ceiling for the numbers. Nota Crush (kind 12): id 0 = a one-line summary (mode, bits, rate with the hold, drive, wet, dither / jitter / noise, post filter, output, anti-alias, auto gain, DC filter), 1 = the live reading (in / out peak and RMS, crest, peak holds, bits with the level count and quantisation noise, the reduced rate, hold and Nyquist, THD+N, images above the Nyquist, the driven peak and folds, auto gain, CPU), 2 = a guide to what each 0..1 parameter value means — or use read_crush for the numbers. Nota EQ-3 (kind 16): id 0 = a one-line summary (slope, the two crossovers, each band's gain or kill, the fader range, output), 1 = the live reading (in / out peaks, each band's level after its gain and the gain in effect now, the crossovers in use, CPU), 2 = a guide to what each 0..1 parameter value means — or use read_eq3 for the numbers and set_eq3 to play it in dB and Hz. Nota EQ-8 (kind 0): id 0 = a one-line summary (bands on, scale, each band on with its type, frequency, gain, Q, slope for the cuts and channel when not stereo, output, auto gain, analyzer), 1 = the live reading (in / out peaks, the auto gain in effect, CPU), 2 = a guide to the parameter layout and units — or use read_eq8 for the numbers, set_eq8_band to edit a band and set_eq8 for the globals.")]
+ [McpServerTool(Name = "get_device_text"), Description("Read a device's resource text. Nota Chamber: id 0 = current IR name, 1 = its category, 2 = the loaded user IR's name, 10 = the built-in IR list (name, category, seconds per line; the IR param selects entry round(v × 16), 1.0 = the user IR). Nota Lens: id 0 = the analysis summary, 1 = the third-octave band table, 2 = the scope measurements, 3 = the strongest spectral peaks, 4 = the A/B cursor measurements — or use read_analyzer, which returns all of it parsed. Delay (kind 3): id 0 = a one-line summary of what it is doing now (sync division or free times, ping-pong, feedback, mix, or that it is frozen). Reverb (kind 2): id 0 = a one-line summary (algorithm, RT60, pre-delay, diffusion, mix, early reflections / vintage, or that the tail is frozen). Compressor (kind 1): id 0 = a one-line summary (character, threshold, ratio, knee, attack / release, detector, range, mix, the reduction right now, external key / unlinked / Listen) — or use read_dynamics for the numbers. Auto Filter (kind 7): id 0 = a one-line summary (type, slope, cutoff, Q, what the envelope and LFO drive and by how much, drive, mix, sidechain key), 1 = the live reading (modulated cutoff with its note, resonance, envelope level, LFO value and phase, onsets counted), 2 = a guide to what each 0..1 parameter value means — or use read_filter_motion for the numbers. Nota Vintage (kind 8): id 0 = a one-line summary (character, drive, tone model and shelves, wow / flutter with their rates, noise, crackle, wear, stage, mix, output, oversampling, auto-comp), 1 = the live reading (in / out peaks, THD with the 2nd and 3rd harmonics, asymmetry, wow and flutter in cents, band-limit, hiss level, auto-comp gain), 2 = a guide to what each 0..1 parameter value means — or use read_vintage for the numbers. Nota Valve (kind 6): id 0 = a one-line summary (model, gain, the tone stack with the middle's frequency, bright / deep, even-only, cabinet with mic, distance, axis and position, low / high cut, gate, mix, output, oversampling, auto-comp), 1 = the live reading (in / out peaks, THD with the 2nd and 3rd harmonics, estimated aliasing, drive, gate open / closed, auto-comp gain, the cab's loss at 4 kHz vs on-axis), 2 = a guide to the parameter values and units — or use read_valve for the numbers. Nota Utility (kind 4): id 0 = a one-line summary (channel mode, width and its L/R or M/S law, mono below with its slope, balance, phase, mute, gain, auto match and its reference, true-peak limit), 1 = the live reading (in / out LUFS-S, peak and RMS, true peak, the delta in the meter's unit, correlation, width, energy balance, auto-match gain, limiter reduction), 2 = a guide to the parameter values and units — or use read_utility for the numbers. Nota Shutter (kind 19): id 0 = a one-line summary (Gate / Duck, threshold, return, shape with attack / hold / release, floor, lookahead, retrigger, internal / external key, the key filter band, peak hold, Listen), 1 = the live reading (state, gain, reduction now and peak, in / out / detector levels, the share of the window it was open, openings in the last bar and since reset, key level, latency), 2 = a guide to what each 0..1 parameter value means — or use read_shutter for the numbers. Nota Auto Shift (kind 10): id 0 = a one-line summary (key and scale or the MIDI target settings, key source, amount, speed, range, human, shift and fine, formant preserve and shift, mix, detection range and sensitivity, skip sibilants, follow), 1 = the live reading (detected note and cents, frequency, clarity, target and correction, ratio, input level, MIDI note held, share sung in scale, the best and runner-up key, Learn running, latency), 2 = a guide to what each 0..1 parameter value means — or use read_auto_shift for the numbers. Nota Beat Repeat (kind 11): id 0 = a one-line summary (mode, interval, grid, offset, gate, chance, variation, pitch and pitch decay, decay, volume, the repeat filter with its type, band and narrowing, mix, Repeat held, latch), 1 = the live reading (idle / capturing / repeating, the pass of how many, the slice in ms and beats, the repeat's gain, pitch and filter, in / repeat / out levels, bar and beat, bursts and skipped intervals since reset), 2 = a guide to what each 0..1 parameter value means — or use read_beat_repeat for the numbers. Nota Dynamic EQ-8 (kind 13): id 0 = a one-line summary (bands on and dynamic, the Dynamic switch, each band on with its type, frequency, gain, Q and — for a dynamic band — mode, threshold, range, attack / release and key, solo, output, whether a key track is routed), 1 = the live reading (in / out peaks, whether a key arrives, each band's detector level and — for a dynamic band — its threshold and the gain it has now of its range, CPU), 2 = a guide to the parameter layout and units — or use read_dynamic_eq for the numbers and set_dynamic_eq_band to edit a band. Nota Ceiling (kind 14): id 0 = a one-line summary (character, gain, ceiling and whether it is true-peak, release or auto, look-ahead, stereo link, key high-pass, key track, the loudness target, Delta), 1 = the live reading (gain reduction now, its mean and deepest over the last 4 s and since reset, in / out peaks and their holds, true peak, the share of time over the ceiling, the release in use and its range, transients that reached the clip, LUFS M / S / I and the distance to the target, LRA, PLR, latency), 2 = a guide to the parameter values and units — or use read_ceiling for the numbers. Nota Crush (kind 12): id 0 = a one-line summary (mode, bits, rate with the hold, drive, wet, dither / jitter / noise, post filter, output, anti-alias, auto gain, DC filter), 1 = the live reading (in / out peak and RMS, crest, peak holds, bits with the level count and quantisation noise, the reduced rate, hold and Nyquist, THD+N, images above the Nyquist, the driven peak and folds, auto gain, CPU), 2 = a guide to what each 0..1 parameter value means — or use read_crush for the numbers. Nota Orbit (kind 9): id 0 = a one-line summary (waveform, free rate in Hz or the Sync division, shape / glide, phase with the mode it makes — tremolo, auto-pan or offset pan — amount, mix), 1 = the live reading (the LFO rate and period, locked to the song or free-running, its place in the two-cycle window, the L / R gain now, the pan and its swing, the floor, in / out levels, tempo and bar, CPU), 2 = a guide to what each 0..1 parameter value means incl. the Division table — or use read_orbit for the numbers. Nota EQ-3 (kind 16): id 0 = a one-line summary (slope, the two crossovers, each band's gain or kill, the fader range, output), 1 = the live reading (in / out peaks, each band's level after its gain and the gain in effect now, the crossovers in use, CPU), 2 = a guide to what each 0..1 parameter value means — or use read_eq3 for the numbers and set_eq3 to play it in dB and Hz. Nota Forge (kind 17): id 0 = a one-line summary (routing, amount, wet, output, each stage on with its type, role, drive, out, feedback, bias, tone and width, the LFO → drive with its rate, env → tone, the master tone / bias / width offsets when set, oversampling and an aliasing warning), 1 = the live reading (in / out peak and RMS, THD of a −6 dB sine through the device and through each stage with its flavour, the LFO value, drive offset and rate, the envelope, the master tilt now, oversampling, latency, CPU), 2 = a guide to what each 0..1 parameter value means — or use read_forge for the numbers and the curve, set_forge and set_forge_stage to play it in units. Nota EQ-8 (kind 0): id 0 = a one-line summary (bands on, scale, each band on with its type, frequency, gain, Q, slope for the cuts and channel when not stereo, output, auto gain, analyzer), 1 = the live reading (in / out peaks, the auto gain in effect, CPU), 2 = a guide to the parameter layout and units — or use read_eq8 for the numbers, set_eq8_band to edit a band and set_eq8 for the globals.")]
public Task<string> GetDeviceText(int trackId, int deviceIndex, int id) => Read(() => E.DeviceText(trackId, deviceIndex, id));
- [McpServerTool(Name = "device_action"), Description("Run a device's own command — the few things that are actions rather than parameters. Delay (kind 3): id 0 clears the loop (empties the delay buffer, so whatever is still circulating stops; useful after Freeze). Reverb (kind 2): id 0 kills the tail (empties the reverb's buffers, so whatever is still ringing — or frozen — stops). Auto Filter (kind 7): id 0 restarts the LFO (from its start phase; in Sync the cycle is re-anchored to the current beat), id 1 resets the envelope follower (drops a held peak). Nota Vintage (kind 8): id 0 resets the wear (restarts the wow and flutter at their zero phase and silences a ringing crackle). Nota Valve (kind 6): id 0 resets the amp (clears the filters, the gate and the auto-comp). Nota Utility (kind 4): id 0 gain match — moves Gain once so the output meets the reference (the input's level, or Target when Match To = 1) over the last 3 s in the Meter's unit; id 1 resets the meters (level history, holds and the auto-match ride). Nota Shutter (kind 19): id 0 resets the meters (peak reduction, the opening count, the history); id 1 sets the history window read_shutter and the card show (intArg 0 = 250 ms, 1 = 1 s, 2 = 4 s). Nota Auto Shift (kind 10): id 0 resets the analysis (the sung-note histogram and the pitch history); id 1 is Learn — intArg 1 starts listening (clears the histogram), 0 stops and sets Key + Scale (Major / Minor) to the best match and Key Source to Manual, 2 cancels. Nota Beat Repeat (kind 11): id 0 resets (stops the repeat, clears the timeline, the meters and the burst count); id 1 fires a repeat now, as if the interval hit (ignores Chance; while the transport plays — to hold one, set the Repeat param to 1). Nota Ceiling (kind 14): id 0 resets the peaks (the peak and true-peak holds, the max reduction, the clip count and the 4 s level window); id 1 resets the loudness (integrated, LRA, the 60 s window) and the peaks. Nota Crush (kind 12): id 0 resets the meters (the peak holds and the spectrum average). Nota EQ-3 (kind 16): id 0 resets the meters (the peaks and the spectrum average). Nota EQ-8 (kind 0): id 0 resets the meters (the peaks and the spectrum averages). Devices without a command ignore the call.")]
+ [McpServerTool(Name = "device_action"), Description("Run a device's own command — the few things that are actions rather than parameters. Delay (kind 3): id 0 clears the loop (empties the delay buffer, so whatever is still circulating stops; useful after Freeze). Reverb (kind 2): id 0 kills the tail (empties the reverb's buffers, so whatever is still ringing — or frozen — stops). Auto Filter (kind 7): id 0 restarts the LFO (from its start phase; in Sync the cycle is re-anchored to the current beat), id 1 resets the envelope follower (drops a held peak). Nota Vintage (kind 8): id 0 resets the wear (restarts the wow and flutter at their zero phase and silences a ringing crackle). Nota Valve (kind 6): id 0 resets the amp (clears the filters, the gate and the auto-comp). Nota Utility (kind 4): id 0 gain match — moves Gain once so the output meets the reference (the input's level, or Target when Match To = 1) over the last 3 s in the Meter's unit; id 1 resets the meters (level history, holds and the auto-match ride). Nota Shutter (kind 19): id 0 resets the meters (peak reduction, the opening count, the history); id 1 sets the history window read_shutter and the card show (intArg 0 = 250 ms, 1 = 1 s, 2 = 4 s). Nota Auto Shift (kind 10): id 0 resets the analysis (the sung-note histogram and the pitch history); id 1 is Learn — intArg 1 starts listening (clears the histogram), 0 stops and sets Key + Scale (Major / Minor) to the best match and Key Source to Manual, 2 cancels. Nota Beat Repeat (kind 11): id 0 resets (stops the repeat, clears the timeline, the meters and the burst count); id 1 fires a repeat now, as if the interval hit (ignores Chance; while the transport plays — to hold one, set the Repeat param to 1). Nota Ceiling (kind 14): id 0 resets the peaks (the peak and true-peak holds, the max reduction, the clip count and the 4 s level window); id 1 resets the loudness (integrated, LRA, the 60 s window) and the peaks. Nota Crush (kind 12): id 0 resets the meters (the peak holds and the spectrum average). Nota Orbit (kind 9): id 0 restarts the LFO (free run: from phase 0; with Sync on and the transport playing it stays locked to the bar), id 1 resets the meters. Nota EQ-3 (kind 16): id 0 resets the meters (the peaks and the spectrum average). Nota Forge (kind 17): id 0 restarts the LFO (free run: from phase 0) and resets the meters. Nota EQ-8 (kind 0): id 0 resets the meters (the peaks and the spectrum averages). Devices without a command ignore the call.")]
public Task DeviceAction(int trackId, int deviceIndex, [Description("Command id — see the device's list in this description")] int id,
int intArg = 0, float floatArg = 0) => Mutate(() => E.DeviceAction(trackId, deviceIndex, id, intArg, floatArg));
@@ -531,6 +531,193 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
R1(V(11) * 100), R1(Db(12)), Math.Round(V(16), 3), (int)V(17), R1(V(13)), V(23) > 0.5f, V(22) > 0.5f, V(5), spec.ToArray());
});
+ public sealed record ForgeStage(int Stage, bool On, string Type, string Role, double DrivePercent, double OutDb, double FeedbackPercent,
+ double BiasPercent, double ToneDb, double WidthPercent, double ThdPercent, string Flavor, double[] HarmonicsDb);
+ public sealed record ForgeReading(string Summary, string Live, string Routing, double AmountDb, double Wet, double OutputDb,
+ double LfoDrivePercent, double EnvTonePercent, bool LfoSync, string LfoRate, double LfoHz, string Oversampling,
+ double MasterTonePercent, double MasterBiasPercent, double MasterWidthPercent, ForgeStage[] Stages, double ThdPercent,
+ string Flavor, double[] HarmonicsDb, double[] TransferCurve, double InputPeakDb, double OutputPeakDb, double InputRmsDb,
+ double OutputRmsDb, double Lfo, double DriveModulation, double Envelope, bool AliasingWarning, int LatencySamples,
+ double CpuPercent, bool Signal, double SampleRate);
+
+ private static readonly string[] ForgeAlgos = { "Tube", "Diode", "Tape", "Fuzz", "Digital", "Fold" };
+ private static readonly string[] ForgeRoutes = { "Serial", "Parallel", "Mid/Side", "Multiband" };
+ private static readonly string[] ForgeDivs = { "2/1", "1/1", "1/2", "1/4", "1/8", "1/16", "1/32", "1/64" };
+ private static readonly string[] ForgeFlavors = { "clean", "odd-heavy", "even-heavy", "mixed" };
+
+ [McpServerTool(Name = "read_forge"), Description(
+ "Read a Nota Forge (built-in effect kind 17 — multi-stage saturator): the routing (Serial 1→2→3 / Parallel averaged / "
+ + "Mid/Side — stage 1 the Mid, 2 the Side, 3 the recombined M+S / Multiband — stage 1 < 180 Hz, 2 the mids, 3 > 2.4 kHz), "
+ + "Amount (dB into the stages), wet, output; each stage — on, type (Tube / Diode / Tape / Fuzz / Digital / Fold), its role, "
+ + "drive %, out dB, feedback %, bias %, tone dB, width % and the THD and harmonics 2..9 (dB against the fundamental) of a "
+ + "−6 dB sine through it alone; the same for the whole device (Flavor: clean / odd-heavy / even-heavy / mixed) with its "
+ + "transfer curve (output at 17 inputs from −1 to +1); the modulation (LFO → drive with its rate, env → tone) and its live "
+ + "values; the master Tone / Bias / Width offsets older projects carry; oversampling with the aliasing warning (Digital / "
+ + "Fold without it); in / out peak and RMS (dBFS, −120 while silent), latency and CPU. set_forge / set_forge_stage change "
+ + "it in units; get_device_text id 2 explains each parameter value.")]
+ public Task<ForgeReading> ReadForge(int trackId, int deviceIndex) => Read(() => ForgeRead(trackId, deviceIndex));
+
+ private ForgeReading ForgeRead(int trackId, int deviceIndex)
+ {
+ if (E.TrackDeviceBuiltinKind(trackId, deviceIndex) != 17) throw new ArgumentException("not a Nota Forge (kind 17)");
+ const int tele = 32, harm = 8, pts = 129, curveOff = tele + harm * 4;
+ var sc = new float[curveOff + pts * 8];
+ int n = E.DeviceScope(trackId, deviceIndex, sc, sc.Length);
+ float V(int i) => n > i ? sc[i] : 0f;
+ float Db(int i) => n > i ? sc[i] : -120f;
+ static double R1(double v) => Math.Round(v, 1);
+ int pc = E.DeviceParamCount(trackId, deviceIndex);
+ float Pm(int p) => p < pc ? E.DeviceGetParam(trackId, deviceIndex, p) : 0.5f;
+ int routing = Math.Clamp((int)Math.Round(Pm(6) * 3), 0, 3);
+ double[] Harm(int set) { var h = new double[harm]; for (int k = 0; k < harm; k++) h[k] = R1(n >= curveOff ? sc[tele + set * harm + k] : -120); return h; }
+ var stages = new ForgeStage[3];
+ for (int s = 0; s < 3; s++)
+ {
+ int b = 11 + s * 5, sh = 27 + s * 3;
+ string role = routing switch { 2 => new[] { "Mid", "Side", "M+S" }[s], 3 => new[] { "Low", "Mid", "High" }[s], 1 => "Parallel", _ => "Serial" };
+ stages[s] = new ForgeStage(s + 1, Pm(b + 4) >= 0.5f, ForgeAlgos[Math.Clamp((int)Math.Round(Pm(b) * 5), 0, 5)], role,
+ R1(Pm(b + 1) * 100), R1((Pm(b + 2) - 0.5) * 24), R1(Pm(b + 3) * 100), R1((Pm(sh) - 0.5) * 200), R1((Pm(sh + 1) - 0.5) * 24),
+ R1(Pm(sh + 2) * 200), R1(V(14 + s)), ForgeFlavors[Math.Clamp((int)V(18 + s), 0, 3)], Harm(s + 1));
+ }
+ var curve = new double[17];
+ for (int i = 0; i < 17; i++) curve[i] = Math.Round(n >= sc.Length ? sc[curveOff + i * 8] : 0, 3);
+ bool sync = Pm(10) >= 0.5f;
+ string rate = sync ? ForgeDivs[Math.Clamp((int)Math.Round(Pm(9) * 7), 0, 7)] : NotaNumInv($"{0.05 * Math.Pow(400, Pm(9)):0.00} Hz");
+ int os = Math.Clamp((int)Math.Round(Pm(26) * 3), 0, 3);
+ return new ForgeReading(E.DeviceText(trackId, deviceIndex, 0), E.DeviceText(trackId, deviceIndex, 1), ForgeRoutes[routing],
+ R1(Pm(0) * 30), Math.Round(Pm(2), 3), R1((Pm(3) - 0.5) * 48), R1(Pm(7) * 100), R1(Pm(8) * 100), sync, rate, Math.Round(V(25), 3),
+ os == 0 ? "Off" : $"{1 << os}x", R1((Pm(1) - 0.5) * 200), R1((Pm(4) - 0.5) * 200), R1(Pm(5) * 200), stages,
+ R1(V(13)), ForgeFlavors[Math.Clamp((int)V(17), 0, 3)], Harm(0), curve, R1(Db(0)), R1(Db(1)), R1(Db(2)), R1(Db(3)),
+ Math.Round(V(8), 3), Math.Round(V(9), 3), Math.Round(V(10), 3), V(22) > 0.5f, (int)V(6), Math.Round(V(5) * 100, 2), V(21) > 0.5f, V(4));
+ }
+
+ private static string NotaNumInv(FormattableString f) => f.ToString(System.Globalization.CultureInfo.InvariantCulture);
+
+ private void ForgeSet(int trackId, int deviceIndex, int p, double v)
+ {
+ E.BeginAutomationWrite(trackId, AutomationTarget.DeviceParam, deviceIndex, p, "");
+ E.DeviceSetParam(trackId, deviceIndex, p, (float)Math.Clamp(v, 0, 1));
+ E.EndAutomationWrite(trackId, AutomationTarget.DeviceParam, deviceIndex, p, "");
+ }
+
+ [McpServerTool(Name = "set_forge"), Description(
+ "Play a Nota Forge's globals (built-in effect kind 17) in units — only the fields you pass change; each change is recorded "
+ + "like a hand edit (so it lands in automation while recording). routing \"Serial\" | \"Parallel\" | \"MidSide\" | "
+ + "\"Multiband\"; amountDb 0..30 into the stages; wetPercent 0..100; outputDb ±24; lfoDrivePercent 0..100 (the LFO sweeps "
+ + "every stage's drive by up to ±30 %); envTonePercent 0..100 (loud parts push the tone brighter); lfoSync with lfoDivision "
+ + "\"2/1\" \"1/1\" \"1/2\" \"1/4\" \"1/8\" \"1/16\" \"1/32\" \"1/64\", or lfoHz 0.05..20 (sets free run); oversampling 1, 2, 4 "
+ + "or 8; masterTonePercent / masterBiasPercent ±100 and masterWidthPercent 0..200 are the master offsets (0 / 0 / 100 = "
+ + "neutral; the per-stage ones are in set_forge_stage). Returns the device as read back.")]
+ public Task<ForgeReading> SetForge(int trackId, int deviceIndex, string? routing = null, double? amountDb = null, double? wetPercent = null,
+ double? outputDb = null, double? lfoDrivePercent = null, double? envTonePercent = null, bool? lfoSync = null, string? lfoDivision = null,
+ double? lfoHz = null, int? oversampling = null, double? masterTonePercent = null, double? masterBiasPercent = null,
+ double? masterWidthPercent = null) => Mutate(() =>
+ {
+ if (E.TrackDeviceBuiltinKind(trackId, deviceIndex) != 17) throw new ArgumentException("not a Nota Forge (kind 17)");
+ void S(int p, double v) => ForgeSet(trackId, deviceIndex, p, v);
+ if (routing is not null)
+ {
+ int r = routing.Trim().ToLowerInvariant().Replace("/", "").Replace("-", "").Replace(" ", "") switch
+ {
+ "serial" => 0, "parallel" => 1, "midside" or "ms" => 2, "multiband" or "multi" => 3,
+ _ => throw new ArgumentException("routing must be Serial, Parallel, MidSide or Multiband"),
+ };
+ S(6, r / 3.0);
+ }
+ if (amountDb is { } a) S(0, a / 30);
+ if (wetPercent is { } w) S(2, w / 100);
+ if (outputDb is { } o) S(3, 0.5 + o / 48);
+ if (lfoDrivePercent is { } l) S(7, l / 100);
+ if (envTonePercent is { } e) S(8, e / 100);
+ if (lfoHz is { } hz) { S(10, 0); S(9, Math.Log(Math.Clamp(hz, 0.05, 20) / 0.05) / Math.Log(400)); }
+ if (lfoSync is { } sy) S(10, sy ? 1 : 0);
+ if (lfoDivision is not null)
+ {
+ int d = Array.IndexOf(ForgeDivs, lfoDivision.Trim());
+ if (d < 0) throw new ArgumentException("lfoDivision must be one of " + string.Join(", ", ForgeDivs));
+ S(10, 1); S(9, d / 7.0);
+ }
+ if (oversampling is { } os)
+ {
+ int i = os switch { 1 => 0, 2 => 1, 4 => 2, 8 => 3, _ => throw new ArgumentException("oversampling must be 1, 2, 4 or 8") };
+ S(26, i / 3.0);
+ }
+ if (masterTonePercent is { } mt) S(1, 0.5 + mt / 200);
+ if (masterBiasPercent is { } mb) S(4, 0.5 + mb / 200);
+ if (masterWidthPercent is { } mw) S(5, mw / 200);
+ return ForgeRead(trackId, deviceIndex);
+ });
+
+ [McpServerTool(Name = "set_forge_stage"), Description(
+ "Edit one Nota Forge stage (built-in effect kind 17) in units — only the fields you pass change; each change is recorded like "
+ + "a hand edit. stage 1..3; on; type \"Tube\" | \"Diode\" | \"Tape\" | \"Fuzz\" | \"Digital\" | \"Fold\"; drivePercent 0..100 "
+ + "(gain 1 … ×21, level made up); outDb ±12; feedbackPercent 0..100 (0..85 % of the output back in); biasPercent ±100 "
+ + "(asymmetry → even harmonics); toneDb ±12 (a tilt after the stage around 800 Hz); widthPercent 0..200 (the stage's "
+ + "stereo image; in Mid/Side stage 2's width scales the side). Returns the device as read back.")]
+ public Task<ForgeReading> SetForgeStage(int trackId, int deviceIndex, [Description("Stage 1..3")] int stage, bool? on = null,
+ string? type = null, double? drivePercent = null, double? outDb = null, double? feedbackPercent = null, double? biasPercent = null,
+ double? toneDb = null, double? widthPercent = null) => Mutate(() =>
+ {
+ if (E.TrackDeviceBuiltinKind(trackId, deviceIndex) != 17) throw new ArgumentException("not a Nota Forge (kind 17)");
+ if (stage is < 1 or > 3) throw new ArgumentException("stage must be 1, 2 or 3");
+ int b = 11 + (stage - 1) * 5, sh = 27 + (stage - 1) * 3;
+ void S(int p, double v) => ForgeSet(trackId, deviceIndex, p, v);
+ if (type is not null)
+ {
+ int t = Array.FindIndex(ForgeAlgos, x => string.Equals(x, type.Trim(), StringComparison.OrdinalIgnoreCase));
+ if (t < 0) throw new ArgumentException("type must be one of " + string.Join(", ", ForgeAlgos));
+ S(b, t / 5.0);
+ }
+ if (drivePercent is { } d) S(b + 1, d / 100);
+ if (outDb is { } o) S(b + 2, 0.5 + o / 24);
+ if (feedbackPercent is { } f) S(b + 3, f / 100);
+ if (on is { } en) S(b + 4, en ? 1 : 0);
+ if (biasPercent is { } bi) S(sh, 0.5 + bi / 200);
+ if (toneDb is { } tn) S(sh + 1, 0.5 + tn / 24);
+ if (widthPercent is { } w) S(sh + 2, w / 200);
+ return ForgeRead(trackId, deviceIndex);
+ });
+
+ public sealed record OrbitReading(string Summary, string Live, string Waveform, bool Sync, string Division, double RateHz, double PeriodMs,
+ double ShapeOrGlide, double PhaseDeg, string Mode, double Amount, double Mix, double FloorDb, double GainLDb, double GainRDb,
+ double Pan, double PanMin, double PanMax, double WindowPhase, bool Locked, bool Playing, double Bpm, double BarBeats,
+ double InputPeakDb, double OutputPeakLDb, double OutputPeakRDb, bool Signal, double SampleRate);
+
+ private static readonly string[] OrbitWaves = { "Sine", "Triangle", "Saw", "Square", "S&H" };
+ private static readonly string[] OrbitDivs = { "4/1", "2/1", "1/1", "1/2D", "1/2", "1/2T", "1/4D", "1/4", "1/4T", "1/8D", "1/8", "1/8T", "1/16D", "1/16", "1/16T", "1/32" };
+
+ [McpServerTool(Name = "read_orbit"), Description(
+ "Read what a Nota Orbit (built-in effect kind 9 — auto-pan / tremolo) is doing right now: the waveform, whether the rate "
+ + "is free (Hz) or synced (the division), the LFO rate and period, shape (glide on S&H), the phase between the channels "
+ + "(degrees) and the mode it makes (tremolo near 0°, auto-pan near 180°, offset pan between), amount, mix and the floor "
+ + "the gain dips to (dB); live — each channel's gain now (dB), the stereo position (−1 left … +1 right) and the swing it "
+ + "covers over two cycles, the LFO's place in its two-cycle window (0..2), whether it is locked to the song position "
+ + "(Sync + transport playing), tempo and beats per bar, input and L / R output peaks (dBFS, −120 = silence). The gains "
+ + "and levels move only while audio runs through the track. Params: 0 Rate, 1 Amount, 2 Waveform, 3 Shape, 4 Phase, "
+ + "5 Mix, 6 Sync, 7 Division — get_device_text id 2 explains each value; device_action 0 restarts the LFO, 1 resets "
+ + "the meters.")]
+ public Task<OrbitReading> ReadOrbit(int trackId, int deviceIndex) => Read(() =>
+ {
+ var sc = new float[32];
+ int n = E.DeviceScope(trackId, deviceIndex, sc, sc.Length);
+ float V(int i) => n > i ? sc[i] : 0f;
+ float Db(int i) => n > i ? sc[i] : -120f;
+ static double R1(double v) => Math.Round(v, 1);
+ static double GDb(double g) => g < 1e-3 ? -120 : Math.Round(20 * Math.Log10(g), 1);
+ float Pm(int p) => E.DeviceGetParam(trackId, deviceIndex, p);
+ int wave = Math.Clamp((int)Math.Round(Pm(2) * 4), 0, 4);
+ int div = Math.Clamp((int)Math.Round(Pm(7) * 15), 0, 15);
+ double deg = Math.Round(Pm(4) * 360);
+ string mode = deg <= 15 || deg >= 345 ? "tremolo" : Math.Abs(deg - 180) <= 15 ? "auto-pan" : "offset pan";
+ double rate = V(7);
+ return new OrbitReading(E.DeviceText(trackId, deviceIndex, 0), E.DeviceText(trackId, deviceIndex, 1),
+ OrbitWaves[wave], Pm(6) >= 0.5f, OrbitDivs[div], Math.Round(rate, 3), rate > 0 ? Math.Round(1000 / rate) : 0,
+ Math.Round(Pm(3), 3), deg, mode, Math.Round(Pm(1), 3), Math.Round(Pm(5), 3), GDb(1 - Pm(1) * Pm(5)),
+ GDb(n > 3 ? V(3) : 1), GDb(n > 4 ? V(4) : 1), Math.Round(V(5), 3), Math.Round(V(16), 3), Math.Round(V(17), 3),
+ Math.Round(V(6), 3), V(10) > 0.5f, V(9) > 0.5f, Math.Round(V(8), 2), V(19), R1(Db(0)), R1(Db(1)), R1(Db(2)),
+ V(21) > 0.5f, V(11));
+ });
+
public sealed record DynEqBand(int Band, bool On, string Type, double FreqHz, double GainDb, double Q, string Mode, double ThresholdDb,
double RangeDb, double AttackMs, double ReleaseMs, string Key, bool Dynamic, double LevelDb, double GainNowDb, double ResponseDb);
public sealed record DynEqSpectrumBand(double Hz, double Db);
diff --git a/src/native/nota.engine/src/AutoPan.h b/src/native/nota.engine/src/AutoPan.h
index 18b3b783..84689e94 100644
--- a/src/native/nota.engine/src/AutoPan.h
+++ b/src/native/nota.engine/src/AutoPan.h
@@ -1,81 +1,256 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Built-in Nota Auto Pan (device kind 9) — a classic LFO-panner-style modulation
-// insert: one LFO drives per-channel amplitude, and a Phase offset between the left
-// and right LFOs sweeps continuously from tremolo (0°, both channels dip together)
-// to auto-pan (180°, one channel loud while the other is quiet). Waveform selectable
-// (Sine / Triangle / Saw / Square / S&H), a Shape control sharpens the smooth waves
-// toward square, Amount sets depth, Mix blends dry/wet.
+// Built-in Nota Orbit (device kind 9, formerly Auto Pan) — auto-pan and tremolo on one LFO:
+// the LFO drives each channel's amplitude, and a Phase offset between the left and right LFOs
+// sweeps continuously from tremolo (0°, both channels dip together) to auto-pan (180°, one
+// channel loud while the other is quiet). Waveform Sine / Triangle / Saw / Square / S&H;
+// Shape sharpens the smooth waves toward a square and, on S&H, is the glide between steps;
+// Amount sets the depth, Mix blends dry / wet.
//
-// The live stereo position is published via gainReductionDb() (a free per-device
-// scalar the UI reads lock-free) so the editor's viz dot tracks the pan in real time.
-// Header-only, allocation-free, JUCE-free. Params normalized 0..1 → persist / clone /
-// automation flow generically through the base Device.
+// rate: Free (Rate, 0.01..40 Hz) or Sync (Division, 4/1 … 1/32 incl. dotted and triplets).
+// In Sync the LFO locks to the song position while the transport plays and restarts on the
+// bar (a cycle longer than a bar restarts on the span of bars that holds it); stopped, it
+// free-runs at the synced rate.
+//
+// S&H steps come from a hash of the cycle index, so the right channel plays the same random
+// line as the left, Phase later — at 0° the steps move both channels together (a random
+// tremolo), at 180° they pan. The channel gains are slewed over ~1 ms so a Square or a
+// transport jump doesn't click.
+//
+// All params are normalized 0..1 and APPEND ONLY: 0..5 are the original layout; Sync and
+// Division are appended and default to Free, so older projects open unchanged. Persistence /
+// automation / clone flow generically through the base Device.
+// Telemetry (scopeRead): kTele live values (levels, the gains now, the pan, the LFO's place in
+// its two-cycle window, the S&H steps around it, the rate, the tempo).
+// deviceText: 0 = status line, 1 = live reading, 2 = parameter guide.
+// deviceAction: 0 = restart the LFO (free run: from phase 0), 1 = reset the meters.
+// The live stereo position (0 = left … 1 = right) also stays on gainReductionDb().
+// Header-only, allocation-free, JUCE-free.
#pragma once
#include "Device.h"
+#include "TransportInfo.h"
#include <algorithm>
#include <atomic>
+#include <chrono>
#include <cmath>
#include <cstdint>
+#include <cstdio>
+#include <string>
namespace nota {
class AutoPan : public Device {
public:
// Param layout — order is the persisted/automation layout. APPEND ONLY.
- enum { Rate = 0, Amount, Waveform, Shape, Phase, Mix, kNumParams };
+ enum { Rate = 0, Amount, Waveform, Shape, Phase, Mix, Sync, Division, kNumParams };
+
+ // Telemetry slots (scopeRead).
+ enum {
+ S_InPeak = 0, // input peak (300 ms fall), dBFS
+ S_OutPeakL, // output peak, left (300 ms fall), dBFS
+ S_OutPeakR, // output peak, right, dBFS
+ S_GainL, // the left gain now (after Mix), linear 0..1
+ S_GainR, // the right gain now, linear
+ S_Pan, // the stereo position now, (gR − gL) / (gR + gL): −1 left … +1 right
+ S_WinPhase, // the LFO's place in its two-cycle window, 0..2 (cycles)
+ S_RateHz, // the LFO rate now, Hz (Sync: from the tempo)
+ S_Bpm, // the tempo the Sync rate follows
+ S_Playing, // 1 while the transport plays
+ S_Locked, // 1 while Sync is on and the LFO is locked to the song position
+ S_SampleRate,
+ S_Sh0, // the S&H steps of the cycles window−1, window, window+1, window+2 (−1..1)
+ S_Sh1,
+ S_Sh2,
+ S_Sh3,
+ S_PanMin, // the pan's swing over the window, −1..1
+ S_PanMax,
+ S_DivBeats, // the Sync division, beats per cycle
+ S_BarBeats, // beats per bar (the restart span's unit)
+ S_Cpu, // share of real time spent in process()
+ S_Signal, // 1 while signal comes in (above −70 dBFS)
+ S_Floor, // the lowest gain (1 − Amount·Mix), linear
+ S_Cycles, // LFO cycles since load / the last restart (free run) or the song cycle (Sync)
+ kTele = 32
+ };
+
+ static constexpr int kDivs = 16;
+ // Sync divisions, slowest → fastest: beats per cycle, and their names.
+ static constexpr double kDivBeats[kDivs] = { 16.0, 8.0, 4.0, 3.0, 2.0, 4.0 / 3.0, 1.5, 1.0, 2.0 / 3.0, 0.75,
+ 0.5, 1.0 / 3.0, 0.375, 0.25, 1.0 / 6.0, 0.125 };
+ static constexpr const char* kDivNames[kDivs] = { "4/1", "2/1", "1/1", "1/2D", "1/2", "1/2T", "1/4D", "1/4", "1/4T",
+ "1/8D", "1/8", "1/8T", "1/16D", "1/16", "1/16T", "1/32" };
+ static constexpr int kDefaultDiv = 10; // 1/8
AutoPan() {
- p_[Rate].store(0.60f); // ~1.5 Hz
+ p_[Rate].store(0.60f); // ~1.45 Hz
p_[Amount].store(0.70f);
p_[Waveform].store(0.0f); // Sine
p_[Shape].store(0.0f); // smooth
p_[Phase].store(0.5f); // 180° → classic auto-pan
p_[Mix].store(1.0f);
+ p_[Sync].store(0.0f); // Free (Hz)
+ p_[Division].store((float)kDefaultDiv / (kDivs - 1));
+ setSampleRate(44100.0, 0);
}
void setSampleRate(double sr, int32_t /*maxBlock*/) override {
sr_ = sr > 0 ? sr : 44100.0;
- phase_ = 0.0; shHeldL_ = shHeldR_ = 0.0f; lastCycle_ = -1;
+ srA_.store((float)sr_, std::memory_order_relaxed);
+ cycle_ = 0; frac_ = 0.0;
+ gLs_ = gRs_ = -1.0f; // snap to the first target
+ resetMeters();
+ }
+
+ // Musical clock for Sync (engine calls this before process()).
+ void setTransport(double beatStart, double spb, bool playing) override {
+ beatStart_ = beatStart; spb_ = spb > 0 ? spb : 0.0; playing_ = playing;
+ }
+ void setTransportInfo(const TransportInfo& ti) override {
+ if (ti.tsNum > 0 && ti.tsDenom > 0) barBeats_ = std::clamp(ti.tsNum * 4.0 / ti.tsDenom, 0.5, 64.0);
}
- // Live stereo position (0 = hard left, 0.5 = centre, 1 = hard right) for the UI dot.
+ // Live stereo position (0 = hard left, 0.5 = centre, 1 = hard right) — the old pan dot's feed.
float gainReductionDb() const override { return panPos_.load(std::memory_order_relaxed); }
void process(float* buf, int32_t frames) override {
- const double rateHz = expMap(get(Rate), 0.01, 40.0);
+ const auto t0 = std::chrono::steady_clock::now();
+ if (restartReq_.exchange(false, std::memory_order_acquire)) { cycle_ = 0; frac_ = 0.0; }
+ if (resetReq_.exchange(false, std::memory_order_acquire)) resetMeters();
+
const float amount = std::clamp(get(Amount), 0.0f, 1.0f);
- const int wave = std::clamp((int)std::lround(get(Waveform) * 4.0f), 0, 4);
+ const int wave = waveIndex();
const float shape = std::clamp(get(Shape), 0.0f, 1.0f);
- const double phOff = std::clamp(get(Phase), 0.0f, 1.0f); // 0..1 cycle → 0..360°
+ const double phOff = std::clamp((double)get(Phase), 0.0, 1.0); // 0..1 cycle → 0..360°
const float mix = std::clamp(get(Mix), 0.0f, 1.0f);
+ const bool sync = get(Sync) >= 0.5f;
+ const double div = kDivBeats[divIndex()];
+ const double spb = spb_ > 0.0 ? spb_ : sr_ * 0.5; // 120 BPM until the engine says otherwise
+ const double rateHz = sync ? sr_ / (spb * div) : expMap(get(Rate), 0.01, 40.0);
const double inc = rateHz / sr_;
+ const bool locked = sync && playing_ && spb_ > 0.0;
+ // The restart span: the bar, or as many bars as a cycle longer than one needs.
+ const double span = barBeats_ * std::max(1.0, std::ceil(div / barBeats_ - 1e-9));
+ const float slew = 1.0f - std::exp(-1.0f / (0.001f * (float)sr_)); // ~1 ms
+ float inPk = 0.0f, outPkL = 0.0f, outPkR = 0.0f;
for (int32_t i = 0; i < frames; ++i) {
- // Sample & hold refreshes once per LFO cycle (independent L/R draws).
- const int cyc = (int)phase_;
- if (wave == 4 && cyc != lastCycle_) { shHeldL_ = whiteBip(); shHeldR_ = whiteBip(); lastCycle_ = cyc; }
+ if (locked) {
+ const double beat = beatStart_ + (double)i / spb_;
+ const double spans = std::floor(beat / span);
+ const double c = (beat - spans * span) / div;
+ const double k = std::floor(c);
+ cycle_ = (int64_t)spans * 4096 + (int64_t)k;
+ frac_ = c - k;
+ }
- const double phL = frac(phase_);
- const double phR = frac(phase_ + phOff);
- const float lfoL = lfo(wave, phL, shape, shHeldL_);
- const float lfoR = lfo(wave, phR, shape, shHeldR_);
+ const float lfoL = lfoAt(wave, shape, cycle_, frac_);
+ const double fr = frac_ + phOff;
+ const float lfoR = fr >= 1.0 ? lfoAt(wave, shape, cycle_ + 1, fr - 1.0) : lfoAt(wave, shape, cycle_, fr);
- // Amplitude gain per channel: lfo=+1 → full, lfo=-1 → (1 - amount).
- const float gL = 1.0f - amount * 0.5f * (1.0f - lfoL);
- const float gR = 1.0f - amount * 0.5f * (1.0f - lfoR);
+ // Amplitude per channel: lfo = +1 → full, lfo = −1 → (1 − amount); Mix blends toward 1.
+ const float tL = 1.0f - mix * amount * 0.5f * (1.0f - lfoL);
+ const float tR = 1.0f - mix * amount * 0.5f * (1.0f - lfoR);
+ if (gLs_ < 0.0f) { gLs_ = tL; gRs_ = tR; }
+ gLs_ += slew * (tL - gLs_);
+ gRs_ += slew * (tR - gRs_);
const float dryL = buf[i * 2], dryR = buf[i * 2 + 1];
- buf[i * 2] = dryL * (1.0f - mix) + dryL * gL * mix;
- buf[i * 2 + 1] = dryR * (1.0f - mix) + dryR * gR * mix;
+ inPk = std::max(inPk, std::max(std::fabs(dryL), std::fabs(dryR)));
+ const float oL = dryL * gLs_, oR = dryR * gRs_;
+ buf[i * 2] = oL; buf[i * 2 + 1] = oR;
+ outPkL = std::max(outPkL, std::fabs(oL));
+ outPkR = std::max(outPkR, std::fabs(oR));
+
+ if (!locked) {
+ frac_ += inc;
+ if (frac_ >= 1.0) { const double w = std::floor(frac_); frac_ -= w; cycle_ += (int64_t)w; }
+ }
+ }
+
+ if (frames > 0) {
+ const float fall = std::pow(10.0f, -(20.0f * frames / (0.3f * (float)sr_)) / 20.0f);
+ inPkM_ = std::max(inPk, inPkM_ * fall);
+ outPkLM_ = std::max(outPkL, outPkLM_ * fall);
+ outPkRM_ = std::max(outPkR, outPkRM_ * fall);
+ }
+ const float gL = gLs_ < 0.0f ? 1.0f : gLs_, gR = gRs_ < 0.0f ? 1.0f : gRs_;
+ inPkA_.store(db(inPkM_), std::memory_order_relaxed);
+ outPkLA_.store(db(outPkLM_), std::memory_order_relaxed);
+ outPkRA_.store(db(outPkRM_), std::memory_order_relaxed);
+ gainLA_.store(gL, std::memory_order_relaxed);
+ gainRA_.store(gR, std::memory_order_relaxed);
+ panPos_.store(0.5f + 0.5f * (gR - gL), std::memory_order_relaxed);
+ cycleA_.store(cycle_, std::memory_order_relaxed);
+ fracA_.store((float)frac_, std::memory_order_relaxed);
+ rateA_.store((float)rateHz, std::memory_order_relaxed);
+ bpmA_.store((float)(60.0 * sr_ / spb), std::memory_order_relaxed);
+ playingA_.store(playing_ ? 1 : 0, std::memory_order_relaxed);
+ lockedA_.store(locked ? 1 : 0, std::memory_order_relaxed);
+ barA_.store((float)barBeats_, std::memory_order_relaxed);
+ if (frames > 0) {
+ const double el = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
+ cpuS_ = cpuS_ * 0.9 + (el / (frames / sr_)) * 0.1;
+ cpuA_.store((float)cpuS_, std::memory_order_relaxed);
+ }
+ }
- phase_ += inc; if (phase_ >= 1.0e7) phase_ = frac(phase_); // keep the cycle counter bounded
- panPos_.store(0.5f + 0.5f * (gR - gL), std::memory_order_relaxed);
+ enum { A_Restart = 0, A_ResetMeters = 1 }; // deviceAction ids
+ void deviceAction(int32_t id, int32_t /*iarg*/, float /*farg*/) override {
+ if (id == A_Restart) restartReq_.store(true, std::memory_order_release);
+ else if (id == A_ResetMeters) resetReq_.store(true, std::memory_order_release);
+ }
+
+ // Telemetry block. Called from the UI / MCP thread; lock-free against audio.
+ int32_t scopeRead(float* out, int32_t maxSamples) const override {
+ if (!out || maxSamples <= 0) return 0;
+ float t[kTele] = {};
+ const int64_t cyc = cycleA_.load(std::memory_order_relaxed);
+ const double fr = fracA_.load(std::memory_order_relaxed);
+ const int64_t base = cyc - (((cyc % 2) + 2) % 2); // the window starts on an even cycle
+ t[S_InPeak] = inPkA_.load(std::memory_order_relaxed);
+ t[S_OutPeakL] = outPkLA_.load(std::memory_order_relaxed);
+ t[S_OutPeakR] = outPkRA_.load(std::memory_order_relaxed);
+ t[S_GainL] = gainLA_.load(std::memory_order_relaxed);
+ t[S_GainR] = gainRA_.load(std::memory_order_relaxed);
+ t[S_Pan] = panOf(t[S_GainL], t[S_GainR]);
+ t[S_WinPhase] = (float)((double)(cyc - base) + fr);
+ t[S_RateHz] = rateA_.load(std::memory_order_relaxed);
+ t[S_Bpm] = bpmA_.load(std::memory_order_relaxed);
+ t[S_Playing] = (float)playingA_.load(std::memory_order_relaxed);
+ t[S_Locked] = (float)lockedA_.load(std::memory_order_relaxed);
+ t[S_SampleRate] = srA_.load(std::memory_order_relaxed);
+ for (int k = 0; k < 4; ++k) t[S_Sh0 + k] = hashBip(base - 1 + k);
+ t[S_DivBeats] = (float)kDivBeats[divIndex()];
+ t[S_BarBeats] = barA_.load(std::memory_order_relaxed);
+ t[S_Cpu] = cpuA_.load(std::memory_order_relaxed);
+ t[S_Signal] = t[S_InPeak] > -70.0f ? 1.0f : 0.0f;
+ t[S_Floor] = 1.0f - std::clamp(get(Amount), 0.0f, 1.0f) * std::clamp(get(Mix), 0.0f, 1.0f);
+ t[S_Cycles] = (float)cyc;
+
+ // The pan's swing over the two-cycle window (the S&H window uses its own steps).
+ const int wave = waveIndex();
+ const float amount = get(Amount), mix = get(Mix), shape = get(Shape);
+ const double off = std::clamp((double)get(Phase), 0.0, 1.0);
+ float mn = 1.0f, mx = -1.0f;
+ for (int s = 0; s < 128; ++s) {
+ const double p = s / 64.0;
+ const int64_t k = (int64_t)std::floor(p);
+ const double f = p - (double)k, f2 = f + off;
+ const float l = lfoAt(wave, shape, base + k, f);
+ const float r = f2 >= 1.0 ? lfoAt(wave, shape, base + k + 1, f2 - 1.0) : lfoAt(wave, shape, base + k, f2);
+ const float gl = 1.0f - mix * amount * 0.5f * (1.0f - l), gr = 1.0f - mix * amount * 0.5f * (1.0f - r);
+ const float pn = panOf(gl, gr);
+ mn = std::min(mn, pn); mx = std::max(mx, pn);
}
+ t[S_PanMin] = mn; t[S_PanMax] = mx;
+
+ int32_t n = 0;
+ for (int k = 0; k < kTele && n < maxSamples; ++k) out[n++] = t[k];
+ return n;
}
const char* displayName() const override { return "Nota Orbit"; }
@@ -85,7 +260,8 @@ public:
const char* paramName(int32_t i) const override {
switch (i) {
case Rate: return "Rate"; case Amount: return "Amount"; case Waveform: return "Waveform";
- case Shape: return "Shape"; case Phase: return "Phase"; case Mix: return "Mix"; default: return "";
+ case Shape: return "Shape"; case Phase: return "Phase"; case Mix: return "Mix";
+ case Sync: return "Sync"; case Division: return "Division"; default: return "";
}
}
float paramMin(int32_t /*i*/) const override { return 0.0f; }
@@ -97,40 +273,122 @@ public:
if (i >= 0 && i < kNumParams) p_[i].store(std::clamp(v, 0.0f, 1.0f), std::memory_order_relaxed);
}
+ // 0 — a one-line status; 1 — the live reading; 2 — a guide to the parameter values.
+ std::string deviceText(int32_t id) const override {
+ static const char* waves[5] = { "Sine", "Triangle", "Saw", "Square", "S&H" };
+ char b[900];
+ const double deg = std::clamp(get(Phase), 0.0f, 1.0f) * 360.0;
+ if (id == 0) {
+ std::string s = waves[waveIndex()];
+ if (get(Sync) >= 0.5f) std::snprintf(b, sizeof b, " - sync %s", kDivNames[divIndex()]);
+ else std::snprintf(b, sizeof b, " - %.2f Hz", expMap(get(Rate), 0.01, 40.0));
+ s += b;
+ std::snprintf(b, sizeof b, " - %s %.0f %% - phase %.0f deg (%s) - amount %.0f %% - mix %.0f %%",
+ waveIndex() == 4 ? "glide" : "shape", get(Shape) * 100.0f, deg, modeWord(deg),
+ get(Amount) * 100.0f, get(Mix) * 100.0f);
+ s += b;
+ return s;
+ }
+ if (id == 1) {
+ float sc[kTele];
+ scopeRead(sc, kTele);
+ auto lv = [](float v) { char t[24]; if (v <= -119.0f) std::snprintf(t, sizeof t, "-inf"); else std::snprintf(t, sizeof t, "%.1f", v); return std::string(t); };
+ auto gdb = [](float g) { char t[24]; if (g < 0.001f) std::snprintf(t, sizeof t, "-inf"); else std::snprintf(t, sizeof t, "%.1f", 20.0f * std::log10(g)); return std::string(t); };
+ std::snprintf(b, sizeof b,
+ "LFO %.2f Hz (period %.0f ms)%s - window phase %.2f of 2 cycles - gain L %s dB, R %s dB - pan %+.0f %% "
+ "(swing %+.0f .. %+.0f %%) - floor %s dB - in %s dBFS - out L %s, R %s dBFS - %.1f BPM, bar %.2g beats - "
+ "transport %s - CPU %.2f %%",
+ sc[S_RateHz], 1000.0 / std::max(1e-3f, sc[S_RateHz]),
+ sc[S_Locked] > 0.5f ? " locked to the song" : get(Sync) >= 0.5f ? " free-running at the synced rate" : "",
+ sc[S_WinPhase], gdb(sc[S_GainL]).c_str(), gdb(sc[S_GainR]).c_str(), sc[S_Pan] * 100.0f,
+ sc[S_PanMin] * 100.0f, sc[S_PanMax] * 100.0f, gdb(sc[S_Floor]).c_str(), lv(sc[S_InPeak]).c_str(),
+ lv(sc[S_OutPeakL]).c_str(), lv(sc[S_OutPeakR]).c_str(), sc[S_Bpm], sc[S_BarBeats],
+ sc[S_Playing] > 0.5f ? "playing" : "stopped", sc[S_Cpu] * 100.0f);
+ return b;
+ }
+ if (id == 2) {
+ std::string divs;
+ for (int i = 0; i < kDivs; ++i) {
+ std::snprintf(b, sizeof b, "%s%.3f = %s", i ? ", " : "", (double)i / (kDivs - 1), kDivNames[i]);
+ divs += b;
+ }
+ return "All params are normalized 0..1. Rate: the free LFO rate, exponential 0.01 Hz (0) .. 40 Hz (1) "
+ "(0.40 = 0.28 Hz, 0.60 = 1.45 Hz, 0.70 = 3.3 Hz, 0.80 = 7.6 Hz). Amount: the depth, 0..1 - each channel dips "
+ "to 1 - Amount at the LFO's low point. Waveform: 0 Sine, 0.25 Triangle, 0.5 Saw, 0.75 Square, 1 S&H "
+ "(random steps, one per cycle; the right channel plays the same steps Phase later). Shape: sharpens Sine / "
+ "Triangle / Saw toward a square (0 = pure); on S&H it is the glide between steps (0 = hard steps, 1 = a "
+ "glide over the whole cycle); Square ignores it. Phase: the right LFO's offset from the left, 0..1 = "
+ "0..360 deg - 0 = tremolo (both together), 0.5 = 180 deg auto-pan, 0.25 = 90 deg. Mix: 0 = dry .. 1 = "
+ "full effect. Sync: >= 0.5 takes the rate from the tempo (Division) and locks the LFO to the song "
+ "position while the transport plays, restarting on the bar (a 2/1 or 4/1 cycle on 2 or 4 bars). "
+ "Division (with Sync): " + divs + ".";
+ }
+ return {};
+ }
+
+ // ---- shared with the card through the guide above ----------------------------------
+ int waveIndex() const { return std::clamp((int)std::lround(get(Waveform) * 4.0f), 0, 4); }
+ int divIndex() const { return std::clamp((int)std::lround(get(Division) * (kDivs - 1)), 0, kDivs - 1); }
+
private:
static constexpr double kPi = 3.14159265358979323846;
float get(int i) const { return p_[i].load(std::memory_order_relaxed); }
static double expMap(float v, double lo, double hi) { return lo * std::pow(hi / lo, std::clamp((double)v, 0.0, 1.0)); }
- static double frac(double x) { return x - std::floor(x); }
- float whiteBip() { rng_ = rng_ * 1664525u + 1013904223u; return (float)((rng_ >> 8) & 0xFFFFFF) / 8388608.0f - 1.0f; }
+ static float db(float lin) { return lin > 1e-6f ? 20.0f * std::log10(lin) : -120.0f; }
+ static float panOf(float gl, float gr) { return (gr - gl) / std::max(gl + gr, 0.001f); }
+ static const char* modeWord(double deg) {
+ return deg <= 15.0 || deg >= 345.0 ? "tremolo" : std::fabs(deg - 180.0) <= 15.0 ? "auto-pan" : "offset pan";
+ }
- // LFO value in [-1,1] at cycle phase `ph` (0..1). Shape sharpens the smooth waves
- // toward a square; Square/S&H ignore it (S&H uses the pre-drawn held value).
- static float lfo(int wave, double ph, float shape, float held) {
+ // The S&H step of cycle k, −1..1 — a hash, so the same cycle always draws the same step.
+ static float hashBip(int64_t k) {
+ uint32_t x = (uint32_t)(uint64_t)k * 0x9E3779B9u ^ 0x53A9C1u;
+ x ^= x >> 16; x *= 0x7FEB352Du; x ^= x >> 15; x *= 0x846CA68Bu; x ^= x >> 16;
+ return (float)(x >> 8) / 8388608.0f - 1.0f;
+ }
+
+ // LFO value in [−1, 1] at cycle k, phase f (0..1). Shape sharpens the smooth waves toward
+ // a square; on S&H it is the glide from the previous step; Square ignores it.
+ static float lfoAt(int wave, float shape, int64_t k, double f) {
double v;
switch (wave) {
- case 1: v = 4.0 * std::fabs(ph - 0.5) - 1.0; break; // triangle
- case 2: v = 2.0 * ph - 1.0; break; // saw
- case 3: return ph < 0.5 ? 1.0f : -1.0f; // square
- case 4: return held; // sample & hold
- default: v = std::sin(2.0 * kPi * ph); break; // sine
+ case 1: v = 4.0 * std::fabs(f - 0.5) - 1.0; break; // triangle
+ case 2: v = 2.0 * f - 1.0; break; // saw
+ case 3: return f < 0.5 ? 1.0f : -1.0f; // square
+ case 4: { // sample & hold (+ glide)
+ const float a = hashBip(k - 1), bb = hashBip(k);
+ double t = shape > 1.0e-3f ? std::min(1.0, f / shape) : 1.0;
+ t = t * t * (3.0 - 2.0 * t);
+ return (float)(a + (bb - a) * t);
+ }
+ default: v = std::sin(2.0 * kPi * f); break; // sine
}
if (shape > 1.0e-3f) {
- const double k = 1.0 + shape * 12.0;
- const double sharp = std::tanh(k * v) / std::tanh(k);
+ const double kk = 1.0 + shape * 12.0;
+ const double sharp = std::tanh(kk * v) / std::tanh(kk);
v = v * (1.0 - shape) + sharp * shape;
}
return (float)v;
}
+ void resetMeters() { inPkM_ = outPkLM_ = outPkRM_ = 0.0f; }
+
double sr_ = 44100.0;
std::atomic<float> p_[kNumParams] = {};
- double phase_ = 0.0;
- int lastCycle_ = -1;
- float shHeldL_ = 0.0f, shHeldR_ = 0.0f;
- uint32_t rng_ = 0x53A9C1u;
+ int64_t cycle_ = 0;
+ double frac_ = 0.0;
+ float gLs_ = -1.0f, gRs_ = -1.0f;
+ double beatStart_ = 0.0, spb_ = 0.0, barBeats_ = 4.0;
+ bool playing_ = false;
+ float inPkM_ = 0.0f, outPkLM_ = 0.0f, outPkRM_ = 0.0f;
+ double cpuS_ = 0.0;
+ std::atomic<bool> restartReq_{false}, resetReq_{false};
std::atomic<float> panPos_{0.5f};
+ std::atomic<float> srA_{44100.0f}, inPkA_{-120.0f}, outPkLA_{-120.0f}, outPkRA_{-120.0f};
+ std::atomic<float> gainLA_{1.0f}, gainRA_{1.0f}, fracA_{0.0f}, rateA_{1.45f}, bpmA_{120.0f}, barA_{4.0f}, cpuA_{0.0f};
+ std::atomic<int64_t> cycleA_{0};
+ std::atomic<int> playingA_{0}, lockedA_{0};
};
} // namespace nota
diff --git a/src/native/nota.engine/src/Forge.h b/src/native/nota.engine/src/Forge.h
index b48be2c8..60a64085 100644
--- a/src/native/nota.engine/src/Forge.h
+++ b/src/native/nota.engine/src/Forge.h
@@ -1,13 +1,32 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Built-in Nota Forge (device kind 17) — a multi-stage saturation effect (mockup 3m).
-// Three saturation stages are ALL visible at once, each with its own algorithm, drive,
-// output trim and self-feedback; four routing topologies (Serial / Parallel / Mid-Side /
-// Multiband) decide how the stages combine. A global Amount drives into the chain, a Tone
-// tilt + Bias (asymmetry) + Width shape the result, and an LFO→Drive / Env→Tone modulation
-// section keeps the transfer curve moving. A core Device (JUCE-free), lock-free params —
-// all normalized 0..1, denormalized in process(); persistence/automation/clone are generic.
+// Built-in Nota Forge (device kind 17) — a multi-stage saturation effect ("Nota Forge" mockup,
+// 700 × 260). Three saturation stages are all on screen, each with its own algorithm, drive,
+// output trim, self-feedback and — since the redesign — its own shape: Bias (asymmetry), Tone
+// (a ±12 dB tilt after the stage) and Width (the stage's stereo image, 0..200 %). Four routing
+// topologies decide how the stages combine:
+// Serial 1 → 2 → 3;
+// Parallel all three from the same input, averaged;
+// Mid/Side stage 1 drives the Mid, stage 2 the Side (its Width scales the side), stage 3 the
+// recombined stereo (M+S);
+// Multiband stage 1 the lows (< 180 Hz), stage 2 the mids, stage 3 the highs (> 2.4 kHz) —
+// a stage that is off lets its band through clean.
+// A global Amount drives into the chain; Wet / Output finish it. The original global Bias /
+// Tone / Width stay as master offsets (Bias adds to every stage's bias, Tone is the post tilt
+// the Env → Tone modulation moves, Width the post image), so older projects sound the same.
+// An LFO → Drive (free Hz or tempo-synced) and an envelope → Tone keep the curve moving.
+//
+// All params are normalized 0..1 and APPEND ONLY: 0..26 are the original layout, the per-stage
+// Bias / Tone / Width (27..35) are appended and default neutral. Persistence / automation /
+// clone flow generically through the base Device.
+// Telemetry (scopeRead): kTele live values, then the harmonic spectra (chain + each stage) of a
+// −6 dB test sine through the static chain, then the transfer curves (chain + each stage,
+// static and LFO-modulated) — computed from the same shapers process() runs, so the card and
+// MCP draw exactly what is heard.
+// deviceText: 0 = status line, 1 = live reading, 2 = parameter guide.
+// deviceAction: 0 = restart the LFO and reset the meters.
+// Header-only, allocation-free after setSampleRate. JUCE-free.
#pragma once
@@ -16,8 +35,11 @@
#include <algorithm>
#include <atomic>
+#include <chrono>
#include <cmath>
#include <cstdint>
+#include <cstdio>
+#include <string>
#include <vector>
namespace nota {
@@ -29,24 +51,70 @@ public:
enum {
Amount = 0, // master input drive (0..1 → 0..+30 dB into the stages)
- Tone, // post tilt (bipolar, 0.5 = flat; + brighter / − darker)
+ Tone, // master post tilt (bipolar, 0.5 = flat; + brighter / − darker); Env → Tone moves it
Wet, // dry/wet mix (0..1)
Output, // master output gain (0.5 = 0 dB, ±24 dB)
- Bias, // shaper asymmetry (bipolar, 0.5 = symmetric)
- Width, // stereo width of the wet signal (0..1 → 0..200 %)
+ Bias, // master asymmetry, added to every stage's bias (bipolar, 0.5 = none)
+ Width, // master stereo width of the wet signal (0..1 → 0..200 %)
Routing, // 0 Serial, 1 Parallel, 2 Mid/Side, 3 Multiband
LfoDrive, // LFO → stage drive depth (0..1)
EnvTone, // envelope → tone depth (0..1)
- LfoRate, // LFO rate (exp 0.05..20 Hz free, or a synced division)
+ LfoRate, // LFO rate (exp 0.05..20 Hz free, or one of 8 synced divisions)
LfoSync, // 0 = free (Hz), 1 = tempo-synced
// per-stage block of 5 (Type, Drive, Out, FB, On), ×3
S1Type, S1Drive, S1Out, S1FB, S1On,
S2Type, S2Drive, S2Out, S2FB, S2On,
S3Type, S3Drive, S3Out, S3FB, S3On,
- Oversampling, // 0..1 → Off / 2× / 4× / 8× (appended last: keeps saved indices stable)
+ Oversampling, // 0..1 → Off / 2× / 4× / 8× (appended: keeps saved indices stable)
+ // per-stage shape block of 3 (Bias, Tone, Width), ×3 — appended by the redesign
+ S1Bias, S1Tone, S1Width,
+ S2Bias, S2Tone, S2Width,
+ S3Bias, S3Tone, S3Width,
kNumParams
};
- static constexpr double kLfoDiv[8] = { 8.0, 4.0, 2.0, 1.0, 0.5, 0.25, 0.125, 0.0625 };
+ static constexpr int kLegacyParams = Oversampling + 1; // 27: the layout before the per-stage shape
+ static constexpr double kLfoDiv[8] = { 8.0, 4.0, 2.0, 1.0, 0.5, 0.25, 0.125, 0.0625 }; // beats per cycle
+ static constexpr const char* kDivNames[8] = { "2/1", "1/1", "1/2", "1/4", "1/8", "1/16", "1/32", "1/64" };
+ static constexpr const char* kAlgoNames[kAlgos] = { "Tube", "Diode", "Tape", "Fuzz", "Digital", "Fold" };
+ static constexpr const char* kRouteNames[4] = { "serial", "parallel", "mid/side", "multiband" };
+ static constexpr double kXoLo = 180.0, kXoHi = 2400.0; // multiband crossovers (Hz)
+
+ // Telemetry slots (scopeRead).
+ enum {
+ S_InPeak = 0, // input peak, dBFS (falls 20 dB / 300 ms)
+ S_OutPeak, // output peak, dBFS
+ S_InRms, // input RMS (300 ms), dBFS
+ S_OutRms, // output RMS, dBFS
+ S_SampleRate,
+ S_Cpu, // share of real time spent in process()
+ S_Latency, // samples
+ S_OsFactor, // 1 / 2 / 4 / 8
+ S_Lfo, // live LFO value 0..1
+ S_DriveMod, // the drive offset the LFO applies now (±0.3 × depth)
+ S_Env, // envelope follower 0..1
+ S_ToneNow, // the master tilt in effect now, incl. Env → Tone (−1..+1.5)
+ S_InLevel, // input peak (linear, fast fall) — where the signal sits on the curve
+ S_ThdChain, // THD % of the −6 dB test sine through the whole device (chain)
+ S_ThdS1, S_ThdS2, S_ThdS3, // … through stage n alone (with Amount / Wet / Output)
+ S_FlavorChain, // 0 clean, 1 odd-heavy, 2 even-heavy, 3 mixed
+ S_FlavorS1, S_FlavorS2, S_FlavorS3,
+ S_Signal, // 1 when the input is above −70 dBFS
+ S_Alias, // 1 when Digital / Fold is on without oversampling (aliasing warning)
+ S_Routing, // 0..3
+ S_OnCount, // stages on
+ S_LfoHz, // the LFO rate in Hz now (synced: from the tempo)
+ S_Bpm, // tempo the synced LFO follows (0 = unknown)
+ S_AmountDb, // Amount in dB
+ S_OutputDb, // Output in dB
+ kTele = 32
+ };
+ static constexpr int kHarm = 8; // harmonics 2..9, dB relative to the fundamental
+ static constexpr int kHarmSets = 4; // chain, stage 1, stage 2, stage 3
+ static constexpr int kHarmOff = kTele;
+ static constexpr int kPts = 129; // transfer-curve points over input −1..+1
+ static constexpr int kCurves = 8; // chain, chain mod, s1, s1 mod, s2, s2 mod, s3, s3 mod
+ static constexpr int kCurveOff = kHarmOff + kHarm * kHarmSets;
+ static constexpr int kScope = kCurveOff + kPts * kCurves;
Forge() {
p_[Amount].store(0.35f); p_[Tone].store(0.5f); p_[Wet].store(1.0f); p_[Output].store(0.5f);
@@ -55,15 +123,15 @@ public:
setStage(0, 0, 0.4f, 0.5f, 0.0f, 1.0f); // Tube, on
setStage(1, 1, 0.3f, 0.5f, 0.0f, 0.0f); // Diode, off
setStage(2, 4, 0.2f, 0.5f, 0.0f, 0.0f); // Digital, off
+ p_[Oversampling].store(0.0f);
+ for (int s = 0; s < kStages; ++s) { p_[S1Bias + s * 3].store(0.5f); p_[S1Tone + s * 3].store(0.5f); p_[S1Width + s * 3].store(0.5f); }
+ setSampleRate(44100.0, 4096);
}
void setSampleRate(double sr, int32_t maxBlock) override {
sr_ = sr > 0 ? sr : 44100.0;
- for (auto& z : fb_) z = 0;
- for (auto& z : lpTone_) z = 0;
- for (auto& z : mbLo_) z = 0;
- for (auto& z : mbHi_) z = 0;
- env_ = 0; lfoPhase_ = 0;
+ srA_.store((float)sr_, std::memory_order_relaxed);
+ clearState();
maxFrames_ = maxBlock > 0 ? maxBlock : 4096;
os_.prepare(maxFrames_);
dryL_.assign(maxFrames_, 0.0f); dryR_.assign(maxFrames_, 0.0f);
@@ -74,82 +142,80 @@ public:
beatStart_ = beatStart; spb_ = spb > 0 ? spb : 0.0; playing_ = playing;
}
- // Publish the live modulated LFO value (0..1) so the UI can breathe the transfer curve.
- // Reuses the generic per-device live-scalar channel (no gain reduction on a saturator).
+ // Live LFO value (0..1) on the generic per-device live-scalar channel (kept for older readers).
float gainReductionDb() const override { return lfoLive_.load(std::memory_order_relaxed); }
void process(float* buf, int32_t frames) override {
- const float amt = std::pow(10.0f, get(Amount) * 30.0f / 20.0f); // 0..+30 dB pre-gain
+ const auto t0 = std::chrono::steady_clock::now();
+ if (resetReq_.exchange(false, std::memory_order_acquire)) {
+ lfoPhase_ = 0; inPkM_ = outPkM_ = 0; msIn_ = msOut_ = 0; inLvl_ = 0;
+ }
+ const Cfg c = cfg();
const float toneBase = (get(Tone) - 0.5f) * 2.0f; // −1..+1
- const float wet = std::clamp(get(Wet), 0.0f, 1.0f);
- const float outGain = std::pow(10.0f, (get(Output) - 0.5f) * 48.0f / 20.0f);
- const float bias = (get(Bias) - 0.5f) * 2.0f; // −1..+1
const float width = std::clamp(get(Width), 0.0f, 1.0f) * 2.0f; // 0..2
- const int routing = std::clamp((int)std::lround(get(Routing) * 3.0f), 0, 3);
const float lfoDepth = std::clamp(get(LfoDrive), 0.0f, 1.0f);
const float envDepth = std::clamp(get(EnvTone), 0.0f, 1.0f);
- // Per-stage denormalized settings.
- int type[kStages]; bool on[kStages]; float drive[kStages], outTrim[kStages], fb[kStages];
- for (int s = 0; s < kStages; ++s) {
- type[s] = std::clamp((int)std::lround(get(S1Type + s * 5) * (kAlgos - 1)), 0, kAlgos - 1);
- drive[s] = std::clamp(get(S1Drive + s * 5), 0.0f, 1.0f);
- outTrim[s] = std::pow(10.0f, (get(S1Out + s * 5) - 0.5f) * 24.0f / 20.0f);
- fb[s] = std::clamp(get(S1FB + s * 5), 0.0f, 1.0f) * 0.85f;
- on[s] = get(S1On + s * 5) >= 0.5f;
- }
-
// LFO increment (free Hz, or synced division).
const bool sync = get(LfoSync) >= 0.5f && spb_ > 0.0;
const double lfoHz = expMap(get(LfoRate), 0.05, 20.0);
- const double divBeats = kLfoDiv[std::clamp((int)std::lround(get(LfoRate) * 7.0f), 0, 7)];
+ const double divBeats = kLfoDiv[divIndex()];
const double phaseInc = lfoHz / sr_;
- // Oversampling: Off/2×/4×/8×. The nonlinear stages (which alias) run at the
- // higher rate; control (LFO/env), the tone tilt, width and dry/wet stay at
- // base. Multiband crossovers run inside the core, so their coeffs use the OS
- // rate; the post tone tilt stays at base.
- const int osIdx = std::clamp((int)std::lround(get(Oversampling) * 3.0f), 0, 3);
- const int factor = 1 << osIdx; // 1,2,4,8
+ // Oversampling: Off/2×/4×/8×. The nonlinear stages (which alias) and everything that
+ // lives between them (per-stage tilts, the multiband crossovers) run at the higher
+ // rate; control (LFO/env), the master tilt, width and dry/wet stay at base.
+ const int factor = 1 << osIndex(); // 1,2,4,8
os_.setActive(factor);
const double osr = sr_ * factor;
- // Tone tilt one-pole (~700 Hz, base rate) + env follower coeffs (base rate).
- const float toneCoef = (float)std::exp(-2.0 * 3.14159265 * 700.0 / sr_);
+ const float toneCoef = (float)std::exp(-2.0 * kPi * 700.0 / sr_); // master tilt (base rate)
const float envAtt = (float)std::exp(-1.0 / (0.005 * sr_));
const float envRel = (float)std::exp(-1.0 / (0.15 * sr_));
- // Multiband crossover one-pole coeffs (200 Hz / 2 kHz) at the oversampled rate.
- const float loCoef = (float)std::exp(-2.0 * 3.14159265 * 200.0 / osr);
- const float hiCoef = (float)std::exp(-2.0 * 3.14159265 * 2000.0 / osr);
+ const float msCoef = (float)std::exp(-1.0 / (0.3 * sr_));
+ const float lvlRel = (float)std::exp(-1.0 / (0.08 * sr_));
+ Core k;
+ k.tiltCoef = (float)std::exp(-2.0 * kPi * 800.0 / osr); // per-stage tilt pivot
+ k.loCoef = (float)std::exp(-2.0 * kPi * kXoLo / osr);
+ k.hiCoef = (float)std::exp(-2.0 * kPi * kXoHi / osr);
if (frames > maxFrames_) frames = maxFrames_;
- // --- Base-rate pre-pass: LFO/env → per-sample control, and stash the dry. ---
+ // --- Base-rate pre-pass: LFO/env → per-sample control, meters, and stash the dry. ---
+ float inPk = 0.0f;
for (int32_t i = 0; i < frames; ++i) {
double phase;
if (sync) { double beat = beatStart_ + (double)i / spb_; phase = beat / divBeats; phase -= std::floor(phase); }
else phase = lfoPhase_;
- const float lfo = (float)(0.5 + 0.5 * std::sin(2.0 * 3.14159265 * phase)); // 0..1
+ const float lfo = (float)(0.5 + 0.5 * std::sin(2.0 * kPi * phase)); // 0..1
lfoLive_.store(lfo, std::memory_order_relaxed);
- dryL_[i] = buf[i * 2]; dryR_[i] = buf[i * 2 + 1];
- const float det = std::max(std::fabs(buf[i * 2] * amt), std::fabs(buf[i * 2 + 1] * amt));
+ const float xl = buf[i * 2], xr = buf[i * 2 + 1];
+ dryL_[i] = xl; dryR_[i] = xr;
+ const float a = std::max(std::fabs(xl), std::fabs(xr));
+ inPk = std::max(inPk, a);
+ inLvl_ = a > inLvl_ ? a : a + lvlRel * (inLvl_ - a);
+ msIn_ = 0.5f * (xl * xl + xr * xr) + msCoef * (msIn_ - 0.5f * (xl * xl + xr * xr));
+ const float det = a * c.amt;
if (det > env_) env_ = det + envAtt * (env_ - det); else env_ = det + envRel * (env_ - det);
- tone_[i] = std::clamp(toneBase + envDepth * std::min(env_, 1.0f) * 1.5f, -1.5f, 1.5f);
+ tone_[i] = std::clamp(toneBase + envDepth * std::min(env_, 1.0f) * 1.5f, -1.0f, 1.5f);
driveMod_[i] = lfoDepth * (lfo - 0.5f) * 0.6f; // ±0.3 to stage drive
if (!sync) { lfoPhase_ += phaseInc; if (lfoPhase_ >= 1.0) lfoPhase_ -= 1.0; }
}
+ if (frames > 0) {
+ driveModLive_.store(driveMod_[frames - 1], std::memory_order_relaxed);
+ toneLive_.store(tone_[frames - 1], std::memory_order_relaxed);
+ }
// --- Oversampled nonlinear core: pre-gain + saturation stages. ---
os_.process(buf, frames, [&](float& l, float& r, int i) {
- l *= amt; r *= amt;
- float wl, wr;
- route(routing, l, r, type, on, drive, outTrim, fb, bias, driveMod_[i], loCoef, hiCoef, wl, wr);
- l = wl; r = wr;
+ l *= c.amt; r *= c.amt;
+ route(c, k, driveMod_[i], l, r);
});
- // --- Base-rate post: tone tilt, width, output, dry/wet. ---
+ // --- Base-rate post: master tilt, width, output, dry/wet, meters. ---
+ float outPk = 0.0f;
for (int32_t i = 0; i < frames; ++i) {
float wl = buf[i * 2], wr = buf[i * 2 + 1];
@@ -158,19 +224,38 @@ public:
wl += tone_[i] * (wl - lpTone_[0]);
wr += tone_[i] * (wr - lpTone_[1]);
- if (routing != 2) { // Mid/Side routing already worked in M/S; leave its image
+ if (c.routing != 2) { // Mid/Side routing already shaped its image
const float m = 0.5f * (wl + wr), s2 = 0.5f * (wl - wr) * width;
wl = m + s2; wr = m - s2;
}
- wl *= outGain; wr *= outGain;
- buf[i * 2] = dryL_[i] * (1.0f - wet) + wl * wet;
- buf[i * 2 + 1] = dryR_[i] * (1.0f - wet) + wr * wet;
+ wl *= c.outGain; wr *= c.outGain;
+ const float ol = dryL_[i] * (1.0f - c.wet) + wl * c.wet;
+ const float orr = dryR_[i] * (1.0f - c.wet) + wr * c.wet;
+ buf[i * 2] = ol; buf[i * 2 + 1] = orr;
+ outPk = std::max(outPk, std::max(std::fabs(ol), std::fabs(orr)));
+ msOut_ = 0.5f * (ol * ol + orr * orr) + msCoef * (msOut_ - 0.5f * (ol * ol + orr * orr));
+ }
+
+ if (frames > 0) {
+ const float fall = std::pow(10.0f, -(20.0f * frames / (0.3f * (float)sr_)) / 20.0f);
+ inPkM_ = std::max(inPk, inPkM_ * fall);
+ outPkM_ = std::max(outPk, outPkM_ * fall);
+ inPkA_.store(db(inPkM_), std::memory_order_relaxed);
+ outPkA_.store(db(outPkM_), std::memory_order_relaxed);
+ inRmsA_.store(dbMs(msIn_), std::memory_order_relaxed);
+ outRmsA_.store(dbMs(msOut_), std::memory_order_relaxed);
+ inLvlA_.store(inLvl_, std::memory_order_relaxed);
+ envA_.store(std::min(env_, 1.0f), std::memory_order_relaxed);
+ const double el = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
+ cpuS_ = cpuS_ * 0.9 + (el / (frames / sr_)) * 0.1;
+ cpuA_.store((float)cpuS_, std::memory_order_relaxed);
}
}
const char* displayName() const override { return "Nota Forge"; }
int32_t builtinKind() const override { return 17; }
+ int32_t latencySamples() const override { return os_.latencySamples(); }
int32_t paramCount() const override { return kNumParams; }
const char* paramName(int32_t i) const override {
@@ -182,6 +267,9 @@ public:
case S2Type: return "S2 Type"; case S2Drive: return "S2 Drive"; case S2Out: return "S2 Out"; case S2FB: return "S2 FB"; case S2On: return "S2 On";
case S3Type: return "S3 Type"; case S3Drive: return "S3 Drive"; case S3Out: return "S3 Out"; case S3FB: return "S3 FB"; case S3On: return "S3 On";
case Oversampling: return "Oversampling";
+ case S1Bias: return "S1 Bias"; case S1Tone: return "S1 Tone"; case S1Width: return "S1 Width";
+ case S2Bias: return "S2 Bias"; case S2Tone: return "S2 Tone"; case S2Width: return "S2 Width";
+ case S3Bias: return "S3 Bias"; case S3Tone: return "S3 Tone"; case S3Width: return "S3 Width";
default: return "";
}
}
@@ -190,8 +278,12 @@ public:
float getParam(int32_t i) const override { return (i >= 0 && i < kNumParams) ? p_[i].load(std::memory_order_relaxed) : 0.0f; }
void setParam(int32_t i, float v) override { if (i >= 0 && i < kNumParams) p_[i].store(std::clamp(v, 0.0f, 1.0f), std::memory_order_relaxed); }
- // Static saturation transfer used by the UI curve/harmonics (kept in sync with process()).
- // driveN/biasN are the normalized params; x is the pre-gained input.
+ void deviceAction(int32_t id, int32_t /*iarg*/, float /*farg*/) override {
+ if (id == 0) resetReq_.store(true, std::memory_order_release);
+ }
+
+ // Static saturation transfer (kept in sync with process()). x is the pre-gained input,
+ // bias the combined bias −1..+1.
static float shape(int type, float x, float bias) {
const float b = bias * 0.6f;
switch (type) {
@@ -205,75 +297,334 @@ public:
}
static float driveGain(float driveN) { return 1.0f + driveN * driveN * 20.0f; }
+ // ---- telemetry -------------------------------------------------------------------------
+ int32_t scopeRead(float* out, int32_t maxSamples) const override {
+ if (!out || maxSamples <= 0) return 0;
+ float t[kScope] = {};
+ const Cfg c = cfg();
+ t[S_InPeak] = inPkA_.load(std::memory_order_relaxed);
+ t[S_OutPeak] = outPkA_.load(std::memory_order_relaxed);
+ t[S_InRms] = inRmsA_.load(std::memory_order_relaxed);
+ t[S_OutRms] = outRmsA_.load(std::memory_order_relaxed);
+ t[S_SampleRate] = srA_.load(std::memory_order_relaxed);
+ t[S_Cpu] = cpuA_.load(std::memory_order_relaxed);
+ t[S_Latency] = (float)latencySamples();
+ t[S_OsFactor] = (float)(1 << osIndex());
+ t[S_Lfo] = lfoLive_.load(std::memory_order_relaxed);
+ const float mod = driveModLive_.load(std::memory_order_relaxed);
+ t[S_DriveMod] = mod;
+ t[S_Env] = envA_.load(std::memory_order_relaxed);
+ t[S_ToneNow] = toneLive_.load(std::memory_order_relaxed);
+ t[S_InLevel] = inLvlA_.load(std::memory_order_relaxed);
+ t[S_Signal] = t[S_InPeak] > -70.0f ? 1.0f : 0.0f;
+ t[S_Alias] = aliasing(c) ? 1.0f : 0.0f;
+ t[S_Routing] = (float)c.routing;
+ t[S_OnCount] = (float)onCount(c);
+ const bool sync = get(LfoSync) >= 0.5f;
+ const double bpm = spb_ > 0.0 ? 60.0 * sr_ / spb_ : 0.0;
+ t[S_LfoHz] = (float)(sync ? (bpm > 0 ? bpm / 60.0 / kLfoDiv[divIndex()] : 0.0) : expMap(get(LfoRate), 0.05, 20.0));
+ t[S_Bpm] = (float)bpm;
+ t[S_AmountDb] = get(Amount) * 30.0f;
+ t[S_OutputDb] = (get(Output) - 0.5f) * 48.0f;
+
+ // Harmonics: chain + each stage alone, the master and stage tilts leaning the partials.
+ const float masterTiltDb = 20.0f * std::log10(std::max(0.06f, 1.0f + t[S_ToneNow]));
+ float chainTilt = 0.0f; int n = 0;
+ for (int s = 0; s < kStages; ++s) if (c.on[s]) { chainTilt += c.toneDb[s]; ++n; }
+ if (c.routing == 1 && n > 0) chainTilt /= (float)n;
+ float odd, even;
+ t[S_ThdChain] = harmonics([&](float x) { return chainStatic(c, x, 0.0f); }, masterTiltDb + chainTilt, t + kHarmOff, odd, even);
+ t[S_FlavorChain] = (float)flavor(t[S_ThdChain], odd, even);
+ for (int s = 0; s < kStages; ++s) {
+ t[S_ThdS1 + s] = harmonics([&](float x) { return stageFull(c, s, x, 0.0f); }, masterTiltDb + c.toneDb[s],
+ t + kHarmOff + kHarm * (s + 1), odd, even);
+ t[S_FlavorS1 + s] = (float)flavor(t[S_ThdS1 + s], odd, even);
+ }
+
+ // Transfer curves over input −1..+1: static and with the live LFO drive offset.
+ for (int i = 0; i < kPts; ++i) {
+ const float x = -1.0f + 2.0f * (float)i / (float)(kPts - 1);
+ float* cv = t + kCurveOff;
+ cv[0 * kPts + i] = chainStatic(c, x, 0.0f);
+ cv[1 * kPts + i] = chainStatic(c, x, mod);
+ for (int s = 0; s < kStages; ++s) {
+ cv[(2 + s * 2) * kPts + i] = stageFull(c, s, x, 0.0f);
+ cv[(3 + s * 2) * kPts + i] = stageFull(c, s, x, mod);
+ }
+ }
+ const int n2 = std::min<int32_t>(maxSamples, kScope);
+ for (int i = 0; i < n2; ++i) out[i] = std::isfinite(t[i]) ? t[i] : 0.0f;
+ return n2;
+ }
+
+ std::string deviceText(int32_t id) const override {
+ const Cfg c = cfg();
+ char b[1200];
+ if (id == 0) {
+ std::string s = kRouteNames[c.routing];
+ std::snprintf(b, sizeof b, " - amount +%.1f dB - wet %.0f %% - output %+.1f dB", get(Amount) * 30.0f, c.wet * 100.0f,
+ (get(Output) - 0.5f) * 48.0f);
+ s += b;
+ for (int st = 0; st < kStages; ++st) {
+ if (!c.on[st]) { std::snprintf(b, sizeof b, " - S%d off", st + 1); s += b; continue; }
+ std::snprintf(b, sizeof b, " - S%d %s%s drive %.0f %%", st + 1, kAlgoNames[c.type[st]], roleWord(c.routing, st),
+ get(S1Drive + st * 5) * 100.0f);
+ s += b;
+ if (std::fabs(get(S1Out + st * 5) - 0.5f) > 0.002f) { std::snprintf(b, sizeof b, " out %+.1f dB", (get(S1Out + st * 5) - 0.5f) * 24.0f); s += b; }
+ if (get(S1FB + st * 5) > 0.005f) { std::snprintf(b, sizeof b, " fb %.0f %%", get(S1FB + st * 5) * 100.0f); s += b; }
+ if (std::fabs(get(S1Bias + st * 3) - 0.5f) > 0.002f) { std::snprintf(b, sizeof b, " bias %+.0f %%", (get(S1Bias + st * 3) - 0.5f) * 200.0f); s += b; }
+ if (std::fabs(c.toneDb[st]) > 0.05f) { std::snprintf(b, sizeof b, " tone %+.1f dB", c.toneDb[st]); s += b; }
+ if (std::fabs(c.width[st] - 1.0f) > 0.005f) { std::snprintf(b, sizeof b, " width %.0f %%", c.width[st] * 100.0f); s += b; }
+ }
+ if (get(LfoDrive) > 0.005f) {
+ std::snprintf(b, sizeof b, " - LFO -> drive %.0f %% at %s", get(LfoDrive) * 100.0f, rateText().c_str()); s += b;
+ }
+ if (get(EnvTone) > 0.005f) { std::snprintf(b, sizeof b, " - env -> tone %.0f %%", get(EnvTone) * 100.0f); s += b; }
+ if (std::fabs(get(Tone) - 0.5f) > 0.002f) { std::snprintf(b, sizeof b, " - master tone %+.0f %%", (get(Tone) - 0.5f) * 200.0f); s += b; }
+ if (std::fabs(get(Bias) - 0.5f) > 0.002f) { std::snprintf(b, sizeof b, " - master bias %+.0f %%", (get(Bias) - 0.5f) * 200.0f); s += b; }
+ if (std::fabs(get(Width) - 0.5f) > 0.002f) { std::snprintf(b, sizeof b, " - master width %.0f %%", get(Width) * 200.0f); s += b; }
+ std::snprintf(b, sizeof b, " - oversampling %s", osIndex() == 0 ? "off" : (std::to_string(1 << osIndex()) + "x").c_str());
+ s += b;
+ if (aliasing(c)) s += " (Digital / Fold without oversampling aliases)";
+ return s;
+ }
+ if (id == 1) {
+ float sc[kCurveOff];
+ scopeRead(sc, kCurveOff);
+ auto lv = [](float v) { char t[24]; if (v <= -119.0f) std::snprintf(t, sizeof t, "-inf"); else std::snprintf(t, sizeof t, "%.1f", v); return std::string(t); };
+ static const char* fl[4] = { "clean", "odd-heavy", "even-heavy", "mixed" };
+ std::snprintf(b, sizeof b,
+ "in %s dBFS peak / %s RMS - out %s dBFS peak / %s RMS - THD (-6 dB sine) %.1f %% %s "
+ "(S1 %.1f %%, S2 %.1f %%, S3 %.1f %%) - LFO %.2f (drive %+.2f) at %.2f Hz - envelope %.2f - "
+ "master tilt %+.2f - oversampling %.0fx, latency %.0f smp - CPU %.2f %%",
+ lv(sc[S_InPeak]).c_str(), lv(sc[S_InRms]).c_str(), lv(sc[S_OutPeak]).c_str(), lv(sc[S_OutRms]).c_str(),
+ sc[S_ThdChain], fl[std::clamp((int)sc[S_FlavorChain], 0, 3)], sc[S_ThdS1], sc[S_ThdS2], sc[S_ThdS3],
+ sc[S_Lfo], sc[S_DriveMod], sc[S_LfoHz], sc[S_Env], sc[S_ToneNow], sc[S_OsFactor], sc[S_Latency], sc[S_Cpu] * 100.0f);
+ return b;
+ }
+ if (id == 2) {
+ return "All params are normalized 0..1. Amount: 0..+30 dB into the stages (0.35 = +10.5 dB). Wet: dry/wet. "
+ "Output: -24..+24 dB (0.5 = 0 dB). Routing: 0 Serial (1 -> 2 -> 3), 0.333 Parallel (averaged), 0.667 "
+ "Mid/Side (S1 = Mid, S2 = Side, S3 = the recombined M+S), 1 Multiband (S1 < 180 Hz, S2 mids, S3 > 2.4 kHz; "
+ "a stage that is off passes its band clean). Per stage n (1..3): Sn Type round(v*5): 0 Tube, 0.2 Diode, "
+ "0.4 Tape, 0.6 Fuzz, 0.8 Digital, 1 Fold; Sn Drive 0..1 (gain 1 + 20 v^2, auto-makeup); Sn Out -12..+12 dB "
+ "(0.5 = 0); Sn FB self-feedback 0..85 %; Sn On >= 0.5; Sn Bias asymmetry -100..+100 % (0.5 = none); Sn Tone "
+ "a tilt after the stage, -12..+12 dB (0.5 = flat); Sn Width the stage's stereo image 0..200 % (0.5 = 100 %; "
+ "in Mid/Side, S2's width scales the side). Master offsets: Bias adds to every stage's bias, Tone is the post "
+ "tilt (0.5 = flat) that Env Tone pushes brighter on loud parts, Width the post image 0..200 %. LFO Drive: "
+ "LFO -> every stage's drive, up to +-0.3. LFO Rate: free 0.05..20 Hz exponential, or with LFO Sync >= 0.5 "
+ "a division round(v*7): 2/1, 1/1, 1/2, 1/4, 1/8, 1/16, 1/32, 1/64 (0.43 = 1/4). Oversampling round(v*3): "
+ "Off, 2x, 4x, 8x (0 latency, minimum phase).";
+ }
+ return {};
+ }
+
private:
+ static constexpr double kPi = 3.14159265358979323846;
+
+ struct Cfg {
+ int type[kStages] = {};
+ bool on[kStages] = {};
+ float drive[kStages] = {}, trim[kStages] = {}, fb[kStages] = {}, bias[kStages] = {};
+ float toneDb[kStages] = {}, lowG[kStages] = {}, highG[kStages] = {}, width[kStages] = {};
+ float amt = 1, wet = 1, outGain = 1;
+ int routing = 0;
+ };
+ struct Core { float tiltCoef = 0, loCoef = 0, hiCoef = 0; };
+
float get(int i) const { return p_[i].load(std::memory_order_relaxed); }
static double expMap(float v, double lo, double hi) { return lo * std::pow(hi / lo, std::clamp((double)v, 0.0, 1.0)); }
+ static float db(float lin) { return lin > 1e-6f ? 20.0f * std::log10(lin) : -120.0f; }
+ static float dbMs(float ms) { return ms > 1e-12f ? 10.0f * std::log10(ms) : -120.0f; }
+ int divIndex() const { return std::clamp((int)std::lround(get(LfoRate) * 7.0f), 0, 7); }
+ int osIndex() const { return std::clamp((int)std::lround(get(Oversampling) * 3.0f), 0, 3); }
void setStage(int s, float type, float drive, float out, float fb, float on) {
p_[S1Type + s * 5].store(type / (kAlgos - 1)); p_[S1Drive + s * 5].store(drive);
p_[S1Out + s * 5].store(out); p_[S1FB + s * 5].store(fb); p_[S1On + s * 5].store(on);
}
+ void clearState() {
+ for (auto& z : fb_) z = 0;
+ for (auto& z : tilt_) z = 0;
+ for (auto& z : lpTone_) z = 0;
+ for (auto& z : mbLo_) z = 0;
+ for (auto& z : mbHi_) z = 0;
+ env_ = 0; lfoPhase_ = 0; inPkM_ = outPkM_ = 0; msIn_ = msOut_ = 0; inLvl_ = 0;
+ }
+
+ Cfg cfg() const {
+ Cfg c;
+ const float masterBias = (get(Bias) - 0.5f) * 2.0f;
+ for (int s = 0; s < kStages; ++s) {
+ c.type[s] = std::clamp((int)std::lround(get(S1Type + s * 5) * (kAlgos - 1)), 0, kAlgos - 1);
+ c.drive[s] = std::clamp(get(S1Drive + s * 5), 0.0f, 1.0f);
+ c.trim[s] = std::pow(10.0f, (get(S1Out + s * 5) - 0.5f) * 24.0f / 20.0f);
+ c.fb[s] = std::clamp(get(S1FB + s * 5), 0.0f, 1.0f) * 0.85f;
+ c.on[s] = get(S1On + s * 5) >= 0.5f;
+ c.bias[s] = std::clamp(masterBias + (get(S1Bias + s * 3) - 0.5f) * 2.0f, -1.0f, 1.0f);
+ c.toneDb[s] = (get(S1Tone + s * 3) - 0.5f) * 24.0f;
+ c.lowG[s] = std::pow(10.0f, -c.toneDb[s] / 40.0f);
+ c.highG[s] = std::pow(10.0f, c.toneDb[s] / 40.0f);
+ c.width[s] = std::clamp(get(S1Width + s * 3), 0.0f, 1.0f) * 2.0f;
+ }
+ c.amt = std::pow(10.0f, get(Amount) * 30.0f / 20.0f);
+ c.wet = std::clamp(get(Wet), 0.0f, 1.0f);
+ c.outGain = std::pow(10.0f, (get(Output) - 0.5f) * 48.0f / 20.0f);
+ c.routing = std::clamp((int)std::lround(get(Routing) * 3.0f), 0, 3);
+ return c;
+ }
+ static int onCount(const Cfg& c) { int n = 0; for (int s = 0; s < kStages; ++s) n += c.on[s] ? 1 : 0; return n; }
+ bool aliasing(const Cfg& c) const {
+ if (osIndex() != 0) return false;
+ for (int s = 0; s < kStages; ++s) if (c.on[s] && (c.type[s] == 4 || c.type[s] == 5)) return true;
+ return false;
+ }
+ static const char* roleWord(int routing, int s) {
+ static const char* ms[3] = { " (mid)", " (side)", " (M+S)" };
+ static const char* mb[3] = { " (low)", " (mid)", " (high)" };
+ return routing == 2 ? ms[s] : routing == 3 ? mb[s] : "";
+ }
+ std::string rateText() const {
+ char b[48];
+ if (get(LfoSync) >= 0.5f) std::snprintf(b, sizeof b, "%s sync", kDivNames[divIndex()]);
+ else std::snprintf(b, sizeof b, "%.2f Hz", expMap(get(LfoRate), 0.05, 20.0));
+ return b;
+ }
- // One stage on one channel, with self-feedback. `slot` indexes the fb state (stage*2+ch).
- inline float stage(int slot, int type, float driveN, float outTrim, float fbAmt, float bias, float driveMod, float x) {
- const float g = driveGain(std::clamp(driveN + driveMod, 0.0f, 1.0f));
- const float in = (x + fbAmt * fb_[slot]) * g;
- float y = shape(type, in, bias);
- y *= 1.0f / std::sqrt(g); // gentle auto-makeup so drive doesn't just get loud
+ // ---- DSP ---------------------------------------------------------------------------------
+ // One stage's shaper on one channel, with self-feedback and the stage tilt. `slot` = stage*2+ch.
+ inline float shapeCh(const Cfg& c, const Core& k, int s, int slot, float driveMod, float x) {
+ const float g = driveGain(std::clamp(c.drive[s] + driveMod, 0.0f, 1.0f));
+ const float in = (x + c.fb[s] * fb_[slot]) * g;
+ float y = shape(c.type[s], in, c.bias[s]) * (1.0f / std::sqrt(g)); // gentle auto-makeup
fb_[slot] = y;
- return y * outTrim;
+ y *= c.trim[s];
+ float& lp = tilt_[slot];
+ lp = y + k.tiltCoef * (lp - y);
+ return lp * c.lowG[s] + (y - lp) * c.highG[s];
+ }
+ // A stage on a stereo pair: both channels, then the stage's width.
+ inline void stagePair(const Cfg& c, const Core& k, int s, float driveMod, float& l, float& r) {
+ l = shapeCh(c, k, s, s * 2, driveMod, l);
+ r = shapeCh(c, k, s, s * 2 + 1, driveMod, r);
+ if (c.width[s] != 1.0f) {
+ const float m = 0.5f * (l + r), sd = 0.5f * (l - r) * c.width[s];
+ l = m + sd; r = m - sd;
+ }
}
- inline void route(int routing, float l, float r, const int* type, const bool* on, const float* drive,
- const float* outTrim, const float* fb, float bias, float driveMod,
- float loCoef, float hiCoef, float& wl, float& wr) {
- auto serial = [&](int ch, float x) {
- for (int s = 0; s < kStages; ++s) if (on[s]) x = stage(s * 2 + ch, type[s], drive[s], outTrim[s], fb[s], bias, driveMod, x);
- return x;
- };
- auto parallel = [&](int ch, float x) {
- float sum = 0; int n = 0;
- for (int s = 0; s < kStages; ++s) if (on[s]) { sum += stage(s * 2 + ch, type[s], drive[s], outTrim[s], fb[s], bias, driveMod, x); ++n; }
- return n ? sum / n : x;
- };
- switch (routing) {
- case 0: wl = serial(0, l); wr = serial(1, r); break;
- case 1: wl = parallel(0, l); wr = parallel(1, r); break;
- case 2: { // Mid/Side: serial chain on M and S independently
- float m = 0.5f * (l + r), s = 0.5f * (l - r);
- m = serial(0, m); s = serial(1, s);
- wl = m + s; wr = m - s; break;
+ inline void route(const Cfg& c, const Core& k, float driveMod, float& l, float& r) {
+ switch (c.routing) {
+ case 0: // Serial
+ for (int s = 0; s < kStages; ++s) if (c.on[s]) stagePair(c, k, s, driveMod, l, r);
+ break;
+ case 1: { // Parallel: every stage from the same input, averaged
+ float sl = 0, sr = 0; int n = 0;
+ for (int s = 0; s < kStages; ++s) if (c.on[s]) { float a = l, b = r; stagePair(c, k, s, driveMod, a, b); sl += a; sr += b; ++n; }
+ if (n) { l = sl / (float)n; r = sr / (float)n; }
+ break;
+ }
+ case 2: { // Mid/Side: S1 → Mid, S2 → Side (width scales it), S3 → the recombined stereo
+ float m = 0.5f * (l + r), sd = 0.5f * (l - r);
+ if (c.on[0]) m = shapeCh(c, k, 0, 0, driveMod, m);
+ if (c.on[1]) sd = shapeCh(c, k, 1, 3, driveMod, sd) * c.width[1];
+ l = m + sd; r = m - sd;
+ if (c.on[2]) stagePair(c, k, 2, driveMod, l, r);
+ break;
}
- default: { // Multiband: stage i drives band i (low / mid / high)
- wl = multiband(0, l, type, on, drive, outTrim, fb, bias, driveMod, loCoef, hiCoef);
- wr = multiband(1, r, type, on, drive, outTrim, fb, bias, driveMod, loCoef, hiCoef);
+ default: { // Multiband: S1 lows, S2 mids, S3 highs (one-pole split, sums back flat)
+ float bl[3], br[3];
+ split(0, l, k, bl); split(1, r, k, br);
+ l = r = 0;
+ for (int s = 0; s < kStages; ++s) {
+ if (c.on[s]) stagePair(c, k, s, driveMod, bl[s], br[s]);
+ l += bl[s]; r += br[s];
+ }
}
}
}
-
- inline float multiband(int ch, float x, const int* type, const bool* on, const float* drive,
- const float* outTrim, const float* fb, float bias, float driveMod, float loCoef, float hiCoef) {
+ inline void split(int ch, float x, const Core& k, float* band) {
float& lo = mbLo_[ch]; float& hi = mbHi_[ch];
- lo = x + loCoef * (lo - x); // low band (LP 200 Hz)
+ lo = x + k.loCoef * (lo - x); // low band (LP 180 Hz)
const float aboveLo = x - lo;
- hi = aboveLo + hiCoef * (hi - aboveLo);// mid band (LP 2 kHz of the >200 Hz part)
- const float mid = hi;
- const float high = aboveLo - hi; // high band
- float y = 0;
- y += on[0] ? stage(0 * 2 + ch, type[0], drive[0], outTrim[0], fb[0], bias, driveMod, lo) : lo;
- y += on[1] ? stage(1 * 2 + ch, type[1], drive[1], outTrim[1], fb[1], bias, driveMod, mid) : mid;
- y += on[2] ? stage(2 * 2 + ch, type[2], drive[2], outTrim[2], fb[2], bias, driveMod, high) : high;
- return y;
+ hi = aboveLo + k.hiCoef * (hi - aboveLo); // mid band (LP 2.4 kHz of the part above 180 Hz)
+ band[0] = lo; band[1] = hi; band[2] = aboveLo - hi;
+ }
+
+ // ---- static model (UI / MCP) -------------------------------------------------------------
+ // A stage's static (DC) response to the pre-gained input v: the feedback settles on a fixed
+ // point (y = f((v + fb·y)·g)), found by a few damped iterations. Tilt / width are frequency /
+ // stereo effects and don't bend the curve.
+ static float stageStaticY(const Cfg& c, int s, float v, float mod) {
+ const float g = driveGain(std::clamp(c.drive[s] + mod, 0.0f, 1.0f));
+ const float mk = 1.0f / std::sqrt(g);
+ float y = shape(c.type[s], v * g, c.bias[s]) * mk;
+ if (c.fb[s] > 0.0f)
+ for (int it = 0; it < 8; ++it) y = 0.5f * y + 0.5f * shape(c.type[s], (v + c.fb[s] * y) * g, c.bias[s]) * mk;
+ return y * c.trim[s];
+ }
+ static float finish(const Cfg& c, float x, float y) { return (c.wet * y + (1.0f - c.wet) * x) * c.outGain; }
+ // The whole device on a mono input x (−1..1). Mid/Side: the mono signal is all Mid (S1 then
+ // S3); Multiband: a broadband sample — each band's shaper sees it, so the stages average.
+ static float chainStatic(const Cfg& c, float x, float mod) {
+ float v = x * c.amt, y = v;
+ switch (c.routing) {
+ case 0: for (int s = 0; s < kStages; ++s) if (c.on[s]) y = stageStaticY(c, s, y, mod); break;
+ case 2: if (c.on[0]) y = stageStaticY(c, 0, y, mod); if (c.on[2]) y = stageStaticY(c, 2, y, mod); break;
+ default: {
+ float sum = 0; int n = 0;
+ for (int s = 0; s < kStages; ++s) if (c.on[s]) { sum += stageStaticY(c, s, v, mod); ++n; }
+ if (n) y = sum / (float)n;
+ }
+ }
+ return finish(c, x, y);
+ }
+ static float stageFull(const Cfg& c, int s, float x, float mod) { return finish(c, x, stageStaticY(c, s, x * c.amt, mod)); }
+
+ // Harmonics 2..9 of a −6 dB sine through fn, in dB relative to the fundamental, leaned by a
+ // tilt (half the tilt per octave above the fundamental). Returns THD in %.
+ template <class Fn>
+ static float harmonics(Fn&& fn, float tiltDb, float* outDb, float& odd, float& even) {
+ constexpr int M = 64;
+ float ys[M];
+ for (int i = 0; i < M; ++i) ys[i] = fn(0.5f * (float)std::sin(2.0 * kPi * i / M));
+ float h[kHarm + 1] = {};
+ for (int kk = 1; kk <= kHarm + 1; ++kk) {
+ double re = 0, im = 0;
+ for (int i = 0; i < M; ++i) { const double a = 2.0 * kPi * kk * i / M; re += ys[i] * std::cos(a); im += ys[i] * std::sin(a); }
+ double v = 2.0 * std::sqrt(re * re + im * im) / M;
+ if (kk > 1) v *= std::pow(10.0, tiltDb * std::log2((double)kk) * 0.5 / 20.0);
+ h[kk - 1] = (float)v;
+ }
+ const float h1 = std::max(h[0], 1e-9f);
+ odd = even = 0;
+ for (int kk = 2; kk <= kHarm + 1; ++kk) {
+ const float v = h[kk - 1];
+ (kk % 2 ? odd : even) += v * v;
+ outDb[kk - 2] = std::max(-120.0f, 20.0f * std::log10(v / h1 + 1e-9f));
+ }
+ return std::sqrt(odd + even) / h1 * 100.0f;
+ }
+ static int flavor(float thd, float odd, float even) {
+ if (thd < 0.3f) return 0;
+ if (odd > even * 1.6f) return 1;
+ if (even > odd * 1.6f) return 2;
+ return 3;
}
double sr_ = 44100.0;
std::atomic<float> p_[kNumParams] = {};
float fb_[kStages * 2] = {}; // per stage/channel self-feedback state
- float lpTone_[2] = {}; // tone tilt one-pole
+ float tilt_[kStages * 2] = {}; // per stage/channel tilt one-pole
+ float lpTone_[2] = {}; // master tilt one-pole
float mbLo_[2] = {}, mbHi_[2] = {};// multiband crossover one-poles
float env_ = 0;
double lfoPhase_ = 0;
double beatStart_ = 0, spb_ = 0; bool playing_ = false;
- std::atomic<float> lfoLive_{0.5f};
+ float inPkM_ = 0, outPkM_ = 0, msIn_ = 0, msOut_ = 0, inLvl_ = 0;
+ double cpuS_ = 0.0;
+ std::atomic<float> lfoLive_{0.5f}, driveModLive_{0.0f}, toneLive_{0.0f}, envA_{0.0f}, inLvlA_{0.0f};
+ std::atomic<float> inPkA_{-120.0f}, outPkA_{-120.0f}, inRmsA_{-120.0f}, outRmsA_{-120.0f}, cpuA_{0.0f}, srA_{44100.0f};
+ std::atomic<bool> resetReq_{false};
Oversampler os_; // nonlinear-stage anti-aliasing
int32_t maxFrames_ = 4096;
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index edb1918a..e53c7918 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -5476,7 +5476,8 @@ Console.WriteLine("-- Nota Level (AutoGain) --");
Console.WriteLine("-- Nota Forge --");
{
// Own engine instance (a driven saturator would pollute the shared master mix used by
- // later tests). Forge = multi-stage saturation (kind 17), 27 params (incl. Oversampling).
+ // later tests). Forge = multi-stage saturation (kind 17), 36 params: the original 27 (incl.
+ // Oversampling) + per-stage Bias / Tone / Width appended by the redesign.
using var fe = new NotaEngine();
fe.SetBpm(120); fe.SetTimeSignature(4, 4);
int ft2 = fe.AddInstrumentTrack();
@@ -5486,50 +5487,145 @@ Console.WriteLine("-- Nota Forge --");
Check(fg >= 0, "add built-in Nota Forge");
Check(fe.DeviceName(ft2, fg) == "Nota Forge", $"name is Nota Forge (got '{fe.DeviceName(ft2, fg)}')");
Check(fe.TrackDeviceBuiltinKind(ft2, fg) == 17, $"builtin kind is 17 (got {fe.TrackDeviceBuiltinKind(ft2, fg)})");
- Check(fe.DeviceParamCount(ft2, fg) == 27, $"Nota Forge exposes 27 params (got {fe.DeviceParamCount(ft2, fg)})");
+ Check(fe.DeviceParamCount(ft2, fg) == 36, $"Nota Forge exposes 36 params (got {fe.DeviceParamCount(ft2, fg)})");
+ // Append-only layout: the old indices keep their names, the per-stage shape sits at 27..35, neutral.
+ Check(fe.DeviceParamName(ft2, fg, 0) == "Amount" && fe.DeviceParamName(ft2, fg, 12) == "S1 Drive" && fe.DeviceParamName(ft2, fg, 26) == "Oversampling"
+ && fe.DeviceParamName(ft2, fg, 27) == "S1 Bias" && fe.DeviceParamName(ft2, fg, 31) == "S2 Tone" && fe.DeviceParamName(ft2, fg, 35) == "S3 Width",
+ "Forge param layout: old indices unchanged, S1 Bias … S3 Width appended at 27..35");
+ bool fNeutral = true;
+ for (int p = 27; p < 36; p++) if (Math.Abs(fe.DeviceParamDefault(ft2, fg, p) - 0.5f) > 1e-6f || Math.Abs(fe.DeviceGetParam(ft2, fg, p) - 0.5f) > 1e-6f) fNeutral = false;
+ Check(fNeutral, "Forge per-stage Bias / Tone / Width default neutral (0.5), so older projects sound the same");
// Param round-trip.
fe.DeviceSetParam(ft2, fg, 0, 0.6f); // Amount
Check(Math.Abs(fe.DeviceGetParam(ft2, fg, 0) - 0.6f) < 1e-4, "Forge param set/get round-trips");
var fb2 = new float[8192 * 2];
- fe.Seek(0); fe.Play(); fe.RenderOffline(fb2, 8192); fe.StopTransport();
- bool ffin = true; foreach (var s in fb2) if (!float.IsFinite(s)) { ffin = false; break; }
- Check(ffin && Rms(fb2, 8192) > 0.001f, $"Forge passes audio (rms {Rms(fb2, 8192):F3})");
+ float[] FRender() { fe.Seek(0); fe.Play(); fe.RenderOffline(fb2, 8192); fe.StopTransport(); return fb2; }
+ bool Fin(float[] b) { foreach (var s in b) if (!float.IsFinite(s)) return false; return true; }
+ FRender();
+ Check(Fin(fb2) && Rms(fb2, 8192) > 0.001f, $"Forge passes audio (rms {Rms(fb2, 8192):F3})");
// Drive adds harmonics → raises level vs a light setting (crude saturation check).
fe.DeviceSetParam(ft2, fg, 0, 0.1f); // low amount
fe.DeviceSetParam(ft2, fg, 12, 0.1f); // S1 drive low
- fe.Seek(0); fe.Play(); fe.RenderOffline(fb2, 8192); fe.StopTransport();
+ FRender();
float rmsLow = Rms(fb2, 8192);
fe.DeviceSetParam(ft2, fg, 0, 0.8f); // high amount
fe.DeviceSetParam(ft2, fg, 12, 0.8f); // S1 drive high
- fe.Seek(0); fe.Play(); fe.RenderOffline(fb2, 8192); fe.StopTransport();
- bool dfin = true; foreach (var s in fb2) if (!float.IsFinite(s)) { dfin = false; break; }
- Check(dfin && Rms(fb2, 8192) > rmsLow, $"more drive → more energy ({Rms(fb2, 8192):F3} > {rmsLow:F3})");
-
- // All four routings render finite + audible.
+ FRender();
+ Check(Fin(fb2) && Rms(fb2, 8192) > rmsLow, $"more drive → more energy ({Rms(fb2, 8192):F3} > {rmsLow:F3})");
+
+ // All four routings render finite + audible, with every stage on and a stage shape set.
+ fe.DeviceSetParam(ft2, fg, 20, 1f); // S2 On
+ fe.DeviceSetParam(ft2, fg, 25, 1f); // S3 On
+ fe.DeviceSetParam(ft2, fg, 29, 0.8f); // S1 Width 160 %
+ fe.DeviceSetParam(ft2, fg, 31, 0.8f); // S2 Tone +7 dB
+ fe.DeviceSetParam(ft2, fg, 33, 0.3f); // S3 Bias −40 %
for (int rt = 0; rt < 4; rt++)
{
- fe.DeviceSetParam(ft2, fg, 6, rt / 3f); // Routing
- fe.DeviceSetParam(ft2, fg, 20, 1f); // S2 On
- fe.DeviceSetParam(ft2, fg, 25, 1f); // S3 On
- fe.Seek(0); fe.Play(); fe.RenderOffline(fb2, 8192); fe.StopTransport();
- bool rfin = true; foreach (var s in fb2) if (!float.IsFinite(s)) { rfin = false; break; }
- Check(rfin && Rms(fb2, 8192) > 0.001f, $"Forge routing {rt} renders finite + audible (rms {Rms(fb2, 8192):F3})");
+ fe.DeviceSetParam(ft2, fg, 6, rt / 3f); // Routing
+ FRender();
+ Check(Fin(fb2) && Rms(fb2, 8192) > 0.001f, $"Forge routing {rt} renders finite + audible (rms {Rms(fb2, 8192):F3})");
}
-
- // Clone: duplicating the track carries Forge params.
+ // Extremes: every stage Fold at full drive, feedback, bias, tone and width, 8× oversampling.
+ for (int st = 0; st < 3; st++)
+ {
+ fe.DeviceSetParam(ft2, fg, 11 + st * 5, 1f); fe.DeviceSetParam(ft2, fg, 12 + st * 5, 1f); fe.DeviceSetParam(ft2, fg, 14 + st * 5, 1f);
+ fe.DeviceSetParam(ft2, fg, 27 + st * 3, 1f); fe.DeviceSetParam(ft2, fg, 28 + st * 3, 1f); fe.DeviceSetParam(ft2, fg, 29 + st * 3, 1f);
+ }
+ fe.DeviceSetParam(ft2, fg, 26, 1f);
+ for (int rt = 0; rt < 4; rt++)
+ {
+ fe.DeviceSetParam(ft2, fg, 6, rt / 3f);
+ FRender();
+ float pk = 0; foreach (var v in fb2) pk = Math.Max(pk, Math.Abs(v));
+ Check(Fin(fb2) && pk < 16f, $"Forge routing {rt} stays finite + bounded at the extremes (peak {pk:F2})");
+ }
+
+ // Per-stage Tone brightens: a +12 dB tilt raises the energy above the pivot vs −12 dB.
+ fe.DeviceSetParam(ft2, fg, 6, 0f); fe.DeviceSetParam(ft2, fg, 26, 0f);
+ for (int st = 0; st < 3; st++) { fe.DeviceSetParam(ft2, fg, 15 + st * 5, st == 0 ? 1f : 0f); fe.DeviceSetParam(ft2, fg, 14 + st * 5, 0f); }
+ fe.DeviceSetParam(ft2, fg, 11, 0f); fe.DeviceSetParam(ft2, fg, 12, 0.5f); fe.DeviceSetParam(ft2, fg, 27, 0.5f); fe.DeviceSetParam(ft2, fg, 29, 0.5f);
+ float Hf(float[] b) { double e = 0, prev = 0; for (int i = 0; i < 8192; i++) { double m = b[i * 2]; e += (m - prev) * (m - prev); prev = m; } return (float)e; }
+ fe.DeviceSetParam(ft2, fg, 28, 0f); FRender(); float dark = Hf(fb2) / Math.Max(1e-9f, Rms(fb2, 8192) * Rms(fb2, 8192));
+ fe.DeviceSetParam(ft2, fg, 28, 1f); FRender(); float bright = Hf(fb2) / Math.Max(1e-9f, Rms(fb2, 8192) * Rms(fb2, 8192));
+ Check(bright > dark * 1.5f, $"Forge S1 Tone tilts the stage (bright {bright:F1} vs dark {dark:F1})");
+ fe.DeviceSetParam(ft2, fg, 28, 0.5f);
+
+ // Telemetry: the scope carries meters, THD and curves from the same shapers.
+ FRender();
+ var fsc = new float[32 + 8 * 4 + 129 * 8];
+ int fsn = fe.DeviceScope(ft2, fg, fsc, fsc.Length);
+ Check(fsn == fsc.Length, $"Forge scope returns telemetry + harmonics + curves ({fsn} values)");
+ bool curveOk = true;
+ for (int i = 1; i < 129; i++) if (!float.IsFinite(fsc[64 + i]) || fsc[64 + i] < fsc[64 + i - 1] - 1e-4f) curveOk = false; // Tube chain: monotonic
+ Check(curveOk && fsc[64] < 0 && fsc[64 + 128] > 0, "Forge transfer curve (Tube) is finite, rising, through the origin");
+ Check(fsc[13] > 0.3f && fsc[4] > 1000 && fsc[0] > -60 && fsc[1] > -60 && fsc[21] > 0.5f,
+ $"Forge scope: THD {fsc[13]:F1} %, sample rate, in / out peaks, signal flag");
+ Check(fsc[22] < 0.5f, "Forge: no aliasing warning with Tube");
+ fe.DeviceSetParam(ft2, fg, 11, 0.8f); // S1 Digital, oversampling off
+ fe.DeviceScope(ft2, fg, fsc, 32);
+ Check(fsc[22] > 0.5f, "Forge: the aliasing warning lights for Digital without oversampling");
+ fe.DeviceSetParam(ft2, fg, 26, 1f / 3f);
+ fe.DeviceScope(ft2, fg, fsc, 32);
+ Check(fsc[22] < 0.5f && Math.Abs(fsc[7] - 2) < 1e-3, "Forge: 2× oversampling clears it");
+ fe.DeviceSetParam(ft2, fg, 11, 0f);
+ fe.DeviceSetParam(ft2, fg, 0, 0.1f); fe.DeviceSetParam(ft2, fg, 12, 0.2f); // a gentle drive …
+ fe.DeviceSetParam(ft2, fg, 27, 0.9f); // … and S1 bias → even harmonics
+ fe.DeviceScope(ft2, fg, fsc, fsc.Length);
+ Check((int)fsc[17] is 2 or 3, $"Forge: a biased Tube reads even-heavy / mixed (flavour {fsc[17]})");
+ fe.DeviceSetParam(ft2, fg, 27, 0.5f);
+ Check(fe.DeviceText(ft2, fg, 0).Contains("serial") && fe.DeviceText(ft2, fg, 1).Contains("THD")
+ && fe.DeviceText(ft2, fg, 2).Contains("Sn Bias"), "Forge device texts: summary, live reading, parameter guide");
+
+ // MCP: read / set in units.
+ var ftools = new Nota.Mcp.Tools.DeviceTools(fe, new Nota.SmokeTest.SyncDispatch(), new Nota.SmokeTest.NoRefresh());
+ var fr = ftools.SetForgeStage(ft2, fg, 2, on: true, type: "Tape", drivePercent: 40, toneDb: -3, widthPercent: 150).Result;
+ Check(fr.Stages[1].On && fr.Stages[1].Type == "Tape" && Math.Abs(fr.Stages[1].DrivePercent - 40) < 0.2 && Math.Abs(fr.Stages[1].ToneDb + 3) < 0.1
+ && Math.Abs(fr.Stages[1].WidthPercent - 150) < 0.2, "MCP set_forge_stage sets a stage in units and reads it back");
+ fr = ftools.SetForge(ft2, fg, routing: "Multiband", amountDb: 12, wetPercent: 80, lfoDivision: "1/8", lfoDrivePercent: 40, oversampling: 4).Result;
+ Check(fr.Routing == "Multiband" && Math.Abs(fr.AmountDb - 12) < 0.1 && Math.Abs(fr.Wet - 0.8) < 1e-3 && fr.LfoSync && fr.LfoRate == "1/8"
+ && fr.Oversampling == "4x" && fr.Stages[0].Role == "Low" && fr.Stages[2].Role == "High" && fr.TransferCurve.Length == 17
+ && fr.HarmonicsDb.Length == 8 && fr.Summary.Contains("multiband") && fr.Live.Length > 0,
+ $"MCP set_forge / read_forge in units (THD {fr.ThdPercent} %, {fr.Flavor})");
+
+ // Clone: duplicating the track carries Forge params, the appended ones included.
fe.DeviceSetParam(ft2, fg, 3, 0.62f); // Output
+ fe.DeviceSetParam(ft2, fg, 34, 0.2f); // S3 Tone
int ftD = fe.DuplicateTrack(ft2); int fgD = fe.TrackDeviceCount(ftD) - 1;
- Check(ftD > 0 && Math.Abs(fe.DeviceGetParam(ftD, fgD, 3) - 0.62f) < 1e-3, "duplicate track clones Forge params");
+ Check(ftD > 0 && Math.Abs(fe.DeviceGetParam(ftD, fgD, 3) - 0.62f) < 1e-3 && Math.Abs(fe.DeviceGetParam(ftD, fgD, 34) - 0.2f) < 1e-3,
+ "duplicate track clones Forge params (incl. the per-stage shape)");
- // Automation drives Amount.
+ // Automation drives Amount and a per-stage param.
int flane = fe.AddAutomationLane(ft2, AutomationTarget.DeviceParam, fg, 0);
Check(flane >= 0, "add Forge Amount automation lane");
fe.SetAutomationPoints(ft2, flane, new[] { new AutomationPoint(0.0, 0.1f), new AutomationPoint(2.0, 0.9f) });
+ int flane2 = fe.AddAutomationLane(ft2, AutomationTarget.DeviceParam, fg, 30);
+ fe.SetAutomationPoints(ft2, flane2, new[] { new AutomationPoint(0.0, 0.0f), new AutomationPoint(2.0, 1.0f) });
fe.Seek(1.99); fe.Play(); fe.RenderOffline(fb2, 4096); fe.StopTransport();
- Check(fe.DeviceGetParam(ft2, fg, 0) > 0.7f, $"automation drives Forge Amount ({fe.DeviceGetParam(ft2, fg, 0):F2})");
+ Check(fe.DeviceGetParam(ft2, fg, 0) > 0.7f && fe.DeviceGetParam(ft2, fg, 30) > 0.8f,
+ $"automation drives Forge Amount ({fe.DeviceGetParam(ft2, fg, 0):F2}) and S2 Bias ({fe.DeviceGetParam(ft2, fg, 30):F2})");
+ fe.RemoveAutomationLane(ft2, flane2); fe.RemoveAutomationLane(ft2, flane);
+
+ // Every factory preset names only real params and renders finite + audible.
+ var fcat = new FactoryPresetCatalog();
+ int fPresets = 0; bool fNamesOk = true, fPresetsOk = true;
+ var fNames = new HashSet<string>();
+ for (int p = 0; p < fe.DeviceParamCount(ft2, fg); p++) fNames.Add(fe.DeviceParamName(ft2, fg, p));
+ foreach (var info in fcat.All())
+ {
+ if (info.IsInstrument || info.IsMidiEffect || info.BuiltinKind != 17) continue;
+ var doc = fcat.Document(info.Id);
+ if (doc is null) continue;
+ fPresets++;
+ foreach (var k in doc.NamedParams!.Keys) if (!fNames.Contains(k)) { fNamesOk = false; Console.WriteLine($" unknown param '{k}' in {info.DisplayName}"); }
+ fcat.ApplyInPlace(fe, info.Id, ft2, fg);
+ FRender();
+ float pk = 0; foreach (var v in fb2) pk = Math.Max(pk, Math.Abs(v));
+ if (!Fin(fb2) || Rms(fb2, 8192) < 1e-3f || pk > 4f) { fPresetsOk = false; Console.WriteLine($" preset {info.DisplayName} not finite / silent / over (rms {Rms(fb2, 8192):F4}, peak {pk:F2})"); }
+ }
+ Check(fPresets >= 25 && fNamesOk && fPresetsOk, $"{fPresets} Forge factory presets, all params known, all render finite and audible");
}
// -- EQ-8: per-band shaping, param round-trip, analyzer scope --
@@ -8472,6 +8568,10 @@ Console.WriteLine("-- Nota Vintage (effect kind 8) --");
// ===================== Nota Orbit (effect kind 9) ======================
Console.WriteLine("-- Nota Orbit (effect kind 9) --");
{
+ // Params (AutoPan.h): 0 Rate, 1 Amount, 2 Waveform, 3 Shape, 4 Phase, 5 Mix, 6 Sync, 7 Division.
+ // Scope: 0 in, 1 out L, 2 out R (dBFS) · 3 gain L, 4 gain R · 5 pan · 6 window phase · 7 rate Hz ·
+ // 8 BPM · 9 playing · 10 locked · 11 sample rate · 12..15 S&H steps · 16 / 17 pan min / max ·
+ // 18 division beats · 19 bar beats · 20 CPU · 21 signal · 22 floor · 23 cycles.
using var apeng = new NotaEngine();
int apt = apeng.AddAudioTrack();
apeng.AddAudioClip(apt, wav, 0.0);
@@ -8480,40 +8580,152 @@ Console.WriteLine("-- Nota Orbit (effect kind 9) --");
Check(apeng.DeviceName(apt, apdi) == "Nota Orbit", $"device is Nota Orbit (got '{apeng.DeviceName(apt, apdi)}')");
Check(apeng.TrackDeviceBuiltinKind(apt, apdi) == 9, "device reports builtin kind 9");
int appc = apeng.DeviceParamCount(apt, apdi);
- Check(appc == 6, $"Nota Orbit exposes 6 params ({appc})");
+ Check(appc == 8, $"Nota Orbit exposes 8 params ({appc})");
+ Check(apeng.DeviceParamName(apt, apdi, 0) == "Rate" && apeng.DeviceParamName(apt, apdi, 5) == "Mix"
+ && apeng.DeviceParamName(apt, apdi, 6) == "Sync" && apeng.DeviceParamName(apt, apdi, 7) == "Division",
+ "original params keep their places; Sync and Division are appended");
+ Check(apeng.DeviceParamDefault(apt, apdi, 6) < 0.5f && Math.Abs(apeng.DeviceParamDefault(apt, apdi, 7) - 10f / 15f) < 1e-3f,
+ "Sync defaults to Free (older projects open unchanged), Division to 1/8");
apeng.DeviceSetParam(apt, apdi, 0, 0.7f); // Rate
Check(Math.Abs(apeng.DeviceGetParam(apt, apdi, 0) - 0.7f) < 1e-3f, "device param set/get round-trips");
+ var apbuf = new float[2048 * 2];
+ var apsc = new float[32];
+ bool ApFinite() { foreach (var s in apbuf) if (!float.IsFinite(s) || Math.Abs(s) > 8f) return false; return true; }
+ void ApRender(int frames = 2048) { apeng.Seek(0); apeng.Play(); apeng.RenderOffline(apbuf, frames); apeng.StopTransport(); }
+ int ApScope() => apeng.DeviceScope(apt, apdi, apsc, apsc.Length);
+
// Each waveform renders audible + finite.
apeng.DeviceSetParam(apt, apdi, 1, 0.8f); // Amount
apeng.SetBpm(120);
- var apbuf = new float[2048 * 2];
for (int wv = 0; wv < 5; wv++)
{
apeng.DeviceSetParam(apt, apdi, 2, wv / 4f);
- apeng.Seek(0); apeng.Play();
- apeng.RenderOffline(apbuf, 2048);
- apeng.StopTransport();
- float rms = Rms(apbuf, 2048); bool finite = true;
- foreach (var s in apbuf) if (!float.IsFinite(s) || Math.Abs(s) > 8f) { finite = false; break; }
- Check(rms > 1e-4f && finite, $"Auto Pan waveform {wv} is audible + stable (rms {rms:0.000})");
+ ApRender();
+ float rms = Rms(apbuf, 2048);
+ Check(rms > 1e-4f && ApFinite(), $"Orbit waveform {wv} is audible + stable (rms {rms:0.000})");
}
- // Phase 180° drives the stereo position off-centre (auto-pan); Phase 0° keeps it
- // centred (tremolo) — the published pan position distinguishes the two.
+ // Phase 180° drives the stereo position off-centre (auto-pan); Phase 0° keeps it centred
+ // (tremolo) — the published pan position distinguishes the two.
apeng.DeviceSetParam(apt, apdi, 2, 0f); // sine (continuous)
apeng.DeviceSetParam(apt, apdi, 1, 1.0f); // Amount full
apeng.DeviceSetParam(apt, apdi, 4, 0.5f); // Phase 180° → pan
- apeng.Seek(0); apeng.Play(); apeng.RenderOffline(apbuf, 2048); apeng.StopTransport();
+ ApRender();
float panPos = apeng.DeviceGainReduction(apt, apdi);
- Check(Math.Abs(panPos - 0.5f) > 0.05f, $"Auto Pan (Phase 180°) pushes the balance off-centre ({panPos:0.00})");
+ Check(Math.Abs(panPos - 0.5f) > 0.05f, $"Orbit (Phase 180°) pushes the balance off-centre ({panPos:0.00})");
+ int apn = ApScope();
+ Check(apn == 32 && apsc[16] < -0.5f && apsc[17] > 0.5f, $"Orbit publishes the pan swing over the window ({apsc[16]:0.00} … {apsc[17]:0.00})");
apeng.DeviceSetParam(apt, apdi, 4, 0f); // Phase 0° → tremolo
- apeng.Seek(0); apeng.Play(); apeng.RenderOffline(apbuf, 2048); apeng.StopTransport();
+ ApRender();
float tremPos = apeng.DeviceGainReduction(apt, apdi);
- Check(Math.Abs(tremPos - 0.5f) < 1e-3f, $"Auto Pan (Phase 0°) stays centred = tremolo ({tremPos:0.00})");
+ Check(Math.Abs(tremPos - 0.5f) < 1e-3f, $"Orbit (Phase 0°) stays centred = tremolo ({tremPos:0.00})");
+ ApScope();
+ Check(Math.Abs(apsc[3] - apsc[4]) < 1e-4f && Math.Abs(apsc[5]) < 1e-3f, "tremolo: both gains equal, pan 0");
+ Check(Math.Abs(apsc[22]) < 1e-4f, $"floor = 1 − Amount·Mix ({apsc[22]:0.000})");
+
+ // Sync: the rate follows the tempo and the LFO locks to the song position.
+ apeng.DeviceSetParam(apt, apdi, 4, 0.5f);
+ apeng.DeviceSetParam(apt, apdi, 6, 1f); // Sync
+ apeng.DeviceSetParam(apt, apdi, 7, 7f / 15f); // 1/4 → 2 Hz at 120 BPM
+ ApRender();
+ ApScope();
+ Check(Math.Abs(apsc[7] - 2f) < 1e-3f, $"Sync 1/4 at 120 BPM runs at 2 Hz ({apsc[7]:0.000})");
+ Check(apsc[10] > 0.5f && Math.Abs(apsc[18] - 1f) < 1e-4f, "the synced LFO locks to the song position");
+ {
+ double sr = apsc[11], beats = (2048 - 1) / (sr * 0.5); // the last sample's beat
+ double want = beats % 2.0; // 1 beat per cycle, window of 2
+ Check(Math.Abs(apsc[6] - want) < 0.01, $"locked window phase follows the beat ({apsc[6]:0.000} vs {want:0.000})");
+ }
+ apeng.DeviceSetParam(apt, apdi, 7, 1f); // 1/32 → 16 Hz
+ ApRender();
+ ApScope();
+ Check(Math.Abs(apsc[7] - 16f) < 1e-2f, $"Sync 1/32 at 120 BPM runs at 16 Hz ({apsc[7]:0.00})");
+ Check(apeng.DeviceText(apt, apdi, 0).Contains("sync 1/32"), $"status names the division ('{apeng.DeviceText(apt, apdi, 0)}')");
+ apeng.SetBpm(90);
+ ApRender();
+ ApScope();
+ Check(Math.Abs(apsc[7] - 12f) < 1e-2f, $"the synced rate follows a tempo change (90 BPM → {apsc[7]:0.00} Hz)");
+ apeng.SetBpm(120);
+ // Free run: the LFO restarts on device_action 0.
+ apeng.DeviceSetParam(apt, apdi, 6, 0f);
+ apeng.DeviceSetParam(apt, apdi, 0, 0.9f); // ~17 Hz
+ ApRender(); ApScope();
+ Check(apsc[10] < 0.5f && apsc[23] >= 1f, $"free run: not locked, cycles run ({apsc[23]:0})");
+ apeng.DeviceAction(apt, apdi, 0, 0, 0f);
+ ApRender(64);
+ ApScope();
+ Check(apsc[23] < 1f && apsc[6] < 0.1f, $"device_action 0 restarts the LFO (cycle {apsc[23]:0}, phase {apsc[6]:0.000})");
+
+ // S&H: deterministic steps in −1..1; Glide (Shape) smooths the gain between them.
+ apeng.DeviceSetParam(apt, apdi, 2, 1f);
+ apeng.DeviceSetParam(apt, apdi, 0, 0.83f); // ~10 Hz
+ float ShJump(float glide)
+ {
+ apeng.DeviceSetParam(apt, apdi, 3, glide);
+ apeng.Seek(0); apeng.Play();
+ float worst = 0, prev = -1;
+ for (int b = 0; b < 64; b++)
+ {
+ apeng.RenderOffline(apbuf, 256);
+ ApScope();
+ if (prev >= 0) worst = Math.Max(worst, Math.Abs(apsc[3] - prev));
+ prev = apsc[3];
+ }
+ apeng.StopTransport();
+ return worst;
+ }
+ ApScope();
+ bool shOk = true; for (int k = 12; k < 16; k++) shOk &= apsc[k] >= -1f && apsc[k] <= 1f;
+ Check(shOk && apsc[12] != apsc[13], "S&H publishes its four window steps in −1..1");
+ float hard = ShJump(0f), glide = ShJump(1f);
+ Check(glide < hard * 0.6f, $"S&H Glide smooths the steps (largest jump per 256 smp {hard:0.000} → {glide:0.000})");
+ apeng.DeviceSetParam(apt, apdi, 3, 0f);
+
+ // Texts and the MCP reading.
+ Check(apeng.DeviceText(apt, apdi, 1).Contains("LFO") && apeng.DeviceText(apt, apdi, 2).Contains("1/16T"),
+ "device text 1 = live reading, 2 = parameter guide with the division table");
+ {
+ apeng.DeviceSetParam(apt, apdi, 2, 0f);
+ apeng.DeviceSetParam(apt, apdi, 6, 1f);
+ apeng.DeviceSetParam(apt, apdi, 7, 7f / 15f);
+ ApRender();
+ var aptools = new Nota.Mcp.Tools.DeviceTools(apeng, new Nota.SmokeTest.SyncDispatch(), new Nota.SmokeTest.NoRefresh());
+ var ar = aptools.ReadOrbit(apt, apdi).Result;
+ Check(ar.Mode == "auto-pan" && ar.Sync && ar.Division == "1/4" && Math.Abs(ar.RateHz - 2) < 1e-2 && ar.Waveform == "Sine"
+ && ar.Locked && ar.Summary.Length > 0 && ar.Live.Length > 0,
+ $"MCP read_orbit reports the settings and the live state ({ar.Mode}, {ar.Division}, {ar.RateHz} Hz, pan {ar.Pan})");
+ }
+
+ // Clone keeps the appended params.
int apcopy = apeng.DuplicateTrack(apt);
- Check(apcopy > 0 && Math.Abs(apeng.DeviceGetParam(apcopy, apdi, 0) - 0.7f) < 1e-3f, "duplicate track clones Auto Pan params");
+ Check(apcopy > 0 && Math.Abs(apeng.DeviceGetParam(apcopy, apdi, 7) - 7f / 15f) < 1e-3f && apeng.DeviceGetParam(apcopy, apdi, 6) > 0.5f,
+ "duplicate track clones Orbit params incl. Sync / Division");
+
+ // Factory presets: ≥ 25, every named param exists, each applies in place and renders.
+ {
+ var names = new HashSet<string>();
+ for (int k = 0; k < appc; k++) names.Add(apeng.DeviceParamName(apt, apdi, k));
+ var cat = new FactoryPresetCatalog();
+ var mine = cat.All().Where(p => !p.IsInstrument && !p.IsMidiEffect && p.BuiltinKind == 9).ToList();
+ Check(mine.Count >= 25, $"Nota Orbit ships ≥ 25 factory presets ({mine.Count})");
+ var bad = mine.SelectMany(p => cat.Document(p.Id)!.NamedParams!.Keys.Where(k => !names.Contains(k)).Select(k => $"{p.DisplayName}:{k}")).ToList();
+ Check(bad.Count == 0, $"every Orbit preset param name exists{(bad.Count > 0 ? " — bad: " + string.Join(", ", bad) : "")}");
+ int pf = 0;
+ foreach (var p in mine)
+ {
+ if (cat.ApplyInPlace(apeng, p.Id, apt, apdi).Length != 0) { pf++; continue; }
+ ApRender();
+ if (!ApFinite() || Rms(apbuf, 2048) < 1e-4f) pf++;
+ }
+ Check(pf == 0, $"every Orbit preset applies and renders ({pf} failed)");
+ cat.ApplyInPlace(apeng, "autopan/Chop Trem", apt, apdi);
+ Check(apeng.DeviceGetParam(apt, apdi, 6) > 0.5f && OrbitDiv(apeng.DeviceGetParam(apt, apdi, 7)) == 13, "Chop Trem preset: synced 1/16");
+ cat.ApplyInPlace(apeng, "autopan/Classic Pan", apt, apdi);
+ Check(apeng.DeviceGetParam(apt, apdi, 6) < 0.5f, "unnamed params (Sync) reset to defaults between presets");
+ static int OrbitDiv(float v) => Math.Clamp((int)Math.Round(v * 15), 0, 15);
+ }
}
// ===================== Nota Auto Shift (effect kind 10) ===================