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
(fix) Keep a controller stroke inside the stretch it draws (#169) (#471)
Chris Laupama312530be3c49
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0382e18f..032444b2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -256,6 +256,10 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.returns, then the master.### Fixed+- **Drawing a controller no longer changes the rest of the curve** (#169): a stroke in the+ piano-roll controller lane replaces only the stretch you draw. A shaped curve on either side+ keeps its bend, and points recorded while the button is down are not replaced by the older+ copy from when the drag began.- **Open an SFZ by dropping it on Nota Mosaic** (#349): drop an `.sfz` file, or the folder ofan SFZ library (such as the Salamander Grand Piano), on a Mosaic card and its zones load, withthe import report. Before, only installed sample packs could bring an SFZ in, so a librarydiff --git a/specs/063-event-lane-cc-velocity-wheel/plan.md b/specs/063-event-lane-cc-velocity-wheel/plan.mdindex deee5f1a..b3d917e2 100644--- a/specs/063-event-lane-cc-velocity-wheel/plan.md+++ b/specs/063-event-lane-cc-velocity-wheel/plan.md@@ -42,7 +42,14 @@ C ABI function, no engine code, no new allocation, lock, I/O or logging on the astored value, so half-pedal values survive moves). Partial values draw as fill height.- Continuous controllers: the MPE lane's stroke model over one clip-wide curve — the strokereplaces the stretch it covers, the old curve resumes after it; RDP thinning on release.- Existing points keep their `Curve` shaping; new points are linear.+ Existing points keep their `Curve` shaping; new points are linear. Splitting a shaped+ segment keeps playback outside the stroke within one CC step (`ControllerStroke`): the+ shortened left piece keeps its exponent, and the right piece is refit instead of starting+ at curve 0. A reload while a stroke is down paints that stroke onto the curve just read,+ so releasing does not write the pre-reload copy over points recorded during the drag.+ A multi-clip editor clears the per-clip view key on every reload, so that match uses the+ active clip's track and index. A stroke that ends before the first point pins the held+ value there, so the untouched stretch does not ramp up to it.- One `SetController` call per gesture (on release) → one undo step.### Lane tabs (`App/PianoRollView.Expression.cs`)diff --git a/src/managed/Nota.App/PianoRollView.Controllers.cs b/src/managed/Nota.App/PianoRollView.Controllers.csindex 91c016fb..8098252c 100644--- a/src/managed/Nota.App/PianoRollView.Controllers.cs+++ b/src/managed/Nota.App/PianoRollView.Controllers.cs@@ -22,6 +22,7 @@ using Avalonia.Controls.Primitives;using Avalonia.Input;using Avalonia.Media;using Nota.Application;+using Nota.Application.Editing;using Nota.Application.Localization;namespace Nota.App;@@ -187,6 +188,22 @@ public sealed partial class PianoRollViewInvalidateVisual();}+ // A reload (recording, undo) drops the curve cache. A draw in progress is painted onto+ // the curve just read, so releasing later does not write the older copy back over+ // points recorded during the drag. Any other gesture is cancelled: its point index+ // or block no longer matches that curve. A different clip drops the gesture entirely.+ internal void OnClipReloaded(bool sameClip)+ {+ if (sameClip && _drag == Drag.Draw && _stroke.Count > 0)+ {+ _orig = _o.ControllerPoints(Ctl).ToList();+ ApplyStroke(StrokeSamples());+ InvalidateVisual();+ return;+ }+ if (_drag != Drag.None) ResetGesture();+ }+private IReadOnlyList<AutomationPoint> Cur => (IReadOnlyList<AutomationPoint>?)_work ?? _o.ControllerPoints(Ctl);// ---- time and value ----@@ -328,22 +345,13 @@ public sealed partial class PianoRollViewreturn hit;}- // The stroke replaces the curve over the stretch it covers; outside it the curve keeps its- // values (pinned at the stroke's edges); with nothing after it, the drawn value holds.+ // The stroke replaces the curve over the stretch it covers. ControllerStroke keeps the+ // value on either side (the right-hand piece stays shaped, it does not fall straight);+ // with nothing after the stroke, the drawn value holds.private void ApplyStroke(List<(double Beat, float Value)> samples){if (samples.Count == 0) return;- samples.Sort((a, b) => a.Beat.CompareTo(b.Beat));- double a = samples[0].Beat, b = samples[^1].Beat;- var outp = _orig.Where(q => q.Beat < a - Eps).ToList();- if (outp.Count > 0) outp.Add(new AutomationPoint(a - Eps, ValueAt(_orig, a - Eps, false)));- foreach (var (sb, sv) in samples) outp.Add(new AutomationPoint(sb, sv));- if (_orig.Any(q => q.Beat > b + Eps))- {- outp.Add(new AutomationPoint(b + Eps, ValueAt(_orig, b + Eps, false)));- outp.AddRange(_orig.Where(q => q.Beat > b + Eps));- }- _work = Normalize(outp);+ _work = Normalize(ControllerStroke.Apply(_orig, samples));}private List<(double Beat, float Value)> StrokeSamples()@@ -636,11 +644,18 @@ public sealed partial class PianoRollViewif (was == Drag.Draw){var samples = StrokeSamples().OrderBy(s => s.Beat).ToList();+ // The curve may have gained points while the button was down (a recording+ // reload). Read it again and paint the stroke onto that, not onto the copy+ // from pointer-down.+ _o.DropControllerCache();+ _orig = _o.ControllerPoints(Ctl).ToList();// A click without a drag is not a stroke. Committing it would write a point// that the second press of a double-click then deletes.if (samples.Count < 2)_work = _orig.ToList();- else if (!_straight)+ else if (_straight)+ ApplyStroke(samples);+ else{// Thin to what the eye can tell apart: a pixel and a half of the lane's scale.float tol = Math.Abs(YToValue(Bounds.Height / 2) - YToValue(Bounds.Height / 2 + 1.5));diff --git a/src/managed/Nota.App/PianoRollView.cs b/src/managed/Nota.App/PianoRollView.csindex 6f126a0c..32b3c3c1 100644--- a/src/managed/Nota.App/PianoRollView.cs+++ b/src/managed/Nota.App/PianoRollView.cs@@ -155,6 +155,10 @@ public sealed partial class PianoRollView : UserControlprivate static readonly Dictionary<(int, int), ViewState> s_view = new();private (int, int) _clipKey = (int.MinValue, int.MinValue);private (int, int) _loadedKey = (int.MinValue, int.MinValue); // the clip Load last showed+ // The active clip the controller lane last loaded. Separate from _clipKey: a multi-clip+ // editor clears that key (view state is not per clip), and recording still reloads the+ // same active clip.+ private (int Track, int Clip) _ctlClip = (int.MinValue, int.MinValue);private double? _pendingVOffset; // absolute vertical offset to apply once the body is laid outprivate bool _pendingCenter; // instead: centre on the clip's notes once laid outprivate bool _restoringView; // suppress view-saves while we programmatically restore@@ -783,6 +787,8 @@ public sealed partial class PianoRollView : UserControlif (!_set.SetActive(slot)) return;_trackBrush = slot < _slotBrushes.Count ? _slotBrushes[slot] : _trackBrush;DropControllerCache();+ _ctlClip = (_set.ActiveClip.TrackId, _set.ActiveClip.ClipIndex);+ _ctlLane.ResetGesture();Invalidate();ActiveClipChanged?.Invoke();Changed?.Invoke();@@ -819,6 +825,13 @@ public sealed partial class PianoRollView : UserControl// commits first, then loads.List<(int Pitch, double Start, float Velocity)>? burstVel = null;bool sameClip = _clipKey.Item1 != int.MinValue && _clipKey == _loadedKey;+ // _clipKey is cleared for every multi-clip reload, so it cannot say whether the+ // controller's clip is the same one. The lane edits the active clip; match that.+ bool sameController = _set.IsMulti+ ? _ctlClip.Track != int.MinValue+ && _set.ActiveClip.TrackId == _ctlClip.Track+ && _set.ActiveClip.ClipIndex == _ctlClip.Clip+ : sameClip;if (!_velWheelBurst || !sameClip){EndVelocityWheel(); // a Session slot commits it before the notes are replaced@@ -830,6 +843,8 @@ public sealed partial class PianoRollView : UserControlburstVel.Add((_notes[i].Pitch, _notes[i].StartBeat, _notes[i].Velocity));}DropControllerCache();+ _ctlLane.OnClipReloaded(sameController);+ _ctlClip = (_set.ActiveClip.TrackId, _set.ActiveClip.ClipIndex);ReplaceAll(notes, owners);if (burstVel is not null){diff --git a/src/managed/Nota.Application/Editing/ControllerStroke.cs b/src/managed/Nota.Application/Editing/ControllerStroke.csnew file mode 100644index 00000000..50aa6eae--- /dev/null+++ b/src/managed/Nota.Application/Editing/ControllerStroke.cs@@ -0,0 +1,197 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// A drawn controller stroke replaces only the stretch it covers (specs/063). The curve on+// either side keeps the value it had: the left piece is the same power curve over a shorter+// span (that shaping is a fraction of the segment, so it needs no new exponent), and the+// right piece is refit because a new segment would otherwise start linear and straighten+// everything after the stroke.++using System;+using System.Collections.Generic;++namespace Nota.Application.Editing;++public static class ControllerStroke+{+ /// <summary>Beats between a drawn stretch and the curve it meets. Matches native+ /// <c>kCtlJunction</c>.</summary>+ public const double Junction = 1.0 / 1024.0;++ /// <summary>How far playback outside the stroke may move: one 7-bit CC step+ /// (<c>ctlThinTolerance</c>).</summary>+ public const float Tolerance = 0.008f;++ private const double MinPiece = 1.0 / 128.0;+ private const int MaxSplits = 8;++ /// <summary>The engine's reading of a continuous controller curve+ /// (<c>ControllerCurve::valueAt</c>): held outside the first and last point.</summary>+ public static float ValueAt(IReadOnlyList<AutomationPoint> p, double beat)+ {+ if (p.Count == 0) return 0;+ if (beat <= p[0].Beat) return p[0].Value;+ if (beat >= p[^1].Beat) return p[^1].Value;+ int i = 1;+ while (p[i].Beat <= beat) i++;+ var a = p[i - 1];+ var b = p[i];+ double span = b.Beat - a.Beat;+ if (span <= 0) return b.Value;+ return (float)(a.Value + (b.Value - a.Value) * Shape((beat - a.Beat) / span, a.Curve));+ }++ /// <summary>The curve after drawing <paramref name="samples"/> over <paramref name="orig"/>.+ /// Samples are in clip-local beats. With nothing after the stroke, the drawn value holds.</summary>+ public static List<AutomationPoint> Apply(+ IReadOnlyList<AutomationPoint> orig, IReadOnlyList<(double Beat, float Value)> samples)+ {+ if (samples.Count == 0) return Copy(orig);+ orig = SortedPoints(orig);+ var ordered = Sorted(samples);+ double a = ordered[0].Beat, b = ordered[^1].Beat;+ var outp = new List<AutomationPoint>(orig.Count + ordered.Count + 4);+ foreach (var q in orig)+ if (q.Beat < a - Junction) outp.Add(q);+ if (outp.Count > 0)+ outp.Add(new AutomationPoint(a - Junction, ValueAt(orig, a - Junction)));+ foreach (var (sb, sv) in ordered)+ outp.Add(new AutomationPoint(sb, sv));++ double edge = b + Junction;+ int next = 0;+ while (next < orig.Count && orig[next].Beat <= edge) next++;+ if (next == 0 && orig.Count > 0)+ {+ // The stroke ends before the first point. The old value is held there, so pin it+ // just after the stroke. Without that pin the last drawn value ramps up to the+ // first point and the untouched stretch moves.+ outp.Add(new AutomationPoint(edge, ValueAt(orig, edge)));+ }+ else if (next > 0 && next < orig.Count)+ {+ var left = orig[next - 1];+ var right = orig[next];+ if (edge > left.Beat + 1e-9 && edge < right.Beat)+ EmitRemainder(outp, left, right, edge, right.Beat, 0);+ }+ for (int i = next; i < orig.Count; i++)+ outp.Add(orig[i]);+ return CollapseBeats(outp);+ }++ // The tail of the segment (left → right) from `from` up to `end` (the next stored point,+ // not emitted here). One power curve when it stays within Tolerance; otherwise the piece+ // is halved and each half is shaped on its own.+ private static void EmitRemainder(+ List<AutomationPoint> outp, AutomationPoint left, AutomationPoint right, double from, double end, int depth)+ {+ float value = ValueOn(left, right, from);+ if (Math.Abs(left.Curve) < 1e-6f)+ {+ outp.Add(new AutomationPoint(from, value, 0f));+ return;+ }+ float curve = FitCurve(left, right, from, end, out float err);+ if (err <= Tolerance || depth >= MaxSplits || end - from <= MinPiece)+ {+ outp.Add(new AutomationPoint(from, value, curve));+ return;+ }+ double mid = (from + end) / 2;+ EmitRemainder(outp, left, right, from, mid, depth + 1);+ EmitRemainder(outp, left, right, mid, end, depth + 1);+ }++ private static float FitCurve(+ AutomationPoint left, AutomationPoint right, double from, double end, out float err)+ {+ float bestC = 0f, bestE = float.MaxValue;+ for (int i = 0; i <= 40; i++)+ Consider(-1f + i / 20f);+ float around = bestC;+ for (int i = -10; i <= 10; i++)+ Consider(Math.Clamp(around + i * 0.01f, -1f, 1f));+ err = bestE;+ return bestC;++ void Consider(float c)+ {+ float e = MaxError(left, right, from, end, c);+ if (e < bestE) { bestE = e; bestC = c; }+ }+ }++ private static float MaxError(+ AutomationPoint left, AutomationPoint right, double from, double end, float curve)+ {+ double span = end - from;+ if (span <= 0) return 0;+ float v0 = ValueOn(left, right, from), v1 = ValueOn(left, right, end);+ float err = 0;+ for (int k = 1; k < 16; k++)+ {+ double beat = from + span * k / 16.0;+ float target = ValueOn(left, right, beat);+ double t = (beat - from) / span;+ float got = (float)(v0 + (v1 - v0) * Shape(t, curve));+ float d = Math.Abs(target - got);+ if (d > err) err = d;+ }+ return err;+ }++ private static float ValueOn(AutomationPoint left, AutomationPoint right, double beat)+ {+ double span = right.Beat - left.Beat;+ if (span <= 0) return right.Value;+ double t = Math.Clamp((beat - left.Beat) / span, 0, 1);+ return (float)(left.Value + (right.Value - left.Value) * Shape(t, left.Curve));+ }++ private static double Shape(double t, float curve)+ => curve == 0f ? t : Math.Pow(t, Math.Pow(2.0, -curve * 4.0));++ private static IReadOnlyList<AutomationPoint> SortedPoints(IReadOnlyList<AutomationPoint> orig)+ {+ for (int i = 1; i < orig.Count; i++)+ if (orig[i].Beat < orig[i - 1].Beat)+ {+ var copy = new List<AutomationPoint>(orig);+ copy.Sort((a, b) => a.Beat.CompareTo(b.Beat));+ return copy;+ }+ return orig;+ }++ private static List<(double Beat, float Value)> Sorted(IReadOnlyList<(double Beat, float Value)> samples)+ {+ for (int i = 1; i < samples.Count; i++)+ if (samples[i].Beat < samples[i - 1].Beat)+ {+ var copy = new List<(double Beat, float Value)>(samples);+ copy.Sort((a, b) => a.Beat.CompareTo(b.Beat));+ return copy;+ }+ if (samples is List<(double Beat, float Value)> list) return list;+ return new List<(double Beat, float Value)>(samples);+ }++ private static List<AutomationPoint> Copy(IReadOnlyList<AutomationPoint> orig)+ {+ var copy = new List<AutomationPoint>(orig.Count);+ foreach (var p in orig) copy.Add(p);+ return copy;+ }++ private static List<AutomationPoint> CollapseBeats(List<AutomationPoint> pts)+ {+ var outp = new List<AutomationPoint>(pts.Count);+ foreach (var p in pts)+ {+ if (outp.Count > 0 && Math.Abs(outp[^1].Beat - p.Beat) < 1e-9) outp[^1] = p;+ else outp.Add(p);+ }+ return outp;+ }+}diff --git a/tests/Nota.SmokeTest/ControllerStrokeTests.cs b/tests/Nota.SmokeTest/ControllerStrokeTests.csnew file mode 100644index 00000000..c5c32e16--- /dev/null+++ b/tests/Nota.SmokeTest/ControllerStrokeTests.cs@@ -0,0 +1,95 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Drawing a controller stroke replaces only that stretch (specs/063). Playback on either+// side stays put: the shortened left piece keeps its shaping, and the right piece is refit+// so it does not fall back to a straight line. Also runnable alone:+// `dotnet run --project tests/Nota.SmokeTest -- --controller-stroke`.++using Nota.Application.Editing;++namespace Nota.SmokeTest;++internal static class ControllerStrokeTests+{+ // The engine formula, written out here so the check is not the implementation calling itself.+ private static float Oracle(IReadOnlyList<AutomationPoint> p, double beat)+ {+ if (p.Count == 0) return 0;+ if (beat <= p[0].Beat) return p[0].Value;+ if (beat >= p[^1].Beat) return p[^1].Value;+ int i = 1;+ while (p[i].Beat <= beat) i++;+ var a = p[i - 1];+ var b = p[i];+ double span = b.Beat - a.Beat;+ if (span <= 0) return b.Value;+ double t = (beat - a.Beat) / span;+ double shaped = a.Curve == 0f ? t : Math.Pow(t, Math.Pow(2.0, -a.Curve * 4.0));+ return (float)(a.Value + (b.Value - a.Value) * shaped);+ }++ private static float Worst(IReadOnlyList<AutomationPoint> orig, IReadOnlyList<AutomationPoint> result, double from, double to)+ {+ float worst = 0;+ for (int k = 0; k <= 40; k++)+ {+ double beat = from + (to - from) * k / 40.0;+ float d = Math.Abs(Oracle(orig, beat) - Oracle(result, beat));+ if (d > worst) worst = d;+ }+ return worst;+ }++ public static IEnumerable<(bool Ok, string Label)> Run()+ {+ var shaped = new AutomationPoint[] { new(0, 0f, -1f), new(4, 1f, 0f) };+ var stroke = new (double Beat, float Value)[] { (1, 0.4f), (2, 0.6f) };+ var merged = ControllerStroke.Apply(shaped, stroke);++ yield return (merged.Count > 0 && merged[0].Beat == 0 && merged[0].Curve == -1f,+ "the point before the stroke keeps its curve");+ yield return (Worst(shaped, merged, 0, 1 - 0.05) < 1e-4f,+ "shortening the left of a shaped segment does not move its values");++ float right = Worst(shaped, merged, 2 + 0.01, 4);+ yield return (right <= ControllerStroke.Tolerance + 0.001f,+ $"the curve after the stroke stays within one step (off by {right:0.0000})");++ bool straightTail = true;+ foreach (var p in merged)+ if (p.Beat > 2 && p.Beat < 4 && Math.Abs(p.Curve) > 1e-4f) straightTail = false;+ yield return (!straightTail, "the right-hand boundary keeps a curve instead of going straight");++ var easeOut = new AutomationPoint[] { new(0, 0f, 1f), new(4, 1f, 0f) };+ var eased = ControllerStroke.Apply(easeOut, stroke);+ float outErr = Math.Max(Worst(easeOut, eased, 0, 0.95), Worst(easeOut, eased, 2.01, 4));+ yield return (outErr <= ControllerStroke.Tolerance + 0.001f,+ "an ease-out keeps both sides");++ var linear = new AutomationPoint[] { new(0, 0f, 0f), new(4, 1f, 0f) };+ var lin = ControllerStroke.Apply(linear, stroke);+ yield return (Worst(linear, lin, 0, 0.95) < 1e-4f && Worst(linear, lin, 2.01, 4) < 1e-4f,+ "a straight segment stays straight outside the stroke");+ bool extraCurve = false;+ foreach (var p in lin)+ if (p.Beat > 2 && Math.Abs(p.Curve) > 1e-4f) extraCurve = true;+ yield return (!extraCurve, "a straight tail does not grow a curve");++ var only = ControllerStroke.Apply(Array.Empty<AutomationPoint>(), stroke);+ yield return (only.Count == 2 && only[0].Value == 0.4f && only[1].Value == 0.6f,+ "a stroke on an empty lane is just the stroke");++ var held = ControllerStroke.Apply(new AutomationPoint[] { new(0, 0.25f, 0.5f) }, stroke);+ yield return (held[^1].Beat <= 2 + 1e-6,+ "with nothing after the stroke the drawn value holds");++ // A stroke that ends before the first point must pin the held value. Otherwise the+ // last drawn value ramps across the untouched stretch up to that point.+ var ahead = new AutomationPoint[] { new(4, 1f, 0f) };+ var early = ControllerStroke.Apply(ahead, new (double Beat, float Value)[] { (1, 0.2f), (2, 0f) });+ float at3 = Oracle(early, 3);+ yield return (Math.Abs(at3 - 1f) < 1e-3f,+ $"drawing before the first point leaves the later value (read {at3:0.00} at beat 3)");+ }+}diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 3b18eeb8..ece96dff 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -326,6 +326,14 @@ if (args.Length >= 1 && args[0] == "--tap")Console.WriteLine(failures == 0 ? "TAP PASSED" : $"TAP FAILED ({failures})");return failures == 0 ? 0 : 1;}+// Controller-stroke shaping alone: `--controller-stroke`. Also part of the full run.+if (args.Length >= 1 && args[0] == "--controller-stroke")+{+ Console.WriteLine("-- controller stroke --");+ foreach (var (ok, label) in ControllerStrokeTests.Run()) Check(ok, label);+ Console.WriteLine(failures == 0 ? "CONTROLLER STROKE PASSED" : $"CONTROLLER STROKE FAILED ({failures})");+ return failures == 0 ? 0 : 1;+}// Piano-roll velocity wheel alone: `--velocity-wheel`. Also part of the full run.if (args.Length >= 1 && args[0] == "--velocity-wheel"){@@ -15493,6 +15501,8 @@ foreach (var (ok, label) in MidiLaneHeightTests.Run()) Check(ok, label);Console.WriteLine("-- velocity wheel --");foreach (var (ok, label) in VelocityWheelTests.Run()) Check(ok, label);+Console.WriteLine("-- controller stroke --");+foreach (var (ok, label) in ControllerStrokeTests.Run()) Check(ok, label);Console.WriteLine("-- velocity reset --");foreach (var (ok, label) in VelocityResetTests.Run()) Check(ok, label);Console.WriteLine("-- bend lane range --");