Skip to content

armgit / nota

Public Imported from GitHub
0

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

Redesign of grane

Egor Khindikaynen096c5f67caea
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e91eb8a7..93c4034f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,27 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
## [Unreleased]
### Added
+- **Nota Grain's editor is now the almanac's card, with a Dry/Wet knob and a live grain
+ cloud.** The vertical tab rail and the separate playhead strip give way to one layout:
+ the sample fills the centre as a graph — the Spray band around the dashed read Position,
+ each held voice's read head and, new, **every grain the engine is playing** as a teal dot
+ at its read position (high for left, low for right, larger the louder its window) — with
+ the five tabs (Grain · Pitch · Variation · Filter · Amp) along its top and each tab's
+ controls beneath it. **Drag across the sample to move Position**; double-click puts it
+ back. The 186 px rail on the right keeps **READ** (Scan / Freeze / Key, Position, Scan
+ speed, Spray) and the output — volume, **Dry/Wet** and the track's meter — on screen on
+ every tab, and a status strip reads the tab back in words beside the sample, voices and
+ live grain count. Knobs now read in the engine's units (grain size in ms, density as an
+ overlap, coarse in semitones, fine in cents, cutoff in Hz, envelope times), the header
+ shows grains per second, and the built-in pad draws its waveform too.
+- **Nota Grain: Dry/Wet.** A new parameter blends the grain cloud with the sample itself,
+ played straight from the read position at the note's pitch, before the filter and amp.
+ It is appended to the parameter list and defaults fully wet, so older projects and
+ presets sound as they did.
+- **Nota Grain ships 25 factory presets** (was 6) — clouds and pads, patches that move
+ through the file, keys and plucks that put the sample's own attack under the cloud,
+ glitch and stutter textures, basses, and Dry/Wet blends down to the plain sample,
+ including the six that existed before.
- **Nota Flux's editor is now the almanac's card, and the vector's worlds carry their own
unison.** The card shrinks from 900 to **700 × 260** and reads left to right: the
**Vector** field (the four worlds in their graph colours, the vector as a brass dot, and a
@@ -295,6 +316,13 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
tokens its own comments named.
### Fixed
+- **Nota Grain: Position is live.** A held note used to read from wherever Position was
+ when it started, so moving the knob or automating it did nothing until the next note.
+ Held notes now follow it — Scan adds its moving offset to it, Freeze sits on it and Key
+ offsets it by the note.
+- **Nota Grain: a repeated note no longer cuts itself off.** A note-off released every
+ voice of its pitch, so a note that started a hair before the previous one of the same
+ pitch ended went silent with it. A note-off now releases only the oldest held one.
- **Nota Flux: with no source assigned, React is off.** It used to listen to Flux's own
output instead, so a patch aimed at the filter or the vector wobbled with its own chords.
The React followers now also run on time constants rather than once per audio block at a
diff --git a/FEATURES.md b/FEATURES.md
index 45f6900f..94230dfb 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -260,7 +260,13 @@ and user presets, automation, persistence and cloning.
- **Nota Sampler** — sampler (one-shot and loop), voice modes Poly 16 / Mono / Choke, loop
crossfade, reverse loop, filter key-tracking, Vel→Vol; Sample · Pitch · Env · Filter
tabs; an editable waveform.
-- **Nota Grain** — granular synthesizer.
+- **Nota Grain** — granular sampler: a read Position that Scans through the file, Freezes
+ or follows the keyboard, grains of a chosen size, density and window shape (Hann /
+ Gauss / Tukey / Tri) sprayed around it, coarse/fine pitch, per-grain position, pitch and
+ pan variation, stereo spread, **Dry/Wet** against the sample itself, an LP/HP/BP filter
+ and an amp envelope. The card draws the sample with the live grain cloud on it (drag to
+ move Position). Drop a sample from the browser to replace the built-in pad. 25 factory
+ presets.
- **Nota Volt** — subtractive synth, two paths: two oscillators and noise, each routed to
one of two filters (LP/HP/BP/Notch, 12/24 dB, with Filter 1 able to feed Filter 2) and
its own amp; amp and filter envelopes, two LFOs (shapes, depth, fade-in, tempo sync), a
diff --git a/src/managed/Nota.App/Controls/GrainWaveViz.cs b/src/managed/Nota.App/Controls/GrainWaveViz.cs
index d970023e..d30d0902 100644
--- a/src/managed/Nota.App/Controls/GrainWaveViz.cs
+++ b/src/managed/Nota.App/Controls/GrainWaveViz.cs
@@ -1,99 +1,187 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Nota Grain sample view — drawn in the app's standard waveform style (like
-// SamplerWaveform): brass min/max waveform on the sunken surface, a centre line and a
-// time grid. The Spray region is a faint amber band around the read Position, and the
-// live grain read positions scan across as bright playheads (green, like the Sampler
-// cursor) so you see the granular motion. Peaks/duration are set on load; position,
-// spray and the live playheads update every UI tick.
+// Nota Grain sample view — a graph window (NotaGraph) with the sample drawn as brass bars
+// (scaled so its loudest peak fills the height) around a centre line and a time grid
+// labelled along the bottom. The Spray region is a Brass Wash band around the read
+// Position (a dashed brass line); each held voice's read head is a Brass Light line with a
+// notch on top, and the live grain cloud — every grain the engine is playing — is a teal
+// dot at its read position, high for left and low for right, larger the louder its window
+// is. Grains/sec sits in the top-left corner.
+//
+// It is also the Position control: drag across it (or click) to move the read position;
+// double-click puts it back on its default. Left button only; GestureBegin/End frame an
+// automation write.
using System;
-using System.Globalization;
using Avalonia;
using Avalonia.Controls;
+using Avalonia.Input;
using Avalonia.Media;
namespace Nota.App;
internal sealed class GrainWaveViz : Control
{
- private static readonly IBrush Bg = NotaPalette.BgSunken;
- private static readonly IBrush Wave = NotaPalette.Accent;
private static readonly IPen MidLine = new Pen(NotaPalette.GridBar, 1);
- private static readonly IPen GridPen = NotaGraph.GridPen;
- private static readonly IBrush SprayFill = NotaPalette.Wash(NotaPalette.Accent, 0x16);
- private static readonly IPen SprayEdge = new Pen(NotaPalette.Wash(NotaPalette.Accent, 0x55), 1);
- private static readonly IPen PosPen = new Pen(NotaPalette.Wash(NotaPalette.AccentBright, 0x9A), 1) { DashStyle = DashStyle.Dash };
- private static readonly IBrush PlayCol = NotaPalette.Success;
- private static readonly IBrush GridText = NotaPalette.TextTertiary;
- private static readonly Typeface Mono = NotaFonts.Mono;
-
- private float[] _peaks = Array.Empty<float>();
+ private static readonly IPen PosPen = new Pen(NotaPalette.AccentDim, 1) { DashStyle = new DashStyle(new double[] { 3, 3 }, 0) };
+ private static readonly IPen HeadPen = new Pen(NotaPalette.AccentBright, 1.2);
+ private static readonly IBrush SprayFill = NotaPalette.AccentSubtle;
+ private static readonly IBrush[] GrainInk =
+ {
+ NotaPalette.Wash(NotaPalette.TealBright, 0x55), NotaPalette.Wash(NotaPalette.TealBright, 0x99),
+ NotaPalette.Wash(NotaPalette.TealBright, 0xDD),
+ };
+
+ private float[] _peaks = Array.Empty<float>(); // min/max pairs across the file
+ private double _gain = 1; // draws the file's loudest peak full height
private double _dur, _pos, _spray, _grPerSec;
private int _mode;
private float[] _heads = Array.Empty<float>();
private int _headN;
+ private float[] _cloud = Array.Empty<float>(); // (position, pan, level) triples
+ private int _grainN;
+ private bool _drag;
- public GrainWaveViz() { MinHeight = 60; ClipToBounds = true; }
+ public Action<double>? ValueChanged;
+ public Action? GestureBegin;
+ public Action? GestureEnd;
+ /// <summary>Double-click: put Position back on its default.</summary>
+ public Action? Reset;
+ public bool Dragging => _drag;
- public void SetPeaks(float[] peaks, double durationSec) { _peaks = peaks; _dur = durationSec; InvalidateVisual(); }
- public void SetState(double pos, double spray, int mode, double grPerSec) { _pos = pos; _spray = spray; _mode = mode; _grPerSec = grPerSec; InvalidateVisual(); }
- public void SetPlayheads(float[] heads, int n) { _heads = heads; _headN = n; InvalidateVisual(); }
+ public GrainWaveViz()
+ {
+ MinHeight = 40; ClipToBounds = true;
+ Cursor = new Cursor(StandardCursorType.SizeWestEast);
+ DoubleTapped += (_, e) => { Reset?.Invoke(); e.Handled = true; };
+ }
+
+ public void SetPeaks(float[] peaks, double durationSec)
+ {
+ float max = 0;
+ foreach (var p in peaks) max = Math.Max(max, Math.Abs(p));
+ _peaks = peaks; _dur = durationSec; _gain = max > 1e-4f ? 1.0 / max : 1;
+ InvalidateVisual();
+ }
+ public void SetState(double pos, double spray, int mode, double grPerSec)
+ {
+ if (pos == _pos && spray == _spray && mode == _mode && Math.Abs(grPerSec - _grPerSec) < 0.5) return;
+ _pos = pos; _spray = spray; _mode = mode; _grPerSec = grPerSec; InvalidateVisual();
+ }
+ public void SetPlayheads(float[] heads, int n)
+ {
+ if (n == 0 && _headN == 0) return;
+ _heads = heads; _headN = n; InvalidateVisual();
+ }
+ /// <summary>The grain cloud as (read position 0..1, pan 0..1, window level 0..1) triples.</summary>
+ public void SetGrains(float[] triples, int n)
+ {
+ if (n == 0 && _grainN == 0) return;
+ _cloud = triples; _grainN = n; InvalidateVisual();
+ }
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return; // right-click bubbles
+ if (e.ClickCount > 1) return; // DoubleTapped resets
+ _drag = true; GestureBegin?.Invoke();
+ e.Pointer.Capture(this);
+ Apply(e.GetPosition(this));
+ e.Handled = true;
+ }
+ protected override void OnPointerMoved(PointerEventArgs e) { if (_drag) Apply(e.GetPosition(this)); }
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ {
+ if (_drag) { _drag = false; e.Pointer.Capture(null); GestureEnd?.Invoke(); }
+ }
+ protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e)
+ {
+ if (_drag) { _drag = false; GestureEnd?.Invoke(); }
+ }
+ private void Apply(Point p)
+ {
+ double w = Bounds.Width - 2 * Inset;
+ if (w <= 0) return;
+ _pos = Math.Clamp((p.X - Inset) / w, 0, 1);
+ ValueChanged?.Invoke(_pos);
+ InvalidateVisual();
+ }
+
+ private const double Inset = 4;
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 cy = h / 2;
+ double W = Bounds.Width, H = Bounds.Height;
+ if (W <= 0 || H <= 0) return;
+ var frame = new Rect(0, 0, W, H);
+ NotaGraph.Window(ctx, frame);
+ using var clip = ctx.PushClip(frame.Deflate(1));
+ double x0 = Inset, w = W - 2 * Inset, cy = H / 2, amp = cy - 14;
- // Time grid + labels behind the waveform.
- if (_dur > 0)
+ // Spray band around the read position (where grains scatter). Key mode moves the
+ // position with the note, so there is no one band to draw.
+ double px = x0 + Math.Clamp(_pos, 0, 1) * w;
+ if (_mode != 2 && _spray > 0.001)
{
- double step = _dur <= 0.5 ? 0.05 : _dur <= 1.5 ? 0.1 : _dur <= 5 ? 0.5 : _dur <= 15 ? 1.0 : 5.0;
- for (double tt = step; tt < _dur; tt += step)
- {
- double x = tt / _dur * w;
- ctx.DrawLine(GridPen, new Point(x, 0), new Point(x, h));
- string lbl = _dur >= 1 ? $"{tt:0.##}\u2009s" : $"{(int)Math.Round(tt * 1000)}";
- ctx.DrawText(new FormattedText(lbl, CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 8, GridText), new Point(x + 2, h - 11));
- }
+ double half = _spray * 0.25 * w;
+ double s0 = Math.Max(x0, px - half), s1 = Math.Min(x0 + w, px + half);
+ ctx.FillRectangle(SprayFill, new Rect(s0, 1, s1 - s0, H - 2));
}
- // Spray band around the read position (grains scatter here).
- if (_mode != 2)
+ // Time grid, labelled along the bottom.
+ if (_dur > 0)
{
- double s0 = Math.Clamp(_pos - _spray * 0.21, 0, 1), s1 = Math.Clamp(_pos + _spray * 0.21, 0, 1);
- if (s1 > s0) { ctx.FillRectangle(SprayFill, new Rect(s0 * w, 0, (s1 - s0) * w, h)); ctx.DrawLine(SprayEdge, new Point(s0 * w, 0), new Point(s0 * w, h)); ctx.DrawLine(SprayEdge, new Point(s1 * w, 0), new Point(s1 * w, h)); }
+ double step = _dur <= 0.5 ? 0.1 : _dur <= 2.5 ? 0.5 : _dur <= 6 ? 1.0 : _dur <= 15 ? 2.0 : _dur <= 40 ? 5.0 : 10.0;
+ for (double tt = step; tt < _dur - step * 0.25; tt += step)
+ {
+ double x = x0 + tt / _dur * w;
+ ctx.DrawLine(NotaGraph.GridPen, new Point(x, 1), new Point(x, H - 1));
+ var ft = NotaGraph.AxisText(NotaNum.Time(tt));
+ ctx.DrawText(ft, new Point(x - ft.Width - 3, H - ft.Height - 2));
+ }
}
+ ctx.DrawLine(MidLine, new Point(1, cy), new Point(W - 1, cy));
- // Brass min/max waveform.
+ // Brass bars, one every 3 px, each the peak of its slice of the file.
int n = _peaks.Length / 2;
- for (int i = 0; i < n; i++)
+ if (n > 0 && amp > 0)
{
- double x = (double)i / n * w;
- double y0 = cy - _peaks[i * 2 + 1] * (cy - 2);
- double y1 = cy - _peaks[i * 2] * (cy - 2);
- ctx.DrawLine(new Pen(Wave, 1), new Point(x, y0), new Point(x, y1));
+ var bar = new Pen(NotaPalette.Accent, 1.4);
+ int bars = Math.Max(1, (int)(w / 3));
+ for (int b = 0; b < bars; b++)
+ {
+ int i0 = b * n / bars, i1 = Math.Max(i0 + 1, (b + 1) * n / bars);
+ float mn = 0, mx = 0;
+ for (int i = i0; i < i1 && i < n; i++) { mn = Math.Min(mn, _peaks[i * 2]); mx = Math.Max(mx, _peaks[i * 2 + 1]); }
+ double x = x0 + (b + 0.5) * w / bars;
+ ctx.DrawLine(bar, new Point(x, cy - Math.Min(1, mx * _gain) * amp), new Point(x, cy - Math.Max(-1, mn * _gain) * amp));
+ }
}
- ctx.DrawLine(MidLine, new Point(0, cy), new Point(w, cy));
- // The set read Position (dashed amber) — where scanning centres / grains seed.
- double px = Math.Clamp(_pos, 0, 1) * w;
- ctx.DrawLine(PosPen, new Point(px, 0), new Point(px, h));
+ // The set read Position — where scanning centres and grains seed.
+ if (_mode != 2) ctx.DrawLine(PosPen, new Point(px, 1), new Point(px, H - 1));
- // Live grain read positions — bright playheads that scan as it plays.
+ // Each held voice's read head.
for (int i = 0; i < _headN && i < _heads.Length; i++)
{
- double hx = Math.Clamp(_heads[i], 0, 1) * w;
- ctx.DrawLine(new Pen(PlayCol, 1.6), new Point(hx, 0), new Point(hx, h));
+ double hx = x0 + Math.Clamp(_heads[i], 0, 1) * w;
+ ctx.DrawLine(HeadPen, new Point(hx, 1), new Point(hx, H - 1));
var tri = new StreamGeometry();
- using (var g = tri.Open()) { g.BeginFigure(new Point(hx - 3, 0), true); g.LineTo(new Point(hx + 3, 0)); g.LineTo(new Point(hx, 4)); g.EndFigure(true); }
- ctx.DrawGeometry(PlayCol, null, tri);
+ using (var g = tri.Open()) { g.BeginFigure(new Point(hx - 3, 1), true); g.LineTo(new Point(hx + 3, 1)); g.LineTo(new Point(hx, 5)); g.EndFigure(true); }
+ ctx.DrawGeometry(NotaPalette.AccentBright, null, tri);
+ }
+
+ // The grain cloud: x = read position, y = pan (left high), size and ink by level.
+ for (int i = 0; i < _grainN && i * 3 + 2 < _cloud.Length; i++)
+ {
+ double gx = x0 + Math.Clamp(_cloud[i * 3], 0, 1) * w;
+ double gy = cy + (Math.Clamp(_cloud[i * 3 + 1], 0, 1) - 0.5) * 2 * amp;
+ double lv = Math.Clamp(_cloud[i * 3 + 2], 0, 1);
+ double r = 1.2 + lv * 2.2;
+ ctx.DrawEllipse(GrainInk[Math.Min(2, (int)(lv * 3))], null, new Point(gx, gy), r, r);
}
- // Grains/sec readout.
- ctx.DrawText(new FormattedText($"{_grPerSec:0} gr/s", CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Mono, 8, GridText), new Point(4, 2));
+ NotaGraph.Axis(ctx, frame, NotaGraph.Corner.TopLeft, NotaNum.Unit(_grPerSec, "0", "gr/s"));
}
}
diff --git a/src/managed/Nota.App/DeviceCards/Instruments/GrainInstrumentCard.cs b/src/managed/Nota.App/DeviceCards/Instruments/GrainInstrumentCard.cs
index a3aa0eaa..ada265ae 100644
--- a/src/managed/Nota.App/DeviceCards/Instruments/GrainInstrumentCard.cs
+++ b/src/managed/Nota.App/DeviceCards/Instruments/GrainInstrumentCard.cs
@@ -1,182 +1,569 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// Detail · Devices — built-in Nota Grain editor (instrument kind 10), built to the 2d
-// mockup (700×260): header (26) · sample strip (74) · always-visible playhead strip
-// (30: Scan mode + Position/Scan/Spray sliders) · vertical tab rail (82) + swapped body
-// (Grain shape icons + knobs / Pitch / Variation / Filter / Amp). Drop a sample from the
-// browser to replace the procedural default. All controls are plugin params.
+// Detail · Devices — built-in Nota Grain editor (instrument kind 10): the granular sampler
+// in the 700 × 260 card the almanac draws for it.
+//
+// Centre the sample as a graph — the Spray band around the dashed read Position
+// (drag across it to move Position), each held voice's read head and the
+// live grain cloud — under a strip of five tabs, each swapping the row of
+// controls beneath the graph:
+// Grain — the window shape (Hann · Gauss · Tukey · Tri) as drawn chips,
+// then size, density and spread.
+// Pitch — coarse and fine.
+// Variation — per-grain position, pitch and pan jitter.
+// Filter — LP / HP / BP, cutoff and resonance, after the cloud.
+// Amp — the envelope of the whole cloud.
+// Rail 186 READ — Scan / Freeze / Key, then Position, Scan speed and Spray — and the
+// output: volume, dry/wet (the sample itself against the cloud) and the
+// track's meter. On screen on every tab.
+// Status 18 the tab read back in words, and the sample, voices and grains live.
+//
+// Brass is the parameter itself; teal is variation and scatter (spread, spray, the three
+// jitters and the grains they make). Drop a sample from the browser to replace the
+// procedural default. Everything is a plugin param → automation / persist / clone, and the
+// card follows automation live.
using System;
using System.Collections.Generic;
-using System.Globalization;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
+using Nota.Application;
using static Nota.App.DeviceCardKit;
namespace Nota.App;
internal sealed class GrainInstrumentCard : IInstrumentCard
{
- // Exact mockup palette.
- private static readonly IBrush CardBg = NotaPalette.BgApp;
- 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 Handle = NotaPalette.TextSecondary;
- private static readonly IBrush AmberSubtle = NotaPalette.Wash(NotaPalette.Accent, 0x28);
- private static readonly Typeface Mono = NotaFonts.Mono;
-
public bool BodyOnly => true;
public string Subtitle => "GRANULAR";
+ private const double RailW = 186, TabH = 20, StatusH = 18;
+
+ private static readonly string[] TabNames = { "Grain", "Pitch", "Variation", "Filter", "Amp" };
+ private static readonly string[] ModeNames = { "Scan", "Freeze", "Key" };
+ private static readonly string[] ShapeWords = { "hann", "gauss", "tukey", "tri" };
+ private static readonly string[] FilterNames = { "LP", "HP", "BP" };
+
+ // The engine's own maps (GrainSynth.h), so a readout says what it does.
+ private static double ExpMap(float v, double lo, double hi) => lo * Math.Pow(hi / lo, Math.Clamp(v, 0f, 1f));
+ private static double SizeSec(float v) => ExpMap(v, 0.004, 0.4);
+ private static double Overlap(float v) => 1 + v * 7;
+ private static double GrainsPerSec(float size, float density) => Overlap(density) / SizeSec(size);
+ private static string Pct(float v) => NotaNum.Pct(v);
+ private static string Size(float v) => NotaNum.Time(SizeSec(v));
+ private static string Density(float v) => NotaNum.Str(Overlap(v), "0.0") + "×";
+ private static string Coarse(float v) => NotaNum.Unit((v - 0.5) * 48, "+0.0;−0.0;0.0", "st");
+ private static string Fine(float v) => NotaNum.Unit(Math.Round((v - 0.5) * 200), "+0;−0;0", "ct");
+ private static string PitchJitter(float v) => v < 0.0005f ? "0 st" : "±" + NotaNum.Unit(v * 12, "0.0", "st");
+ private static string ScanSpeed(float v) => NotaNum.Str((v - 0.5) * 8, "+0.0;−0.0;0.0") + "×";
+ private static string Hz(float v) => NotaNum.Hz(ExpMap(v, 60, 18000));
+ private static string Attack(float v) => NotaNum.Time(ExpMap(v, 0.001, 3.0));
+ private static string Decay(float v) => NotaNum.Time(ExpMap(v, 0.002, 4.0));
+ private static string Release(float v) => NotaNum.Time(ExpMap(v, 0.003, 6.0));
+ private static string GrRate(double v) => NotaNum.Unit(v, "0", "gr/s");
+
+ public string? VoiceLabel(IAudioEngine engine, int trackId, int active)
+ {
+ float size = 0.42f, density = 0.6f;
+ int pc = engine.PluginParamCount(trackId, -1);
+ for (int k = 0; k < pc; k++)
+ {
+ string id = engine.PluginParamId(trackId, -1, k);
+ if (id == "grainsize") size = engine.PluginParamGet(trackId, -1, k);
+ else if (id == "density") density = engine.PluginParamGet(trackId, -1, k);
+ }
+ return GrRate(GrainsPerSec(size, density));
+ }
+
public Control Build(DeviceCardContext ctx)
{
var engine = ctx.Engine;
int track = ctx.TrackId;
- int pcount = engine.PluginParamCount(track, -1);
+ int pc = engine.PluginParamCount(track, -1);
var idx = new Dictionary<string, int>();
- for (int i = 0; i < pcount; i++) idx[engine.PluginParamId(track, -1, i)] = i;
- float G(string id) => idx.TryGetValue(id, out var i) ? engine.PluginParamGet(track, -1, i) : 0f;
+ for (int i = 0; i < pc; i++) idx[engine.PluginParamId(track, -1, i)] = i;
int I(string id) => idx.TryGetValue(id, out var i) ? i : -1;
+ 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)); }
- static double Exp(double v, double lo, double hi) => lo * Math.Pow(hi / lo, Math.Clamp(v, 0, 1));
+ 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); }
+ int Sel(string id, int n) => Math.Clamp((int)Math.Round(G(id) * (n - 1)), 0, n - 1);
+ int Mode() => Sel("scanmode", 3);
var readouts = new List<Action>();
- var wave = new GrainWaveViz();
- if (engine.TryGetGrainInfo(track, out var gi) && gi.SampleId != 0
- && engine.TryGetSampleInfo(gi.SampleId, out var sinfo) && sinfo.Channels > 0)
- {
- var raw = engine.ReadSample(gi.SampleId);
- int ch = sinfo.Channels; long fr = sinfo.Frames;
- const int buckets = 340;
- var peaks = new float[buckets * 2];
- for (int b = 0; b < buckets; b++)
+ int tab = 0;
+ Action showTab = () => { };
+
+ // Live state: each voice's read head and the grain cloud, from the engine's scope.
+ var heads = new float[8];
+ int headN = 0;
+ var scope = new float[2 + 8 * 12 * 3];
+ var cloud = new float[8 * 12 * 3];
+ int voices = 0, grains = 0;
+
+ // ---- the sample -------------------------------------------------------
+ var wave = new GrainWaveViz { VerticalAlignment = VerticalAlignment.Stretch };
+ long sampleId = -1;
+ double sampleSec = 0, sampleKHz = 0;
+ void LoadPeaks()
+ {
+ engine.TryGetGrainInfo(track, out var gi);
+ if (gi.SampleId == sampleId) return;
+ sampleId = gi.SampleId;
+ if (gi.SampleId != 0 && engine.TryGetSampleInfo(gi.SampleId, out var si) && si.Channels > 0 && si.Frames > 0)
{
- long a = (long)((double)b / buckets * fr), e = (long)((double)(b + 1) / buckets * fr);
- float mn = 0, mx = 0;
- for (long i = a; i < e; i++) for (int c = 0; c < ch; c++) { long k = i * ch + c; if (k < raw.Length) { float v = raw[k]; if (v < mn) mn = v; if (v > mx) mx = v; } }
- peaks[b * 2] = mn; peaks[b * 2 + 1] = mx;
+ var raw = engine.ReadSample(gi.SampleId);
+ wave.SetPeaks(Peaks(raw, si.Channels, si.Frames), si.SampleRate > 0 ? (double)si.Frames / si.SampleRate : 0);
+ sampleSec = si.SampleRate > 0 ? (double)si.Frames / si.SampleRate : 0;
+ sampleKHz = si.SampleRate / 1000.0;
+ }
+ else
+ {
+ // The procedural default the engine plays until a sample is dropped.
+ var (peaks, sec) = DefaultSamplePeaks();
+ wave.SetPeaks(peaks, sec);
+ sampleSec = sec; sampleKHz = 0;
}
- wave.SetPeaks(peaks, sinfo.SampleRate > 0 ? fr / sinfo.SampleRate : 0);
}
+ LoadPeaks();
+
+ var hint = new TextBlock
+ {
+ FontSize = NotaType.Axis, Foreground = TextTertiary, FontFamily = NotaFonts.MonoFamily,
+ VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Right,
+ Margin = new Thickness(0, 0, 8, 0), TextTrimming = TextTrimming.CharacterEllipsis,
+ };
+ var status = new TextBlock { FontSize = 8, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
+ var meta = new TextBlock { FontSize = 8, Foreground = TextSecondary, VerticalAlignment = VerticalAlignment.Center, FontFamily = NotaFonts.MonoFamily };
- var headBuf = new float[8];
void Refresh()
{
- double overlap = 1 + G("density") * 7, sizeSec = Exp(G("grainsize"), 0.004, 0.4);
- wave.SetState(G("position"), G("spray"), (int)Math.Round(G("scanmode") * 2), overlap / sizeSec);
- int hn = engine.GrainPlayPositions(track, headBuf);
- wave.SetPlayheads(headBuf, hn);
- foreach (var a in readouts) a();
+ if (!wave.Dragging) wave.SetState(G("position"), G("spray"), Mode(), GrainsPerSec(G("grainsize"), G("density")));
+ wave.SetPlayheads(heads, headN);
+ wave.SetGrains(cloud, grains);
+ foreach (var r in readouts) r();
+ hint.Text = Hint();
+ status.Text = Summary();
+ meta.Text = Meta();
}
- // Header (dot / name / subtitle) is provided by the shared shell.
+ wave.ValueChanged += v => { SetP("position", (float)v); Refresh(); };
+ wave.GestureBegin += () => Begin("position");
+ wave.GestureEnd += () => End("position");
+ wave.Reset = () =>
+ {
+ if (I("position") is not (var pi and >= 0)) return;
+ Begin("position"); SetP("position", engine.InstrumentParamDefault(track, pi)); End("position");
+ Refresh();
+ };
+ ToolTip.SetTip(wave, "Drag to move the read position · double-click to reset");
+ if (I("position") is var wpi and >= 0) MidiLearn.Bind(wave, MidiTarget.PluginParam(track, -1, wpi), "Position");
+
+ // ---- shared builders --------------------------------------------------
+ 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 = 8) => new()
+ {
+ Text = t, FontSize = fs, Foreground = c ?? TextSecondary,
+ VerticalAlignment = VerticalAlignment.Center, FontFamily = NotaFonts.MonoFamily,
+ };
- // ---- horizontal param slider (playhead strip) ----
- Control Slider(string id, double trackW, Func<double, string> fmt)
+ // Every knob is a table cell: a short label on the card while MIDI learn and the CV
+ // menu keep the parameter's full name.
+ Control PKnob(string id, string label, string learn, Func<float, string> fmt,
+ double size = 26, double cellW = 46, IBrush? arc = null)
+ {
+ if (!idx.TryGetValue(id, out var pi)) return new Panel();
+ var value = new TextBlock
+ {
+ Text = fmt(G(id)), FontSize = NotaType.KnobValue, FontFamily = NotaFonts.MonoFamily,
+ Foreground = TextPrimary, HorizontalAlignment = HorizontalAlignment.Center,
+ TextAlignment = TextAlignment.Center, LineHeight = 10,
+ };
+ var knob = new Knob(G(id), 1.0)
+ {
+ Accent = true, ArcColor = arc, Default = engine.InstrumentParamDefault(track, pi),
+ Width = size, Height = size, HorizontalAlignment = HorizontalAlignment.Center,
+ };
+ 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), learn);
+ var cell = KnobCell(label, knob, value, cellW);
+ cell.VerticalAlignment = VerticalAlignment.Center;
+ return cell;
+ }
+
+ Border Chips(string id, string[] names, string learn, Func<bool>? dim = null)
+ {
+ int n = names.Length;
+ var seg = Segments(names, () => Sel(id, n), iv => { Begin(id); SetP(id, iv / (float)(n - 1)); End(id); Refresh(); },
+ out var sync, dim: dim);
+ readouts.Add(sync);
+ if (I(id) is var pi and >= 0) MidiLearn.Bind(seg, MidiTarget.PluginParam(track, -1, pi), learn);
+ return seg;
+ }
+
+ Grid Slider(string label, string id, Func<string> text, bool bipolar = false, bool mod = false, Func<bool>? dim = null)
{
int pi = I(id);
- string label = id == "position" ? "POSITION" : id == "scan" ? "SCAN" : "SPRAY";
- var row = DeviceCardKit.SliderRow(label, () => G(id), n => { if (pi >= 0) engine.PluginParamSet(track, -1, pi, (float)n); Refresh(); }, () => fmt(G(id)), out var sync,
- trackWidth: trackW, valueWidth: 40);
+ 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 ? () => { SetP(id, engine.InstrumentParamDefault(track, pi)); Refresh(); } : null,
+ bipolar: bipolar, dim: dim, labelWidth: 46, valueWidth: 40, modulation: mod);
readouts.Add(sync);
+ if (pi >= 0) MidiLearn.Bind(row, MidiTarget.PluginParam(track, -1, pi), label);
return row;
}
- // Scan-mode segmented (param-backed).
- Control ScanSeg()
+ // The window shape: four drawn chips in a 2 × 2 block; the chosen one in Brass Wash
+ // with a brass edge and a brass curve.
+ Control ShapeChips()
{
- string[] names = { "Scan", "Freeze", "Key" }; var arr = new Border[3];
- void Hi() { int cur = Math.Clamp((int)Math.Round(G("scanmode") * 2), 0, 2); for (int i = 0; i < 3; i++) { bool on = i == cur; arr[i].Background = on ? NotaPalette.Accent : Brushes.Transparent; ((TextBlock)arr[i].Child!).Foreground = on ? NotaPalette.TextOnAccent : MutedC; } }
- var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 1 };
- for (int i = 0; i < 3; i++) { int iv = i; var c = new Border { CornerRadius = NotaRadius.Badge, Padding = new Thickness(7, 1), Cursor = new Cursor(StandardCursorType.Hand), Child = new TextBlock { Text = names[i], FontSize = 9, FontWeight = FontWeight.SemiBold, Foreground = MutedC } }; c.PointerPressed += (_, _) => { SetP("scanmode", iv / 2f); Hi(); Refresh(); }; arr[i] = c; row.Children.Add(c); }
- readouts.Add(Hi); Hi();
- return new Border { Background = Inset, BorderBrush = Border2, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Control, Padding = new Thickness(1), VerticalAlignment = VerticalAlignment.Center, Child = row };
+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto"), RowDefinitions = new RowDefinitions("Auto,Auto"), ColumnSpacing = 4, RowSpacing = 4, VerticalAlignment = VerticalAlignment.Center };
+ var cells = new Border[4];
+ var icons = new GrainShapeIcon[4];
+ for (int i = 0; i < 4; i++)
+ {
+ int iv = i;
+ var ic = new GrainShapeIcon(i) { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };
+ var c = new Border
+ {
+ Width = 26, Height = 19, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Control,
+ Cursor = new Cursor(StandardCursorType.Hand), Child = ic,
+ };
+ ToolTip.SetTip(c, $"{char.ToUpperInvariant(ShapeWords[i][0])}{ShapeWords[i][1..]} window");
+ c.PointerPressed += (_, e) =>
+ {
+ if (!e.GetCurrentPoint(c).Properties.IsLeftButtonPressed) return;
+ Begin("grainshape"); SetP("grainshape", iv / 3f); End("grainshape"); Refresh(); e.Handled = true;
+ };
+ Grid.SetColumn(c, i % 2); Grid.SetRow(c, i / 2);
+ cells[i] = c; icons[i] = ic; g.Children.Add(c);
+ }
+ void Paint()
+ {
+ int cur = Sel("grainshape", 4);
+ for (int i = 0; i < 4; i++)
+ {
+ bool on = i == cur;
+ cells[i].Background = on ? NotaPalette.AccentSubtle : NotaPalette.BgSunken;
+ cells[i].BorderBrush = on ? Brass : BorderDef;
+ icons[i].Stroke = on ? AccentBright : TextTertiary;
+ icons[i].InvalidateVisual();
+ }
+ }
+ readouts.Add(Paint); Paint();
+ if (I("grainshape") is var pi and >= 0) MidiLearn.Bind(g, MidiTarget.PluginParam(track, -1, pi), "Grain Shape");
+ return g;
}
- var strip = new Border { Height = 30, Background = HdrBg, BorderBrush = Border2, BorderThickness = new Thickness(0, 0, 0, 1),
- Child = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(9, 0), Children = {
- ScanSeg(),
- Slider("position", 74, v => $"{v * 100:0}\u2009%"),
- Slider("scan", 60, v => $"{(v - 0.5) * 8:+0.0;−0.0;0.0}×"),
- Slider("spray", 52, v => $"{v * 100:0}\u2009%") } } };
+ static StackPanel Row(params Control[] items)
+ {
+ var sp = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, VerticalAlignment = VerticalAlignment.Center };
+ foreach (var c in items) sp.Children.Add(c);
+ return sp;
+ }
- // ---- knobs (gauge) ----
- Control K(string id, string name, bool mod = false) => InstrumentControls.InstKnob(ctx, idx, id, name, Refresh, 40, 62, mod ? Teal : null);
- Control KnobRow(params Control[] ks) { var sp = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center }; foreach (var k in ks) sp.Children.Add(k); return sp; }
+ // ---- the tabs ---------------------------------------------------------
+ var filterChips = Chips("filtype", FilterNames, "Filter Type");
+ filterChips.Margin = new Thickness(0, 0, 8, 0);
+ var shapes = ShapeChips();
+ shapes.Margin = new Thickness(0, 0, 8, 0);
+ var bodies = new Control[]
+ {
+ Row(shapes,
+ PKnob("grainsize", "SIZE", "Grain Size", Size),
+ PKnob("density", "DENSITY", "Density", Density),
+ PKnob("spread", "SPREAD", "Spread", Pct, arc: Teal)),
+ Row(PKnob("coarse", "COARSE", "Coarse", Coarse),
+ PKnob("fine", "FINE", "Fine", Fine)),
+ Row(PKnob("posrand", "POSITION", "Pos Rand", Pct, arc: Teal),
+ PKnob("pitchrand", "PITCH", "Pitch Rand", PitchJitter, arc: Teal),
+ PKnob("panrand", "PAN", "Pan Rand", Pct, arc: Teal)),
+ Row(filterChips,
+ PKnob("filfreq", "FREQ", "Filter Freq", Hz),
+ PKnob("filreso", "RESO", "Filter Reso", Pct)),
+ Row(PKnob("attack", "ATTACK", "Attack", Attack),
+ PKnob("decay", "DECAY", "Decay", Decay),
+ PKnob("sustain", "SUSTAIN", "Sustain", Pct),
+ PKnob("release", "RELEASE", "Release", Release)),
+ };
- // Grain-shape icon selector (GrainShape param).
- Control ShapeIcons()
+ 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++)
{
- var boxes = new Border[4]; var icons = new GrainShapeIcon[4];
- void Hi() { int cur = Math.Clamp((int)Math.Round(G("grainshape") * 3), 0, 3); for (int i = 0; i < 4; i++) { bool on = i == cur; boxes[i].Background = on ? NotaPalette.Accent : Inset; boxes[i].BorderBrush = on ? NotaPalette.Accent : Border2; icons[i].Stroke = on ? NotaPalette.TextOnAccent : MutedC; icons[i].InvalidateVisual(); } }
- var col = new StackPanel { Spacing = 3, VerticalAlignment = VerticalAlignment.Center };
- for (int i = 0; i < 4; i++)
+ 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);
+
+ showTab = () =>
+ {
+ for (int i = 0; i < TabNames.Length; i++)
+ {
+ 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;
+ }
+ Refresh();
+ };
+
+ var controls = new Panel { Height = NotaSize.ParamCell };
+ foreach (var b in bodies) controls.Children.Add(b);
+ var controlsHost = new Border
+ {
+ BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 1, 0, 0),
+ Padding = new Thickness(0, 5, 0, 0), Child = controls,
+ };
+ var centreBody = new Grid { RowDefinitions = new RowDefinitions("*,Auto"), RowSpacing = 5, Margin = new Thickness(7, 5, 7, 5) };
+ centreBody.Children.Add(wave);
+ Grid.SetRow(controlsHost, 1); centreBody.Children.Add(controlsHost);
+ var tabGrid = new Grid { RowDefinitions = new RowDefinitions("Auto,*") };
+ tabGrid.Children.Add(HeaderStrip(tabStrip));
+ Grid.SetRow(centreBody, 1); tabGrid.Children.Add(centreBody);
+ var tabPanel = SectionBox(tabGrid);
+
+ // ---- rail · READ + output ---------------------------------------------
+ var modeChips = Chips("scanmode", ModeNames, "Scan Mode");
+ modeChips.HorizontalAlignment = HorizontalAlignment.Right;
+ modeChips.Margin = new Thickness(0, 0, 6, 0);
+ ToolTip.SetTip(modeChips, "Scan moves through the file · Freeze holds Position · Key moves it with the note");
+ var readCap = Cap("READ"); readCap.Margin = new Thickness(8, 0, 0, 0);
+ var readHead = new Grid { Height = TabH, ColumnDefinitions = new ColumnDefinitions("Auto,*") };
+ readHead.Children.Add(readCap);
+ Grid.SetColumn(modeChips, 1); readHead.Children.Add(modeChips);
+
+ var readRows = new StackPanel
+ {
+ Spacing = 6, Margin = new Thickness(8, 7, 8, 0),
+ Children =
{
- int iv = i; var ic = new GrainShapeIcon(i) { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };
- var b = new Border { Width = 34, Height = 22, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Control, Cursor = new Cursor(StandardCursorType.Hand), Child = ic };
- b.PointerPressed += (_, _) => { SetP("grainshape", iv / 3f); Hi(); };
- boxes[i] = b; icons[i] = ic; col.Children.Add(b);
+ Slider("POSITION", "position", () => Pct(G("position"))),
+ // Scan speed only moves the read position in Scan mode.
+ Slider("SCAN", "scan", () => ScanSpeed(G("scan")), bipolar: true, dim: () => Mode() != 0),
+ Slider("SPRAY", "spray", () => Pct(G("spray")), mod: true),
+ },
+ };
+
+ var meter = new MeterBar { VerticalAlignment = VerticalAlignment.Stretch, Width = MeterScale.StereoWidth };
+ ctx.AddDeviceRefresher(() => { if (engine.TryGetTrackMeter(track, out var m)) meter.Push(m); });
+ var meterScale = new Grid
+ {
+ VerticalAlignment = VerticalAlignment.Stretch,
+ RowDefinitions = new RowDefinitions(string.Join(",", ScaleRows(0, -12, -48))),
+ };
+ for (int i = 0; i < 3; i++)
+ {
+ var c = Mono(i == 0 ? "0" : i == 1 ? "−12" : "−48", NotaPalette.TextAxis, NotaType.Axis);
+ Grid.SetRow(c, i * 2 + 1); meterScale.Children.Add(c);
+ }
+ var meterBlock = new Grid
+ {
+ ColumnDefinitions = new ColumnDefinitions("Auto,Auto"), ColumnSpacing = 4,
+ HorizontalAlignment = HorizontalAlignment.Right, Margin = new Thickness(0, 0, 0, 9),
+ };
+ meterBlock.Children.Add(meter);
+ Grid.SetColumn(meterScale, 1); meterBlock.Children.Add(meterScale);
+
+ var outRow = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*"), VerticalAlignment = VerticalAlignment.Stretch };
+ var volCell = PKnob("volume", "VOLUME", "Volume", Pct, NotaSize.KnobMain, 50);
+ var mixCell = PKnob("drywet", "DRY/WET", "Dry/Wet", Pct, NotaSize.KnobRegular, 46);
+ ToolTip.SetTip(mixCell, "Blend the sample itself (dry) with the grain cloud (wet)");
+ outRow.Children.Add(volCell);
+ Grid.SetColumn(mixCell, 1); outRow.Children.Add(mixCell);
+ Grid.SetColumn(meterBlock, 2); outRow.Children.Add(meterBlock);
+ var outFrame = new Border
+ {
+ BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 1, 0, 0),
+ Margin = new Thickness(8, 7, 8, 5), Padding = new Thickness(0, 4, 0, 0), Child = outRow,
+ };
+
+ var railBody = new Grid { RowDefinitions = new RowDefinitions("Auto,*") };
+ railBody.Children.Add(readRows);
+ Grid.SetRow(outFrame, 1); railBody.Children.Add(outFrame);
+ var railGrid = new Grid { RowDefinitions = new RowDefinitions("Auto,*") };
+ railGrid.Children.Add(HeaderStrip(readHead));
+ Grid.SetRow(railBody, 1); railGrid.Children.Add(railBody);
+ var rail = SectionBox(railGrid);
+ rail.Width = RailW;
+
+ // ---- status strip -----------------------------------------------------
+ string ModeWord() => ModeNames[Mode()].ToLowerInvariant();
+ string Read() => Mode() switch
+ {
+ 0 => $"scan {ScanSpeed(G("scan"))} from {Pct(G("position"))}",
+ 1 => $"freeze at {Pct(G("position"))}",
+ _ => $"key from {Pct(G("position"))} at C4",
+ };
+ string Mix() => G("drywet") >= 0.9995f ? "" : $" · dry/wet {Pct(G("drywet"))}";
+
+ // The line at the right of the tab strip: what this tab holds, in a few words.
+ string Hint() => tab switch
+ {
+ 0 => $"{ModeWord()} · {ShapeWords[Sel("grainshape", 4)]} · {Size(G("grainsize"))} · {Density(G("density"))}",
+ 1 => $"{ModeWord()} · {Coarse(G("coarse"))} · {Fine(G("fine"))}",
+ 2 => $"{ModeWord()} · position · pitch · pan",
+ 3 => $"{ModeWord()} · {FilterNames[Sel("filtype", 3)]} · {Hz(G("filfreq"))}",
+ _ => $"{ModeWord()} · a · d · s · r",
+ };
+ string Summary() => tab switch
+ {
+ 0 => $"Window {ShapeWords[Sel("grainshape", 4)]} · size {Size(G("grainsize"))} · density {Density(G("density"))} · spread {Pct(G("spread"))} · {Read()}{Mix()}",
+ 1 => Math.Abs(G("coarse") - 0.5f) < 0.001f && Math.Abs(G("fine") - 0.5f) < 0.0026f
+ ? "Coarse 0 · fine 0 — the grains play at the note's pitch"
+ : $"Coarse {Coarse(G("coarse"))} · fine {Fine(G("fine"))} — every grain transposed by it",
+ 2 => $"Variation: position {Pct(G("posrand"))} · pitch {PitchJitter(G("pitchrand"))} · pan {Pct(G("panrand"))} — per grain",
+ 3 => $"Filter {FilterNames[Sel("filtype", 3)]} · {Hz(G("filfreq"))} · reso {Pct(G("filreso"))} — after the grain cloud",
+ _ => $"Amp {Attack(G("attack"))} · {Decay(G("decay"))} · {Pct(G("sustain"))} · {Release(G("release"))} — the envelope shapes the cloud, not the grain",
+ };
+ string Meta()
+ {
+ string sample = sampleId == 0 ? "DEFAULT" : "SAMPLE";
+ string rate = sampleKHz > 0 ? " · " + NotaNum.Unit(sampleKHz, "0.#", "kHz") : "";
+ return $"{sample} {NotaNum.Time(sampleSec)}{rate} · {voices} VOICES · {grains} GRAINS";
+ }
+ 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 },
+ };
+
+ // Live tick: the read heads and the grain cloud, then every readout.
+ void Tick()
+ {
+ LoadPeaks();
+ headN = engine.GrainPlayPositions(track, heads);
+ int n = engine.InstrumentScope(track, scope);
+ if (n >= 2)
+ {
+ voices = (int)scope[0];
+ grains = Math.Clamp((int)scope[1], 0, Math.Min(cloud.Length / 3, (n - 2) / 3));
+ Array.Copy(scope, 2, cloud, 0, grains * 3);
}
- readouts.Add(Hi); Hi();
- return col;
+ else { voices = 0; grains = 0; }
+ Refresh();
}
+ ctx.SetInstLiveViz(Tick);
+ showTab();
+ Tick();
+ return root;
+ }
- // ---- vertical tab rail + swapped body ----
- string[] tabs = { "Grain", "Pitch", "Variation", "Filter", "Amp" };
- bool[] tealTab = { false, false, true, false, true };
- var tabHost = new ContentControl { VerticalAlignment = VerticalAlignment.Center };
- Control TabBody(int t) => t switch
- {
- 1 => KnobRow(K("coarse", "COARSE"), K("fine", "FINE")),
- 2 => KnobRow(K("posrand", "POSITION", true), K("pitchrand", "PITCH", true), K("panrand", "PAN", true)),
- 3 => new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10, VerticalAlignment = VerticalAlignment.Center, Children = { FilterTypeChips(), KnobRow(K("filfreq", "FREQ"), K("filreso", "RESO")) } },
- 4 => KnobRow(K("attack", "ATTACK"), K("decay", "DECAY"), K("sustain", "SUSTAIN"), K("release", "RELEASE")),
- _ => new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10, VerticalAlignment = VerticalAlignment.Center, Children = { ShapeIcons(), KnobRow(K("grainsize", "SIZE"), K("density", "DENSITY"), K("spread", "SPREAD", true)) } },
- };
- Control FilterTypeChips()
- {
- string[] names = { "LP", "HP", "BP" }; var arr = new Border[3];
- void Hi() { int cur = Math.Clamp((int)Math.Round(G("filtype") * 2), 0, 2); for (int i = 0; i < 3; i++) { bool on = i == cur; arr[i].Background = on ? NotaPalette.Accent : Brushes.Transparent; ((TextBlock)arr[i].Child!).Foreground = on ? NotaPalette.TextOnAccent : MutedC; } }
- var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 1 };
- for (int i = 0; i < 3; i++) { int iv = i; var c = new Border { CornerRadius = NotaRadius.Badge, Padding = new Thickness(7, 2), Cursor = new Cursor(StandardCursorType.Hand), Child = new TextBlock { Text = names[i], FontSize = 9, Foreground = MutedC } }; c.PointerPressed += (_, _) => { SetP("filtype", iv / 2f); Hi(); }; arr[i] = c; row.Children.Add(c); }
- readouts.Add(Hi); Hi();
- var seg = new Border { Background = Inset, BorderBrush = Border2, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Control, Padding = new Thickness(1), VerticalAlignment = VerticalAlignment.Center, Child = row };
- if (I("filtype") is var pi and >= 0) MidiLearn.Bind(seg, MidiTarget.PluginParam(track, -1, pi), "filtype");
- return seg;
+ // Min/max pairs across the file, one per slice, from interleaved samples.
+ private static float[] Peaks(float[] raw, int channels, long frames, int buckets = 360)
+ {
+ var peaks = new float[buckets * 2];
+ for (int b = 0; b < buckets; b++)
+ {
+ long a = b * frames / buckets, e = (b + 1) * frames / buckets;
+ float mn = 0, mx = 0;
+ for (long i = a; i < e; i++)
+ for (int c = 0; c < channels; c++)
+ {
+ long k = i * channels + c;
+ if (k >= raw.Length) break;
+ float v = raw[k];
+ if (v < mn) mn = v; if (v > mx) mx = v;
+ }
+ peaks[b * 2] = mn; peaks[b * 2 + 1] = mx;
}
+ return peaks;
+ }
- int tabSel = 0; var tabBtns = new Border[tabs.Length];
- void HiTabs() { for (int i = 0; i < tabs.Length; i++) { bool on = i == tabSel; tabBtns[i].Background = on ? NotaPalette.SurfaceRaised : Brushes.Transparent; tabBtns[i].BorderBrush = on ? (tealTab[i] ? TealC : Amber) : Brushes.Transparent; ((TextBlock)tabBtns[i].Child!).Foreground = on ? TxtC : MutedC; } }
- var railCol = new StackPanel { Spacing = 2 };
- for (int i = 0; i < tabs.Length; i++)
+ // GrainSynth::makeDefaultSample, drawn: a 1.6 s harmonic pad on 110 Hz with a slow drift
+ // and a 50 ms fade-in. Rendered at a low rate — enough for its peaks.
+ private static (float[] Peaks, double Sec) DefaultSamplePeaks()
+ {
+ const double sr = 22050, sec = 1.6;
+ int n = (int)(sec * sr);
+ var s = new float[n];
+ for (int i = 0; i < n; i++)
+ {
+ double t = i / sr, v = 0;
+ for (int k = 1; k <= 6; k++)
+ {
+ double det = 1.0 + 0.002 * Math.Sin(2 * Math.PI * 0.3 * t * k);
+ v += 1.0 / k * Math.Sin(2 * Math.PI * 110 * k * det * t);
+ }
+ double env = i < 0.05 * sr ? 0.5 - 0.5 * Math.Cos(2 * Math.PI * Math.Min(1.0, i / (0.05 * sr))) : 1.0;
+ s[i] = (float)(v * 0.16 * env);
+ }
+ return (Peaks(s, 1, n), sec);
+ }
+
+ // A device section: card ground, hairline, radius 6 — the almanac's section box.
+ private static Border SectionBox(Control child) => new()
+ {
+ 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,
+ };
+
+ /// <summary>Row definitions that put a caption for each dB mark at its place on the
+ /// meter's scale: a star gap, the caption (Auto), … and a star gap for the remainder.</summary>
+ private static IEnumerable<string> ScaleRows(params double[] dbs)
+ {
+ double prev = 0;
+ foreach (var db in dbs)
{
- int iv = i; var b = new Border { Height = 20, CornerRadius = NotaRadius.Control, Padding = new Thickness(7, 0), BorderThickness = new Thickness(2, 0, 0, 0), BorderBrush = Brushes.Transparent, Child = new TextBlock { Text = tabs[i], FontSize = 9, FontWeight = FontWeight.Medium, Foreground = MutedC, VerticalAlignment = VerticalAlignment.Center } };
- b.PointerPressed += (_, _) => { tabSel = iv; HiTabs(); tabHost.Content = TabBody(iv); };
- tabBtns[i] = b; railCol.Children.Add(b);
+ double fromTop = 1.0 - MeterScale.NormDb(db);
+ yield return Math.Max(0, fromTop - prev).ToString("0.000", NotaNum.Culture) + "*";
+ yield return "Auto";
+ prev = fromTop;
}
- HiTabs(); tabHost.Content = TabBody(0);
- var rail = new Border { Width = 82, Background = RailBg, BorderBrush = Border2, BorderThickness = new Thickness(0, 0, 1, 0), Padding = new Thickness(5), Child = railCol };
- DockPanel.SetDock(rail, Dock.Left);
- var body = new DockPanel { LastChildFill = true, Children = { rail, new Border { Padding = new Thickness(10, 0), Child = tabHost } } };
-
- // ---- assemble ----
- wave.Height = 74; DockPanel.SetDock(wave, Dock.Top);
- DockPanel.SetDock(strip, Dock.Top);
- var dockRoot = new DockPanel { LastChildFill = true, Background = CardBg, Children = { wave, strip, body } };
-
- ctx.SetInstLiveViz(Refresh);
- Refresh();
- return dockRoot;
+ yield return Math.Max(0, 1.0 - prev).ToString("0.000", NotaNum.Culture) + "*";
}
}
diff --git a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
index af412d23..039ab5f4 100644
--- a/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/FactoryPresetCatalog.cs
@@ -573,14 +573,43 @@ public sealed class FactoryPresetCatalog : IFactoryPresets
("dcoarse", 0f), ("dlevel", 1f), ("ddec", 0.3f), ("dsus", 0f), ("drel", 0.22f),
("veltofm", 0.6f), ("filfreq", 0.55f), ("volume", 0.85f));
- // ---- Nota Grain (kind 10) — granular. Scan Mode 0 Scan/.5 Freeze/1 Key; Coarse 0.5 = 0 st
- // (±24); presets shape the built-in default sample (drop your own to replace).
+ // ---- Nota Grain (kind 10) — granular, 25 presets. Scan Mode 0 Scan · .5 Freeze · 1 Key;
+ // Scan 0.5 = still (±4×, 0.625 = 1×); Coarse 0.5 = 0 st (±24, 0.75 = +12); window
+ // 0 Hann · 1/3 Gauss · 2/3 Tukey · 1 Tri; filter 0 LP · .5 HP · 1 BP; Dry/Wet 1 = the
+ // cloud alone, 0 = the sample played straight. Presets shape whatever sample is
+ // loaded (the built-in pad until you drop your own).
+ // The first six.
Inst("grain", 10, "Frozen Choir", ("scanmode", 0.5f), ("position", 0.3f), ("spray", 0.2f), ("grainsize", 0.5f), ("density", 0.8f), ("spread", 0.6f), ("posrand", 0.15f), ("attack", 0.3f), ("release", 0.6f), ("filfreq", 0.9f), ("volume", 0.8f));
Inst("grain", 10, "Drift Cloud", ("scanmode", 0f), ("scan", 0.6f), ("grainsize", 0.6f), ("density", 0.7f), ("spread", 0.7f), ("posrand", 0.3f), ("panrand", 0.5f), ("attack", 0.2f), ("release", 0.7f), ("volume", 0.78f));
Inst("grain", 10, "Glitch Spray", ("scanmode", 0.5f), ("grainsize", 0.15f), ("density", 0.9f), ("spray", 0.6f), ("posrand", 0.5f), ("pitchrand", 0.3f), ("attack", 0.02f), ("release", 0.2f), ("volume", 0.8f));
Inst("grain", 10, "Key Scan", ("scanmode", 1f), ("grainsize", 0.4f), ("density", 0.6f), ("spread", 0.4f), ("attack", 0.05f), ("release", 0.4f), ("volume", 0.82f));
Inst("grain", 10, "Shimmer", ("scanmode", 0.5f), ("coarse", 0.75f), ("grainsize", 0.5f), ("density", 0.8f), ("pitchrand", 0.1f), ("spread", 0.6f), ("filfreq", 1f), ("release", 0.6f), ("volume", 0.76f));
Inst("grain", 10, "Sub Grain", ("scanmode", 0.5f), ("coarse", 0.25f), ("grainsize", 0.6f), ("density", 0.7f), ("filfreq", 0.4f), ("filreso", 0.2f), ("volume", 0.85f));
+ // Clouds and pads.
+ Inst("grain", 10, "Slow Bloom", ("scanmode", 0.5f), ("grainshape", 1f / 3f), ("grainsize", 0.8f), ("density", 0.9f), ("spread", 0.7f), ("posrand", 0.2f), ("attack", 0.85f), ("release", 0.9f), ("filfreq", 0.75f), ("volume", 0.78f));
+ Inst("grain", 10, "Glass Halo", ("scanmode", 0.5f), ("coarse", 0.75f), ("fine", 0.52f), ("grainsize", 0.55f), ("density", 0.85f), ("pitchrand", 0.05f), ("spread", 0.8f), ("panrand", 0.6f), ("filtype", 0.5f), ("filfreq", 0.35f), ("attack", 0.7f), ("release", 0.85f), ("volume", 0.74f));
+ Inst("grain", 10, "Dust Cloud", ("scanmode", 0.5f), ("grainshape", 1f), ("grainsize", 0.2f), ("density", 0.95f), ("spray", 0.5f), ("posrand", 0.6f), ("panrand", 0.8f), ("spread", 0.9f), ("filtype", 1f), ("filfreq", 0.42f), ("filreso", 0.35f), ("attack", 0.5f), ("release", 0.75f), ("volume", 0.8f));
+ Inst("grain", 10, "Detuned Swarm",("scanmode", 0.5f), ("fine", 0.52f), ("pitchrand", 0.03f), ("grainsize", 0.55f), ("density", 1f), ("spread", 1f), ("panrand", 0.7f), ("attack", 0.6f), ("release", 0.7f), ("volume", 0.76f));
+ // Moving through the file.
+ Inst("grain", 10, "Tape Stretch", ("scanmode", 0f), ("scan", 0.52f), ("grainshape", 2f / 3f), ("grainsize", 0.75f), ("density", 0.8f), ("posrand", 0.05f), ("spread", 0.3f), ("attack", 0.6f), ("release", 0.7f), ("volume", 0.8f));
+ Inst("grain", 10, "Reverse Tide", ("scanmode", 0f), ("scan", 0.4f), ("grainsize", 0.6f), ("density", 0.75f), ("spread", 0.6f), ("panrand", 0.4f), ("attack", 0.65f), ("release", 0.8f), ("volume", 0.8f));
+ Inst("grain", 10, "Wide Scan", ("scanmode", 0f), ("scan", 0.6f), ("grainsize", 0.5f), ("density", 0.8f), ("spread", 1f), ("panrand", 1f), ("posrand", 0.15f), ("drywet", 0.8f), ("attack", 0.4f), ("release", 0.7f), ("volume", 0.78f));
+ Inst("grain", 10, "Key Morph", ("scanmode", 1f), ("grainshape", 1f / 3f), ("grainsize", 0.55f), ("density", 0.75f), ("spread", 0.5f), ("posrand", 0.08f), ("attack", 0.4f), ("release", 0.6f), ("volume", 0.8f));
+ // Keys and plucks — Dry/Wet puts the sample's own attack under the cloud.
+ Inst("grain", 10, "Grain Keys", ("scanmode", 0.5f), ("grainsize", 0.6f), ("density", 0.7f), ("spray", 0.05f), ("posrand", 0.03f), ("attack", 0.2f), ("decay", 0.5f), ("sustain", 0.4f), ("release", 0.55f), ("drywet", 0.55f), ("volume", 0.82f));
+ Inst("grain", 10, "Soft Pluck", ("scanmode", 0.5f), ("grainsize", 0.5f), ("density", 0.6f), ("attack", 0.1f), ("decay", 0.45f), ("sustain", 0f), ("release", 0.45f), ("filfreq", 0.7f), ("drywet", 0.5f), ("volume", 0.85f));
+ Inst("grain", 10, "Granular Perc",("scanmode", 0.5f), ("grainsize", 0.3f), ("density", 0.6f), ("posrand", 0.2f), ("attack", 0f), ("decay", 0.35f), ("sustain", 0f), ("release", 0.3f), ("filfreq", 0.8f), ("filreso", 0.3f), ("volume", 0.85f));
+ // Rhythm and damage.
+ Inst("grain", 10, "Stutter", ("scanmode", 0.5f), ("grainshape", 2f / 3f), ("grainsize", 0.35f), ("density", 0f), ("spray", 0.3f), ("posrand", 0.2f), ("attack", 0.02f), ("release", 0.3f), ("volume", 0.82f));
+ Inst("grain", 10, "Bit Rain", ("scanmode", 0.5f), ("grainshape", 1f), ("grainsize", 0.05f), ("density", 0.35f), ("spray", 0.8f), ("posrand", 0.8f), ("pitchrand", 0.5f), ("panrand", 1f), ("filtype", 0.5f), ("filfreq", 0.45f), ("attack", 0.05f), ("release", 0.4f), ("volume", 0.78f));
+ Inst("grain", 10, "Broken Radio", ("scanmode", 0f), ("scan", 0.7f), ("grainsize", 0.25f), ("density", 0.5f), ("spray", 0.4f), ("pitchrand", 0.15f), ("filtype", 1f), ("filfreq", 0.6f), ("filreso", 0.6f), ("volume", 0.8f));
+ // Low end.
+ Inst("grain", 10, "Grain Bass", ("scanmode", 0.5f), ("coarse", 0.25f), ("grainsize", 0.7f), ("density", 0.65f), ("spread", 0.1f), ("panrand", 0f), ("posrand", 0.02f), ("filfreq", 0.45f), ("filreso", 0.25f), ("attack", 0.1f), ("decay", 0.45f), ("sustain", 0.7f), ("release", 0.35f), ("drywet", 0.4f), ("volume", 0.85f));
+ Inst("grain", 10, "Deep Drone", ("scanmode", 0f), ("scan", 0.52f), ("coarse", 0.25f), ("grainsize", 0.9f), ("density", 0.9f), ("spread", 0.5f), ("filfreq", 0.5f), ("attack", 0.8f), ("release", 0.9f), ("volume", 0.84f));
+ // The sample itself, blended.
+ Inst("grain", 10, "Half Frozen", ("scanmode", 0.5f), ("grainsize", 0.7f), ("density", 0.8f), ("spread", 0.6f), ("posrand", 0.1f), ("drywet", 0.5f), ("attack", 0.5f), ("release", 0.7f), ("volume", 0.8f));
+ Inst("grain", 10, "Sample Plus", ("scanmode", 0.5f), ("grainsize", 0.45f), ("density", 0.7f), ("spread", 0.8f), ("panrand", 0.6f), ("pitchrand", 0.02f), ("drywet", 0.25f), ("attack", 0.1f), ("release", 0.5f), ("volume", 0.8f));
+ Inst("grain", 10, "Plain Sampler",("drywet", 0f), ("filfreq", 1f), ("attack", 0.05f), ("release", 0.45f), ("volume", 0.8f));
// ---- Nota Flux (kind 11) — vector-morph synth, 25 presets. Vector (X,Y) blends the
// corners WARM (0,0) · GLASS (1,0) · MOOG (0,1) · GRAIN (1,1); target: 0 Filter,
diff --git a/src/native/nota.engine/src/GrainSynth.h b/src/native/nota.engine/src/GrainSynth.h
index 68bce840..d8ca3668 100644
--- a/src/native/nota.engine/src/GrainSynth.h
+++ b/src/native/nota.engine/src/GrainSynth.h
@@ -6,11 +6,17 @@
// through the file (Scan speed, or Freeze, or Key = position follows the keyboard),
// grains of a chosen Size spawn at a Density (overlap), each sprayed randomly around
// the position, pitched by the note (+ Coarse/Fine), spread across the stereo field,
-// with per-grain position / pitch / pan randomisation. The grain cloud feeds a
-// subtractive filter and an amp ADSR. Ships with a procedural default sample so it
-// sounds before you drop your own.
+// with per-grain position / pitch / pan randomisation. Dry/Wet blends the cloud with the
+// sample itself, played straight from the read position at the note's pitch. The mix
+// feeds a subtractive filter and an amp ADSR. Ships with a procedural default sample so
+// it sounds before you drop your own.
//
-// sample ─▶ [Position/Scan] ─▶ grain cloud (Size · Density · Spray · Pitch · Spread) ─▶ filter ─▶ amp ─▶ out
+// sample ─▶ [Position/Scan] ─▶ grain cloud (Size · Density · Spray · Pitch · Spread) ─┬▶ filter ─▶ amp ─▶ out
+// └▶ dry read head (the sample at the note's pitch) ──────────── Dry/Wet ─────┘
+//
+// Position is live: a held note follows it (and its automation) — Scan adds a moving
+// offset to it, Freeze sits on it, Key offsets it by the note. The audio thread publishes
+// every live grain (read position, pan, window level) through scopeRead for the UI.
//
// Holds a shared SampleBuffer like the Sampler (so project save bundles it by id). All
// params ride the plugin-param interface (normalized 0..1) → automation / persist /
@@ -38,6 +44,7 @@ public:
Position = 0, Scan, Spray, GrainSize, Density, Coarse, Fine, Spread,
PosRand, PitchRand, PanRand, ScanMode, FilterType, FilterFreq, FilterReso,
Attack, Decay, Sustain, Release, Volume, Pan, GrainShape,
+ DryWet, // appended 2026-09: older projects load fully wet, as they sounded
kNumParams
};
@@ -49,6 +56,7 @@ public:
set(FilterType, 0.0f); set(FilterFreq, 0.9f); set(FilterReso, 0.1f);
set(Attack, 0.06f); set(Decay, 0.3f); set(Sustain, 0.85f); set(Release, 0.4f);
set(Volume, 0.8f); set(Pan, 0.5f); set(GrainShape, 0.0f);
+ set(DryWet, 1.0f);
for (auto& p : posPub_) p.store(-1.0f, std::memory_order_relaxed);
}
@@ -72,6 +80,19 @@ public:
for (int i = 0; i < kVoices && c < maxN; ++i) { float p = posPub_[i].load(std::memory_order_relaxed); if (p >= 0.0f) out[c++] = p; }
return c;
}
+ int32_t activeVoiceCount() const override { return activeVoices_.load(std::memory_order_relaxed); }
+
+ // Scope telemetry: [0] active voices · [1] live grains n · then n triples of (read
+ // position 0..1 through the sample, pan 0..1, window level 0..1) — the grain cloud.
+ int32_t scopeRead(float* out, int32_t maxN) const override {
+ if (!out || maxN < 2) return 0;
+ const int n = std::min<int>((int)scope_[1].load(std::memory_order_relaxed), (maxN - 2) / 3);
+ out[0] = scope_[0].load(std::memory_order_relaxed);
+ out[1] = (float)n;
+ for (int i = 0; i < n * 3; ++i) out[2 + i] = scope_[2 + i].load(std::memory_order_relaxed);
+ return 2 + n * 3;
+ }
+
void setSample(std::shared_ptr<SampleBuffer> s, int32_t rootNote, bool /*loop*/) {
if (s && !s->empty()) { sample_ = std::move(s); rootNote_ = rootNote; }
}
@@ -82,14 +103,14 @@ public:
static const char* ids[] = {
"position", "scan", "spray", "grainsize", "density", "coarse", "fine", "spread",
"posrand", "pitchrand", "panrand", "scanmode", "filtype", "filfreq", "filreso",
- "attack", "decay", "sustain", "release", "volume", "pan", "grainshape" };
+ "attack", "decay", "sustain", "release", "volume", "pan", "grainshape", "drywet" };
return (i >= 0 && i < kNumParams) ? std::string(ids[i]) : std::string{};
}
std::string pluginParamName(int32_t i) const override {
static const char* nm[] = {
"Position", "Scan", "Spray", "Grain Size", "Density", "Coarse", "Fine", "Spread",
"Pos Rand", "Pitch Rand", "Pan Rand", "Scan Mode", "Filter Type", "Filter Freq", "Filter Reso",
- "Attack", "Decay", "Sustain", "Release", "Volume", "Pan", "Grain Shape" };
+ "Attack", "Decay", "Sustain", "Release", "Volume", "Pan", "Grain Shape", "Dry/Wet" };
return (i >= 0 && i < kNumParams) ? std::string(nm[i]) : std::string{};
}
float pluginParamGet(int32_t i) const override {
@@ -123,21 +144,21 @@ public:
// ---- notes ----
void noteOn(int32_t pitch, float velocity) override {
Voice* v = findFreeVoice();
- v->active = true; v->pitch = pitch; v->vel = std::clamp(velocity, 0.0f, 1.0f);
- v->env = 0.0f; v->stage = Stage::Attack; v->grainClock = 0.0;
+ v->active = true; v->pitch = pitch; v->vel = std::clamp(velocity, 0.0f, 1.0f); v->seq = ++seq_;
+ v->env = 0.0f; v->stage = Stage::Attack; v->grainClock = 0.0; v->scanOff = 0.0;
v->s1L = v->s2L = v->s1R = v->s2R = 0.0;
for (auto& g : v->grains) g.active = false;
const int64_t frames = sample_ ? sample_->frames : 0;
- const int mode = scanModeNow();
- if (mode == 2) { // Key: position follows the keyboard, pitch stays at root
- double pos01 = std::clamp((double)get(Position) + (pitch - 60) / 36.0, 0.0, 1.0);
- v->readPos = pos01 * frames;
- } else {
- v->readPos = (double)get(Position) * frames;
- }
+ v->readPos = basePos01(pitch, scanModeNow()) * frames;
+ v->dryPos = v->readPos;
}
+ // Releases the oldest held voice of the pitch only: a repeat that started a hair before
+ // the previous one of the same pitch ended keeps sounding.
void noteOff(int32_t pitch) override {
- for (auto& v : voices_) if (v.active && v.pitch == pitch && v.stage != Stage::Release) v.stage = Stage::Release;
+ Voice* oldest = nullptr;
+ for (auto& v : voices_)
+ if (v.active && v.pitch == pitch && v.stage != Stage::Release && (!oldest || v.seq < oldest->seq)) oldest = &v;
+ if (oldest) oldest->stage = Stage::Release;
}
void allNotesOff() override { for (auto& v : voices_) v.active = false; }
@@ -170,6 +191,20 @@ public:
const double gpL = std::cos((panv + 1.0) * 0.25 * kPi), gpR = std::sin((panv + 1.0) * 0.25 * kPi);
const double fg = std::tan(kPi * std::min(fbase, sampleRate_ * 0.49) / sampleRate_);
const double fa1 = 1.0 / (1.0 + fg * (fg + fk));
+ const double wet = get(DryWet);
+ const bool doWet = wet > 1e-4, doDry = wet < 1.0 - 1e-4;
+ const float wetGain = (float)wet, dryGain = (float)((1.0 - wet) * kDryTrim);
+ const double dryEnd = (double)std::max<int64_t>(1, slen - 1);
+ const double dryFade = std::max(1.0, 0.004 * (sb->sourceSampleRate > 0 ? sb->sourceSampleRate : sampleRate_));
+
+ // Per-voice, per-block: where the read position sits (live), how fast the dry head runs.
+ for (auto& v : voices_) {
+ if (!v.active) continue;
+ v.base = basePos01(v.pitch, mode) * slen;
+ if (mode != 0) v.scanOff = 0.0;
+ const double semis = (mode == 2 ? 0.0 : (v.pitch - rootNote_)) + coarse + fine;
+ v.dryRate = std::pow(2.0, semis / 12.0) * srcRatio;
+ }
for (int32_t i = 0; i < frames; ++i) {
float mixL = 0.0f, mixR = 0.0f;
@@ -178,12 +213,28 @@ public:
advanceEnv(v.env, v.stage, aA, aD, aS, aR);
if (v.stage == Stage::Off) { v.active = false; continue; }
- // Scan the read position (Scan mode only; wraps within the file).
- if (mode == 0) { v.readPos += scanRate; if (v.readPos >= slen) v.readPos -= slen; else if (v.readPos < 0) v.readPos += slen; }
+ // The read position: the live base, plus the moving offset in Scan mode
+ // (wrapping within the file).
+ if (mode == 0) { v.scanOff += scanRate; if (v.scanOff >= slen) v.scanOff -= slen; else if (v.scanOff < 0) v.scanOff += slen; }
+ v.readPos = v.base + v.scanOff;
+ if (v.readPos >= slen) v.readPos -= slen;
+
+ // The dry head: the sample itself from the read position at the note's
+ // pitch, wrapping at the end with both ends faded so the wrap doesn't click.
+ float dl = 0.0f, dr = 0.0f;
+ if (doDry) {
+ const int64_t d0 = (int64_t)v.dryPos; const double df = v.dryPos - d0;
+ float l0, r0, l1, r1; sb->readStereo(d0, l0, r0); sb->readStereo(std::min<int64_t>(d0 + 1, slen - 1), l1, r1);
+ const float fade = (float)std::min({ 1.0, v.dryPos / dryFade, (dryEnd - v.dryPos) / dryFade });
+ dl = (l0 + (l1 - l0) * (float)df) * fade;
+ dr = (r0 + (r1 - r0) * (float)df) * fade;
+ v.dryPos += v.dryRate;
+ if (v.dryPos >= dryEnd) v.dryPos = std::fmod(v.dryPos, dryEnd);
+ }
// Spawn grains at the density interval.
v.grainClock += 1.0;
- if (v.grainClock >= interval) {
+ if (doWet && v.grainClock >= interval) {
v.grainClock -= interval;
Grain* g = freeGrain(v);
if (g) {
@@ -195,6 +246,7 @@ public:
double pan = 0.5 + (spread * 0.5 + panRand * 0.5) * (rnd() * 2.0 - 1.0);
pan = std::clamp(pan, 0.0, 1.0);
g->gL = (float)std::cos(pan * 0.5 * kPi); g->gR = (float)std::sin(pan * 0.5 * kPi);
+ g->pan = (float)pan;
g->active = true;
}
}
@@ -213,8 +265,9 @@ public:
g.age += 1.0;
if (g.age >= g.len) g.active = false;
}
- const float norm = (float)(1.0 / std::sqrt(overlap));
- double yL = gl * norm, yR = gr * norm;
+ if (!doWet) v.grainClock = std::min(v.grainClock, interval);
+ const float norm = (float)(1.0 / std::sqrt(overlap)) * wetGain;
+ double yL = gl * norm + dl * dryGain, yR = gr * norm + dr * dryGain;
// Subtractive TPT filter per channel.
yL = svf(v.s1L, v.s2L, yL, fg, fa1, fk, ftype);
yR = svf(v.s1R, v.s2R, yR, fg, fa1, fk, ftype);
@@ -224,10 +277,25 @@ public:
out[i * 2] += (float)((mixL * gpL) * volume * 2.4);
out[i * 2 + 1] += (float)((mixR * gpR) * volume * 2.4);
}
- // Publish each voice's read position (0..1) for the UI playheads.
+ // Publish each voice's read position (0..1) for the UI playheads, and the cloud.
const double inv = slen > 0 ? 1.0 / slen : 0.0;
- for (int vi = 0; vi < kVoices; ++vi)
- posPub_[vi].store(voices_[vi].active ? (float)(voices_[vi].readPos * inv) : -1.0f, std::memory_order_relaxed);
+ int nv = 0, ng = 0;
+ for (int vi = 0; vi < kVoices; ++vi) {
+ const Voice& v = voices_[vi];
+ posPub_[vi].store(v.active ? (float)(v.readPos * inv) : -1.0f, std::memory_order_relaxed);
+ if (!v.active) continue;
+ ++nv;
+ for (const auto& g : v.grains) {
+ if (!g.active || ng >= kVoices * kGrains) continue;
+ scope_[2 + ng * 3].store((float)((g.pos + g.age * g.rate) * inv), std::memory_order_relaxed);
+ scope_[3 + ng * 3].store(g.pan, std::memory_order_relaxed);
+ scope_[4 + ng * 3].store(grainWindow(gshape, g.age / g.len) * v.env, std::memory_order_relaxed);
+ ++ng;
+ }
+ }
+ scope_[0].store((float)nv, std::memory_order_relaxed);
+ scope_[1].store((float)ng, std::memory_order_relaxed);
+ activeVoices_.store(nv, std::memory_order_relaxed);
}
private:
@@ -235,13 +303,18 @@ private:
static constexpr double kTwoPi = 6.283185307179586;
static constexpr int kVoices = 8;
static constexpr int kGrains = 12;
+ // The dry head against the cloud: the cloud's windows and its 1/√overlap normalisation
+ // leave it well under the raw sample, so the dry side is trimmed to meet it.
+ static constexpr double kDryTrim = 0.5;
enum class Stage { Attack, Decay, Sustain, Release, Off };
- struct Grain { bool active = false; double pos = 0, age = 0, len = 1, rate = 1; float gL = 0.7f, gR = 0.7f; };
+ struct Grain { bool active = false; double pos = 0, age = 0, len = 1, rate = 1; float gL = 0.7f, gR = 0.7f, pan = 0.5f; };
struct Voice {
- bool active = false; int32_t pitch = 0; float vel = 0.0f;
+ bool active = false; int32_t pitch = 0; float vel = 0.0f; uint64_t seq = 0;
float env = 0.0f; Stage stage = Stage::Off;
double readPos = 0.0, grainClock = 0.0;
+ double base = 0.0, scanOff = 0.0; // read position = base (live) + scan offset
+ double dryPos = 0.0, dryRate = 1.0; // the dry head
double s1L = 0, s2L = 0, s1R = 0, s2R = 0;
Grain grains[kGrains];
};
@@ -250,6 +323,12 @@ private:
void set(Param p, float v) { pn_[p].store(v, std::memory_order_relaxed); }
float get(Param p) const { return pn_[p].load(std::memory_order_relaxed); }
int scanModeNow() const { return std::clamp((int)std::lround(get(ScanMode) * 2.0f), 0, 2); }
+ // Where a note reads (0..1): Position, or in Key mode Position moved by the note — C4
+ // reads at Position, each octave moves it a third of the file.
+ double basePos01(int32_t pitch, int mode) const {
+ const double p = get(Position);
+ return mode == 2 ? std::clamp(p + (pitch - 60) / 36.0, 0.0, 1.0) : p;
+ }
static double expMap(double v, double lo, double hi) { return lo * std::pow(hi / lo, std::clamp(v, 0.0, 1.0)); }
float rateOf(Param p, double lo, double hi) const { return (float)(1.0 / (expMap(get(p), lo, hi) * sampleRate_)); }
float rnd() { rng_ ^= rng_ << 13; rng_ ^= rng_ >> 17; rng_ ^= rng_ << 5; return (rng_ & 0xFFFFFF) / 16777216.0f; }
@@ -311,6 +390,9 @@ private:
uint32_t rng_ = 0x1234567u;
std::atomic<float> pn_[kNumParams];
std::atomic<float> posPub_[kVoices] = {};
+ std::atomic<float> scope_[2 + kVoices * kGrains * 3] = {};
+ std::atomic<int32_t> activeVoices_{0};
+ uint64_t seq_ = 0;
};
} // namespace nota
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index d298f7d4..c6a38e4d 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -2433,7 +2433,7 @@ Console.WriteLine("-- Nota Grain --");
Check(ge.TrackInstrumentKind(t) == 10, $"instrument kind is 10 (got {ge.TrackInstrumentKind(t)})");
Check(ge.DeviceName(t, -1) == "Nota Grain", $"instrument is Nota Grain (got '{ge.DeviceName(t, -1)}')");
int pc = ge.PluginParamCount(t, -1);
- Check(pc == 22, $"Nota Grain exposes 22 params (got {pc})");
+ Check(pc == 23, $"Nota Grain exposes 23 params (got {pc})");
int posI = -1; bool idsOk = true;
for (int i = 0; i < pc; i++) { if (ge.PluginParamId(t, -1, i).Length == 0) idsOk = false; if (ge.PluginParamId(t, -1, i) == "position") posI = i; }
Check(idsOk && posI >= 0, "params have ids; position present");
@@ -2477,6 +2477,126 @@ Console.WriteLine("-- Nota Grain --");
Check(rt > 0 && Math.Abs(gdst.PluginParamGet(rt, -1, posI) - 0.4f) < 1e-3, "reloaded Grain restores its params");
}
finally { try { System.IO.Directory.Delete(gdir, true); } catch { } try { System.IO.File.Delete(gpath); } catch { } }
+
+ // From here on: a fresh Grain on the built-in pad, rendered alone.
+ using var gx = new NotaEngine();
+ gx.SetBpm(120);
+ int g = gx.AddGrainSynthTrack();
+ int gpc = gx.PluginParamCount(g, -1);
+ var gIds = new System.Collections.Generic.HashSet<string>();
+ int GI(string id) { for (int i = 0; i < gpc; i++) if (gx.PluginParamId(g, -1, i) == id) return i; return -1; }
+ for (int i = 0; i < gpc; i++) gIds.Add(gx.PluginParamId(g, -1, i));
+ int wetI = GI("drywet");
+ Check(wetI == 22 && gx.PluginParamName(g, -1, wetI) == "Dry/Wet", "Dry/Wet is appended as param 22");
+ Check(Math.Abs(gx.InstrumentParamDefault(g, wetI) - 1f) < 1e-6, "Dry/Wet defaults fully wet (older projects sound as before)");
+ // A state saved before Dry/Wet existed (22 floats) loads fully wet, as it sounded.
+ {
+ var st = gx.GetPluginState(g, -1);
+ int g2 = gx.AddGrainSynthTrack();
+ gx.SetPluginState(g2, -1, st[..(22 * 4)]);
+ Check(Math.Abs(gx.PluginParamGet(g2, -1, wetI) - 1f) < 1e-6, "a 22-param state loads fully wet");
+ gx.RemoveTrack(g2);
+ }
+ int GrainFrames(double beats) => (int)Math.Round(beats * 60.0 / 120.0 * (gx.SampleRate > 0 ? gx.SampleRate : 48000.0));
+ void GrainStop() { gx.StopTransport(); gx.RenderOffline(new float[64 * 2], 64); }
+ void GrainRender(float[] buf, Action? perBlock = null)
+ {
+ var blk = new float[1024 * 2];
+ for (int at = 0; at < buf.Length / 2; at += 1024)
+ {
+ int n = Math.Min(1024, buf.Length / 2 - at);
+ gx.RenderOffline(blk, n);
+ Array.Copy(blk, 0, buf, at * 2, n * 2);
+ perBlock?.Invoke();
+ }
+ }
+ gx.AddMidiClip(g, 0.0, 4.0);
+ gx.SetClipNotes(g, 0, new[] { new NotaNote(60, 0.0, 3.0, 0.9f) });
+
+ // Dry, half and wet are each audible and finite.
+ foreach (var (wv, word) in new[] { (0f, "dry"), (0.5f, "half"), (1f, "wet") })
+ {
+ gx.PluginParamSet(g, -1, wetI, wv);
+ var wbuf = new float[GrainFrames(2.0) * 2];
+ gx.Seek(0.0); gx.Play(); GrainRender(wbuf); GrainStop();
+ float r = Rms(wbuf, wbuf.Length / 2); bool fin = true;
+ foreach (var x in wbuf) if (!float.IsFinite(x) || Math.Abs(x) > 4f) { fin = false; break; }
+ Check(r > 0.005f && fin, $"Grain {word} (Dry/Wet {wv:0.0}) is audible + finite (RMS {r:F3})");
+ }
+ gx.PluginParamSet(g, -1, wetI, 1f);
+
+ // The scope publishes the voices and the live grain cloud; Position is live — a held
+ // note's read head follows it (Freeze).
+ {
+ int posJ = GI("position");
+ gx.PluginParamSet(g, -1, GI("scanmode"), 0.5f);
+ gx.PluginParamSet(g, -1, posJ, 0.2f);
+ var sc = new float[2 + 8 * 12 * 3];
+ var heads = new float[8];
+ int maxGrains = 0, scN = 0; bool inRange = true;
+ float headBefore = -1, headAfter = -1;
+ gx.Seek(0.0); gx.Play();
+ var blk = new float[1024 * 2];
+ for (int b = 0; b < 40; b++)
+ {
+ if (b == 20) { headBefore = gx.GrainPlayPositions(g, heads) > 0 ? heads[0] : -1; gx.PluginParamSet(g, -1, posJ, 0.7f); }
+ gx.RenderOffline(blk, 1024);
+ scN = gx.InstrumentScope(g, sc);
+ if (scN >= 2)
+ {
+ int n = (int)sc[1];
+ maxGrains = Math.Max(maxGrains, n);
+ for (int k = 0; k < n; k++)
+ for (int c = 0; c < 3; c++) { float v = sc[2 + k * 3 + c]; if (!(v >= 0f && v <= 1.0001f)) inRange = false; }
+ }
+ }
+ headAfter = gx.GrainPlayPositions(g, heads) > 0 ? heads[0] : -1;
+ GrainStop();
+ Check(scN >= 2 && sc[0] >= 0, $"Grain scope publishes voices + grains ({scN} values)");
+ Check(maxGrains >= 2 && inRange, $"Grain scope carries the live cloud in range ({maxGrains} grains)");
+ Check(Math.Abs(headBefore - 0.2f) < 0.02f && Math.Abs(headAfter - 0.7f) < 0.02f,
+ $"a held note follows Position live (read head {headBefore:F2} → {headAfter:F2})");
+ gx.PluginParamSet(g, -1, posJ, gx.InstrumentParamDefault(g, posJ));
+ }
+
+ // A repeated note that starts a hair before the previous one ends keeps sounding.
+ {
+ gx.PluginParamSet(g, -1, GI("attack"), 0f); gx.PluginParamSet(g, -1, GI("release"), 0f);
+ float WindowRms(NotaNote[] notes)
+ {
+ gx.SetClipNotes(g, 0, notes);
+ var obuf = new float[GrainFrames(2.2) * 2];
+ gx.Seek(0.0); gx.Play(); GrainRender(obuf); GrainStop();
+ int from = GrainFrames(1.4), len = GrainFrames(0.4);
+ double acc = 0; for (int i = from; i < from + len; i++) acc += obuf[i * 2] * obuf[i * 2];
+ return (float)Math.Sqrt(acc / len);
+ }
+ float alone = WindowRms(new[] { new NotaNote(60, 0.0, 1.02, 0.9f) });
+ float held = WindowRms(new[] { new NotaNote(60, 0.0, 1.02, 0.9f), new NotaNote(60, 1.0, 1.5, 0.9f) });
+ Check(held > 0.01f && held > alone * 5, $"Grain: an overlapping repeat of a note keeps sounding (RMS {held:F3} vs {alone:F4} released)");
+ }
+
+ // Factory presets: 25 ship, every named param is a real Grain id, each applies in place
+ // and renders audible and finite.
+ {
+ var cat = new FactoryPresetCatalog();
+ var mine = cat.All().Where(p => p.IsInstrument && p.BuiltinKind == 10).ToList();
+ Check(mine.Count == 25, $"Nota Grain ships 25 factory presets (got {mine.Count})");
+ var bad = mine.SelectMany(p => cat.Document(p.Id)!.NamedParams!.Keys.Where(k => !gIds.Contains(k)).Select(k => $"{p.DisplayName}:{k}")).ToList();
+ Check(bad.Count == 0, $"every Grain preset param id exists{(bad.Count > 0 ? " — bad: " + string.Join(", ", bad) : "")}");
+ gx.SetClipNotes(g, 0, new[] { new NotaNote(48, 0.0, 1.5, 0.9f), new NotaNote(60, 0.0, 1.5, 0.9f), new NotaNote(67, 0.5, 1.0, 0.9f) });
+ var off = new System.Collections.Generic.List<string>();
+ var pbuf = new float[GrainFrames(2.0) * 2];
+ foreach (var p in mine)
+ {
+ if (cat.ApplyInPlace(gx, p.Id, g, -1).Length != 0) { off.Add($"{p.DisplayName} (apply)"); continue; }
+ gx.Seek(0.0); gx.Play(); GrainRender(pbuf); GrainStop();
+ bool ok = true; foreach (var x in pbuf) if (!float.IsFinite(x) || Math.Abs(x) > 1.01f) { ok = false; break; }
+ float r = Rms(pbuf, pbuf.Length / 2);
+ if (!ok || r < 0.005f) off.Add($"{p.DisplayName} (RMS {r:F3})");
+ }
+ Check(off.Count == 0, $"every Grain preset is audible and finite{(off.Count > 0 ? " — off: " + string.Join(", ", off) : "")}");
+ }
}
// ============================ Nota Flux ====================================