Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.
C# audioaudio-unitavaloniacpp20cross-platformdawdigital-audio-workstationdspjucelinux-audiomcp-servermidimusicmusic-productionpiano-rollplugin-hostsequencersynthesizervstvst3
Redesign of Pendulum
Egor Khindikaynen1d8e58c154f0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a0f4543e..7902a7af 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,6 +19,35 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.## [Unreleased]### Added+- **Nota Pendulum's editor is now the almanac's card, and it shows the balls the engine is+ actually swinging.** The card moves onto the 700 × 260 frame the other instruments use — a+ **Balls** / **Voice** tab panel with a one-line reading beside the tabs, a fixed 186 px ball+ rail and a status strip:+ - **Balls** — Free / Sync, the division (or, in Free, the swing time), a bipolar Rate and+ the Motion curve; then **one lane per ball**: x is pitch, low to high, the chord's degrees+ as ticks, the wall the ball came from, the wall it strikes ("hit"), and in teal how long+ until it reaches the wall ahead. Under the lanes, the **bar**: the generated notes land on+ its 1/16 grid — this bar in brass, the last bar's notes ahead of the playhead in deep+ brass — so the lanes say why a note, the bar says when.+ - **Voice** — Keys / Glass / Saw / Sqr / Bell, Tone, Bright, FM and **Length** (the note+ gate, now on the card), the envelope and Volume, with the last generated note and a level+ bar per sounding voice.+ - **Rail** — every ball's division, rate, phase and note, always in view, the one that fired+ last lit. Under it: the ball count, Sort and Quantize, Hold / First note / Reset on Balls;+ the spread (rate, detune, pan and — new on the card — the **Humanize amount**), a+ **Scale** menu (root and mode in one place) and Humanize / Reset on Voice.+ The header shows the ball count. Everything comes from the engine's telemetry, so the lanes+ and the bar follow the audio thread (a Pendulum inside a rack chain swings from its+ parameters instead).+- **MCP: `read_pendulum` and `set_pendulum`.** Read a Nota Pendulum track — a summary, a guide+ to every parameter, the held chord, each ball's phase, position, direction, note and time to+ the wall, and the notes on the bar's grid — and shape it in musical terms: balls, rate in+ percent, division or free seconds, motion, quantize, sort, spread, hold, first note, wave and+ a scale like "A minor penta".+- **Nota Pendulum ships 28 factory presets** (was 6) — music boxes and bells, pentatonic and+ modal patterns (Pentatonic Rain, Dorian Drift, Mixolydian Sun), saw and square arps, FM+ glints, reverse and bouncing patterns, a held pad, and slow free-running swings.+- **Nota Chorus.** A new built-in audio effect (kind 25): modulated delay voices in three modes —**Classic** (two voices, left and right, on 8 ± 5 ms), **Ensemble** (three voices 120° apart on12 ± 6 ms, the string-machine shimmer) and **Vibrato** (the pitch wobble alone, wet only). The card@@ -127,6 +156,9 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.level, the effective attack and release, look-ahead latency and how often it kicked in.### Changed+- **Nota Pendulum's automation menu is grouped.** Its parameters list under **Balls**,+ **Motion**, **Voice**, **Spread** and **Scale** (e.g. Motion › Rate, Spread › Humanize); the+ ids are unchanged, so existing lanes and projects keep working.- **Nota Level is redrawn as a full leveler.** The card follows the new mockup on the 700 × 260frame, in the language of EQ-8 and Forge:- **Correction.** Manual / Auto sit over a fader around 0 dB. Auto rides it in teal. Indiff --git a/FEATURES.md b/FEATURES.mdindex a7719e0d..18aee7dd 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -286,7 +286,9 @@ and user presets, automation, persistence and cloning.(±2/±5/±12) and modulation wheels, VEL→FM, VEL→LEVEL, KEY→LEVEL, Glide, Mono.- **Nota Pendulum** — a "pendulum" sequencer: swinging balls generate notes, with swingcurves (Linear/Pendulum/Ease/Bounce), bipolar Rate, a held chord, Scale, Hold, First- Note, Reset, Humanize and Pan Spread.+ Note, Reset, Humanize and Pan Spread. The card draws one lane per ball from the engine's+ telemetry (direction, the wall it strikes, the time to the next one) over a bar strip of+ the generated notes; 28 factory presets; MCP `read_pendulum` / `set_pendulum`.- **Nota Bass** — mono-first bass synth: a morphing oscillator (sine → tri → saw → pulse,pulse width), a sub oscillator (sine/square/tri, −1/−2 oct), a filter (LP/HP/BP/Notch,12/24 dB) with pre-drive, its own envelope, key tracking and LFO, amp envelope, LFO todiff --git a/src/managed/Nota.App/Controls/Glyph.cs b/src/managed/Nota.App/Controls/Glyph.csindex eb19abc7..82aba4fb 100644--- a/src/managed/Nota.App/Controls/Glyph.cs+++ b/src/managed/Nota.App/Controls/Glyph.cs@@ -22,7 +22,7 @@ internal enum GlyphKindPlay, Stop, Record, RecordRing, Close, Check, Cross,ChevronDown, ChevronUp, ChevronLeft, ChevronRight,StepLeft, StepRight, // filled small triangles (◀ ▶ as "move")- Edit, Freeze, PopOut, Cycle, Dot, Bypass, Plus, Grip,+ Edit, Freeze, PopOut, Cycle, Dot, Bypass, Plus, Grip, Minus,}internal sealed class Glyph : Control@@ -113,6 +113,12 @@ internal sealed class Glyph : Controlctx.DrawLine(pen, new Point(cx, cy - d), new Point(cx, cy + d));break;}+ case GlyphKind.Minus:+ {+ double d = s * 0.36;+ ctx.DrawLine(pen, new Point(cx - d, cy), new Point(cx + d, cy));+ break;+ }case GlyphKind.Grip:{// Two columns of three dots: a drag handle.diff --git a/src/managed/Nota.App/Controls/PendulumViews.cs b/src/managed/Nota.App/Controls/PendulumViews.csnew file mode 100644index 00000000..fca25736--- /dev/null+++ b/src/managed/Nota.App/Controls/PendulumViews.cs@@ -0,0 +1,300 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Nota Pendulum's windows, drawn from the engine's own telemetry (PendulumModel.Snapshot):+//+// PendulumLanesView one lane per ball — x is pitch (low … high), the chord's degree+// boundaries as faint ticks, the ball with a short trail showing which+// way it travels, the wall it came from (dim brass), the one it strikes+// (brass), and in teal how long until it reaches the wall ahead. The+// space answers "why this note".+// PendulumBarView the bar as a 1/16 strip the generated notes fall into (height =+// pitch within the chord), this bar in brass, the last bar's notes+// ahead of the playhead in deep brass. It answers "when".+// PendulumBallList the rail's ball rows — division · rate · phase · note — sized to fit.+// PendulumVoiceBars a tiny level bar per sounding voice.++using System;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Media;+using Nota.Application;++namespace Nota.App;++internal static class PendulumInk+{+ public static FormattedText Mono(string t, IBrush ink, double size = 7)+ => new(t, NotaNum.Culture, FlowDirection.LeftToRight, NotaFonts.Mono, size, ink);++ /// <summary>Seconds as the lanes print them: 0.12 s, 1.3 s, or — when never.</summary>+ public static string Secs(double s) => s < 0 || s > 99 ? "—" : s < 10 ? NotaNum.Unit(s, "0.00", "s") : NotaNum.Unit(s, "0.0", "s");++ /// <summary>A moving ball "strikes" while it is this close to a wall (in lane widths)+ /// and within its turning half of the swing.</summary>+ public static bool AtWall(PendulumModel.Ball b)+ => b.Dir != 0 && (b.Pos < 0.04 || b.Pos > 0.96) && Math.Min(Math.Min(b.Phase, Math.Abs(b.Phase - 0.5)), 1.0 - b.Phase) < 0.08;+ /// <summary>A note is "fresh" (lit) for this long after its ball fired.</summary>+ public const double Fresh = 0.16;+}++internal sealed class PendulumLanesView : Control+{+ private PendulumModel.Snapshot _s = new();+ private int _count = 4, _motion = 1;+ private int[] _held = Array.Empty<int>();+ private string _div = "1/2";++ public void Set(PendulumModel.Snapshot s, int count, int motion, int[] held, string divLabel)+ {+ _s = s; _count = Math.Clamp(count, 1, PendulumModel.MaxBalls); _motion = motion;+ _held = held; _div = divLabel;+ 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));++ const double padX = 6, padTop = 4, axisH = 9, leftW = 22, rightW = 20, gap = 6;+ double laneX0 = padX + leftW + gap, laneX1 = w - padX - rightW - gap, laneW = Math.Max(10, laneX1 - laneX0);+ double top = padTop, bot = h - axisH - 2;+ double rowH = (bot - top) / _count;+ int degrees = Math.Max(0, _held.Length);++ var accent = NotaPalette.Accent;+ var hairPen = new Pen(NotaPalette.GraphBorder, 1);+ var tickPen = new Pen(NotaPalette.GridBeat, 1);+ var leadPen = new Pen(NotaPalette.Wash(NotaPalette.Teal, 0x8C), 1);++ for (int b = 0; b < _count; b++)+ {+ var ball = _s.BallState[b];+ double cy = top + rowH * (b + 0.5);+ double wallTop = cy - rowH * 0.36, wallBot = cy + rowH * 0.36;++ // Division (or free cycle) left, the ball's note right.+ var divT = PendulumInk.Mono(_div, NotaPalette.AccentDim);+ ctx.DrawText(divT, new Point(padX, cy - divT.Height / 2));+ bool fresh = ball.Pitch >= 0 && ball.Since < PendulumInk.Fresh;+ var noteT = PendulumInk.Mono(PendulumModel.NoteName(ball.Pitch), fresh ? NotaPalette.AccentBright : ball.Pitch >= 0 ? NotaPalette.TextPrimary : NotaPalette.TextDisabled);+ ctx.DrawText(noteT, new Point(w - padX - noteT.Width, cy - noteT.Height / 2));++ // The lane: centre hairline, degree boundaries, the two walls.+ ctx.DrawLine(hairPen, new Point(laneX0, cy), new Point(laneX1, cy));+ for (int d = 1; d < degrees; d++)+ {+ double tx = laneX0 + laneW * d / degrees;+ ctx.DrawLine(tickPen, new Point(tx, cy - rowH * 0.18), new Point(tx, cy + rowH * 0.18));+ }+ bool striking = PendulumInk.AtWall(ball);+ bool strikeHigh = ball.Pos > 0.5;+ IBrush WallInk(bool high)+ {+ if (striking && strikeHigh == high) return accent;+ bool cameFrom = ball.Dir > 0 ? !high : ball.Dir < 0 && high;+ return cameFrom ? NotaPalette.AccentDim : NotaPalette.BorderStrong;+ }+ ctx.DrawRectangle(WallInk(false), null, new RoundedRect(new Rect(laneX0 - 1, wallTop, 2, wallBot - wallTop), 1));+ ctx.DrawRectangle(WallInk(true), null, new RoundedRect(new Rect(laneX1 - 1, wallTop, 2, wallBot - wallTop), 1));++ double bx = laneX0 + Math.Clamp(ball.Pos, 0, 1) * laneW;++ // Where it is going: a teal lead to the wall ahead and the time to get there.+ if (ball.Dir != 0 && !striking)+ {+ double wx = ball.Dir > 0 ? laneX1 : laneX0;+ ctx.DrawLine(leadPen, new Point(bx, cy), new Point(wx, cy));+ string t = PendulumInk.Secs(ball.ToWall);+ var ft = PendulumInk.Mono(ball.Dir > 0 ? $"→ {t}" : $"{t} ←", NotaPalette.TealBright);+ double ty = Math.Max(cy - rowH * 0.5, cy - ft.Height - 2);+ ctx.DrawText(ft, new Point(ball.Dir > 0 ? laneX1 - 4 - ft.Width : laneX0 + 4, ty));+ }+ else if (striking)+ {+ var ft = PendulumInk.Mono("hit", NotaPalette.AccentBright);+ double ty = Math.Max(cy - rowH * 0.5, cy - ft.Height - 2);+ ctx.DrawText(ft, new Point(strikeHigh ? laneX1 - 4 - ft.Width : laneX0 + 4, ty));+ }++ // Trail: three earlier places along the swing, fading, then the ball itself.+ if (ball.Dir != 0)+ {+ double sign = Math.Sign(ball.Rate);+ for (int k = 3; k >= 1; k--)+ {+ double ph = ball.Phase - sign * k * 0.018;+ ph -= Math.Floor(ph);+ double tx = laneX0 + PendulumModel.Position(ph, _motion) * laneW;+ double r = 2.5 + (3 - k) * 0.5;+ byte a = k switch { 3 => 0x38, 2 => 0x66, _ => 0x9E };+ ctx.DrawEllipse(NotaPalette.Wash(NotaPalette.Accent, a), null, new Point(tx, cy), r, r);+ }+ }+ double br = Math.Min(striking ? 5.5 : 4.5, rowH * 0.36);+ if (striking) ctx.DrawEllipse(NotaPalette.AccentBright, new Pen(NotaPalette.AccentSubtle, 2), new Point(bx, cy), br, br);+ else ctx.DrawEllipse(NotaPalette.AccentBright, null, new Point(bx, cy), br, br);+ }++ // Axis: what x means.+ double ay = h - axisH - 1;+ var lo = PendulumInk.Mono("low", NotaPalette.TextAxis);+ var mid = PendulumInk.Mono(degrees > 0 ? $"x = pitch · {degrees} notes held" : "x = pitch · hold a chord", NotaPalette.TextAxis);+ var hi = PendulumInk.Mono("high", NotaPalette.TextAxis);+ ctx.DrawText(lo, new Point(laneX0, ay));+ ctx.DrawText(mid, new Point(laneX0 + (laneW - mid.Width) / 2, ay));+ ctx.DrawText(hi, new Point(laneX1 - hi.Width, ay));+ }+}++internal sealed class PendulumBarView : Control+{+ private PendulumModel.Snapshot _s = new();+ private string _quant = "1/16", _sort = "up";++ public void Set(PendulumModel.Snapshot s, string quant, string sort)+ {+ _s = s; _quant = quant; _sort = sort;+ InvalidateVisual();+ }++ /// <summary>The generated notes the strip shows (this bar and the last bar's tail).</summary>+ public static int Visible(PendulumModel.Snapshot s)+ {+ int n = 0;+ for (int i = 0; i < s.StepCount; i++) if (s.Steps[i].Pitch >= 0) n++;+ return n;+ }++ 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));++ const double padX = 6;+ var cap = new FormattedText("NOTES", NotaNum.Culture, FlowDirection.LeftToRight, NotaFonts.SansBold, 7, NotaPalette.TextTertiary);+ ctx.DrawText(cap, new Point(padX, 3));+ var sub = PendulumInk.Mono($"bar · quantize {_quant.ToLowerInvariant()}", NotaPalette.TextAxis);+ ctx.DrawText(sub, new Point(padX + cap.Width + 6, 3));+ int shown = Visible(_s);+ var right = PendulumInk.Mono($"{_sort} · {shown} {(shown == 1 ? "note" : "notes")}", NotaPalette.TealBright);+ ctx.DrawText(right, new Point(w - padX - right.Width, 3));++ int n = Math.Max(1, _s.StepCount);+ double gx0 = padX, gx1 = w - padX, gy0 = 4 + cap.Height + 2, gy1 = h - 3;+ double cw = (gx1 - gx0 + 1) / n;+ int lo = int.MaxValue, hi = int.MinValue;+ for (int i = 0; i < n; i++) if (_s.Steps[i].Pitch >= 0) { lo = Math.Min(lo, _s.Steps[i].Pitch); hi = Math.Max(hi, _s.Steps[i].Pitch); }++ // The freshest note of this bar: the last filled step at or before the playhead.+ int play = Math.Clamp((int)(_s.BarPos * n), 0, n - 1), latest = -1;+ for (int k = 0; k < n; k++)+ {+ int i = ((play - k) % n + n) % n;+ if (_s.Steps[i].Pitch >= 0 && _s.Steps[i].Age == 0) { latest = i; break; }+ }++ double fullH = gy1 - gy0;+ for (int i = 0; i < n; i++)+ {+ var st = _s.Steps[i];+ double x = gx0 + i * cw;+ double frac; IBrush ink;+ if (st.Pitch < 0) { frac = 0.18; ink = NotaPalette.GridBeat; }+ else+ {+ frac = hi > lo ? 0.5 + 0.5 * (st.Pitch - lo) / (double)(hi - lo) : 0.75;+ ink = i == latest ? NotaPalette.AccentBright : st.Age == 0 ? NotaPalette.Accent : NotaPalette.AccentDeep;+ }+ double bh = Math.Max(2, fullH * frac);+ ctx.DrawRectangle(ink, null, new RoundedRect(new Rect(x, gy1 - bh, Math.Max(1, cw - 1), bh), 1));+ }+ double px = gx0 + Math.Clamp(_s.BarPos, 0, 1) * (gx1 - gx0);+ ctx.DrawLine(new Pen(NotaPalette.AccentDim, 1), new Point(px, gy0 - 2), new Point(px, gy1 + 2));+ }+}++internal sealed class PendulumBallList : Control+{+ private PendulumModel.Snapshot _s = new();+ private int _count = 4;+ private string _div = "1/2";+ private double _gap = 4, _maxRow = 17;++ public double Gap { get => _gap; set { _gap = value; InvalidateVisual(); } }+ public double MaxRow { get => _maxRow; set { _maxRow = value; InvalidateVisual(); } }++ public void Set(PendulumModel.Snapshot s, int count, string divLabel)+ {+ _s = s; _count = Math.Clamp(count, 1, PendulumModel.MaxBalls); _div = divLabel;+ InvalidateVisual();+ }++ public override void Render(DrawingContext ctx)+ {+ double w = Bounds.Width, h = Bounds.Height;+ if (w <= 0 || h <= 0) return;+ // Rows keep their natural height while they fit; when they don't, the gaps close to+ // 1px first and then the rows shrink — every ball keeps its row.+ double gap = _gap;+ double rowH = Math.Min(_maxRow, (h - gap * (_count - 1)) / _count);+ if (rowH < 11) { gap = 1; rowH = Math.Min(_maxRow, (h - gap * (_count - 1)) / _count); }+ rowH = Math.Max(6, rowH);+ for (int b = 0; b < _count; b++)+ {+ var ball = _s.BallState[b];+ double y = b * (rowH + gap);+ bool sel = b == _s.LastBall;+ var rr = new RoundedRect(new Rect(0.5, y + 0.5, w - 1, rowH - 1), NotaRadius.BadgeValue);+ ctx.DrawRectangle(sel ? NotaPalette.AccentSubtle : NotaPalette.BgSunken, new Pen(sel ? NotaPalette.BorderBrass : NotaPalette.GraphBorder, 1), rr);+ double cy = y + rowH / 2, x = 6;+ ctx.DrawEllipse(sel ? NotaPalette.AccentBright : NotaPalette.Accent, null, new Point(x + 3, cy), 3, 3);+ x += 11;+ void Col(string t, IBrush ink, double width)+ {+ var ft = PendulumInk.Mono(t, ink);+ ctx.DrawText(ft, new Point(x, cy - ft.Height / 2));+ x += width;+ }+ Col(_div, NotaPalette.TextPrimary, 25);+ Col(NotaNum.Unit(ball.Rate * 100, "+0;−0;0", "%"), sel ? NotaPalette.AccentBright : NotaPalette.TextSecondary, 33);+ Col(NotaNum.Unit(ball.Phase * 100, "0", "%"), sel ? NotaPalette.TextMuted : NotaPalette.TextTertiary, 30);+ bool fresh = ball.Pitch >= 0 && ball.Since < PendulumInk.Fresh;+ var note = PendulumInk.Mono(PendulumModel.NoteName(ball.Pitch), fresh ? NotaPalette.AccentBright : ball.Pitch >= 0 ? NotaPalette.TextPrimary : NotaPalette.TextDisabled);+ ctx.DrawText(note, new Point(w - 6 - note.Width, cy - note.Height / 2));+ }+ }+}++internal sealed class PendulumVoiceBars : Control+{+ private readonly double[] _lv = new double[PendulumModel.MaxLevels];+ private int _n;++ public PendulumVoiceBars() { Width = PendulumModel.MaxLevels * 3; Height = 11; }++ public void Set(double[] levels)+ {+ _n = 0;+ foreach (var l in levels) if (l > 0.002 && _n < _lv.Length) _lv[_n++] = l;+ InvalidateVisual();+ }++ public override void Render(DrawingContext ctx)+ {+ double h = Bounds.Height;+ if (h <= 0) return;+ double max = 0;+ for (int i = 0; i < _n; i++) max = Math.Max(max, _lv[i]);+ double x = Bounds.Width - _n * 3;+ for (int i = 0; i < _n; i++)+ {+ double lh = Math.Max(1, h * Math.Clamp(Math.Sqrt(_lv[i]), 0, 1));+ IBrush ink = _lv[i] >= max - 1e-6 ? NotaPalette.AccentBright : _lv[i] > 0.3 ? NotaPalette.Accent : NotaPalette.AccentDeep;+ ctx.DrawRectangle(ink, null, new Rect(x + i * 3, h - lh, 2, lh));+ }+ }+}diff --git a/src/managed/Nota.App/Controls/PendulumViz.cs b/src/managed/Nota.App/Controls/PendulumViz.csdeleted file mode 100644index 2e9d4c9f..00000000--- a/src/managed/Nota.App/Controls/PendulumViz.cs+++ /dev/null@@ -1,188 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.-//-// Nota Pendulum field (mockup 2l) — the instrument drawn as itself. Balls swing across a-// triangular ∧∨ field; horizontal position = pitch (the held chord's degrees, labelled-// along the top with lane lines). Both swing paths are shown (∧ solid teal, ∨ dimmed);-// a dashed trigger line runs through the apex with a ring where a hit lands. Each ball-// drags a fading motion trail (the trail) showing which way it travels, and the ball-// currently crossing a degree lights accent-bright. Illustrative: it self-animates from-// the current Rate/Balls/Motion/Spread params via an internal timer (so it lives even-// when the transport is stopped) and mirrors the DSP's motion curve, but is not-// sample-locked to the audio.--using System;-using System.Globalization;-using Avalonia;-using Avalonia.Controls;-using Avalonia.Media;-using Avalonia.Threading;-using static Nota.App.DeviceCardKit;--namespace Nota.App;--internal sealed class PendulumViz : Control-{- private static readonly IBrush Sunken = NotaPalette.BgSunken;- private static readonly IBrush FieldBorder = NotaPalette.GraphBorder;- private static readonly IBrush Brass = NotaPalette.Accent;- private static readonly IBrush AccentBright = NotaPalette.AccentBright;- private static readonly IBrush Lane = NotaPalette.SurfaceCard;- private static readonly IBrush TextTertiary = NotaPalette.TextTertiary;- private static Color TrailColor => NotaPalette.Accent.Color;- private static readonly IBrush RailUp = NotaPalette.Teal; // ∧ solid teal- private static readonly IBrush RailDn = NotaPalette.Wash(NotaPalette.Teal, 0x8C); // ∨ dimmed- private static readonly Pen TriggerPen = new(NotaPalette.Wash(NotaPalette.AccentBright, 0x47), 1) { DashStyle = DashStyle.Dash };- private static readonly Pen ApexPen = new(NotaPalette.Wash(NotaPalette.AccentBright, 0x59), 1);- private static readonly Typeface Face = NotaFonts.Mono;-- private const int MaxBalls = 6;- private const int TrailLen = 14;- private readonly double[] _phase = new double[MaxBalls];- private readonly double[,] _trailX = new double[MaxBalls, TrailLen]; // stored 0..1 field position- private readonly double[,] _trailB = new double[MaxBalls, TrailLen]; // stored -1..1 vertical bob- private int _trailHead;- private readonly int[] _lastDeg = new int[MaxBalls];-- private int _count = 4, _degrees = 5, _motion = 1;- private double _cyclesPerSec = 0.8, _spread = 0.25;- private int[] _held = Array.Empty<int>();- private string _lastTrig = "";- private readonly DispatcherTimer _timer;- private readonly bool _mini;-- public PendulumViz(bool mini = false)- {- _mini = mini;- MinWidth = 200; MinHeight = mini ? 40 : 80;- for (int i = 0; i < MaxBalls; i++) { _phase[i] = (double)i / MaxBalls; _lastDeg[i] = -1; }- _timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(33) };- _timer.Tick += (_, _) =>- {- const double dt = 0.033;- _trailHead = (_trailHead + 1) % TrailLen;- for (int i = 0; i < _count; i++)- {- _phase[i] += _cyclesPerSec * (1.0 + _spread * i * 0.37) * dt;- _phase[i] -= Math.Floor(_phase[i]);- double pos = Position(_phase[i], _motion);- _trailX[i, _trailHead] = pos;- _trailB[i, _trailHead] = Math.Sin(2 * Math.PI * _phase[i]);- if (_degrees > 0)- {- int deg = Math.Clamp((int)(pos * _degrees), 0, _degrees - 1);- if (deg != _lastDeg[i]) { _lastDeg[i] = deg; if (_held.Length > 0) _lastTrig = NoteName(_held[Math.Clamp(deg, 0, _held.Length - 1)]); }- }- }- InvalidateVisual();- };- }-- protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) { base.OnAttachedToVisualTree(e); _timer.Start(); }- protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e) { _timer.Stop(); base.OnDetachedFromVisualTree(e); }-- // Live per-ball state, for the editor's per-ball list to stay in step with the field.- public double BallPhase(int i) => (i >= 0 && i < MaxBalls) ? _phase[i] : 0;- public int BallDegree(int i) => (i >= 0 && i < MaxBalls) ? _lastDeg[i] : -1;-- // count = balls, motion 0..3 curve, cyclesPerSec (signed → direction), spread 0..1,- // held = the currently sounding chord pitches (empty ⇒ show placeholder lanes).- public void Set(int count, int motion, double cyclesPerSec, double spread, int[] held)- {- _count = Math.Clamp(count, 1, MaxBalls); _motion = Math.Clamp(motion, 0, 3);- _cyclesPerSec = cyclesPerSec; _spread = spread;- _held = held ?? Array.Empty<int>();- _degrees = _held.Length > 0 ? _held.Length : 5;- if (_held.Length == 0) _lastTrig = "";- }-- private static double Position(double ph, int type)- {- double tri = 1.0 - 2.0 * Math.Abs(ph - 0.5);- return type switch- {- 1 => 0.5 - 0.5 * Math.Cos(2 * Math.PI * ph),- 2 => tri * tri * (3.0 - 2.0 * tri),- 3 => Math.Clamp(1.0 - Math.Pow(1.0 - tri, 2.0) + 0.06 * Math.Sin(2 * Math.PI * 3.0 * tri) * (1.0 - tri), 0, 1),- _ => tri,- };- }-- 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 labelH = _mini ? 2 : 14, capH = _mini ? 2 : 12;- double pad = 8, x0 = pad, x1 = w - pad;- double top = labelH + 2, bot = h - capH - 2;- double W = x1 - x0, midY = (top + bot) / 2, cx = (x0 + x1) / 2;- double amp = (bot - top) * 0.34;-- double LaneX(int d) => x0 + (_degrees <= 1 ? 0.5 : (double)d / (_degrees - 1)) * W;-- // Pitch lane lines + note-name labels along the top.- for (int d = 0; d < _degrees; d++)- {- double gx = LaneX(d);- ctx.DrawLine(new Pen(Lane, 1), new Point(gx, top), new Point(gx, bot));- if (!_mini && d < _held.Length)- {- var ft = new FormattedText(NoteName(_held[d]), CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Face, 9, TextTertiary);- ctx.DrawText(ft, new Point(Math.Clamp(gx - ft.Width / 2, 1, w - ft.Width - 1), 2));- }- }-- // Both swing paths: ∧ solid, ∨ dimmed — the generative rails (teal = modulation).- var up = new StreamGeometry(); var dn = new StreamGeometry();- using (var gu = up.Open())- using (var gd = dn.Open())- {- gu.BeginFigure(new Point(x0, bot), false); gu.LineTo(new Point(cx, top)); gu.LineTo(new Point(x1, bot));- gd.BeginFigure(new Point(x0, top), false); gd.LineTo(new Point(cx, bot)); gd.LineTo(new Point(x1, top));- }- ctx.DrawGeometry(null, new Pen(RailDn, 1.4, lineJoin: PenLineJoin.Round), dn);- ctx.DrawGeometry(null, new Pen(RailUp, 1.6, lineJoin: PenLineJoin.Round), up);-- // Trigger line through the apex + a ring where the hit lands.- ctx.DrawLine(TriggerPen, new Point(cx, top - 2), new Point(cx, bot + 2));- if (!_mini) ctx.DrawEllipse(null, ApexPen, new Point(cx, top + 2), 8, 8);-- // Balls with fading motion trails (the trail): oldest → newest.- for (int i = 0; i < _count; i++)- {- double pos = Position(_phase[i], _motion);- double bx = x0 + pos * W;- double by = midY - Math.Sin(2 * Math.PI * _phase[i]) * amp;- int deg = Math.Clamp((int)(pos * _degrees), 0, _degrees - 1);- double slotX = LaneX(deg);- bool near = Math.Abs(bx - slotX) < W / Math.Max(1, _degrees * 3);-- for (int t = 1; t < TrailLen; t++)- {- int idx = ((_trailHead - t) % TrailLen + TrailLen) % TrailLen;- double frac = 1.0 - (double)t / TrailLen; // 1 = freshest trail sample- double tx = x0 + _trailX[i, idx] * W;- double ty = midY - _trailB[i, idx] * amp;- byte a = (byte)(frac * frac * 150);- double rr = 1.2 + frac * (_mini ? 1.6 : 2.6);- ctx.DrawEllipse(new SolidColorBrush(Color.FromArgb(a, TrailColor.R, TrailColor.G, TrailColor.B)), null, new Point(tx, ty), rr, rr);- }-- if (near && !_mini) ctx.DrawLine(new Pen(AccentBright, 1), new Point(slotX, top), new Point(slotX, bot));- double br = _mini ? 3.0 : 4.5;- ctx.DrawEllipse(near ? AccentBright : Brass, null, new Point(bx, by), br, br);- }-- if (_mini) return;-- // Captions: legend bottom-left, live trigger note bottom-right.- ctx.DrawText(new FormattedText("x = pitch · ∧ ∨ = swing paths", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Face, 8, TextTertiary), new Point(x0, bot + 2));- if (_lastTrig.Length > 0)- {- var ft = new FormattedText($"trigger at apex → {_lastTrig}", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Face, 8, AccentBright);- ctx.DrawText(ft, new Point(x1 - ft.Width, bot + 2));- }- }-}diff --git a/src/managed/Nota.App/DeviceCardKit.cs b/src/managed/Nota.App/DeviceCardKit.csindex 87bbd73e..e72fb4e5 100644--- a/src/managed/Nota.App/DeviceCardKit.cs+++ b/src/managed/Nota.App/DeviceCardKit.cs@@ -114,10 +114,11 @@ internal static class DeviceCardKit// solid brass with dark text — a fill, not an outline. 9px inside a device. Two to four// choices; more than four is a dropdown. `current` returns the lit index, or −1 when// the value sits between choices. `fill` spreads the segments over the full width;- // `padX` narrows each segment's side padding where a strip must fit a tight column.+ // `padX` narrows each segment's side padding where a strip must fit a tight column, and+ // `fontSize` drops to 8 (never below 7) where a dense control strip needs it.// Left button picks; right-click bubbles. `sync` repaints — register it with the card.internal static Border Segments(string[] names, Func<int> current, Action<int> pick, out Action sync,- bool fill = false, double minSegWidth = 0, Func<bool>? dim = null, double padX = 6)+ bool fill = false, double minSegWidth = 0, Func<bool>? dim = null, double padX = 6, double fontSize = NotaType.DeviceSection){int n = names.Length;var cells = new Border[n];@@ -128,7 +129,7 @@ internal static class DeviceCardKitint iv = i;var tb = new TextBlock{- Text = names[i], FontSize = NotaType.DeviceSection, HorizontalAlignment = HorizontalAlignment.Center,+ Text = names[i], FontSize = Math.Max(7, fontSize), HorizontalAlignment = HorizontalAlignment.Center,VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis,};var c = new Borderdiff --git a/src/managed/Nota.App/DeviceCards/Instruments/PendulumInstrumentCard.cs b/src/managed/Nota.App/DeviceCards/Instruments/PendulumInstrumentCard.csindex 7a26da2c..beddaccd 100644--- a/src/managed/Nota.App/DeviceCards/Instruments/PendulumInstrumentCard.cs+++ b/src/managed/Nota.App/DeviceCards/Instruments/PendulumInstrumentCard.cs@@ -1,17 +1,32 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// Detail · Devices — the Nota Pendulum editor (instrument kind 8), rebuilt to mockup 2l-// (700×260 on the shared shell). The pendulum field IS the instrument, so it gets the-// stage: a LIVE strip (Sync/Free · divisions · bipolar Rate · Motion curve) over a body-// of tab rail (70: Balls / Voice + ball count) | the field viz | a right area that is-// either the per-ball list (Balls tab) or the voice/env knobs + spread rail (Voice tab,-// with the field collapsed to a 62px strip so it's never lost). Teal marks only the-// generative bits — the swing paths and Humanize. All controls are plugin params →-// automation / persist / clone.+// Detail · Devices — the Nota Pendulum editor (instrument kind 8): arpeggios out of+// bounces, in the 700 × 260 card the almanac draws for it. Held notes form a chord; balls+// swing across it and every degree a ball crosses plays that note.+//+// Centre two tabs:+// Balls — Free / Sync · the division (or the free swing time) · bipolar+// Rate · the Motion curve; then one lane per ball (x = pitch, the+// wall it came from, the wall it strikes, the time to the wall ahead)+// over the bar strip the generated notes fall into. The space says+// "why this note", the strip "when".+// Voice — what the bounces sound with: the wave, tone / bright / FM / note+// length, the envelope and volume; the last note and a level bar+// per sounding voice.+// Rail 186 the balls themselves (division · rate · phase · note), always visible;+// under them the tab's own controls — count, sort, quantize, Hold / First+// note / Reset on Balls; spread (rate, detune, pan, humanize), the scale and+// Humanize / Reset on Voice.+//+// Everything live comes from the engine's telemetry (PendulumModel), so the lanes are the+// balls the audio thread is actually swinging. Brass is the parameter, teal is where a+// ball is going and the spread (modulation). Every control is a plugin param →+// automation / persist / clone, and the card follows automation live.using System;using System.Collections.Generic;+using System.Diagnostics;using Avalonia;using Avalonia.Controls;using Avalonia.Input;@@ -28,28 +43,19 @@ internal sealed class PendulumInstrumentCard : IInstrumentCardpublic string Subtitle => "GEN KEYS";public double CardWidth => 700;- private const int MaxBalls = 6;- private static readonly double[] DivBeats = { 4, 2, 1, 0.5, 0.25 };- private static readonly string[] DivNames = { "1/1", "1/2", "1/4", "1/8", "1/16" };- private static readonly string[] MotionNames = { "Linear", "Pendulum", "Ease", "Bounce" };- private static readonly string[] WaveNames = { "Keys", "Glass", "Saw", "Sqr", "Bell" };- private static readonly string[] QuantNames = { "Off", "1/16", "1/8" };- private static readonly string[] ModeNames = { "Off", "Major", "Minor", "Dorian", "Mixo", "Penta" };- private static readonly string[] RootNames = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };-- 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 TealC = NotaPalette.Teal;- private static readonly IBrush TxtC = NotaPalette.TextPrimary;- private static readonly IBrush MutedC = NotaPalette.TextTertiary;- private static readonly IBrush AmberSubtle = NotaPalette.Wash(NotaPalette.Accent, 0x28);- private static readonly IBrush RowLit = NotaPalette.SurfaceRaised;-- private static double Exp(double v, double lo, double hi) => lo * Math.Pow(hi / lo, Math.Clamp(v, 0, 1));+ public string? VoiceLabel(IAudioEngine engine, int trackId, int active)+ {+ for (int i = 0, n = engine.PluginParamCount(trackId, -1); i < n; i++)+ if (engine.PluginParamId(trackId, -1, i) == "balls")+ return $"{PendulumModel.BallCount(engine.PluginParamGet(trackId, -1, i))} balls";+ return null;+ }++ private const double RailW = 186, TabH = 20, StripH = 22, StatusH = 18, BarH = 34;+ private static readonly string[] TabNames = { "Balls", "Voice" };++ private static string Secs(double s) => NotaNum.Time(s);+ private static string DbOf(float v) => NotaNum.Db(v <= 0.001f ? double.NegativeInfinity : 20 * Math.Log10(v));public Control Build(DeviceCardContext ctx){@@ -58,295 +64,569 @@ internal sealed class PendulumInstrumentCard : IInstrumentCardint pc = engine.PluginParamCount(track, -1);var idx = new Dictionary<string, int>();for (int i = 0; i < pc; i++) idx[engine.PluginParamId(track, -1, i)] = i;- float G(string id) => idx.TryGetValue(id, out var i) ? engine.PluginParamGet(track, -1, i) : 0f;int I(string id) => idx.TryGetValue(id, out var i) ? i : -1;- int GI(string id, int n) => Math.Clamp((int)Math.Round(G(id) * (n - 1)), 0, n - 1);- void SetId(string id, double v) { if (I(id) is var ci and >= 0) engine.PluginParamSet(track, -1, ci, (float)v); }+ float G(string id) => I(id) is var i and >= 0 ? engine.PluginParamGet(track, -1, i) : 0f;+ void SetP(string id, float v) { if (I(id) is var i and >= 0) engine.PluginParamSet(track, -1, i, Math.Clamp(v, 0f, 1f)); }+ void Begin(string id) { if (I(id) >= 0) engine.BeginAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, id); }+ void End(string id) { if (I(id) >= 0) engine.EndAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, id); }+ void Write(string id, float v) { Begin(id); SetP(id, v); End(id); }+ float Def(string id) => I(id) is var i and >= 0 ? engine.InstrumentParamDefault(track, i) : 0f;+ int Sel(string id, int n) => PendulumModel.Index(G(id), n);+ int Count() => PendulumModel.BallCount(G("balls"));+ bool Synced() => G("sync") >= 0.5f;+ string DivLabel() => Synced() ? PendulumModel.DivNames[Sel("division", 5)] : NotaNum.Unit(PendulumModel.FreeSeconds(G("freerate")), "0.0", "s");var readouts = new List<Action>();- var fieldFull = new PendulumViz { VerticalAlignment = VerticalAlignment.Stretch };- var fieldMini = new PendulumViz(mini: true) { Height = 62 };+ int tab = 0;+ var snap = new PendulumModel.Snapshot();+ var scope = new float[PendulumModel.ScopeLength];var heldBuf = new int[16];- int heldN = 0;+ int[] held = Array.Empty<int>();++ var lanes = new PendulumLanesView { VerticalAlignment = VerticalAlignment.Stretch };+ ToolTip.SetTip(lanes, "One lane per ball: x is pitch, low to high. Crossing a chord degree plays that note; teal shows the wall ahead");+ var bar = new PendulumBarView { Height = BarH };+ ToolTip.SetTip(bar, "The bar: generated notes land on the 1/16 grid — brass this bar, deep brass the last bar ahead of the playhead");+ var ballList = new PendulumBallList();+ var voiceBars = new PendulumVoiceBars { VerticalAlignment = VerticalAlignment.Center };++ static TextBlock Cap(string t, IBrush? c = null) => new()+ {+ Text = t, FontSize = NotaType.KnobLabel, FontWeight = FontWeight.Bold,+ LetterSpacing = NotaType.KnobLabelTracking, Foreground = c ?? TextTertiary,+ VerticalAlignment = VerticalAlignment.Center,+ };+ static TextBlock Mono(string t, IBrush? c = null, double fs = 7) => new()+ {+ Text = t, FontSize = fs, Foreground = c ?? TextSecondary,+ VerticalAlignment = VerticalAlignment.Center, FontFamily = NotaFonts.MonoFamily,+ };++ var hint = Mono("", TextTertiary);+ hint.HorizontalAlignment = HorizontalAlignment.Right; hint.Margin = new Thickness(0, 0, 8, 0);+ hint.TextTrimming = TextTrimming.CharacterEllipsis;+ var status = new TextBlock { FontSize = 8, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };+ var meta = Mono("", TextSecondary, 8);+ var lastNote = Mono("", TextTertiary);+ Action showTab = () => { };++ // ---- live state -------------------------------------------------------------+ // The engine's snapshot; inside a rack chain the scope is empty, so the balls are+ // swung here from the params instead (same curves, not sample-locked).+ var simPhase = new double[PendulumModel.MaxBalls];+ for (int b = 0; b < simPhase.Length; b++) simPhase[b] = (double)b / simPhase.Length;+ var clock = Stopwatch.StartNew();+ double lastT = 0;+ void Simulate()+ {+ double now = clock.Elapsed.TotalSeconds, dt = Math.Clamp(now - lastT, 0, 0.1);+ lastT = now;+ int count = Count(), motion = Sel("motion", 4);+ double cyc = PendulumModel.CycleSeconds(G, engine.Bpm) * Math.Abs(PendulumModel.RateSigned(G("rate")) * 2.0);+ snap.Balls = count; snap.Held = held.Length;+ for (int b = 0; b < PendulumModel.MaxBalls; b++)+ {+ double rate = PendulumModel.BallRate(G("rate"), G("spread"), b);+ double inc = cyc > 0 && double.IsFinite(cyc) ? rate * 2.0 / cyc : 0; // phase per second+ double ph = simPhase[b] + inc * dt;+ ph -= Math.Floor(ph);+ simPhase[b] = ph;+ int dir = Math.Abs(inc) < 1e-9 ? 0 : (inc > 0 ? ph < 0.5 : ph > 0.5) ? 1 : -1;+ double next = inc > 0 ? (ph < 0.5 ? 0.5 : 1.0) : (ph > 0.5 ? 0.5 : 0.0);+ double toWall = dir == 0 ? -1 : Math.Abs(next - ph) / Math.Abs(inc);+ snap.BallState[b] = new PendulumModel.Ball(ph, PendulumModel.Position(ph, motion), dir, -1, toWall, 1e9, rate, -1);+ }+ double bpb = 4, beat = now * engine.Bpm / 60.0;+ snap.BarPos = beat / bpb - Math.Floor(beat / bpb);+ snap.StepCount = 16;+ }++ void Poll()+ {+ int n = engine.InstrumentScope(track, scope);+ PendulumModel.Parse(scope.AsSpan(0, Math.Max(0, n)), snap);+ int hn = engine.InstrumentHeldNotes(track, heldBuf);+ if (hn != held.Length) held = new int[hn];+ Array.Copy(heldBuf, held, hn);+ if (!snap.Live) Simulate();+ }void Refresh(){- int count = Math.Clamp(2 + (int)Math.Round(G("balls") * 4), 2, MaxBalls);- int motion = GI("motion", 4);- double spread = G("spread");- double rateMult = (G("rate") - 0.5) * 4.0;- bool synced = G("sync") >= 0.5f;- double divB = DivBeats[GI("division", 5)];- double freeSec = Exp(G("freerate"), 0.1, 4.0);- double cyclesPerSec = synced ? rateMult * (120.0 / 60.0) / divB : rateMult / freeSec;- heldN = engine.InstrumentHeldNotes(track, heldBuf);- var held = new int[heldN];- Array.Copy(heldBuf, held, heldN);- fieldFull.Set(count, motion, cyclesPerSec, spread, held);- fieldMini.Set(count, motion, cyclesPerSec, spread, held);- foreach (var a in readouts) a();+ foreach (var r in readouts) r();+ hint.Text = Hint();+ status.Text = Summary();}- // ---------- shared builders ----------- Control Cap(string t, IBrush? c = null) => new TextBlock { Text = t, FontSize = 8, FontWeight = FontWeight.Bold, Foreground = c ?? MutedC, VerticalAlignment = VerticalAlignment.Center };+ void Live()+ {+ Poll();+ int count = Count();+ var sorted = held;+ if (G("chordsort") >= 0.5f) { sorted = (int[])held.Clone(); Array.Reverse(sorted); }+ lanes.Set(snap, count, Sel("motion", 4), sorted, DivLabel());+ bar.Set(snap, PendulumModel.QuantNames[Sel("quantize", 3)], G("chordsort") >= 0.5f ? "down" : "up");+ ballList.Set(snap, count, DivLabel());+ voiceBars.Set(snap.Levels);+ int voices = snap.Live ? snap.Voices : Math.Max(0, engine.InstrumentVoiceCount(track));+ lastNote.Text = $"last note {PendulumModel.NoteName(snap.LastPitch)} · {voices} {(voices == 1 ? "voice" : "voices")}";+ double sr = engine.SampleRate > 0 ? engine.SampleRate : 48000;+ meta.Text = $"{voices}/{PendulumModel.Voices} voices · {NotaNum.Unit(sr / 1000, "0.#", "kHz")} · {NotaNum.Bpm(engine.Bpm)} BPM · CPU {NotaNum.Unit(engine.CpuLoad * 100, "0.0", "%")}";+ status.Text = Summary();+ }- // Param-backed segmented control (fill = active choice), writing i/(n-1).- Control Seg(string id, string[] names, double fs = 9, double padX = 6)+ // ---- shared builders ----------------------------------------------------------+ Control PKnob(string id, string label, Func<float, string> fmt, double size = NotaSize.KnobSecondary, double cellW = 54, IBrush? arc = null)+ {+ if (!idx.TryGetValue(id, out var pi)) return new Panel();+ var value = new TextBlock { Text = fmt(G(id)), Foreground = TextPrimary };+ var knob = new Knob(G(id), 1.0)+ {+ Accent = true, ArcColor = arc, Default = engine.InstrumentParamDefault(track, pi),+ Width = size, Height = size,+ };+ knob.ValueChanged += v => { engine.PluginParamSet(track, -1, pi, (float)v); value.Text = fmt((float)v); Refresh(); };+ knob.GestureBegin += () => Begin(id);+ knob.GestureEnd += () => End(id);+ ctx.AddInstFader(pi, knob, value, fmt);+ MidiLearn.Bind(knob, MidiTarget.PluginParam(track, -1, pi), engine.PluginParamName(track, -1, pi));+ var cell = KnobCell(label, knob, value, cellW);+ cell.VerticalAlignment = VerticalAlignment.Center;+ return cell;+ }++ Border Chips(string id, string[] names, double padX = 5, double fontSize = 8, Func<bool>? dim = null){int n = names.Length;- var seg = DeviceCardKit.Segments(names, () => GI(id, n), iv => { SetId(id, n > 1 ? iv / (double)(n - 1) : 0); Refresh(); }, out var sync);+ var seg = Segments(names, () => Sel(id, n), iv => { Write(id, iv / (float)(n - 1)); Refresh(); }, out var sync,+ dim: dim, padX: padX, fontSize: fontSize);readouts.Add(sync);- if (I(id) is var pi and >= 0) MidiLearn.Bind(seg, MidiTarget.PluginParam(track, -1, pi), id);+ if (I(id) is var pi and >= 0) MidiLearn.Bind(seg, MidiTarget.PluginParam(track, -1, pi), engine.PluginParamName(track, -1, pi));return seg;}- // Outlined 0/1 toggle (filled only when on); teal option marks modulation.- Control OutToggle(string id, string label, bool teal = false)+ Grid Slider(string label, string id, Func<string> text, bool bipolar = false, bool modulation = false,+ double labelWidth = 30, double valueWidth = 26){- var accent = teal ? TealC : Amber;- var accentLit = teal ? TealC : AmberLit;- var fillOn = teal ? NotaPalette.Wash(NotaPalette.Teal, 0x24) : AmberSubtle;- var b = new Border { CornerRadius = NotaRadius.Control, BorderThickness = new Thickness(1), Padding = new Thickness(8, 2), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center, Child = new TextBlock { Text = label, FontSize = 9, FontWeight = FontWeight.SemiBold } };- void Hi() { bool on = G(id) > 0.5f; b.Background = on ? fillOn : Brushes.Transparent; b.BorderBrush = on ? accent : Border2; ((TextBlock)b.Child!).Foreground = on ? accentLit : MutedC; }- b.PointerPressed += (_, _) => { SetId(id, G(id) > 0.5f ? 0 : 1); Refresh(); };- readouts.Add(Hi);- if (I(id) is var pi and >= 0) MidiLearn.Bind(b, MidiTarget.PluginParam(track, -1, pi), label);- return b;+ int pi = I(id);+ var row = SliderRow(label, () => G(id), v => { SetP(id, (float)v); Refresh(); }, text, out var sync,+ begin: pi >= 0 ? () => Begin(id) : null,+ end: pi >= 0 ? () => End(id) : null,+ reset: pi >= 0 ? () => { Write(id, engine.InstrumentParamDefault(track, pi)); Refresh(); } : null,+ bipolar: bipolar, labelWidth: labelWidth, valueWidth: valueWidth, modulation: modulation);+ row.ColumnSpacing = 5;+ readouts.Add(sync);+ if (pi >= 0) MidiLearn.Bind(row, MidiTarget.PluginParam(track, -1, pi), engine.PluginParamName(track, -1, pi));+ return row;}- // Momentary action button (writes 1 → the engine self-clears it).- Control ActionBtn(string label, Action click)+ // A rail button: raised at rest; a latching one turns brass-washed while on.+ Border RailButton(string text, Action click, Func<bool>? on = null, string? id = null, double height = 16){- var b = new Border { CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), BorderBrush = Border2, Background = RowLit, Padding = new Thickness(0, 2), Cursor = new Cursor(StandardCursorType.Hand), Child = new TextBlock { Text = label, FontSize = 9, Foreground = TextSecondary, HorizontalAlignment = HorizontalAlignment.Center } };- b.PointerPressed += (_, _) => click();+ var tb = new TextBlock+ {+ Text = text, FontSize = NotaType.KnobLabel, FontWeight = FontWeight.SemiBold,+ HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center,+ };+ var b = new Border+ {+ Height = height, CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1),+ Cursor = new Cursor(StandardCursorType.Hand), Child = tb,+ };+ void Paint()+ {+ bool lit = on?.Invoke() ?? false;+ b.Background = lit ? NotaPalette.AccentSubtle : NotaPalette.SurfaceRaised;+ b.BorderBrush = lit ? NotaPalette.BorderBrass : BorderDef;+ tb.Foreground = lit ? AccentBright : NotaPalette.TextStrong;+ }+ b.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return;+ click(); Paint(); Refresh(); e.Handled = true;+ };+ readouts.Add(Paint);+ Paint();+ if (id is not null && I(id) is var pi and >= 0) MidiLearn.Bind(b, MidiTarget.PluginParam(track, -1, pi), engine.PluginParamName(track, -1, pi));return b;}- // Real-unit gauge knob (own live-follow so the unit text isn't overwritten by Pct).- Control KUnit(string id, string name, Func<double, string> fmt, bool mod = false, double size = 34, double cellW = 54)+ static Grid Row(params (Control C, string W)[] cols){- if (!idx.TryGetValue(id, out var i)) return new Panel();- var value = new TextBlock { Text = fmt(G(id)), FontSize = 8, Foreground = TxtC };- value.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");- var knob = new Knob(G(id), 1.0) { Accent = true, ArcColor = mod ? Teal : null, Default = engine.InstrumentParamDefault(track, i), Width = size, Height = size };- knob.ValueChanged += v => { engine.PluginParamSet(track, -1, i, (float)v); value.Text = fmt(v); Refresh(); };- knob.GestureBegin += () => engine.BeginAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, id);- knob.GestureEnd += () => engine.EndAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, id);- MidiLearn.Bind(knob, MidiTarget.PluginParam(track, -1, i), name);- readouts.Add(() => { if (!knob.Dragging) { double v = G(id); if (Math.Abs(v - knob.Value) > 1e-3) knob.Value = v; value.Text = fmt(v); } });- return KnobCell(name, knob, value, cellW);+ var g = new Grid { ColumnSpacing = 4 };+ for (int i = 0; i < cols.Length; i++)+ {+ g.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Parse(cols[i].W)));+ Grid.SetColumn(cols[i].C, i); g.Children.Add(cols[i].C);+ }+ return g;}- // Horizontal param slider (label · track · value). Optional teal (modulation) fill.- Control HSlider(string id, string label, Func<double, string> fmt, bool teal = false, double lw = 38)+ // ---- Balls tab ----------------------------------------------------------------+ var syncSeg = Chips("sync", new[] { "Free", "Sync" }, padX: 5, fontSize: 7);+ ToolTip.SetTip(syncSeg, "Sync: a swing takes a note division of the tempo · Free: it takes a time in seconds");+ var divSeg = Chips("division", PendulumModel.DivNames, padX: 4, fontSize: 7);+ ToolTip.SetTip(divSeg, "How long one swing (low → high → low) takes at +100\u2009%");+ var timeRow = Slider("TIME", "freerate", () => Secs(PendulumModel.FreeSeconds(G("freerate"))), labelWidth: 0, valueWidth: 32);+ timeRow.Width = 100;+ ToolTip.SetTip(timeRow, "Free: seconds per swing at +100\u2009%");+ var cycleHost = new Panel { VerticalAlignment = VerticalAlignment.Center, Children = { divSeg, timeRow } };+ readouts.Add(() => { divSeg.IsVisible = Synced(); timeRow.IsVisible = !Synced(); });+ var rateRow = Slider("RATE", "rate", () => NotaNum.Unit(PendulumModel.RateSigned(G("rate")) * 100, "+0;−0;0", "%"), bipolar: true, labelWidth: 0, valueWidth: 28);+ ToolTip.SetTip(rateRow, "Swing speed — centre stops the balls, left of centre runs them in reverse");+ var motionSeg = Chips("motion", PendulumModel.MotionNames, padX: 4, fontSize: 7);+ ToolTip.SetTip(motionSeg, "The swing curve — Pendulum slows at the walls, Linear keeps one speed, Bounce settles with a ripple");+ var ballStrip = Row((syncSeg, "Auto"), (cycleHost, "Auto"), (rateRow, "*"), (Cap("MOTION"), "Auto"), (motionSeg, "Auto"));+ ballStrip.ColumnSpacing = 7;+ ballStrip.Margin = new Thickness(7, 0);++ var ballsView = new Grid { RowDefinitions = new RowDefinitions("*,Auto"), RowSpacing = 4, Margin = new Thickness(7, 5) };+ ballsView.Children.Add(lanes);+ Grid.SetRow(bar, 1); ballsView.Children.Add(bar);+ var ballsBody = new Grid { RowDefinitions = new RowDefinitions("Auto,*") };+ ballsBody.Children.Add(StripBox(ballStrip));+ Grid.SetRow(ballsView, 1); ballsBody.Children.Add(ballsView);++ // ---- Voice tab ----------------------------------------------------------------+ var waveSeg = Chips("wave", PendulumModel.WaveNames, padX: 6, fontSize: 7);+ ToolTip.SetTip(waveSeg, "The voice: soft Keys, bright Glass, Saw, hollow Square or inharmonic Bell");+ var voiceStrip = Row((waveSeg, "Auto"), (new Panel(), "*"), (lastNote, "Auto"), (voiceBars, "Auto"));+ voiceStrip.ColumnSpacing = 7;+ voiceStrip.Margin = new Thickness(7, 0);++ var toneRow = new StackPanel{- if (!idx.TryGetValue(id, out var pi)) return new Panel();- var row = DeviceCardKit.SliderRow(label, () => G(id), n => engine.PluginParamSet(track, -1, pi, (float)n), () => fmt(G(id)), out var sync,- begin: () => { engine.BeginAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, id); Refresh(); },- end: () => engine.EndAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, id),- labelWidth: lw, valueWidth: 34);- MidiLearn.Bind(row, MidiTarget.PluginParam(track, -1, pi), label);- readouts.Add(sync);- return row;- }+ Orientation = Orientation.Horizontal, Spacing = 22, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center,+ Children =+ {+ PKnob("tone", "TONE", PendulumModel.ToneWord),+ PKnob("bright", "BRIGHT", v => NotaNum.Pct(v)),+ PKnob("fm", "FM", v => NotaNum.Pct(v), arc: Teal),+ PKnob("notelen", "LENGTH", v => Secs(PendulumModel.NoteSeconds(v))),+ },+ };+ var envRow = new StackPanel+ {+ Orientation = Orientation.Horizontal, Spacing = 18, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center,+ Children =+ {+ PKnob("attack", "ATTACK", v => Secs(PendulumModel.AttackSeconds(v))),+ PKnob("decay", "DECAY", v => Secs(PendulumModel.DecaySeconds(v))),+ PKnob("release", "RELEASE", v => Secs(PendulumModel.ReleaseSeconds(v))),+ PKnob("volume", "VOLUME", DbOf),+ },+ };+ var toneHost = new Border { BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 0, 0, 1), Child = toneRow };+ var voiceView = new Grid { RowDefinitions = new RowDefinitions("*,*"), Margin = new Thickness(8, 0, 8, 4) };+ voiceView.Children.Add(toneHost);+ Grid.SetRow(envRow, 1); voiceView.Children.Add(envRow);+ var voiceBody = new Grid { RowDefinitions = new RowDefinitions("Auto,*") };+ voiceBody.Children.Add(StripBox(voiceStrip));+ Grid.SetRow(voiceView, 1); voiceBody.Children.Add(voiceView);- // Bipolar Rate slider: centre detent, fills from the middle, signed %, reverse hint.- Control RateBipolar()+ // ---- the tab strip ------------------------------------------------------------+ var bodies = new Control[] { ballsBody, voiceBody };+ var tabCells = new Border[TabNames.Length];+ var tabTexts = new TextBlock[TabNames.Length];+ var tabRow = new StackPanel { Orientation = Orientation.Horizontal };+ for (int i = 0; i < TabNames.Length; i++){- const double TW = 84;- var basec = new Border { Height = 5, Background = Inset, CornerRadius = NotaRadius.Badge, VerticalAlignment = VerticalAlignment.Center };- var center = new Border { Width = 1, Background = NotaPalette.BorderStrong, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Stretch, Margin = new Thickness(4, 1) };- var fill = new Border { Height = 5, Background = Amber, CornerRadius = NotaRadius.Badge, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center };- var handle = new Border { Width = 8, Height = 11, Background = NotaPalette.TextSecondary, CornerRadius = NotaRadius.Clip, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center };- var slot = new Panel { Width = TW, Height = 11, Children = { basec, center, fill, handle } };- var val = new TextBlock { Text = "", FontSize = 9, Foreground = TxtC, VerticalAlignment = VerticalAlignment.Center };- val.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");- bool drag = false;- void Upd() { double v = G("rate"); double cxp = TW * 0.5, hx = v * TW; handle.Margin = new Thickness(Math.Clamp(hx - 4, 0, TW - 8), 0, 0, 0); double a = Math.Min(cxp, hx), b = Math.Max(cxp, hx); fill.Margin = new Thickness(a + 4, 0, 0, 0); fill.Width = Math.Max(0, b - a - 4); val.Text = $"{(v - 0.5) * 2 * 100:+0;−0;0}\u2009%"; }- void SetFromX(double x) { SetId("rate", Math.Clamp(x / TW, 0, 1)); Upd(); }- slot.PointerPressed += (_, e) => { drag = true; e.Pointer.Capture(slot); engine.BeginAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, "rate"); SetFromX(e.GetPosition(slot).X); Refresh(); };- slot.PointerMoved += (_, e) => { if (drag) SetFromX(e.GetPosition(slot).X); };- slot.PointerReleased += (_, e) => { if (drag) { drag = false; e.Pointer.Capture(null); engine.EndAutomationWrite(track, AutomationTarget.PluginParam, -1, -1, "rate"); } };- readouts.Add(() => { if (!drag) Upd(); });- return new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Children = {- Cap("RATE"), slot, val, new TextBlock { Text = "← reverse", FontSize = 8, Foreground = MutedC, VerticalAlignment = VerticalAlignment.Center } } };+ int iv = i;+ var tb = new TextBlock { Text = TabNames[i], FontSize = NotaType.DeviceSection, VerticalAlignment = VerticalAlignment.Center };+ var cell = new Border+ {+ Padding = new Thickness(8, 0), BorderThickness = new Thickness(0, 0, 0, 2),+ Cursor = new Cursor(StandardCursorType.Hand), Child = tb,+ };+ cell.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(cell).Properties.IsLeftButtonPressed) return;+ tab = iv; showTab(); e.Handled = true;+ };+ tabCells[i] = cell; tabTexts[i] = tb; tabRow.Children.Add(cell);}+ var tabStrip = new Grid { Height = TabH, ColumnDefinitions = new ColumnDefinitions("Auto,*") };+ tabStrip.Children.Add(tabRow);+ Grid.SetColumn(hint, 1); tabStrip.Children.Add(hint);- string Pct(double v) => $"{v * 100:0}\u2009%";- string Ms(double v, double lo, double hi) { double s = Exp(v, lo, hi); return s < 1.0 ? $"{s * 1000:0}\u2009ms" : $"{s:0.00}\u2009s"; }- string Db(double v) => v <= 0.001 ? "−∞\u2009dB" : $"{20 * Math.Log10(v):+0.0;−0.0;0.0}\u2009dB";- string Cents(double v) => $"{v * 14:0}\u2009c";- string Tone(double v) => v < 0.34 ? "dark" : v < 0.67 ? "warm" : "bright";-- // ---------- LIVE strip ----------- var motionSeg = Seg("motion", MotionNames, 9, 7);- 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 = {- new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center, Children = {- Seg("sync", new[] { "Free", "Sync" }, 9, 7), Seg("division", DivNames, 8, 5), RateBipolar() } },- new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center, [DockPanel.DockProperty] = Dock.Right, Children = {- Cap("MOTION"), motionSeg } } } } };-- // ---------- tab rail ----------- var tabNames = new[] { "Balls", "Voice" };- var tabBtns = new Border[tabNames.Length];- int tab = 0;- var bodyContent = new ContentControl { HorizontalAlignment = HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Stretch };- Control ballsTab = new Panel(), voiceTab = new Panel();- void SelectTab(int t)+ var tabHost = new Panel();+ foreach (var b in bodies) tabHost.Children.Add(b);+ var tabGrid = new Grid { RowDefinitions = new RowDefinitions("Auto,*") };+ tabGrid.Children.Add(HeaderStrip(tabStrip));+ Grid.SetRow(tabHost, 1); tabGrid.Children.Add(tabHost);+ var tabPanel = SectionBox(tabGrid);++ // ---- rail · the balls ---------------------------------------------------------+ var railCap = Cap("BALLS"); railCap.LetterSpacing = NotaType.SectionLabelTracking; railCap.Margin = new Thickness(8, 0, 0, 0);+ var railSub = Mono("rate · phase · note", TextTertiary); railSub.HorizontalAlignment = HorizontalAlignment.Right; railSub.Margin = new Thickness(0, 0, 8, 0);+ var railHead = new Grid { Height = TabH, ColumnDefinitions = new ColumnDefinitions("Auto,*") };+ railHead.Children.Add(railCap);+ Grid.SetColumn(railSub, 1); railHead.Children.Add(railSub);++ // Balls-tab foot: count stepper, sort + quantize, Hold / First note / Reset.+ var countText = Mono("", TextPrimary);+ readouts.Add(() => countText.Text = Count().ToString(NotaNum.Culture));+ void StepBalls(int d) => Write("balls", PendulumModel.BallCountNorm(Count() + d));+ Border StepBtn(GlyphKind g, int d, string tip){- tab = t; bodyContent.Content = t == 0 ? ballsTab : voiceTab;- for (int i = 0; i < tabBtns.Length; i++) { bool on = i == t; tabBtns[i].Background = on ? RowLit : Brushes.Transparent; tabBtns[i].BorderBrush = on ? Amber : Brushes.Transparent; ((TextBlock)tabBtns[i].Child!).Foreground = on ? TxtC : MutedC; }+ var b = new Border+ {+ Width = 16, Height = 14, CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1),+ BorderBrush = BorderDef, Background = NotaPalette.SurfaceRaised, Cursor = new Cursor(StandardCursorType.Hand),+ Child = new Glyph(g, 7) { Foreground = NotaPalette.TextStrong, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center },+ };+ ToolTip.SetTip(b, tip);+ b.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) return;+ StepBalls(d); Refresh(); e.Handled = true;+ };+ return b;}- var railCol = new StackPanel { Spacing = 2 };- for (int i = 0; i < tabNames.Length; i++)+ var steppers = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 3, Children = { StepBtn(GlyphKind.Minus, -1, "One ball fewer (2 at least)"), StepBtn(GlyphKind.Plus, +1, "One ball more (6 at most)") } };+ var countRow = Row((Cap("BALLS"), "Auto"), (countText, "Auto"), (new Panel(), "*"), (steppers, "Auto"));+ countRow.ColumnSpacing = 6;+ if (I("balls") is var bi and >= 0) MidiLearn.Bind(countRow, MidiTarget.PluginParam(track, -1, bi), engine.PluginParamName(track, -1, bi));++ var sortSeg = Chips("chordsort", new[] { "Up", "Down" }, padX: 4, fontSize: 7);+ ToolTip.SetTip(sortSeg, "Up: the low wall plays the chord's lowest note · Down: its highest");+ var quantSeg = Chips("quantize", PendulumModel.QuantNames, padX: 3, fontSize: 7);+ ToolTip.SetTip(quantSeg, "Quantize: a crossing waits for the next 1/16 or 1/8 before it plays");+ var sortRow = Row((Cap("SORT"), "Auto"), (sortSeg, "Auto"), (new Panel(), "*"), (Cap("QUANT"), "Auto"), (quantSeg, "Auto"));++ var holdBtn = RailButton("Hold", () => Write("hold", G("hold") >= 0.5f ? 0 : 1), () => G("hold") >= 0.5f, "hold");+ ToolTip.SetTip(holdBtn, "Latch the chord — it keeps swinging after you let go; the next chord replaces it");+ var firstBtn = RailButton("First note", () => Write("firstnote", G("firstnote") >= 0.5f ? 0 : 1), () => G("firstnote") >= 0.5f, "firstnote");+ ToolTip.SetTip(firstBtn, "Restart every ball from its start when a new chord begins");+ var resetBtn = RailButton("Reset", () => SetP("reset", 1), id: "reset");+ ToolTip.SetTip(resetBtn, "Restart every ball's swing now");+ var actionRow = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,*"), ColumnSpacing = 4 };+ actionRow.Children.Add(holdBtn);+ Grid.SetColumn(firstBtn, 1); actionRow.Children.Add(firstBtn);+ Grid.SetColumn(resetBtn, 2); actionRow.Children.Add(resetBtn);++ var ballsFoot = new Grid { RowDefinitions = new RowDefinitions("Auto,*,Auto,Auto"), RowSpacing = 4 };+ ballsFoot.Children.Add(countRow);+ Grid.SetRow(sortRow, 2); ballsFoot.Children.Add(sortRow);+ Grid.SetRow(actionRow, 3); ballsFoot.Children.Add(actionRow);++ // Voice-tab foot: spread, scale, Humanize / Reset.+ string Cents(float v) => NotaNum.Unit(PendulumModel.DetuneCents(v), "0", "c");+ var spreadBlock = new StackPanel+ {+ Spacing = 2,+ Children =+ {+ Cap("SPREAD"),+ Slider("RATE", "spread", () => NotaNum.Pct(G("spread")), modulation: true, labelWidth: 40),+ Slider("DETUNE", "detune", () => Cents(G("detune")), modulation: true, labelWidth: 40),+ Slider("PAN", "panspread", () => NotaNum.Pct(G("panspread")), modulation: true, labelWidth: 40),+ Slider("HUMAN", "humanize", () => NotaNum.Pct(G("humanize")), modulation: true, labelWidth: 40),+ },+ };+ ToolTip.SetTip(spreadBlock.Children[1], "How far the balls' rates drift apart — each ball a little faster than the one before");+ ToolTip.SetTip(spreadBlock.Children[2], "Detune of the chorus partner inside each voice");+ ToolTip.SetTip(spreadBlock.Children[3], "Fan the notes across the stereo field by where the ball is");+ ToolTip.SetTip(spreadBlock.Children[4], "Level and pitch jitter per note");+ var spreadHost = new Border { BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 1, 0, 0), Padding = new Thickness(0, 3, 0, 0), Child = spreadBlock };++ var scaleText = Mono("", TextPrimary);+ readouts.Add(() => scaleText.Text = PendulumModel.ScaleText(G("root"), G("scalemode")));+ var scaleBox = new Border+ {+ Height = 14, CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), BorderBrush = BorderDef,+ Background = NotaPalette.BgSunken, Padding = new Thickness(6, 0), Cursor = new Cursor(StandardCursorType.Hand),+ Child = new DockPanel+ {+ Children =+ {+ new Glyph(GlyphKind.ChevronDown, 7) { Foreground = TextTertiary, VerticalAlignment = VerticalAlignment.Center, [DockPanel.DockProperty] = Dock.Right },+ scaleText,+ },+ },+ };+ ToolTip.SetTip(scaleBox, "Snap the generated notes to a scale");+ scaleBox.PointerPressed += (_, e) =>+ {+ if (!e.GetCurrentPoint(scaleBox).Properties.IsLeftButtonPressed) return;+ var fly = new MenuFlyout();+ int cur = Sel("scalemode", PendulumModel.ModeNames.Length), curRoot = Sel("root", 12);+ for (int m = 0; m < PendulumModel.ModeNames.Length; m++)+ {+ int mv = m;+ var mi = new MenuItem { Header = PendulumModel.ModeNames[m] };+ if (m == cur) mi.Icon = new Avalonia.Controls.Shapes.Ellipse { Width = 6, Height = 6, Fill = Brass };+ mi.Click += (_, _) => { Write("scalemode", mv / (float)(PendulumModel.ModeNames.Length - 1)); Refresh(); };+ fly.Items.Add(mi);+ }+ fly.Items.Add(new Separator());+ var rootMenu = new MenuItem { Header = $"Root · {PendulumModel.RootNames[curRoot]}" };+ for (int r = 0; r < 12; r++)+ {+ int rv = r;+ var ri = new MenuItem { Header = PendulumModel.RootNames[r] };+ if (r == curRoot) ri.Icon = new Avalonia.Controls.Shapes.Ellipse { Width = 6, Height = 6, Fill = Brass };+ ri.Click += (_, _) => { Write("root", rv / 11f); Refresh(); };+ rootMenu.Items.Add(ri);+ }+ fly.Items.Add(rootMenu);+ fly.ShowAt(scaleBox);+ e.Handled = true;+ };+ scaleBox.PointerWheelChanged += (_, e) =>+ {+ int n = PendulumModel.ModeNames.Length;+ int m = Math.Clamp(Sel("scalemode", n) + (e.Delta.Y < 0 ? 1 : -1), 0, n - 1);+ Write("scalemode", m / (float)(n - 1)); Refresh(); e.Handled = true;+ };+ if (I("scalemode") is var smi and >= 0) MidiLearn.Bind(scaleBox, MidiTarget.PluginParam(track, -1, smi), engine.PluginParamName(track, -1, smi));+ var scaleRow = Row((Cap("SCALE"), "Auto"), (scaleBox, "*"));+ scaleRow.ColumnSpacing = 5;++ float lastHuman = G("humanize") > 0.005f ? G("humanize") : 0.3f;+ var humanBtn = RailButton("Humanize", () =>+ {+ if (G("humanize") > 0.005f) { lastHuman = G("humanize"); Write("humanize", 0); }+ else Write("humanize", lastHuman);+ }, () => G("humanize") > 0.005f, "humanize", 14);+ ToolTip.SetTip(humanBtn, "Humanize on / off — the amount is the HUMAN slider");+ var spreadResetBtn = RailButton("Reset", () =>{- int ti = i;- var b = new Border { Height = 20, CornerRadius = NotaRadius.Control, Padding = new Thickness(7, 0), BorderThickness = new Thickness(2, 0, 0, 0), Cursor = new Cursor(StandardCursorType.Hand), Child = new TextBlock { Text = tabNames[i], FontSize = 9, FontWeight = FontWeight.Medium, Foreground = MutedC, VerticalAlignment = VerticalAlignment.Center } };- b.PointerPressed += (_, _) => SelectTab(ti);- tabBtns[i] = b; railCol.Children.Add(b);+ foreach (var id in new[] { "spread", "detune", "panspread", "humanize", "root", "scalemode" }) Write(id, Def(id));+ }, height: 14);+ ToolTip.SetTip(spreadResetBtn, "Reset spread, humanize and scale to their defaults");+ var voiceBtns = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), ColumnSpacing = 4 };+ voiceBtns.Children.Add(humanBtn);+ Grid.SetColumn(spreadResetBtn, 1); voiceBtns.Children.Add(spreadResetBtn);++ var voiceFoot = new Grid { RowDefinitions = new RowDefinitions("Auto,*,Auto,Auto"), RowSpacing = 3 };+ voiceFoot.Children.Add(spreadHost);+ Grid.SetRow(scaleRow, 2); voiceFoot.Children.Add(scaleRow);+ Grid.SetRow(voiceBtns, 3); voiceFoot.Children.Add(voiceBtns);++ // The list keeps its natural height (rows of 17 / 16) while it fits; otherwise it+ // takes what the foot leaves and the rows tighten.+ var feet = new Panel { Children = { ballsFoot, voiceFoot } };+ var railBody = new Grid { RowDefinitions = new RowDefinitions("Auto,*"), RowSpacing = 4, Margin = new Thickness(8, 5, 8, 5) };+ railBody.Children.Add(ballList);+ Grid.SetRow(feet, 1); railBody.Children.Add(feet);+ (int, int, double, double) fitKey = default;+ void FitList()+ {+ var key = (tab, Count(), railBody.Bounds.Width, railBody.Bounds.Height);+ if (key == fitKey) return;+ fitKey = key;+ bool balls = tab == 0;+ ballList.Gap = balls ? 4 : 3;+ ballList.MaxRow = balls ? 17 : 16;+ int n = Count();+ double natural = n * ballList.MaxRow + (n - 1) * ballList.Gap;+ double avail = railBody.Bounds.Height;+ if (avail <= 0) { ballList.Height = natural; return; }+ Control foot = balls ? ballsFoot : voiceFoot;+ foot.Measure(new Size(railBody.Bounds.Width, double.PositiveInfinity));+ double footMin = foot.DesiredSize.Height;+ ballList.Height = Math.Max(n * 7, Math.Min(natural, avail - footMin - railBody.RowSpacing));}- // Ball-count stepper pinned to the rail bottom.- var ballsNum = new TextBlock { Text = "3", FontSize = 9, Foreground = TxtC, [DockPanel.DockProperty] = Dock.Right };- ballsNum.BindResource(TextBlock.FontFamilyProperty, "Font.Mono");- void StepBalls(int d) { int c = Math.Clamp(2 + (int)Math.Round(G("balls") * 4) + d, 2, MaxBalls); SetId("balls", (c - 2) / 4.0); Refresh(); }- Border StepBtn(string t, int d) { var b = new Border { CornerRadius = NotaRadius.Badge, BorderThickness = new Thickness(1), BorderBrush = NotaPalette.BorderStrong, Background = RowLit, Cursor = new Cursor(StandardCursorType.Hand), Child = new TextBlock { Text = t, FontSize = 9, Foreground = TextSecondary, HorizontalAlignment = HorizontalAlignment.Center } }; b.PointerPressed += (_, _) => StepBalls(d); return b; }- var stepGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*"), ColumnSpacing = 3 };- var sm = StepBtn("−", -1); var sp = StepBtn("+", +1); Grid.SetColumn(sp, 1); stepGrid.Children.Add(sm); stepGrid.Children.Add(sp);- var ballsBox = new StackPanel { Spacing = 3, Children = {- new DockPanel { LastChildFill = false, Children = { Cap("BALLS"), ballsNum } }, stepGrid } };- DockPanel.SetDock(railCol, Dock.Top); DockPanel.SetDock(ballsBox, Dock.Bottom);- readouts.Add(() => ballsNum.Text = Math.Clamp(2 + (int)Math.Round(G("balls") * 4), 2, MaxBalls).ToString());- var tabRail = new Border { Width = 70, Background = RailBg, BorderBrush = Border2, BorderThickness = new Thickness(0, 0, 1, 0), Padding = new Thickness(5), Child = new DockPanel { LastChildFill = false, Children = { railCol, ballsBox } } };-- // ---------- Balls tab: field + per-ball list ----------- var fieldWrap = new Border { Padding = new Thickness(8, 7), Child = fieldFull };-- var rowBorder = new Border[MaxBalls]; var rowDot = new Border[MaxBalls];- var rDiv = new TextBlock[MaxBalls]; var rRate = new TextBlock[MaxBalls]; var rPhase = new TextBlock[MaxBalls]; var rDir = new TextBlock[MaxBalls]; var rNote = new TextBlock[MaxBalls];- var ballList = new StackPanel { Spacing = 3 };- for (int i = 0; i < MaxBalls; i++)+ readouts.Add(FitList);+ railBody.SizeChanged += (_, _) => FitList();++ var railGrid = new Grid { RowDefinitions = new RowDefinitions("Auto,*") };+ railGrid.Children.Add(HeaderStrip(railHead));+ Grid.SetRow(railBody, 1); railGrid.Children.Add(railBody);+ var rail = SectionBox(railGrid);+ rail.Width = RailW;++ // ---- words: the tab hint and the status line -----------------------------------+ string Cycle() => Synced() ? "sync " + PendulumModel.DivNames[Sel("division", 5)] : "free " + Secs(PendulumModel.FreeSeconds(G("freerate")));+ string RateText() => NotaNum.Unit(PendulumModel.RateSigned(G("rate")) * 100, "+0;−0;0", "%");+ string MotionWord() => PendulumModel.MotionNames[Sel("motion", 4)].ToLowerInvariant();+ string Hint() => tab == 0+ ? $"{Cycle()} · {MotionWord()} · {RateText()}"+ : $"{PendulumModel.WaveNames[Sel("wave", 5)].ToLowerInvariant()} · {PendulumModel.ToneWord(G("tone"))} · {Secs(PendulumModel.AttackSeconds(G("attack")))}";+ string Summary(){- TextBlock Mn(double w, IBrush c) { var t = new TextBlock { FontSize = 9, Foreground = c, Width = w, VerticalAlignment = VerticalAlignment.Center }; t.BindResource(TextBlock.FontFamilyProperty, "Font.Mono"); return t; }- rDot(i, out var dot); rowDot[i] = dot;- rDiv[i] = Mn(30, TxtC); rRate[i] = Mn(30, NotaPalette.TextSecondary); rPhase[i] = Mn(30, MutedC);- rDir[i] = new TextBlock { FontSize = 9, Foreground = MutedC, VerticalAlignment = VerticalAlignment.Center };- rNote[i] = new TextBlock { FontSize = 9, Foreground = TxtC, HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Center, [DockPanel.DockProperty] = Dock.Right };- rNote[i].BindResource(TextBlock.FontFamilyProperty, "Font.Mono");- var inner = new DockPanel { LastChildFill = false, Children = { new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, Children = { dot, rDiv[i], rRate[i], rPhase[i], rDir[i] } }, rNote[i] } };- rowBorder[i] = new Border { BorderThickness = new Thickness(1), BorderBrush = Border2, Background = RailBg, CornerRadius = NotaRadius.Control, Padding = new Thickness(6, 3), Child = inner };- ballList.Children.Add(rowBorder[i]);+ if (tab == 0)+ {+ int n = Count();+ var notes = new List<string>();+ for (int b = 0; b < n; b++) notes.Add(PendulumModel.NoteName(snap.BallState[b].Pitch));+ string chord = held.Length == 0 ? "hold a chord" : string.Join(" ", notes);+ string s = $"{(Synced() ? "Sync " + PendulumModel.DivNames[Sel("division", 5)] : "Free " + Secs(PendulumModel.FreeSeconds(G("freerate"))))} · {MotionWord()} · rate {RateText()}"+ + $" · {n} balls → {chord} · sort {(G("chordsort") >= 0.5f ? "down" : "up")} · quantize {PendulumModel.QuantNames[Sel("quantize", 3)].ToLowerInvariant()}";+ if (G("hold") >= 0.5f) s += " · hold";+ return s;+ }+ string sc = PendulumModel.ScaleText(G("root"), G("scalemode"));+ return $"{PendulumModel.WaveNames[Sel("wave", 5)]} · {PendulumModel.ToneWord(G("tone"))} · "+ + $"{NotaNum.Str(PendulumModel.AttackSeconds(G("attack")) * 1000, "0")} / {NotaNum.Str(PendulumModel.DecaySeconds(G("decay")) * 1000, "0")} / "+ + $"{NotaNum.Str(PendulumModel.ReleaseSeconds(G("release")) * 1000, "0")} ms · {DbOf(G("volume"))} · spread rate {NotaNum.Pct(G("spread"))} · "+ + $"detune {Cents(G("detune"))} · pan {NotaNum.Pct(G("panspread"))}"+ + (G("humanize") > 0.005f ? $" · humanize {NotaNum.Pct(G("humanize"))}" : "")+ + (sc == "Off" ? "" : $" · {sc}");}- void rDot(int i, out Border dot) => dot = new Border { Width = 7, Height = 7, CornerRadius = NotaRadius.Control, Background = Amber, VerticalAlignment = VerticalAlignment.Center };- var listHeader = new DockPanel { LastChildFill = false, Children = {- Cap("BALLS"), new TextBlock { Text = "rate · phase · note", FontSize = 8, Foreground = MutedC, VerticalAlignment = VerticalAlignment.Center, [DockPanel.DockProperty] = Dock.Right } } };- var sortRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center, Children = {- Cap("SORT"), Seg("chordsort", new[] { "Up", "Down" }, 8, 6),- new TextBlock { Text = "QUANTIZE", FontSize = 8, FontWeight = FontWeight.Bold, Foreground = MutedC, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(6, 0, 0, 0) }, Seg("quantize", QuantNames, 8, 5) } };- var actionRow = new Grid { ColumnDefinitions = new ColumnDefinitions("*,*,*"), ColumnSpacing = 4 };- var holdBtn = OutToggle("hold", "Hold"); var firstBtn = OutToggle("firstnote", "First note"); var resetBtn = ActionBtn("Reset", () => { SetId("reset", 1); });- Grid.SetColumn((Control)firstBtn, 1); Grid.SetColumn((Control)resetBtn, 2);- actionRow.Children.Add(holdBtn); actionRow.Children.Add((Control)firstBtn); actionRow.Children.Add((Control)resetBtn);- var ballsPanelInner = new DockPanel { LastChildFill = true };- DockPanel.SetDock(listHeader, Dock.Top);- var bottomStack = new StackPanel { Spacing = 5, [DockPanel.DockProperty] = Dock.Bottom, Children = { new Border { Height = 1, Background = RowLit }, sortRow, actionRow } };- ballsPanelInner.Children.Add(listHeader); ballsPanelInner.Children.Add(bottomStack);- ballsPanelInner.Children.Add(new StackPanel { Spacing = 4, Margin = new Thickness(0, 5, 0, 5), Children = { ballList } });- var ballsRight = new Border { Width = 214, Background = RailBg, BorderBrush = Border2, BorderThickness = new Thickness(1, 0, 0, 0), Padding = new Thickness(8, 6), Child = ballsPanelInner };- DockPanel.SetDock(ballsRight, Dock.Right);- ballsTab = new DockPanel { LastChildFill = true, Children = { ballsRight, fieldWrap } };-- // Live per-ball rows.- readouts.Add(() =>+ showTab = () =>{- int count = Math.Clamp(2 + (int)Math.Round(G("balls") * 4), 2, MaxBalls);- int motion = GI("motion", 4); double baseRate = (G("rate") - 0.5) * 2; double spread = G("spread"); bool sortDown = G("chordsort") >= 0.5f;- for (int i = 0; i < MaxBalls; i++)+ for (int i = 0; i < TabNames.Length; i++){- rowBorder[i].IsVisible = i < count;- if (i >= count) continue;- double rr = baseRate * (1.0 + spread * i * 0.37);- double ph = fieldFull.BallPhase(i);- double pos = PosCurve(ph, motion);- double scaled = pos * Math.Max(1, heldN); double frac = scaled - Math.Floor(scaled);- bool near = heldN > 0 && (frac < 0.14 || frac > 0.86);- int deg = fieldFull.BallDegree(i);- rDiv[i].Text = DivNames[GI("division", 5)];- rRate[i].Text = $"{rr * 100:+0;−0;0}\u2009%";- rPhase[i].Text = $"{ph * 100:0}\u2009%";- rDir[i].Text = baseRate >= 0 ? "→" : "←";- rNote[i].Text = (deg >= 0 && heldN > 0) ? NoteName(heldBuf[Math.Clamp(sortDown ? heldN - 1 - deg : deg, 0, heldN - 1)]) : "—";- rowDot[i].Background = near ? AccentBright : Amber;- rowBorder[i].Background = near ? RowLit : RailBg;- rowBorder[i].BorderBrush = near ? Amber : Border2;- rNote[i].Foreground = near ? AmberLit : TxtC;+ bool on = i == tab;+ tabCells[i].Background = on ? NotaPalette.SurfaceRaised : Brushes.Transparent;+ tabCells[i].BorderBrush = on ? Brass : Brushes.Transparent;+ tabTexts[i].Foreground = on ? AccentBright : TextTertiary;+ tabTexts[i].FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;+ bodies[i].IsVisible = on;}- });-- // ---------- Voice tab: collapsed field + voice/env + spread rail ----------- var miniStrip = new Border { Height = 62, Background = Inset, BorderBrush = Border2, BorderThickness = new Thickness(0, 0, 0, 1), Child = new Panel { Children = {- fieldMini,- new TextBlock { Text = "FIELD", FontSize = 8, FontWeight = FontWeight.Bold, Foreground = MutedC, Margin = new Thickness(8, 4, 0, 0), HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top },- new TextBlock { Text = "Balls tab above", FontSize = 8, Foreground = MutedC, Margin = new Thickness(0, 0, 8, 3), HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Bottom } } } };- var wavesRow = Seg("wave", WaveNames, 9, 9);- var voiceKnobs = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 2, HorizontalAlignment = HorizontalAlignment.Center, Children = {- KUnit("tone", "TONE", Tone), KUnit("bright", "BRIGHT", Pct), KUnit("fm", "FM", Pct, mod: true) } };- var envKnobs = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 2, HorizontalAlignment = HorizontalAlignment.Center, Children = {- KUnit("attack", "ATTACK", v => Ms(v, 0.001, 1.0)), KUnit("decay", "DECAY", v => Ms(v, 0.01, 2.0)),- KUnit("release", "RELEASE", v => Ms(v, 0.02, 3.0)), KUnit("volume", "VOLUME", Db) } };- voiceKnobs.VerticalAlignment = VerticalAlignment.Center; envKnobs.VerticalAlignment = VerticalAlignment.Center;- var voiceCenter = new Grid { Margin = new Thickness(9, 6), RowDefinitions = new RowDefinitions("Auto,*,Auto,*") };- Grid.SetRow(wavesRow, 0);- var vRow = new Border { Child = voiceKnobs }; Grid.SetRow(vRow, 1);- var vDiv = new Border { Height = 1, Background = RowLit, VerticalAlignment = VerticalAlignment.Center }; Grid.SetRow(vDiv, 2);- var eRow = new Border { Child = envKnobs }; Grid.SetRow(eRow, 3);- voiceCenter.Children.Add(wavesRow); voiceCenter.Children.Add(vRow); voiceCenter.Children.Add(vDiv); voiceCenter.Children.Add(eRow);-- // scale root + mode cyclers- var rootBox = new Border { Height = 18, MinWidth = 30, Background = Inset, BorderBrush = Border2, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Padding = new Thickness(6, 0), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center };- var rootTx = new TextBlock { FontSize = 9, Foreground = TxtC, VerticalAlignment = VerticalAlignment.Center }; rootTx.BindResource(TextBlock.FontFamilyProperty, "Font.Mono"); rootBox.Child = rootTx;- rootBox.PointerPressed += (_, _) => { int r = (GI("root", 12) + 1) % 12; SetId("root", r / 11.0); Refresh(); };- var modeBox = new Border { Height = 18, Background = Inset, BorderBrush = Border2, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Badge, Padding = new Thickness(6, 0), Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center };- var modeTx = new TextBlock { FontSize = 9, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center }; modeBox.Child = new DockPanel { Children = { new Glyph(GlyphKind.ChevronDown, 8) { Foreground = MutedC, VerticalAlignment = VerticalAlignment.Center, [DockPanel.DockProperty] = Dock.Right, Margin = new Thickness(6, 0, 0, 0) }, modeTx } };- modeBox.PointerPressed += (_, _) => { int m = (GI("scalemode", 6) + 1) % 6; SetId("scalemode", m / 5.0); Refresh(); };- readouts.Add(() => { rootTx.Text = RootNames[GI("root", 12)]; modeTx.Text = ModeNames[GI("scalemode", 6)]; });- var spreadRail = new Border { Width = 104, Background = RailBg, BorderBrush = Border2, BorderThickness = new Thickness(1, 0, 0, 0), Padding = new Thickness(8, 6), Child =- new DockPanel { LastChildFill = false, Children = {- new StackPanel { Spacing = 5, [DockPanel.DockProperty] = Dock.Top, Children = {- Cap("SPREAD"),- HSlider("spread", "Rate", Pct, lw: 30), HSlider("detune", "Detune", Cents, lw: 30), HSlider("panspread", "Pan", Pct, lw: 30),- new Border { Height = 1, Background = RowLit },- OutToggle("humanize", "Humanize", teal: true) } },- new StackPanel { Spacing = 3, [DockPanel.DockProperty] = Dock.Bottom, Children = {- new DockPanel { LastChildFill = false, Children = { Cap("SCALE"), new StackPanel { Orientation = Orientation.Horizontal, Spacing = 3, [DockPanel.DockProperty] = Dock.Right, Children = { rootBox } } } },- modeBox } } } } };- DockPanel.SetDock(spreadRail, Dock.Right);- DockPanel.SetDock(miniStrip, Dock.Top);- voiceTab = new DockPanel { LastChildFill = true, Children = { miniStrip, new DockPanel { LastChildFill = true, Children = { spreadRail, voiceCenter } } } };-- // ---------- assemble ----------- DockPanel.SetDock(tabRail, Dock.Left);- var body = new DockPanel { LastChildFill = true, Children = { tabRail, bodyContent } };- DockPanel.SetDock(live, Dock.Top);- var root = new DockPanel { LastChildFill = true, Background = NotaPalette.BgApp, Children = { live, body } };-- SelectTab(0);+ ballsFoot.IsVisible = tab == 0;+ voiceFoot.IsVisible = tab == 1;+ Refresh();+ };++ // ---- status strip -------------------------------------------------------------+ var statusBar = new Grid { Height = StatusH, ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = 10 };+ statusBar.Children.Add(status);+ Grid.SetColumn(meta, 1); statusBar.Children.Add(meta);+ var statusHost = new Border+ {+ Height = StatusH, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 1, 0, 0),+ Background = NotaPalette.SurfaceAbyss, Padding = new Thickness(8, 0), Child = statusBar,+ };++ // ---- assembly -----------------------------------------------------------------+ var body = new Grid+ {+ ColumnDefinitions = new ColumnDefinitions("*,Auto"), ColumnSpacing = NotaSpace.DeviceGap,+ Margin = new Thickness(NotaSpace.DeviceGap),+ };+ body.Children.Add(tabPanel);+ Grid.SetColumn(rail, 1); body.Children.Add(rail);++ DockPanel.SetDock(statusHost, Dock.Bottom);+ var root = new DockPanel { LastChildFill = true, Background = NotaPalette.Gutter, Children = { statusHost, body } };++ ctx.AddDeviceRefresher(Live);ctx.SetInstLiveViz(Refresh);- Refresh();+ showTab();+ Live();return root;}- // Same four swing curves the DSP + viz use (for the per-ball list's trigger proximity).- private static double PosCurve(double ph, int type)+ // A section: card ground, hairline, radius 6 — the almanac's section box.+ private static Border SectionBox(Control child) => new(){- double tri = 1.0 - 2.0 * Math.Abs(ph - 0.5);- return type switch- {- 1 => 0.5 - 0.5 * Math.Cos(2 * Math.PI * ph),- 2 => tri * tri * (3.0 - 2.0 * tri),- 3 => Math.Clamp(1.0 - Math.Pow(1.0 - tri, 2.0) + 0.06 * Math.Sin(2 * Math.PI * 3.0 * tri) * (1.0 - tri), 0, 1),- _ => tri,- };- }+ Background = NotaPalette.SurfaceCard, BorderBrush = BorderDef, BorderThickness = new Thickness(1),+ CornerRadius = NotaRadius.Tile, ClipToBounds = true, Child = child,+ };++ // A section's own header strip: a hairline under it, nothing else.+ private static Border HeaderStrip(Control child) => new()+ {+ BorderBrush = BorderDef, BorderThickness = new Thickness(0, 0, 0, 1), Child = child,+ };++ // A tab's control strip under the tab row: 22 tall, a fainter hairline under it.+ private static Border StripBox(Control child) => new()+ {+ Height = StripH, BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 0, 0, 1), Child = child,+ };}diff --git a/src/managed/Nota.Application/Instruments/PendulumModel.cs b/src/managed/Nota.Application/Instruments/PendulumModel.csnew file mode 100644index 00000000..df1c2466--- /dev/null+++ b/src/managed/Nota.Application/Instruments/PendulumModel.cs@@ -0,0 +1,170 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Nota Pendulum (built-in instrument kind 8) — the engine's own value maps, in one place+// for the editor card and the MCP server: what a normalized 0..1 parameter means (ball+// count, swing rate, cycle, envelope times, cents), how the engine's scope telemetry is+// laid out (balls, the bar's note grid, voice levels), a one-line summary of the patch and+// a guide to every parameter. Mirrors PendulumSynth.h.++using System;+using System.Collections.Generic;+using System.Globalization;+using System.Text;++namespace Nota.Application;++public static class PendulumModel+{+ public const int Kind = 8;+ public const int MaxBalls = 6;+ public const int Voices = 24;++ // scopeRead layout (PendulumSynth::kHead …).+ public const int ScopeHead = 12, BallStride = 8, MaxSteps = 32, MaxLevels = 8;+ public const int BallsAt = ScopeHead;+ public const int StepsAt = BallsAt + MaxBalls * BallStride;+ public const int LevelsAt = StepsAt + MaxSteps * 2;+ public const int ScopeLength = LevelsAt + MaxLevels;++ public static readonly double[] DivBeats = { 4, 2, 1, 0.5, 0.25 };+ public static readonly string[] DivNames = { "1/1", "1/2", "1/4", "1/8", "1/16" };+ public static readonly string[] MotionNames = { "Linear", "Pendulum", "Ease", "Bounce" };+ public static readonly string[] WaveNames = { "Keys", "Glass", "Saw", "Sqr", "Bell" };+ public static readonly string[] QuantNames = { "Off", "1/16", "1/8" };+ public static readonly string[] ModeNames = { "Off", "Major", "Minor", "Dorian", "Mixolydian", "Minor penta" };+ public static readonly string[] RootNames = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };++ public static double ExpMap(double v, double lo, double hi) => lo * Math.Pow(hi / lo, Math.Clamp(v, 0.0, 1.0));+ public static int Index(float v, int n) => Math.Clamp((int)Math.Round(v * (n - 1)), 0, n - 1);++ public static int BallCount(float v) => Math.Clamp(2 + (int)Math.Round(v * 4), 2, MaxBalls);+ public static float BallCountNorm(int count) => (Math.Clamp(count, 2, MaxBalls) - 2) / 4f;+ /// <summary>Rate → signed swing speed, 1 = +100 % (the engine's ±2 multiplier halved).</summary>+ public static double RateSigned(float v) => (v - 0.5) * 2.0;+ /// <summary>A ball's own rate: the base, spread apart by Spread (ball 0 keeps the base).</summary>+ public static double BallRate(float rate, float spread, int ball) => RateSigned(rate) * (1.0 + spread * ball * 0.37);+ public static double FreeSeconds(float v) => ExpMap(v, 0.1, 4.0);+ public static double NoteSeconds(float v) => ExpMap(v, 0.05, 1.5);+ public static double AttackSeconds(float v) => ExpMap(v, 0.001, 1.0);+ public static double DecaySeconds(float v) => ExpMap(v, 0.01, 2.0);+ public static double ReleaseSeconds(float v) => ExpMap(v, 0.02, 3.0);+ public static double ToneHz(float v) => ExpMap(v, 300.0, 12000.0);+ public static double DetuneCents(float v) => v * 14.0;+ public static string ToneWord(float v) => v < 0.34f ? "dark" : v < 0.67f ? "warm" : "bright";++ /// <summary>Seconds one ball needs for a full swing (low → high → low) at the base rate, or+ /// +∞ when stopped; synced cycles take the tempo.</summary>+ public static double CycleSeconds(Func<string, float> g, double bpm)+ {+ double mult = Math.Abs(RateSigned(g("rate")) * 2.0);+ if (mult < 1e-6) return double.PositiveInfinity;+ double cyc = g("sync") >= 0.5f ? DivBeats[Index(g("division"), 5)] * 60.0 / Math.Max(1, bpm) : FreeSeconds(g("freerate"));+ return cyc / mult;+ }++ /// <summary>The four swing curves (low 0 → high 1 → low 0 over a cycle).</summary>+ public static double Position(double ph, int motion)+ {+ double tri = 1.0 - 2.0 * Math.Abs(ph - 0.5);+ return motion switch+ {+ 1 => 0.5 - 0.5 * Math.Cos(2 * Math.PI * ph),+ 2 => tri * tri * (3.0 - 2.0 * tri),+ 3 => Math.Clamp(1.0 - Math.Pow(1.0 - tri, 2.0) + 0.06 * Math.Sin(2 * Math.PI * 3.0 * tri) * (1.0 - tri), 0, 1),+ _ => tri,+ };+ }++ public static string ScaleText(float root, float mode)+ {+ int m = Index(mode, ModeNames.Length);+ return m == 0 ? "Off" : $"{RootNames[Index(root, 12)]} {ModeNames[m].ToLowerInvariant()}";+ }++ public static string NoteName(int note) => note < 0 ? "—" : $"{RootNames[((note % 12) + 12) % 12]}{note / 12 - 1}";++ // ---- telemetry --------------------------------------------------------------------++ public readonly record struct Ball(double Phase, double Pos, int Dir, int Pitch, double ToWall, double Since, double Rate, int Degree);+ public readonly record struct Step(int Pitch, int Age);++ public sealed class Snapshot+ {+ public int Voices, Balls, Held, LastPitch = -1, LastBall = -1, StepCount = 16, BarNotes;+ public double BarPos, SwingSeconds, SinceNote = 1e9, BeatsPerBar = 4;+ public bool Playing, Live;+ public readonly Ball[] BallState = new Ball[MaxBalls];+ public readonly Step[] Steps = new Step[MaxSteps];+ public readonly double[] Levels = new double[MaxLevels];+ }++ /// <summary>Parse the engine scope into a snapshot. <c>Live</c> is false when the scope+ /// is empty (e.g. a Pendulum inside a rack chain) — the caller may simulate then.</summary>+ public static void Parse(ReadOnlySpan<float> s, Snapshot o)+ {+ o.Live = s.Length >= ScopeLength;+ if (!o.Live) return;+ o.Voices = (int)s[0]; o.Balls = (int)s[1]; o.Held = (int)s[2]; o.LastPitch = (int)s[3];+ o.BarPos = s[4]; o.StepCount = Math.Clamp((int)s[5], 1, MaxSteps); o.SwingSeconds = s[6];+ o.LastBall = (int)s[7]; o.SinceNote = s[8]; o.BarNotes = (int)s[9]; o.BeatsPerBar = s[10]; o.Playing = s[11] >= 0.5f;+ for (int b = 0; b < MaxBalls; b++)+ {+ int at = BallsAt + b * BallStride;+ o.BallState[b] = new Ball(s[at], s[at + 1], (int)s[at + 2], (int)s[at + 3], s[at + 4], s[at + 5], s[at + 6], (int)s[at + 7]);+ }+ for (int i = 0; i < MaxSteps; i++) o.Steps[i] = new Step((int)s[StepsAt + i * 2], (int)s[StepsAt + i * 2 + 1]);+ for (int i = 0; i < MaxLevels; i++) o.Levels[i] = s[LevelsAt + i];+ }++ // ---- words ------------------------------------------------------------------------++ private static string S(double v, string f) => v.ToString(f, CultureInfo.InvariantCulture);+ private static string Secs(double s) => s < 1 ? S(s * 1000, "0") + " ms" : S(s, "0.00") + " s";+ private static string Pct(double v) => S(v * 100, "0") + " %";+ private static string Signed(double v) => (v > 0 ? "+" : v < 0 ? "-" : "") + S(Math.Abs(v) * 100, "0") + " %";++ /// <summary>A one-line summary of the patch, from a param-id getter.</summary>+ public static string Summary(Func<string, float> g)+ {+ var sb = new StringBuilder();+ int balls = BallCount(g("balls"));+ bool sync = g("sync") >= 0.5f;+ sb.Append(balls).Append(" balls · ");+ sb.Append(sync ? "sync " + DivNames[Index(g("division"), 5)] : "free " + Secs(FreeSeconds(g("freerate"))));+ sb.Append(" · ").Append(MotionNames[Index(g("motion"), 4)].ToLowerInvariant());+ double r = RateSigned(g("rate"));+ sb.Append(" · rate ").Append(Math.Abs(r) < 0.005 ? "stopped" : Signed(r) + (r < 0 ? " (reverse)" : ""));+ if (g("spread") > 0.005f) sb.Append(" · spread ").Append(Pct(g("spread")));+ sb.Append(" · sort ").Append(g("chordsort") >= 0.5f ? "down" : "up");+ sb.Append(" · quantize ").Append(QuantNames[Index(g("quantize"), 3)]);+ if (g("hold") >= 0.5f) sb.Append(" · hold");+ if (g("firstnote") >= 0.5f) sb.Append(" · restart on first note");+ sb.Append(" → ").Append(WaveNames[Index(g("wave"), 5)].ToLowerInvariant()).Append(' ').Append(ToneWord(g("tone")));+ sb.Append(" · bright ").Append(Pct(g("bright")));+ if (g("fm") > 0.005f) sb.Append(" · fm ").Append(Pct(g("fm")));+ sb.Append(" · env ").Append(Secs(AttackSeconds(g("attack")))).Append(" / ").Append(Secs(DecaySeconds(g("decay"))))+ .Append(" / ").Append(Secs(ReleaseSeconds(g("release")))).Append(", note ").Append(Secs(NoteSeconds(g("notelen"))));+ sb.Append(" · detune ").Append(S(DetuneCents(g("detune")), "0")).Append(" c · pan ").Append(Pct(g("panspread")));+ if (g("humanize") > 0.005f) sb.Append(" · humanize ").Append(Pct(g("humanize")));+ string sc = ScaleText(g("root"), g("scalemode"));+ if (sc != "Off") sb.Append(" · scale ").Append(sc);+ sb.Append(" · vol ").Append(Pct(g("volume")));+ return sb.ToString();+ }++ /// <summary>What each 0..1 parameter value means, one line per group.</summary>+ public const string Guide =+ "All params are normalized 0..1 (set_instrument_param_by_id). Hold a chord: the balls swing across it and every chord degree a ball "+ + "crosses plays that note — x = pitch (low … high), so the chord comes out as an evolving arpeggio.\n"+ + "balls: 2 + round(v*4) → 2..6 balls (0, .25, .5, .75, 1). rate: 0.5 = stopped, above = forward, below = reverse; speed (v-0.5)*200 %. "+ + "sync: 0 free (freerate: 0.1 … 4 s per swing, exp) / 1 synced (division: 1/1 0 · 1/2 .25 · 1/4 .5 · 1/8 .75 · 1/16 1 per swing). "+ + "motion: Linear 0 · Pendulum .33 · Ease .67 · Bounce 1 (the swing curve — pendulum dwells at the walls). "+ + "spread: how far the balls' rates drift apart (ball n runs at rate × (1 + spread·n·0.37)).\n"+ + "quantize: Off 0 · 1/16 0.5 · 1/8 1 (notes wait for the grid). chordsort: 0 up (low degree = low note) / 1 down. "+ + "hold: 1 latches the chord after release. firstnote: 1 restarts the swing when a new chord starts. reset: write 1 to restart every ball (self-clears).\n"+ + "wave: Keys 0 · Glass .25 · Saw .5 · Sqr .75 · Bell 1. tone: low-pass 300 Hz … 12 kHz (exp). bright: upper partials. fm: phase modulation depth. "+ + "attack 1 ms … 1 s, decay 10 ms … 2 s (to a 62 % sustain), release 20 ms … 3 s, notelen 50 ms … 1.5 s gate (all exp). volume: output level.\n"+ + "detune: chorus partner ±0 … 14 cents. panspread: balls fan across the stereo field by position. humanize: level / pitch jitter.\n"+ + "root: C 0 … B 1 in 1/11 steps. scalemode: Off 0 · Major .2 · Minor .4 · Dorian .6 · Mixolydian .8 · Minor penta 1 (snaps generated notes).";+}diff --git a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.csindex 132f6af4..0aa0e6fd 100644--- a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs+++ b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs@@ -508,15 +508,40 @@ public sealed class FactoryPresetCatalog : IFactoryPresets("filfreq", 0.38f), ("filreso", 0.55f), ("fildrive", 0.4f), ("filenv", 0.55f),("fillfo", 0.8f), ("lforate", 0.62f), ("lfowave", 1.0f), ("drive", 0.3f), ("volume", 0.8f));- // ---- Nota Pendulum (kind 8) — generative keys. Sync Free 0 / Sync 1; Division 0 1/1..- // 1 1/16; Rate 0.5 = stop, <0.5 reverse; Motion 0 Linear/.33 Pendulum/.67 Ease/- // 1 Bounce; Quantize 0 Off/.5 1/16/1 1/8; Chord Sort Up 0 / Down 1; Scale 0 Off.+ // ---- Nota Pendulum (kind 8) — generative keys, 28 patches. Balls 0 2 … 1 6 (quarter+ // steps); Sync Free 0 / Sync 1; Division 0 1/1 · .25 1/2 · .5 1/4 · .75 1/8 · 1 1/16;+ // Rate 0.5 = stop, <0.5 reverse; Motion 0 Linear/.33 Pendulum/.67 Ease/1 Bounce;+ // Quantize 0 Off/.5 1/16/1 1/8; Chord Sort Up 0 / Down 1; Wave 0 Keys/.25 Glass/+ // .5 Saw/.75 Sqr/1 Bell; Scale Mode 0 Off/.2 Major/.4 Minor/.6 Dorian/.8 Mixolydian/+ // 1 Minor penta, Root = semitone/11.Inst("pendulum", 8, "Warm Cascade", ("balls", 0.4f), ("rate", 0.72f), ("sync", 1f), ("division", 0.25f), ("motion", 0.33f), ("quantize", 0.5f), ("spread", 0.25f), ("notelen", 0.4f), ("tone", 0.42f), ("attack", 0.14f), ("decay", 0.45f), ("release", 0.45f), ("detune", 0.3f), ("volume", 0.8f), ("panspread", 0.4f), ("humanize", 0.2f));Inst("pendulum", 8, "Slow Bloom", ("balls", 0.2f), ("rate", 0.62f), ("sync", 0f), ("freerate", 0.7f), ("motion", 0.67f), ("quantize", 0f), ("spread", 0.4f), ("notelen", 0.7f), ("tone", 0.35f), ("attack", 0.3f), ("decay", 0.6f), ("release", 0.7f), ("detune", 0.45f), ("volume", 0.78f), ("wave", 0.5f), ("bright", 0.3f), ("panspread", 0.55f), ("humanize", 0.35f));Inst("pendulum", 8, "Fast Sparkle", ("balls", 1.0f), ("rate", 0.85f), ("sync", 1f), ("division", 0.5f), ("motion", 0.33f), ("quantize", 0.5f), ("spread", 0.3f), ("notelen", 0.25f), ("tone", 0.6f), ("attack", 0.05f), ("decay", 0.3f), ("release", 0.3f), ("detune", 0.25f), ("volume", 0.8f), ("wave", 0.25f), ("bright", 0.7f), ("panspread", 0.5f));Inst("pendulum", 8, "Reverse Drift", ("balls", 0.6f), ("rate", 0.28f), ("sync", 1f), ("division", 0.25f), ("motion", 0.67f), ("quantize", 0.5f), ("spread", 0.6f), ("notelen", 0.45f), ("tone", 0.4f), ("attack", 0.18f), ("decay", 0.5f), ("release", 0.5f), ("detune", 0.35f), ("volume", 0.8f), ("wave", 1f), ("bright", 0.6f), ("fm", 0.4f), ("humanize", 0.3f));Inst("pendulum", 8, "Down Runs", ("balls", 0.4f), ("rate", 0.75f), ("sync", 1f), ("division", 0.25f), ("motion", 0f), ("quantize", 1f), ("chordsort", 1f), ("spread", 0.2f), ("notelen", 0.4f), ("tone", 0.48f), ("attack", 0.1f), ("decay", 0.4f), ("release", 0.4f), ("detune", 0.3f), ("volume", 0.8f), ("panspread", 0.3f));Inst("pendulum", 8, "Glass Bounce", ("balls", 0.8f), ("rate", 0.8f), ("sync", 1f), ("division", 0.5f), ("motion", 1f), ("quantize", 0.5f), ("spread", 0.35f), ("notelen", 0.2f), ("tone", 0.7f), ("attack", 0.02f), ("decay", 0.35f), ("release", 0.35f), ("detune", 0.2f), ("volume", 0.8f), ("wave", 0.25f), ("bright", 0.8f), ("fm", 0.15f), ("panspread", 0.6f), ("humanize", 0.25f));+ Inst("pendulum", 8, "Music Box", ("balls", 0.4f), ("rate", 0.7f), ("sync", 1f), ("division", 0.5f), ("motion", 0.33f), ("quantize", 0.5f), ("spread", 0.15f), ("notelen", 0.2f), ("tone", 0.75f), ("attack", 0.02f), ("decay", 0.3f), ("release", 0.5f), ("detune", 0.12f), ("wave", 0.25f), ("bright", 0.75f), ("fm", 0.1f), ("panspread", 0.5f), ("humanize", 0.1f), ("volume", 0.78f));+ Inst("pendulum", 8, "Bell Garden", ("balls", 0.75f), ("rate", 0.66f), ("sync", 1f), ("division", 0.25f), ("motion", 0.67f), ("quantize", 0.5f), ("spread", 0.35f), ("notelen", 0.35f), ("tone", 0.6f), ("attack", 0.05f), ("decay", 0.55f), ("release", 0.7f), ("detune", 0.2f), ("wave", 1f), ("bright", 0.55f), ("fm", 0.2f), ("panspread", 0.65f), ("humanize", 0.2f), ("scalemode", 0.2f), ("volume", 0.76f));+ Inst("pendulum", 8, "Pentatonic Rain", ("balls", 1f), ("rate", 0.78f), ("sync", 1f), ("division", 0.5f), ("motion", 0.33f), ("quantize", 0.5f), ("spread", 0.45f), ("notelen", 0.25f), ("tone", 0.55f), ("attack", 0.03f), ("decay", 0.35f), ("release", 0.45f), ("detune", 0.25f), ("wave", 0.25f), ("bright", 0.6f), ("panspread", 0.8f), ("humanize", 0.3f), ("scalemode", 1f), ("root", 9f / 11f), ("volume", 0.76f));+ Inst("pendulum", 8, "Dorian Drift", ("balls", 0.5f), ("rate", 0.6f), ("sync", 0f), ("freerate", 0.6f), ("motion", 0.33f), ("quantize", 0f), ("spread", 0.5f), ("notelen", 0.6f), ("tone", 0.4f), ("attack", 0.25f), ("decay", 0.6f), ("release", 0.8f), ("detune", 0.4f), ("bright", 0.35f), ("panspread", 0.5f), ("humanize", 0.3f), ("scalemode", 0.6f), ("root", 2f / 11f), ("volume", 0.8f));+ Inst("pendulum", 8, "Hold Pad", ("balls", 0.5f), ("rate", 0.58f), ("sync", 0f), ("freerate", 0.8f), ("motion", 0.67f), ("quantize", 0f), ("spread", 0.3f), ("notelen", 1f), ("tone", 0.38f), ("attack", 0.6f), ("decay", 0.8f), ("release", 0.85f), ("detune", 0.5f), ("bright", 0.25f), ("panspread", 0.6f), ("humanize", 0.15f), ("hold", 1f), ("volume", 0.74f));+ Inst("pendulum", 8, "Saw Arp", ("balls", 0.25f), ("rate", 0.8f), ("sync", 1f), ("division", 0.75f), ("motion", 0f), ("quantize", 0.5f), ("spread", 0f), ("notelen", 0.2f), ("tone", 0.55f), ("attack", 0.01f), ("decay", 0.3f), ("release", 0.25f), ("detune", 0.35f), ("wave", 0.5f), ("bright", 0.5f), ("panspread", 0.2f), ("humanize", 0f), ("volume", 0.7f));+ Inst("pendulum", 8, "Square Steps", ("balls", 0.25f), ("rate", 0.75f), ("sync", 1f), ("division", 0.5f), ("motion", 0f), ("quantize", 1f), ("spread", 0.1f), ("notelen", 0.25f), ("tone", 0.5f), ("attack", 0.02f), ("decay", 0.3f), ("release", 0.3f), ("detune", 0.25f), ("wave", 0.75f), ("bright", 0.45f), ("panspread", 0.3f), ("humanize", 0.05f), ("volume", 0.72f));+ Inst("pendulum", 8, "FM Glints", ("balls", 0.75f), ("rate", 0.82f), ("sync", 1f), ("division", 0.5f), ("motion", 0.33f), ("quantize", 0.5f), ("spread", 0.25f), ("notelen", 0.15f), ("tone", 0.7f), ("attack", 0.01f), ("decay", 0.25f), ("release", 0.35f), ("detune", 0.15f), ("bright", 0.6f), ("fm", 0.55f), ("panspread", 0.55f), ("humanize", 0.15f), ("volume", 0.76f));+ Inst("pendulum", 8, "Two Clocks", ("balls", 0f), ("rate", 0.7f), ("sync", 1f), ("division", 0.25f), ("motion", 0.33f), ("quantize", 0.5f), ("spread", 1f), ("notelen", 0.35f), ("tone", 0.45f), ("attack", 0.08f), ("decay", 0.45f), ("release", 0.5f), ("detune", 0.3f), ("panspread", 0.9f), ("humanize", 0.1f), ("volume", 0.82f));+ Inst("pendulum", 8, "Six Pendulums", ("balls", 1f), ("rate", 0.64f), ("sync", 1f), ("division", 0f), ("motion", 0.33f), ("quantize", 0.5f), ("spread", 0.55f), ("notelen", 0.4f), ("tone", 0.45f), ("attack", 0.1f), ("decay", 0.5f), ("release", 0.55f), ("detune", 0.3f), ("panspread", 0.7f), ("humanize", 0.2f), ("volume", 0.74f));+ Inst("pendulum", 8, "Rewind", ("balls", 0.5f), ("rate", 0.2f), ("sync", 1f), ("division", 0.5f), ("motion", 0.33f), ("quantize", 0.5f), ("spread", 0.3f), ("notelen", 0.3f), ("tone", 0.5f), ("attack", 0.05f), ("decay", 0.4f), ("release", 0.45f), ("detune", 0.25f), ("wave", 0.25f), ("bright", 0.55f), ("panspread", 0.45f), ("humanize", 0.15f), ("volume", 0.78f));+ Inst("pendulum", 8, "Linear Ladder", ("balls", 0.5f), ("rate", 0.76f), ("sync", 1f), ("division", 0.25f), ("motion", 0f), ("quantize", 0.5f), ("spread", 0f), ("notelen", 0.3f), ("tone", 0.5f), ("attack", 0.03f), ("decay", 0.35f), ("release", 0.35f), ("detune", 0.2f), ("panspread", 0.3f), ("humanize", 0f), ("volume", 0.8f));+ Inst("pendulum", 8, "Rubber Bounce", ("balls", 0.5f), ("rate", 0.74f), ("sync", 1f), ("division", 0.25f), ("motion", 1f), ("quantize", 0f), ("spread", 0.2f), ("notelen", 0.25f), ("tone", 0.45f), ("attack", 0.02f), ("decay", 0.4f), ("release", 0.35f), ("detune", 0.25f), ("wave", 0.75f), ("bright", 0.35f), ("fm", 0.1f), ("panspread", 0.4f), ("humanize", 0.25f), ("volume", 0.76f));+ Inst("pendulum", 8, "Free Chimes", ("balls", 0.75f), ("rate", 0.7f), ("sync", 0f), ("freerate", 0.35f), ("motion", 0.67f), ("quantize", 0f), ("spread", 0.6f), ("notelen", 0.3f), ("tone", 0.7f), ("attack", 0.01f), ("decay", 0.6f), ("release", 0.9f), ("detune", 0.1f), ("wave", 1f), ("bright", 0.7f), ("fm", 0.15f), ("panspread", 0.85f), ("humanize", 0.35f), ("volume", 0.72f));+ Inst("pendulum", 8, "Lullaby", ("balls", 0.25f), ("rate", 0.6f), ("sync", 1f), ("division", 0.25f), ("motion", 0.33f), ("quantize", 0.5f), ("spread", 0.1f), ("notelen", 0.55f), ("tone", 0.3f), ("attack", 0.3f), ("decay", 0.6f), ("release", 0.75f), ("detune", 0.35f), ("bright", 0.2f), ("panspread", 0.3f), ("humanize", 0.15f), ("scalemode", 0.2f), ("volume", 0.82f));+ Inst("pendulum", 8, "Minor Cascade", ("balls", 0.75f), ("rate", 0.74f), ("sync", 1f), ("division", 0.5f), ("motion", 0.67f), ("quantize", 0.5f), ("spread", 0.3f), ("notelen", 0.35f), ("tone", 0.45f), ("attack", 0.06f), ("decay", 0.45f), ("release", 0.55f), ("detune", 0.3f), ("bright", 0.45f), ("panspread", 0.5f), ("humanize", 0.2f), ("scalemode", 0.4f), ("volume", 0.78f));+ Inst("pendulum", 8, "Eighth Machine", ("balls", 0.5f), ("rate", 0.85f), ("sync", 1f), ("division", 0.75f), ("motion", 0f), ("quantize", 0.5f), ("spread", 0f), ("notelen", 0.12f), ("tone", 0.6f), ("attack", 0.005f), ("decay", 0.2f), ("release", 0.15f), ("detune", 0.2f), ("wave", 0.5f), ("bright", 0.6f), ("panspread", 0.25f), ("humanize", 0f), ("volume", 0.7f));+ Inst("pendulum", 8, "Mixolydian Sun", ("balls", 0.75f), ("rate", 0.7f), ("sync", 1f), ("division", 0.5f), ("motion", 0.33f), ("quantize", 0.5f), ("spread", 0.4f), ("notelen", 0.3f), ("tone", 0.65f), ("attack", 0.03f), ("decay", 0.35f), ("release", 0.45f), ("detune", 0.2f), ("wave", 0.25f), ("bright", 0.65f), ("panspread", 0.6f), ("humanize", 0.2f), ("scalemode", 0.8f), ("root", 7f / 11f), ("volume", 0.76f));+ Inst("pendulum", 8, "Deep Keys", ("balls", 0.5f), ("rate", 0.66f), ("sync", 1f), ("division", 0.25f), ("motion", 0.33f), ("quantize", 0.5f), ("spread", 0.2f), ("notelen", 0.5f), ("tone", 0.22f), ("attack", 0.12f), ("decay", 0.55f), ("release", 0.6f), ("detune", 0.45f), ("bright", 0.15f), ("panspread", 0.3f), ("humanize", 0.15f), ("volume", 0.85f));+ Inst("pendulum", 8, "Wide Shimmer", ("balls", 1f), ("rate", 0.72f), ("sync", 1f), ("division", 0.5f), ("motion", 0.67f), ("quantize", 0.5f), ("spread", 0.5f), ("notelen", 0.2f), ("tone", 0.8f), ("attack", 0.02f), ("decay", 0.3f), ("release", 0.6f), ("detune", 0.6f), ("wave", 0.25f), ("bright", 0.85f), ("fm", 0.2f), ("panspread", 1f), ("humanize", 0.3f), ("volume", 0.72f));+ Inst("pendulum", 8, "Restart Motif", ("balls", 0.25f), ("rate", 0.75f), ("sync", 1f), ("division", 0.25f), ("motion", 0.33f), ("quantize", 0.5f), ("spread", 0.25f), ("firstnote", 1f), ("notelen", 0.35f), ("tone", 0.5f), ("attack", 0.04f), ("decay", 0.4f), ("release", 0.45f), ("detune", 0.3f), ("panspread", 0.35f), ("humanize", 0.1f), ("volume", 0.8f));+ Inst("pendulum", 8, "Slow Swing", ("balls", 0.25f), ("rate", 0.56f), ("sync", 0f), ("freerate", 0.9f), ("motion", 0.33f), ("quantize", 0f), ("spread", 0.2f), ("notelen", 0.8f), ("tone", 0.35f), ("attack", 0.35f), ("decay", 0.7f), ("release", 0.8f), ("detune", 0.4f), ("bright", 0.3f), ("panspread", 0.5f), ("humanize", 0.25f), ("volume", 0.82f));// ---- Nota Operator (kind 9) — 4-op FM, 25 patches across keys, bells, basses,// leads, pads and percussion. Coarse = ratio index / 15 (0 ×0.5 · .0667 ×1 ·diff --git a/src/managed/Nota.Mcp/Tools/InstrumentTools.cs b/src/managed/Nota.Mcp/Tools/InstrumentTools.csindex 2cf54464..5ca591ea 100644--- a/src/managed/Nota.Mcp/Tools/InstrumentTools.cs+++ b/src/managed/Nota.Mcp/Tools/InstrumentTools.cs@@ -113,6 +113,112 @@ public sealed class InstrumentTools(IAudioEngine engine, IEngineDispatch dispatcG("r2on") >= 0.5f, G("structure") < 0.5f ? "1>2 serial" : "1+2 parallel", a1, a2, r1, r2);});+ public sealed record PendulumBall(int Index, double Phase, double Position, string Direction, string Note,+ double SecondsToWall, double RatePercent, bool JustFired);+ public sealed record PendulumStep(int Step, string Note, string Bar);+ public sealed record PendulumReading(string Summary, string Guide, int ActiveVoices, int MaxVoices, string[] HeldChord,+ string LastNote, double BarPosition, int StepsPerBar, double SwingSeconds, bool TransportRolling, bool Live,+ PendulumBall[] Balls, PendulumStep[] BarNotes);++ [McpServerTool(Name = "read_pendulum"), Description(+ "Read a Nota Pendulum track (built-in instrument kind 8 — generative keys: hold a chord and 2-6 balls swing across it; "+ + "x = pitch, so each chord degree a ball crosses plays that note, weaving an arpeggio). Returns a one-line summary of the "+ + "patch, a guide to what each 0..1 parameter value means (ids for set_instrument_param_by_id, or use set_pendulum), the "+ + "sounding voices, the held chord (low to high), the last generated note, where the bar is (0..1) and the live balls exactly "+ + "as the audio thread swings them: phase, position 0 (low wall) .. 1 (high wall), direction, the note it sits on, seconds "+ + "to the wall ahead (-1 = stopped), its own rate (% of full speed, negative = reverse) and whether it just fired. BarNotes "+ + "lists the generated notes on the bar's 1/16 grid (Bar = this or last).")]+ public Task<PendulumReading?> ReadPendulum(int trackId) => Read<PendulumReading?>(() =>+ {+ if (E.TrackInstrumentKind(trackId) != PendulumModel.Kind) return null;+ var g = PendulumGetter(trackId);+ var sc = new float[PendulumModel.ScopeLength];+ int n = E.InstrumentScope(trackId, sc);+ var s = new PendulumModel.Snapshot();+ PendulumModel.Parse(sc.AsSpan(0, Math.Max(0, n)), s);+ var heldBuf = new int[16];+ int hn = E.InstrumentHeldNotes(trackId, heldBuf);+ var held = new string[hn];+ for (int i = 0; i < hn; i++) held[i] = PendulumModel.NoteName(heldBuf[i]);+ int count = PendulumModel.BallCount(g("balls"));+ var balls = new PendulumBall[count];+ for (int b = 0; b < count; b++)+ {+ var x = s.BallState[b];+ balls[b] = new PendulumBall(b, Math.Round(x.Phase, 3), Math.Round(x.Pos, 3), x.Dir > 0 ? "up" : x.Dir < 0 ? "down" : "still",+ PendulumModel.NoteName(x.Pitch), x.ToWall < 0 ? -1 : Math.Round(x.ToWall, 3), Math.Round(x.Rate * 100, 1), x.Pitch >= 0 && x.Since < 0.16);+ }+ var steps = new List<PendulumStep>();+ for (int i = 0; i < s.StepCount; i++)+ if (s.Steps[i].Pitch >= 0) steps.Add(new PendulumStep(i, PendulumModel.NoteName(s.Steps[i].Pitch), s.Steps[i].Age == 0 ? "this" : "last"));+ return new PendulumReading(PendulumModel.Summary(g), PendulumModel.Guide, s.Voices, PendulumModel.Voices, held,+ PendulumModel.NoteName(s.LastPitch), Math.Round(s.BarPos, 3), s.StepCount, Math.Round(s.SwingSeconds, 3), s.Playing, s.Live,+ balls, steps.ToArray());+ });++ [McpServerTool(Name = "set_pendulum"), Description(+ "Shape a Nota Pendulum track (kind 8) in musical terms; every argument is optional and only the given ones change. "+ + "balls 2..6; ratePercent -100..100 (0 stops, negative reverses); sync true = a swing takes a note division (division "+ + "\"1/1\", \"1/2\", \"1/4\", \"1/8\", \"1/16\"), false = freeSeconds 0.1..4 per swing; motion Linear | Pendulum | Ease | Bounce; "+ + "quantize Off | 1/16 | 1/8; sort up | down; spreadPercent 0..100 (the balls drift apart); hold / firstNote on/off; "+ + "wave Keys | Glass | Saw | Sqr | Bell; scale \"Off\" or \"<root> <mode>\" with mode major | minor | dorian | mixolydian | "+ + "minor penta (e.g. \"A minor penta\"); restart = restart every ball now. Returns the new summary, or an error line naming "+ + "the value it could not use. Voice / envelope / spread details: set_instrument_param_by_id with the read_pendulum guide.")]+ public Task<string> SetPendulum(int trackId, int? balls = null, double? ratePercent = null, bool? sync = null, string? division = null,+ double? freeSeconds = null, string? motion = null, string? quantize = null, string? sort = null, double? spreadPercent = null,+ bool? hold = null, bool? firstNote = null, string? wave = null, string? scale = null, bool? restart = null) => Mutate(() =>+ {+ if (E.TrackInstrumentKind(trackId) != PendulumModel.Kind) return $"error: track {trackId} is not a Nota Pendulum";+ int pc = E.PluginParamCount(trackId, -1);+ var ids = new Dictionary<string, int>();+ for (int i = 0; i < pc; i++) ids[E.PluginParamId(trackId, -1, i)] = i;+ void Set(string id, double v) { if (ids.TryGetValue(id, out var i)) E.PluginParamSet(trackId, -1, i, (float)Math.Clamp(v, 0, 1)); }+ static int Find(string[] names, string? v) => v is null ? -1 : Array.FindIndex(names, n => string.Equals(n, v.Trim(), StringComparison.OrdinalIgnoreCase));+ var errors = new List<string>();++ if (balls is { } bc) Set("balls", PendulumModel.BallCountNorm(bc));+ if (ratePercent is { } rp) Set("rate", 0.5 + Math.Clamp(rp, -100, 100) / 200.0);+ if (sync is { } sy) Set("sync", sy ? 1 : 0);+ if (division is not null) { int d = Find(PendulumModel.DivNames, division); if (d < 0) errors.Add($"division '{division}'"); else { Set("division", d / 4.0); Set("sync", 1); } }+ if (freeSeconds is { } fs) { Set("freerate", Math.Log(Math.Clamp(fs, 0.1, 4.0) / 0.1) / Math.Log(40.0)); if (sync is null) Set("sync", 0); }+ if (motion is not null) { int m = Find(PendulumModel.MotionNames, motion); if (m < 0) errors.Add($"motion '{motion}'"); else Set("motion", m / 3.0); }+ if (quantize is not null) { int q = Find(PendulumModel.QuantNames, quantize); if (q < 0) errors.Add($"quantize '{quantize}'"); else Set("quantize", q / 2.0); }+ if (sort is not null)+ {+ if (string.Equals(sort, "up", StringComparison.OrdinalIgnoreCase)) Set("chordsort", 0);+ else if (string.Equals(sort, "down", StringComparison.OrdinalIgnoreCase)) Set("chordsort", 1);+ else errors.Add($"sort '{sort}'");+ }+ if (spreadPercent is { } sp) Set("spread", sp / 100.0);+ if (hold is { } h) Set("hold", h ? 1 : 0);+ if (firstNote is { } fn) Set("firstnote", fn ? 1 : 0);+ if (wave is not null) { int w = Find(PendulumModel.WaveNames, wave); if (w < 0) errors.Add($"wave '{wave}'"); else Set("wave", w / 4.0); }+ if (scale is not null)+ {+ var t = scale.Trim();+ if (string.Equals(t, "off", StringComparison.OrdinalIgnoreCase)) Set("scalemode", 0);+ else+ {+ int sp2 = t.IndexOf(' ');+ int root = sp2 > 0 ? Find(PendulumModel.RootNames, t[..sp2]) : -1;+ int mode = sp2 > 0 ? Find(PendulumModel.ModeNames, t[(sp2 + 1)..]) : -1;+ if (root < 0 || mode <= 0) errors.Add($"scale '{scale}'");+ else { Set("root", root / 11.0); Set("scalemode", mode / (double)(PendulumModel.ModeNames.Length - 1)); }+ }+ }+ if (restart == true) Set("reset", 1);+ string summary = PendulumModel.Summary(PendulumGetter(trackId));+ return errors.Count == 0 ? summary : $"error: could not use {string.Join(", ", errors)} · {summary}";+ });++ private Func<string, float> PendulumGetter(int trackId)+ {+ int pc = E.PluginParamCount(trackId, -1);+ var vals = new Dictionary<string, float>();+ for (int i = 0; i < pc; i++) vals[E.PluginParamId(trackId, -1, i)] = E.PluginParamGet(trackId, -1, i);+ return id => vals.TryGetValue(id, out var v) ? v : 0f;+ }+[McpServerTool(Name = "set_instrument_param_by_id"), Description("Set a track instrument parameter by its stable id (e.g. \"cutoff\", \"pmoscb\") to a normalized value (0..1). "+ "Ids never change between versions, unlike indices. Returns false if the instrument has no such parameter.")]diff --git a/src/native/nota.engine/src/PendulumSynth.h b/src/native/nota.engine/src/PendulumSynth.hindex cc3207a2..68226d99 100644--- a/src/native/nota.engine/src/PendulumSynth.h+++ b/src/native/nota.engine/src/PendulumSynth.h@@ -16,12 +16,17 @@// Pan Spread fans them across the stereo field; Humanize adds gentle level/pitch jitter;// Hold latches the chord and First note restarts the pattern on a new chord; an optional// Scale snaps generated notes. Needs the musical clock via Instrument::setTransport-// (samples-per-beat for Sync/Quantize). All params ride the plugin-param interface-// (normalized 0..1) → automation / persist / clone free. Header-only, alloc-free.+// (samples-per-beat for Sync/Quantize) and setTransportInfo (the bar, for the note strip).+// All params ride the plugin-param interface (normalized 0..1) → automation / persist /+// clone free. Header-only, alloc-free.+//+// Telemetry (scopeRead, kTele floats) for the editor's lanes / note strip and the MCP+// reader — see the layout above kTele. Mirrored by Nota.Application/PendulumModel.cs.#pragma once#include "Instrument.h"+#include "TransportInfo.h"#include <algorithm>#include <atomic>@@ -74,13 +79,48 @@ public:set(ScaleMode, 0.0f); // Offset(Reset, 0.0f);resetPhases();+ for (int st = 0; st < kMaxSteps; ++st) { stepPitch_[st] = -1; stepBar_[st] = -8; }+ for (int b = 0; b < kMaxBalls; ++b) { ballPitch_[b] = -1; ballSince_[b] = 1e9; }+ for (auto& t : tele_) t.store(0.0f, std::memory_order_relaxed);}int32_t kind() const override { return 8; }const char* displayName() const override { return "Nota Pendulum"; }void setSampleRate(double sr) override { sampleRate_ = sr > 0 ? sr : 44100.0; }- void setTransport(double /*beatStart*/, double spb, bool /*playing*/) override { if (spb > 0) spb_ = spb; }+ void setTransport(double beatStart, double spb, bool playing) override {+ if (spb > 0) spb_ = spb;+ playing_ = playing;+ if (playing && std::isfinite(beatStart)) beat_ = beatStart; // stopped: the clock free-runs on+ }+ void setTransportInfo(const TransportInfo& ti) override {+ if (ti.tsNum > 0 && ti.tsDenom > 0) beatsPerBar_ = std::clamp(ti.tsNum * 4.0 / ti.tsDenom, 1.0, 8.0);+ }++ int32_t activeVoiceCount() const override { return activeVoices_.load(std::memory_order_relaxed); }++ // ---- telemetry ----------------------------------------------------------+ // Head (kHead): [0] sounding voices · [1] balls · [2] held-chord size · [3] last+ // generated pitch (−1 none yet) · [4] place in the bar 0..1 · [5] steps per bar (1/16+ // grid) · [6] seconds per swing at the base rate (0 = stopped) · [7] ball that fired+ // last (−1) · [8] seconds since the last note · [9] notes fired this bar · [10] beats+ // per bar · [11] transport rolling (0/1).+ // Then kMaxBalls × kBallStride: phase 0..1 · position 0..1 · direction (+1 → high,+ // −1 → low, 0 still) · pitch now (−1) · seconds to the wall ahead (−1 never) · seconds+ // since this ball fired · signed rate (1 = +100 %) · chord degree (−1).+ // Then kMaxSteps × 2 — the bar grid: pitch (−1 empty) · age in bars (0 this bar, 1 the+ // last). Then kMaxVoices level of each sounding voice (0 = silent slot).+ static constexpr int kHead = 12, kBallStride = 8, kMaxSteps = 32, kMaxLevels = 8;+ static constexpr int kBallsAt = kHead;+ static constexpr int kStepsAt = kBallsAt + 6 * kBallStride;+ static constexpr int kLevelsAt = kStepsAt + kMaxSteps * 2;+ static constexpr int kTele = kLevelsAt + kMaxLevels;+ int32_t scopeRead(float* out, int32_t maxN) const override {+ if (!out || maxN <= 0) return 0;+ const int n = std::min<int>(maxN, kTele);+ for (int i = 0; i < n; ++i) out[i] = tele_[i].load(std::memory_order_relaxed);+ return n;+ }// ---- parameters -------------------------------------------------------int32_t pluginParamCount() const override { return kNumParams; }@@ -92,10 +132,15 @@ public:return (i >= 0 && i < kNumParams) ? std::string(ids[i]) : std::string{};}std::string pluginParamName(int32_t i) const override {+ // Display names group by their head in the automation menu (Balls › Count …);+ // the ids are what persists, so names may change.static const char* nm[] = {- "Balls", "Rate", "Sync", "Division", "Free Rate", "Motion", "Quantize", "Chord Sort", "Spread",- "Note Length", "Tone", "Attack", "Release", "Detune", "Volume", "Wave", "Bright", "FM",- "Decay", "Pan Spread", "Humanize", "Hold", "First Note", "Scale Root", "Scale", "Reset" };+ "Balls Count", "Motion Rate", "Motion Sync", "Motion Division", "Motion Time", "Motion Curve",+ "Balls Quantize", "Balls Sort", "Spread Rate",+ "Voice Length", "Voice Tone", "Voice Attack", "Voice Release", "Spread Detune", "Volume",+ "Voice Wave", "Voice Bright", "Voice FM",+ "Voice Decay", "Spread Pan", "Spread Humanize", "Balls Hold", "Balls Restart", "Scale Root",+ "Scale Mode", "Balls Reset" };return (i >= 0 && i < kNumParams) ? std::string(nm[i]) : std::string{};}float pluginParamGet(int32_t i) const override {@@ -207,8 +252,13 @@ public:const double gridSamp = quant == 0 ? 0.0 : (quant == 1 ? 0.25 : 0.5) * spb_;detUp_ = detUp; detDn_ = detDn;+ const double beatInc = spb_ > 0 ? 1.0 / spb_ : 0.0;+ const int steps = std::clamp((int)std::lround(beatsPerBar_ * 4.0), 1, kMaxSteps);for (int32_t i = 0; i < frames; ++i) {+ beat_ += beatInc;+ sinceNote_ += 1.0;+ for (int b = 0; b < kMaxBalls; ++b) ballSince_[b] += 1.0;// Grid gate for Quantize: evaluate crossings continuously (Off) or on grid ticks.bool evaluate = true;if (gridSamp > 0.0) { gridAcc_ += 1.0; if (gridAcc_ >= gridSamp) { gridAcc_ -= gridSamp; evaluate = true; } else evaluate = false; }@@ -228,6 +278,7 @@ public:const float lvl = 1.0f + (float)(human * 0.4 * rndBi()); // level jitterconst double det = 1.0 + human * 0.012 * rndBi(); // micro-detune jittertrigger(pitch, gateLen, (float)pan, lvl, det);+ noteFired(b, pitch, steps);}}}@@ -261,6 +312,8 @@ public:out[i * 2] += l * g;out[i * 2 + 1] += r * g;}++ publish(count, baseInc, spread, motion, steps, rateMult, cycleSamp);}private:@@ -351,6 +404,66 @@ private:}}+ // Bar bookkeeping for a generated note: the step it lands on, its bar, who fired it.+ void noteFired(int ball, int pitch, int steps) {+ const double bar = std::floor(beat_ / beatsPerBar_);+ const double inBar = beat_ / beatsPerBar_ - bar;+ const int st = std::clamp((int)(inBar * steps), 0, steps - 1);+ stepPitch_[st] = pitch; stepBar_[st] = (int64_t)bar;+ if ((int64_t)bar != countBar_) { countBar_ = (int64_t)bar; barNotes_ = 0; }+ ++barNotes_;+ lastPitch_ = pitch; lastBall_ = ball; sinceNote_ = 0.0; ballSince_[ball] = 0.0;+ ballPitch_[ball] = pitch;+ }++ // Once per block: the snapshot the editor and the MCP reader see.+ void publish(int count, double baseInc, double spread, int motion, int steps, double rateMult, double cycleSamp) {+ auto put = [this](int i, double v) { tele_[i].store((float)v, std::memory_order_relaxed); };+ const double sr = sampleRate_;+ int active = 0, lv = 0;+ for (const auto& v : voices_) {+ if (!v.active) continue;+ ++active;+ if (lv < kMaxLevels) put(kLevelsAt + lv++, std::clamp(v.env * v.env * v.lvl, 0.0f, 1.0f));+ }+ for (; lv < kMaxLevels; ++lv) put(kLevelsAt + lv, 0.0);+ activeVoices_.store(active, std::memory_order_relaxed);++ const double bar = std::floor(beat_ / beatsPerBar_);+ if ((int64_t)bar != countBar_) { countBar_ = (int64_t)bar; barNotes_ = 0; }+ put(0, active); put(1, count); put(2, heldCount_); put(3, lastPitch_);+ put(4, beat_ / beatsPerBar_ - bar); put(5, steps);+ put(6, std::fabs(rateMult) > 1e-6 ? cycleSamp / std::fabs(rateMult) / sr : 0.0);+ put(7, lastBall_); put(8, sinceNote_ / sr); put(9, barNotes_); put(10, beatsPerBar_); put(11, playing_ ? 1 : 0);++ for (int b = 0; b < kMaxBalls; ++b) {+ const int at = kBallsAt + b * kBallStride;+ const double inc = baseInc * (1.0 + spread * (double)b * 0.37);+ const double ph = ballPhase_[b];+ // Walls sit at phase 0 (low end) and 0.5 (high end) for every swing curve.+ double dir = 0.0, toWall = -1.0;+ if (std::fabs(inc) > 1e-12) {+ const bool up = inc > 0;+ const bool rising = up ? ph < 0.5 : ph > 0.5;+ dir = rising ? 1.0 : -1.0;+ const double next = up ? (ph < 0.5 ? 0.5 : 1.0) : (ph > 0.5 ? 0.5 : 0.0);+ toWall = std::fabs(next - ph) / std::fabs(inc) / sr;+ }+ const int deg = b < count ? lastIdx_[b] : -1;+ int pitch = -1;+ if (deg >= 0 && deg < heldCount_) pitch = ballPitch_[b];+ put(at + 0, ph); put(at + 1, position(ph, motion)); put(at + 2, dir); put(at + 3, pitch);+ put(at + 4, toWall); put(at + 5, ballSince_[b] / sr);+ put(at + 6, rateMult * 0.5 * (1.0 + spread * (double)b * 0.37)); put(at + 7, deg);+ }+ for (int st = 0; st < kMaxSteps; ++st) {+ const int64_t age = (int64_t)bar - stepBar_[st];+ const bool live = st < steps && stepPitch_[st] >= 0 && age >= 0 && age <= 1;+ put(kStepsAt + st * 2, live ? stepPitch_[st] : -1);+ put(kStepsAt + st * 2 + 1, live ? (double)age : -1.0);+ }+ }+void trigger(int pitch, int gateLen, float pan, float lvl, double detJit) {Voice* v = findFreeVoice();const double f = 440.0 * std::pow(2.0, (pitch - 69) / 12.0);@@ -379,6 +492,18 @@ private:double gridAcc_ = 0.0;double detUp_ = 1.0, detDn_ = 1.0;uint32_t rng_ = 0x1234567u;++ // Musical clock (follows the transport while it rolls, free-runs when stopped) and+ // the telemetry state behind scopeRead.+ double beat_ = 0.0, beatsPerBar_ = 4.0;+ bool playing_ = false;+ int stepPitch_[kMaxSteps] = {}; int64_t stepBar_[kMaxSteps] = {};+ int64_t countBar_ = 0; int barNotes_ = 0;+ int lastPitch_ = -1, lastBall_ = -1;+ int ballPitch_[kMaxBalls] = {};+ double sinceNote_ = 1e9, ballSince_[kMaxBalls] = {};+ std::atomic<int32_t> activeVoices_{0};+ std::atomic<float> tele_[kTele];};} // namespace notadiff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 91203e64..3b123168 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -2425,6 +2425,103 @@ Console.WriteLine("-- Nota Pendulum --");float rms = Rms(nbuf, 16384); bool finite = true;foreach (var s in nbuf) if (!float.IsFinite(s) || Math.Abs(s) > 8f) { finite = false; break; }Check(rms > 0.001f && finite, $"Nota Pendulum arpeggiates a held chord (RMS {rms:F3})");++ // Display names group by head in the automation menu (ids unchanged).+ Check(pe.PluginParamName(t, -1, rateI) == "Motion Rate", $"pendulum names group by head (rate → '{pe.PluginParamName(t, -1, rateI)}')");++ // Telemetry: the balls, the bar grid and the voices the audio thread is actually playing.+ {+ int tt = pe.AddPendulumSynthTrack();+ pe.AddMidiClip(tt, 0.0, 8.0);+ pe.SetClipNotes(tt, 0, new[] { new NotaNote(60, 0.0, 8.0, 0.9f), new NotaNote(64, 0.0, 8.0, 0.9f), new NotaNote(67, 0.0, 8.0, 0.9f) });+ var tb = new float[512 * 2];+ pe.Seek(0.0); pe.Play();+ for (int k = 0; k < 120; k++) pe.RenderOffline(tb, 512); // ~1.4 s @ 44.1k, into bar 1+ var sc = new float[PendulumModel.ScopeLength];+ int sn = pe.InstrumentScope(tt, sc);+ var snap = new PendulumModel.Snapshot();+ PendulumModel.Parse(sc.AsSpan(0, Math.Max(0, sn)), snap);+ Check(sn == PendulumModel.ScopeLength && snap.Live, $"pendulum scope carries {PendulumModel.ScopeLength} telemetry floats (got {sn})");+ Check(snap.Balls == 4 && snap.Held == 3, $"telemetry: 4 balls over a 3-note chord (got {snap.Balls} / {snap.Held})");+ Check(snap.Voices > 0 && pe.InstrumentVoiceCount(tt) == snap.Voices, $"telemetry voices match the header voice count ({snap.Voices} / {pe.InstrumentVoiceCount(tt)})");+ Check(snap.LastPitch is 60 or 64 or 67, $"last generated note is a chord tone (got {snap.LastPitch})");+ Check(snap.StepCount == 16 && snap.BarPos >= 0 && snap.BarPos < 1 && snap.Playing, $"bar clock: 16 steps, position {snap.BarPos:F2}, rolling");+ int onGrid = 0; bool gridOk = true;+ for (int i = 0; i < snap.StepCount; i++) if (snap.Steps[i].Pitch >= 0) { onGrid++; if (snap.Steps[i].Pitch is not (60 or 64 or 67) || snap.Steps[i].Age is < 0 or > 1) gridOk = false; }+ Check(onGrid > 0 && gridOk, $"bar grid holds generated chord tones ({onGrid} steps)");+ bool ballsOk = true;+ for (int b = 0; b < 4; b++)+ {+ var x = snap.BallState[b];+ if (x.Phase is < 0 or >= 1 || x.Pos is < 0 or > 1 || x.Dir == 0 || x.ToWall < 0 || x.ToWall > 10 || x.Rate <= 0) ballsOk = false;+ }+ Check(ballsOk, "each ball reports phase, position, direction, time to the wall and a forward rate");+ Check(snap.BallState[3].Rate > snap.BallState[0].Rate, $"spread runs later balls faster ({snap.BallState[0].Rate:F2} → {snap.BallState[3].Rate:F2})");+ // Reverse: the rate's sign flips every ball's.+ int ri = -1; for (int i = 0; i < pc; i++) if (pe.PluginParamId(tt, -1, i) == "rate") ri = i;+ pe.PluginParamSet(tt, -1, ri, 0.25f);+ pe.RenderOffline(tb, 512);+ pe.InstrumentScope(tt, sc); PendulumModel.Parse(sc, snap);+ Check(snap.BallState[0].Rate < 0 && snap.BallState[2].Rate < 0, "a rate left of centre reverses the balls");+ pe.StopTransport();+ }++ // Hold latches the chord: it keeps swinging after the keys are released.+ {+ static float RmsRange(float[] b, int from, int to) { double sum = 0; for (int i = from * 2; i < to * 2; i++) sum += b[i] * (double)b[i]; return (float)Math.Sqrt(sum / Math.Max(1, (to - from) * 2)); }+ int th = pe.AddPendulumSynthTrack();+ int hi = -1; for (int i = 0; i < pc; i++) if (pe.PluginParamId(th, -1, i) == "hold") hi = i;+ pe.PluginParamSet(th, -1, hi, 1f);+ pe.AddMidiClip(th, 0.0, 1.0);+ pe.SetClipNotes(th, 0, new[] { new NotaNote(57, 0.0, 0.5, 0.9f), new NotaNote(60, 0.0, 0.5, 0.9f), new NotaNote(64, 0.0, 0.5, 0.9f) });+ var hb = new float[44100 * 2 * 3];+ pe.Seek(0.0); pe.Play(); pe.RenderOffline(hb, 44100 * 3);+ int hn = pe.InstrumentHeldNotes(th, new int[16]);+ pe.StopTransport();+ float tail = RmsRange(hb, 44100 * 2, 44100 * 3);+ Check(hn == 3 && tail > 0.001f, $"Hold keeps the chord ({hn} notes) sounding after release (tail RMS {tail:F3})");+ }++ // Factory presets: ≥ 25, every named id real, each applies in place and sounds a held chord.+ {+ var ids = new HashSet<string>();+ for (int i = 0; i < pc; i++) ids.Add(pe.PluginParamId(t, -1, i));+ var cat = new FactoryPresetCatalog();+ var mine = cat.All().Where(p => p.IsInstrument && p.BuiltinKind == 8).ToList();+ Check(mine.Count >= 25, $"Nota Pendulum ships ≥ 25 factory presets (got {mine.Count})");+ var bad = mine.SelectMany(p => cat.Document(p.Id)!.NamedParams!.Keys.Where(k => !ids.Contains(k)).Select(k => $"{p.DisplayName}:{k}")).ToList();+ Check(bad.Count == 0, $"every Pendulum preset param id exists{(bad.Count > 0 ? " — bad: " + string.Join(", ", bad) : "")}");+ var quiet = new List<string>();+ foreach (var p in mine)+ {+ using var ep = new NotaEngine();+ ep.SetBpm(120); ep.SetTimeSignature(4, 4);+ int tp = ep.AddPendulumSynthTrack();+ if (cat.ApplyInPlace(ep, p.Id, tp, -1).Length != 0) { quiet.Add($"{p.DisplayName} (apply)"); continue; }+ ep.AddMidiClip(tp, 0.0, 8.0);+ ep.SetClipNotes(tp, 0, new[] { new NotaNote(48, 0, 8, 0.9f), new NotaNote(55, 0, 8, 0.9f), new NotaNote(60, 0, 8, 0.9f), new NotaNote(64, 0, 8, 0.9f) });+ var pb = new float[44100 * 2 * 3];+ ep.Seek(0.0); ep.Play(); ep.RenderOffline(pb, 44100 * 3); ep.StopTransport();+ float r = Rms(pb, 44100 * 3), pk = pb.Max(Math.Abs);+ if (!pb.All(float.IsFinite) || r < 0.003f || pk > 2f) quiet.Add($"{p.DisplayName} ({r:F3}/{pk:F2})");+ }+ Check(quiet.Count == 0, $"every Pendulum preset sounds a held chord, finite and not clipping hard{(quiet.Count > 0 ? " — " + string.Join(", ", quiet) : "")}");+ }++ // MCP: read_pendulum / set_pendulum.+ {+ var mcp = new Nota.Mcp.Tools.InstrumentTools(pe, new Nota.SmokeTest.SyncDispatch(), new Nota.SmokeTest.NoRefresh());+ int mt = mcp.AddInstrumentTrack(8).Result;+ var rd = mcp.ReadPendulum(mt).Result;+ Check(rd is not null && rd.Balls.Length == 4 && rd.Summary.Contains("4 balls") && rd.Guide.Contains("scalemode"), $"read_pendulum reads a fresh Pendulum ({rd?.Summary})");+ Check(mcp.ReadPendulum(pe.AddInstrumentTrack()).Result is null, "read_pendulum returns null for another instrument");+ string res = mcp.SetPendulum(mt, balls: 6, ratePercent: -30, division: "1/8", motion: "Bounce", scale: "A minor penta", wave: "Bell").Result;+ var rd2 = mcp.ReadPendulum(mt).Result!;+ Check(!res.StartsWith("error") && rd2.Balls.Length == 6 && res.Contains("sync 1/8") && res.Contains("bounce") && res.Contains("reverse") && res.Contains("A minor penta") && res.Contains("bell"),+ $"set_pendulum shapes the pattern in musical terms ({res})");+ string err = mcp.SetPendulum(mt, motion: "Wobble").Result;+ Check(err.StartsWith("error") && err.Contains("Wobble"), $"set_pendulum names a value it cannot use ({err})");+ }}// ============================ Nota Operator ================================