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
Map gamepad sticks and triggers as continuous controls
Egor Khindikaynen53df788ad319
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6da9fa34..8aecc71a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,13 +19,18 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.## [Unreleased]### Added-- **Gamepad buttons can be mapped like a MIDI controller** (macOS). Arm MIDI Learn, click- a control, press a button — that button now drives the control and stops playing its- note, while every unmapped button keeps the built-in layout, so one pad both plays and- mixes. Nothing is reserved: mapping the d-pad takes it over from octave/velocity.- Gamepad sources share the mapping table with CCs and notes, show up in the browser's- MIDI Map tab, and travel with the project. Mappings match on the button rather than the- pad slot, so unplugging and reconnecting a controller does not break them.+- **A gamepad can be mapped like a MIDI controller** (macOS). Arm MIDI Learn, click a+ control, then press a button or move a stick — that control is now driven by the pad.+ A mapped button stops playing its note while every unmapped one keeps the built-in+ layout, so one pad both plays and mixes; nothing is reserved, and mapping the d-pad+ takes it over from octave/velocity.+ - **Sticks and triggers** come along as continuous sources — both axes of each stick and+ the two trigger travels — so a pad can sweep a filter or ride a fader, not just switch+ things. They play no notes and do nothing until mapped. Sticks rest centred behind a+ deadzone so a worn one does not drift a mapped parameter; triggers rest at zero.+ - Gamepad sources share the mapping table with CCs and notes, appear in the browser's+ MIDI Map tab, and travel with the project. Mappings match on the control rather than+ the pad slot, so unplugging and reconnecting a controller does not break them.- **Light theme.** *Ember Paper* joins *Ember Graphite*: the same design system on a warmpaper ground, with brass darkened to bronze so marks keep their weight against a lightbackground. Preferences → Appearance picks Ember Graphite, Ember Paper or System (which@@ -42,6 +47,12 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.- `WaveformView` was still painted in the pre-Ember cool-slate palette; it now uses thetokens its own comments named.+### Fixed+- A MIDI mapping onto a switch (mute, solo, a transport button) fired on every incoming+ message past the half-way point, so sweeping a mapped CC across it made the target+ flutter instead of toggling once. It now fires on the crossing only — which is also what+ makes a mapped gamepad trigger usable.+## [0.38.0] — 2026-09-12### Highlightsdiff --git a/FEATURES.md b/FEATURES.mdindex d099e3d0..b9da569c 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -132,8 +132,13 @@ the mixer opens as a separate floating window (**View → Mixer**, ⌘M).- **Any button can be mapped instead** through MIDI Learn — a mapped button drives thatcontrol and stops playing its note, while the rest of the pad keeps the layout above,so one controller both plays and mixes. Nothing is reserved: mapping the D-pad takes- it over from octave/velocity. Mappings match on the button, not the pad slot, so a+ it over from octave/velocity. Mappings match on the control, not the pad slot, so areplug does not break them.+ - **Sticks and triggers map as continuous controls** — both stick axes on each stick+ plus the two trigger travels, so a pad can sweep a filter or ride a fader, not just+ switch things. They play no notes and do nothing until mapped. Sticks are bipolar and+ rest centred (a deadzone keeps a worn stick from drifting a mapped parameter);+ triggers are unipolar and rest at zero.- **Highlighting** of the pressed key on the roll's keyboard and as a bar along its row.- **Audio→MIDI** (right-click an audio clip → Convert):- **Convert Melody** — monophonic pitch detection (YIN) → a new Nota Synth track.@@ -189,9 +194,11 @@ the mixer opens as a separate floating window (**View → Mixer**, ⌘M).and filter included), track volume/pan/mute/solo, the master, the transport, rackmacros, and chain and Drum Rack pad mute/solo. The **Map** tab in the browser exposesrange, inversion and deletion. Saved with the project.- - Sources are a **CC**, a **MIDI note**, or a **gamepad button** (macOS) — all three- share one mapping table. A button is momentary: it fires a toggle target once on- press, and holds a continuous one at the top of its range until released.+ - Sources are a **CC**, a **MIDI note**, or a **gamepad button, stick or trigger**+ (macOS) — all of them share one mapping table. A button is momentary: it fires a+ toggle target once on press, and holds a continuous one at the top of its range until+ released. A stick or trigger drives a continuous target over its whole travel, and+ fires a toggle target once as it crosses the half-way point.---diff --git a/src/managed/Nota.App/MainWindow.Gamepad.cs b/src/managed/Nota.App/MainWindow.Gamepad.csindex a7c983c6..54201165 100644--- a/src/managed/Nota.App/MainWindow.Gamepad.cs+++ b/src/managed/Nota.App/MainWindow.Gamepad.cs@@ -9,13 +9,15 @@ using Nota.Infrastructure;namespace Nota.App;-/// <summary>Gamepad input: polls the queued button edges every UI tick (hooked off-/// <see cref="MainWindowViewModel.PlayheadUpdated"/>) and gives each one to MIDI-/// Learn first. A button the user has mapped drives that control; everything else-/// falls through to the built-in layout, turning a press into-/// <c>Engine.NoteOn</c>/<c>NoteOff</c> — the exact same entry points as the computer-/// keyboard, so armed-track recording, the piano-roll key highlight, and the engine's-/// velocity handling all apply without a parallel path. Wired in MainWindow.</summary>+/// <summary>Gamepad input, on the UI tick (hooked off+/// <see cref="MainWindowViewModel.PlayheadUpdated"/>). Two shapes, one destination:+/// button edges are drained from the engine's queue, and stick/trigger positions are+/// sampled from its latest-value table. Both go to MIDI Learn first. A control the user+/// has mapped drives that control; every unmapped button falls through to the built-in+/// layout, turning a press into <c>Engine.NoteOn</c>/<c>NoteOff</c> — the exact same+/// entry points as the computer keyboard, so armed-track recording, the piano-roll key+/// highlight, and the engine's velocity handling all apply without a parallel path.+/// Axes have no built-in behaviour: unmapped, they do nothing. Wired in MainWindow.</summary>public partial class MainWindow{// Base pitches (same shape as the computer keyboard's A-row = C4 major scale).@@ -26,6 +28,8 @@ public partial class MainWindowprivate readonly Dictionary<(int pad, int button), int> _gamepadHeldPitch = new();private readonly GamepadButtonEvent[] _gamepadEventBuf = new GamepadButtonEvent[32]; // UI-tick batch+ private readonly int[] _gamepadAxisBuf = new int[(int)GamepadAxis.Count];+ private readonly Dictionary<(int pad, int axis), int> _gamepadAxisLast = new(); // last value dispatchedprivate IGamepadService? _gamepads;private int _gamepadOctave; // semitone shift = *12, mirrored into Settingsprivate int _gamepadPadCount; // last seen pad count — fires PadsChanged on diff@@ -57,7 +61,9 @@ public partial class MainWindow// pending note-off would arrive under a different pad index and never// match its held entry — release everything to avoid a hung note. A pad// joining only appends, so held notes stay valid and keep ringing.- if (count < _gamepadPadCount) ReleaseAllGamepadNotes();+ // …and the same reshuffle would leave the axis cache pointing at the wrong+ // pad, so drop it and let the axes re-seed from their new slots.+ if (count < _gamepadPadCount) { ReleaseAllGamepadNotes(); _gamepadAxisLast.Clear(); }_gamepadPadCount = count;(_gamepads as Infrastructure.GamepadService)?.RaisePadsChanged();}@@ -67,6 +73,42 @@ public partial class MainWindowint n = Engine.PollGamepadEvents(_gamepadEventBuf);for (int i = 0; i < n; i++)HandleGamepadEdge(_gamepadEventBuf[i]);++ PollGamepadAxes(count);+ }++ // Sticks and triggers are sampled, not queued: the engine keeps their latest position+ // and we read it here, so a stick sweep costs one dispatch per tick instead of a+ // hundred queued events. Only a value that actually moved is forwarded, which also+ // keeps a resting pad silent.+ private void PollGamepadAxes(int padCount)+ {+ if (_learn is null) return;+ for (int pad = 0; pad < padCount; pad++)+ {+ int n = Engine.GamepadAxisValues(pad, _gamepadAxisBuf);+ for (int a = 0; a < n; a++)+ {+ int value = _gamepadAxisBuf[a];+ var key = (pad, a);+ // First sight of an axis seeds the last value without dispatching, so a+ // pad that connects with a trigger already held does not fire on arrival.+ if (!_gamepadAxisLast.TryGetValue(key, out int prev)) { _gamepadAxisLast[key] = value; continue; }+ if (value == prev) continue;+ _gamepadAxisLast[key] = value;++ int id = GamepadControls.AxisId((GamepadAxis)a);+ bool consumed = _learn.HandleGamepadAxis(id, value);+ // Flash the Preferences readout as the control leaves rest, not on every+ // sample — a swept stick would otherwise rewrite the label 30 times a second.+ if (prev == GamepadControls.Rest(id) && consumed)+ {+ var mapped = _learn.GamepadMappingFor(id);+ (_gamepads as Infrastructure.GamepadService)?.RaiseActivity(+ pad, mapped is null ? GamepadControls.Name(id) : $"→ {mapped.DisplayName}");+ }+ }+ }}private void HandleGamepadEdge(GamepadButtonEvent ev)@@ -92,7 +134,7 @@ public partial class MainWindow{var mapped = _learn.GamepadMappingFor(ev.ButtonId);(_gamepads as Infrastructure.GamepadService)?.RaiseActivity(- ev.Pad, mapped is null ? GamepadButtons.Name(ev.ButtonId) : $"→ {mapped.DisplayName}");+ ev.Pad, mapped is null ? GamepadControls.Name(ev.ButtonId) : $"→ {mapped.DisplayName}");return;}@@ -111,7 +153,7 @@ public partial class MainWindow// layout. Buttons beyond that are shown but play nothing (options/// share/system buttons).int idx = ev.ButtonId - 1;- if (idx < 0 || idx >= GamepadPitchByButton.Length) { label = GamepadButtons.Name(ev.ButtonId); break; }+ if (idx < 0 || idx >= GamepadPitchByButton.Length) { label = GamepadControls.Name(ev.ButtonId); break; }if (_gamepadHeldPitch.ContainsKey(key)) return; // auto-repeat guardint note = Math.Clamp(GamepadPitchByButton[idx] + _gamepadOctave * 12, 0, 127);diff --git a/src/managed/Nota.App/MidiLearn.cs b/src/managed/Nota.App/MidiLearn.csindex 831240d5..3df8dec7 100644--- a/src/managed/Nota.App/MidiLearn.cs+++ b/src/managed/Nota.App/MidiLearn.cs@@ -1,8 +1,8 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// MIDI Learn — map a hardware controller's CCs/notes, or a gamepad button, onto-// Nota's on-screen controls. The mapping *target* reuses the engine's automation addressing+// MIDI Learn — map a hardware controller's CCs/notes, or a gamepad button, stick+// or trigger, onto Nota's on-screen controls. The mapping *target* reuses the engine's automation addressing// (track + AutomationTarget + device/param index) plus a few globals (master// volume, transport, per-track mute/solo), so an incoming MIDI message can be// applied straight through the existing engine setters, whether or not the@@ -27,19 +27,45 @@ namespace Nota.App;/// apply path — a button edge is just a 0/127 momentary source.</summary>public enum MidiSourceKind { Cc = 0, Note = 1, Gamepad = 2 }-/// <summary>Display names for the button ids that come out of the native gamepad queue:-/// the d-pad has its own sentinels, everything else is a HID usage index whose physical-/// label we cannot know, so it is shown by number.</summary>-public static class GamepadButtons+/// <summary>The gamepad's mappable controls, flattened into one id space so a mapping+/// needs no extra field to say which kind it is. Buttons keep the ids the native queue+/// emits (1..N HID usage, d-pad sentinels at -1000); the six continuous axes sit below+/// them at -2000. A mapping stores the id in <see cref="MidiMapping.Number"/>.</summary>+public static class GamepadControls{- public static string Name(int buttonId) => (GamepadButton)buttonId switch+ private const int AxisBase = -2000;++ public static int AxisId(GamepadAxis axis) => AxisBase - (int)axis;+ public static bool IsAxis(int controlId) => controlId <= AxisBase && controlId > AxisBase - (int)GamepadAxis.Count;+ public static GamepadAxis Axis(int controlId) => (GamepadAxis)(AxisBase - controlId);++ /// <summary>Where an idle control sits, in the 0..127 scale the engine reports:+ /// a spring-centred stick returns to the middle, a trigger falls back to zero.+ /// Used to tell a deliberate move from a control settling back to rest.</summary>+ public static int Rest(int controlId)+ => IsAxis(controlId) && Axis(controlId) is not (GamepadAxis.LeftTrigger or GamepadAxis.RightTrigger) ? 64 : 0;++ public static string Name(int controlId){- GamepadButton.DpadUp => "D-pad ↑",- GamepadButton.DpadDown => "D-pad ↓",- GamepadButton.DpadLeft => "D-pad ←",- GamepadButton.DpadRight => "D-pad →",- _ => $"Button {buttonId}",- };+ if (IsAxis(controlId))+ return Axis(controlId) switch+ {+ GamepadAxis.LeftX => "Left stick ←→",+ GamepadAxis.LeftY => "Left stick ↑↓",+ GamepadAxis.RightX => "Right stick ←→",+ GamepadAxis.RightY => "Right stick ↑↓",+ GamepadAxis.LeftTrigger => "Left trigger",+ _ => "Right trigger",+ };+ return (GamepadButton)controlId switch+ {+ GamepadButton.DpadUp => "D-pad ↑",+ GamepadButton.DpadDown => "D-pad ↓",+ GamepadButton.DpadLeft => "D-pad ←",+ GamepadButton.DpadRight => "D-pad →",+ _ => $"Button {controlId}",+ };+ }}/// <summary>What a mapping drives. The first three mirror <see cref="AutomationTarget"/>;@@ -126,15 +152,20 @@ public sealed class MidiMappingpublic string DisplayName { get; set; } = "";public MidiSourceKind SourceKind { get; init; }public int Channel { get; init; } // 0..15 (unused, and always 0, for Gamepad)- public int Number { get; init; } // CC number, note pitch, or gamepad button id+ public int Number { get; init; } // CC number, note pitch, or GamepadControls idpublic double RangeMin { get; set; } // normalized output floorpublic double RangeMax { get; set; } = 1; // normalized output ceilingpublic bool Invert { get; set; }+ /// <summary>Last on/off state applied to a button target, so only the crossing fires.+ /// Runtime state, not part of the mapping — a swept CC or a squeezed trigger sends a+ /// run of values past the threshold, and every one of them used to toggle.</summary>+ internal bool TriggerLatch { get; set; }+public string SourceLabel => SourceKind switch{MidiSourceKind.Cc => $"CC {Number} · ch{Channel + 1}",- MidiSourceKind.Gamepad => $"Pad · {GamepadButtons.Name(Number)}",+ MidiSourceKind.Gamepad => $"Pad · {GamepadControls.Name(Number)}",_ => $"Note {Number} · ch{Channel + 1}",};}diff --git a/src/managed/Nota.App/MidiLearnService.cs b/src/managed/Nota.App/MidiLearnService.csindex 2b3c5cd8..830ea9ad 100644--- a/src/managed/Nota.App/MidiLearnService.cs+++ b/src/managed/Nota.App/MidiLearnService.cs@@ -85,11 +85,11 @@ public sealed class MidiLearnService/// <summary>The mapping bound to <paramref name="target"/>, if any (for the "mapped" badge).</summary>public MidiMapping? MappingFor(MidiTarget target) => _mappings.FirstOrDefault(m => m.Target.Equals(target));- /// <summary>The mapping a gamepad button drives, if any. Matched on the button alone,+ /// <summary>The mapping a gamepad control drives, if any. Matched on the control alone,/// not on which pad sent it: pad slots reshuffle when a controller is unplugged, so/// binding to a slot would silently break the mapping on the next replug.</summary>- public MidiMapping? GamepadMappingFor(int buttonId)- => _mappings.FirstOrDefault(m => m.SourceKind == MidiSourceKind.Gamepad && m.Number == buttonId);+ public MidiMapping? GamepadMappingFor(int controlId)+ => _mappings.FirstOrDefault(m => m.SourceKind == MidiSourceKind.Gamepad && m.Number == controlId);/// <summary>Feed a gamepad button edge through the learn/dispatch machine. Returns/// true when the edge was consumed — it bound the pending control, or it drove a@@ -100,7 +100,7 @@ public sealed class MidiLearnServiceif (pressed && _pending is { } p){Bind(p, MidiSourceKind.Gamepad, 0, buttonId);- LogMidi($"MIDI learn: gamepad {GamepadButtons.Name(buttonId)} → bound to '{p.Name}'");+ LogMidi($"MIDI learn: gamepad {GamepadControls.Name(buttonId)} → bound to '{p.Name}'");_padBoundOnPress = buttonId;return true;}@@ -117,6 +117,25 @@ public sealed class MidiLearnServicereturn Dispatch(MidiSourceKind.Gamepad, 0, buttonId, pressed ? 127 : 0) > 0;}+ // How far a stick or trigger must leave its rest position to count as a deliberate+ // move rather than a spring settling back. Only gates *learning*: once bound, the+ // whole travel drives the target.+ private const int AxisLearnThreshold = 24;++ /// <summary>Feed a gamepad stick or trigger position (0..127) through the same machine.+ /// Sampled on the UI tick, so call it only when the value actually moved. Returns true+ /// when it bound the pending control or drove a mapping.</summary>+ public bool HandleGamepadAxis(int axisId, int value127)+ {+ if (_pending is { } p && Math.Abs(value127 - GamepadControls.Rest(axisId)) >= AxisLearnThreshold)+ {+ Bind(p, MidiSourceKind.Gamepad, 0, axisId);+ LogMidi($"MIDI learn: gamepad {GamepadControls.Name(axisId)} → bound to '{p.Name}'");+ return true;+ }+ return Dispatch(MidiSourceKind.Gamepad, 0, axisId, value127) > 0;+ }+public void RemoveMapping(MidiMapping m){if (_mappings.Remove(m)) MappingsChanged?.Invoke();@@ -229,9 +248,14 @@ public sealed class MidiLearnServicevar t = m.Target;if (t.IsButton){- // Trigger on a note-on or a CC crossing the half-way point.- bool trigger = m.SourceKind == MidiSourceKind.Note ? value127 > 0 : value127 >= 64;- if (!m.Invert ? trigger : !trigger) Trigger(t);+ // A note-on, or anything else crossing the half-way point. Latch on the edge:+ // a swept CC or a squeezed trigger sends a run of values past the threshold,+ // and toggling on each one would make the target flutter.+ bool on = m.SourceKind == MidiSourceKind.Note ? value127 > 0 : value127 >= 64;+ if (m.Invert) on = !on;+ if (on == m.TriggerLatch) return;+ m.TriggerLatch = on;+ if (on) Trigger(t);return;}diff --git a/src/managed/Nota.App/MidiMapView.cs b/src/managed/Nota.App/MidiMapView.csindex d1e47d33..9d302c03 100644--- a/src/managed/Nota.App/MidiMapView.cs+++ b/src/managed/Nota.App/MidiMapView.cs@@ -39,7 +39,7 @@ public sealed class MidiMapView : UserControl{_rows.Children.Add(new TextBlock{- Text = "No mappings yet.\n\nClick MIDI (top-right), then click any highlighted\ncontrol and move a knob or fader on your controller —\nor press a button on a connected gamepad.",+ Text = "No mappings yet.\n\nClick MIDI (top-right), then click any highlighted\ncontrol and move a knob or fader on your controller —\nor press a button or move a stick on a gamepad.",FontSize = 11, TextWrapping = TextWrapping.Wrap, LineHeight = 16,Margin = new Avalonia.Thickness(6, 10), Foreground = NotaPalette.TextTertiary,});diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.csindex 05dd0d1e..098a1ce2 100644--- a/src/managed/Nota.App/PreferencesWindow.cs+++ b/src/managed/Nota.App/PreferencesWindow.cs@@ -371,7 +371,7 @@ public sealed class PreferencesWindow : NotaWindowbody.Children.Add(DividerLine());body.Children.Add(SectionLabel("LAYOUT"));body.Children.Add(Caption("Face buttons play C4 D4 E4 F4 · shoulder buttons play G4 A4 B4 C5 · d-pad up/down shifts the octave · d-pad left/right nudges velocity. Notes go to the armed (record-enabled) instrument track — enable Record to capture them, or use the audition track to just play."));- body.Children.Add(Caption("Any button can be mapped to a control instead: click MIDI in the top-right, click the control, then press the button. A mapped button drives that control and stops playing its note; the rest of the pad keeps the layout above. Mappings are listed in the browser's MIDI Map tab and travel with the project."));+ body.Children.Add(Caption("Any button can be mapped to a control instead: click MIDI in the top-right, click the control, then press the button. A mapped button drives that control and stops playing its note; the rest of the pad keeps the layout above. The sticks and the trigger travel map the same way and are continuous, so they suit a knob or a fader — they play no notes, and do nothing until mapped. Mappings are listed in the browser's MIDI Map tab and travel with the project."));return body;}@@ -609,6 +609,7 @@ public sealed class PreferencesWindow : NotaWindow("D-pad ↑ / ↓", "Shift the gamepad octave"),("D-pad ← / →", "Lower / raise velocity"),("Any button", "Mappable through MIDI Learn — a mapped button drives the control instead"),+ ("Sticks · triggers", "Mappable as continuous controls (a knob, a fader); they play no notes"),}),("MOUSE", new[]{diff --git a/src/managed/Nota.Application/Engine/EngineContracts.cs b/src/managed/Nota.Application/Engine/EngineContracts.csindex 5ab2575a..9e388950 100644--- a/src/managed/Nota.Application/Engine/EngineContracts.cs+++ b/src/managed/Nota.Application/Engine/EngineContracts.cs@@ -171,6 +171,17 @@ public enum GamepadButtonDpadRight = -1003,}+/// <summary>The pad's continuous controls, in the order+/// <see cref="IAudioEngine.GamepadAxisValues"/> writes them. Values are 0..127: a stick+/// axis is bipolar and rests at 64, trigger travel is unipolar and rests at 0. The+/// triggers also fire L2/R2 button edges — the edge plays a note, the travel drives a+/// mapped parameter.</summary>+public enum GamepadAxis+{+ LeftX = 0, LeftY = 1, RightX = 2, RightY = 3, LeftTrigger = 4, RightTrigger = 5,+ Count = 6,+}+/// <summary>An Instrument Rack macro mapping: macro <paramref name="Macro"/> drives the target/// param over [<paramref name="RangeMin"/>, <paramref name="RangeMax"/>] in the target's own units./// <paramref name="DeviceIndex"/> < 0 targets the chain's instrument (plugin-param index);diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.csindex bbaf727b..275a70bf 100644--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs@@ -660,6 +660,11 @@ public interface IAudioEngine : IDisposableint GamepadCount { get; }IReadOnlyList<GamepadDevice> Gamepads();int PollGamepadEvents(GamepadButtonEvent[] buffer);+ /// <summary>Latest position of every axis on <paramref name="pad"/>, written into+ /// <paramref name="buffer"/> in <see cref="GamepadAxis"/> order as 0..127. Returns the+ /// count written (0 for an out-of-range pad). Sampled rather than queued: a stick+ /// would flood an event ring and only its latest position matters.</summary>+ int GamepadAxisValues(int pad, int[] buffer);// --- Audio preview / audition (M7-4a) ----------------------------------void PreviewFile(string path);diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Gamepad.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Gamepad.csindex d84df731..0ccb87e0 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Gamepad.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Gamepad.cs@@ -27,4 +27,7 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_gamepad_poll_events")]internal static partial int GamepadPollEvents(IntPtr engine, [Out] GamepadButtonEvent[] buf, int max);++ [LibraryImport(Lib, EntryPoint = "nota_gamepad_axis_values")]+ internal static partial int GamepadAxisValues(IntPtr engine, int pad, [Out] int[] buf, int max);}diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Gamepad.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Gamepad.csindex 197391b6..846acc59 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Gamepad.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Gamepad.cs@@ -43,4 +43,14 @@ public sealed partial class NotaEngineif (buffer is null || buffer.Length < 1) return 0;return NativeMethods.GamepadPollEvents(_handle, buffer, buffer.Length);}++ /// <summary>Latest position of each axis on <paramref name="pad"/>, 0..127 in+ /// <see cref="GamepadAxis"/> order (sticks centre at 64, triggers rest at 0). Sampled+ /// on the UI tick rather than queued — see nota_gamepad_axis_values.</summary>+ public int GamepadAxisValues(int pad, int[] buffer)+ {+ ThrowIfDisposed();+ if (buffer is null || buffer.Length < 1) return 0;+ return NativeMethods.GamepadAxisValues(_handle, pad, buffer, buffer.Length);+ }}diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.hindex 965f4ba0..ce7f0227 100644--- a/src/native/nota.engine/include/nota/nota_engine.h+++ b/src/native/nota.engine/include/nota/nota_engine.h@@ -1223,10 +1223,11 @@ NOTA_API int32_t nota_midi_poll_control_events(NotaEngine* engine, int32_t** drained into `out` with nota_gamepad_poll_events(). The UI then maps each* edge to nota_engine_note_on / nota_engine_note_off — the same entry points* the computer keyboard uses, so live play, armed-track recording and the- * piano-roll key highlight all reuse the existing pipeline. Only buttons are- * reported (d-pad hats resolve to U/D/L/R buttons); sticks/triggers are not- * note input and are ignored in v1. Currently macOS only; other platforms- * report zero pads. */+ * piano-roll key highlight all reuse the existing pipeline. Buttons are edges+ * (d-pad hats resolve to U/D/L/R buttons); sticks and trigger travel are+ * continuous and are read as latest values instead, with+ * nota_gamepad_axis_values(). Currently macOS only; other platforms report+ * zero pads. *//* One button edge: pressed = 1 down / 0 up. buttonId identifies the control* (1..N = HID button usage; DpadUp/Down/Left/Right = -1000..-1003).@@ -1259,6 +1260,27 @@ NOTA_API const char* nota_gamepad_name(NotaEngine* engine, int32_t index);* Returns the count written (<= max). Call from a UI-thread tick. */NOTA_API int32_t nota_gamepad_poll_events(NotaEngine* engine, NotaGamepadButtonEvent* out, int32_t max);+/* The pad's continuous controls, in this order. A stick axis is bipolar and+ * rests centred; trigger travel is unipolar and rests at zero. The triggers+ * also fire button edges (L2/R2) — the edge is for note play, the travel for a+ * mapped parameter. */+typedef enum NotaGamepadAxis {+ NOTA_GAMEPAD_AXIS_LEFT_X = 0,+ NOTA_GAMEPAD_AXIS_LEFT_Y,+ NOTA_GAMEPAD_AXIS_RIGHT_X,+ NOTA_GAMEPAD_AXIS_RIGHT_Y,+ NOTA_GAMEPAD_AXIS_LEFT_TRIGGER,+ NOTA_GAMEPAD_AXIS_RIGHT_TRIGGER,+ NOTA_GAMEPAD_AXIS_COUNT+} NotaGamepadAxis;++/* Latest position of every axis on pad `pad`, written to `out` in+ * NotaGamepadAxis order as 0..127 (sticks centre at 64, triggers rest at 0).+ * Returns the count written, 0 for an out-of-range pad. Unlike button edges+ * these are not queued: a stick would flood a ring and only the latest position+ * matters, so the UI samples this on its own tick. */+NOTA_API int32_t nota_gamepad_axis_values(NotaEngine* engine, int32_t pad, int32_t* out, int32_t max);+#ifdef __cplusplus} /* extern "C" */diff --git a/src/native/nota.engine/src/Engine.cpp b/src/native/nota.engine/src/Engine.cppindex 6942df75..20da40e7 100644--- a/src/native/nota.engine/src/Engine.cpp+++ b/src/native/nota.engine/src/Engine.cpp@@ -120,6 +120,9 @@ void Engine::gamepadInfo(int32_t i, const char** uid, const char** name) constint32_t Engine::pollGamepadEvents(GamepadInput::ButtonEvent* out, int32_t max) {return (gamepadInput_ && out && max > 0) ? gamepadInput_->pollEvents(out, max) : 0;}+int32_t Engine::gamepadAxisValues(int32_t pad, int32_t* out, int32_t max) const {+ return (gamepadInput_ && out && max > 0) ? gamepadInput_->axisValues(pad, out, max) : 0;+}void Engine::stop() {if (midiInput_) midiInput_->close();diff --git a/src/native/nota.engine/src/Engine.h b/src/native/nota.engine/src/Engine.hindex 516fbe95..3fbe8cc8 100644--- a/src/native/nota.engine/src/Engine.h+++ b/src/native/nota.engine/src/Engine.h@@ -102,6 +102,7 @@ public:int32_t gamepadCount() const;void gamepadInfo(int32_t i, const char** outUid, const char** outName) const;int32_t pollGamepadEvents(GamepadInput::ButtonEvent* out, int32_t max);+ int32_t gamepadAxisValues(int32_t pad, int32_t* out, int32_t max) const;// --- audio preview / audition (M7-4a) ---// Decode a file and mix it into the live output without a track, so thediff --git a/src/native/nota.engine/src/GamepadInput.h b/src/native/nota.engine/src/GamepadInput.hindex b5f82b01..ac9ab1a0 100644--- a/src/native/nota.engine/src/GamepadInput.h+++ b/src/native/nota.engine/src/GamepadInput.h@@ -15,8 +15,13 @@// GCController decodes the report properly and is silent when idle.//// The face buttons (A/B/X/Y) map to logical buttons 1..4, the shoulders and-// triggers (L1/R1/L2/R2) to 5..8, and the d-pad to U/D/L/R events; sticks are-// ignored (this is note input, not CC). A pad is identified by a session uid.+// triggers (L1/R1/L2/R2) to 5..8, and the d-pad to U/D/L/R events. A pad is+// identified by a session uid.+//+// Sticks and trigger travel are continuous, so they are NOT queued as events:+// a stick would flood the ring in a few frames and the UI only ever wants the+// latest position anyway. They live in a small latest-value table the UI reads+// on its tick (axisValues), which coalesces by construction and cannot overflow.//// v1 is macOS-only; Win (XInput/RawInput) and Linux (evdev) come next.@@ -54,6 +59,11 @@ public:// drop on overflow — losing a few edges on a saturated tick is fine.int32_t pollEvents(ButtonEvent* out, int32_t max);+ // Latest position of every axis on pad `i`, written in GamepadAxis order as+ // 0..127: sticks rest at 64, trigger travel rests at 0. Returns the count+ // written (0 if the pad index is out of range).+ int32_t axisValues(int32_t i, int32_t* out, int32_t max) const;+struct Impl;private:Impl* impl_ = nullptr;@@ -70,4 +80,13 @@ namespace GamepadButton {inline constexpr bool isDpad(int32_t id) { return id >= DpadRight && id <= DpadUp; }}+// The continuous controls, in the order axisValues() writes them. Triggers are+// reported twice on purpose: as a button edge (L2/R2, for note play) and as+// travel (for a mapped parameter), because those are two different questions.+namespace GamepadAxis {+ inline constexpr int32_t LeftX = 0, LeftY = 1, RightX = 2, RightY = 3;+ inline constexpr int32_t LeftTrigger = 4, RightTrigger = 5;+ inline constexpr int32_t Count = 6;+}+} // namespace notadiff --git a/src/native/nota.engine/src/GamepadInput.mm b/src/native/nota.engine/src/GamepadInput.mmindex 9a5decb2..050c37e2 100644--- a/src/native/nota.engine/src/GamepadInput.mm+++ b/src/native/nota.engine/src/GamepadInput.mm@@ -11,7 +11,9 @@#import <GameController/GameController.h>#import <Foundation/Foundation.h>+#include <algorithm>#include <atomic>+#include <cmath>#include <cstdint>#include <memory>#include <mutex>@@ -31,8 +33,29 @@ struct Pad {std::string name;bool lastBtn[9] = {false}; // indexed by logical id 1..8bool lastDpad[4] = {false}; // up, down, left, right+ // Latest axis positions, 0..127. Written on the handler queue, read on the+ // UI thread, so each one is atomic; there is nothing to synchronise between+ // them (a torn read across two axes is a frame of skew nobody can feel).+ std::atomic<int32_t> axis[GamepadAxis::Count] = {};};+// A thumbstick rests near zero but rarely at zero. Snap the dead centre out and+// rescale what is left, so a worn stick does not drift a mapped parameter and+// the first millimetre of real travel still reads as the bottom of the range.+constexpr float kStickDeadzone = 0.10f;++int32_t quantizeStick(float v) {+ v = std::clamp(v, -1.0f, 1.0f);+ float a = std::fabs(v);+ a = a <= kStickDeadzone ? 0.0f : (a - kStickDeadzone) / (1.0f - kStickDeadzone);+ if (v < 0) a = -a;+ return static_cast<int32_t>(std::lround(a * 63.5f + 63.5f)); // -1..1 -> 0..127, centre 64+}++int32_t quantizeTrigger(float v) {+ return static_cast<int32_t>(std::lround(std::clamp(v, 0.0f, 1.0f) * 127.0f));+}+struct State {std::atomic<bool> running{false};std::mutex padsMutex;@@ -88,6 +111,14 @@ void syncState(State* s, Pad* p) {dpad(1, GamepadButton::DpadDown, g.dpad.down.isPressed);dpad(2, GamepadButton::DpadLeft, g.dpad.left.isPressed);dpad(3, GamepadButton::DpadRight, g.dpad.right.isPressed);++ // Continuous controls: overwrite rather than queue (see GamepadInput.h).+ p->axis[GamepadAxis::LeftX].store(quantizeStick(g.leftThumbstick.xAxis.value), std::memory_order_relaxed);+ p->axis[GamepadAxis::LeftY].store(quantizeStick(g.leftThumbstick.yAxis.value), std::memory_order_relaxed);+ p->axis[GamepadAxis::RightX].store(quantizeStick(g.rightThumbstick.xAxis.value), std::memory_order_relaxed);+ p->axis[GamepadAxis::RightY].store(quantizeStick(g.rightThumbstick.yAxis.value), std::memory_order_relaxed);+ p->axis[GamepadAxis::LeftTrigger].store(quantizeTrigger(g.leftTrigger.value), std::memory_order_relaxed);+ p->axis[GamepadAxis::RightTrigger].store(quantizeTrigger(g.rightTrigger.value), std::memory_order_relaxed);}void addController(State* s, GCController* c) {@@ -97,6 +128,12 @@ void addController(State* s, GCController* c) {for (auto& up : s->pads) if (up->controller == c) return; // already trackedif (s->pads.size() >= 8) return; // UI capauto pad = std::make_unique<Pad>();+ // Sticks rest centred, so a pad that has never been touched must read 64+ // rather than 0 — otherwise it looks like both sticks are hard left/down.+ pad->axis[GamepadAxis::LeftX].store(64, std::memory_order_relaxed);+ pad->axis[GamepadAxis::LeftY].store(64, std::memory_order_relaxed);+ pad->axis[GamepadAxis::RightX].store(64, std::memory_order_relaxed);+ pad->axis[GamepadAxis::RightY].store(64, std::memory_order_relaxed);pad->controller = [c retain];pad->uid = "gc-" + std::to_string(reinterpret_cast<uintptr_t>(c));pad->name = c.vendorName ? std::string(c.vendorName.UTF8String) : "Gamepad";@@ -190,6 +227,16 @@ void GamepadInput::padInfo(int32_t i, const char** outUid, const char** outName)*outName = impl_->state.snapshotNames[i].c_str();}+int32_t GamepadInput::axisValues(int32_t i, int32_t* out, int32_t max) const {+ if (!out || max <= 0) return 0;+ std::lock_guard<std::mutex> lock(impl_->state.padsMutex);+ if (i < 0 || i >= static_cast<int32_t>(impl_->state.pads.size())) return 0;+ const Pad* p = impl_->state.pads[i].get();+ int32_t n = std::min(max, GamepadAxis::Count);+ for (int32_t a = 0; a < n; ++a) out[a] = p->axis[a].load(std::memory_order_relaxed);+ return n;+}+int32_t GamepadInput::pollEvents(ButtonEvent* out, int32_t max) {if (!out || max <= 0) return 0;int32_t n = 0;diff --git a/src/native/nota.engine/src/GamepadInput_stub.cpp b/src/native/nota.engine/src/GamepadInput_stub.cppindex 12131a2c..5be4de32 100644--- a/src/native/nota.engine/src/GamepadInput_stub.cpp+++ b/src/native/nota.engine/src/GamepadInput_stub.cpp@@ -23,5 +23,6 @@ void GamepadInput::padInfo(int32_t, const char** outUid, const char** outName) c*outName = "";}int32_t GamepadInput::pollEvents(ButtonEvent*, int32_t) { return 0; }+int32_t GamepadInput::axisValues(int32_t, int32_t*, int32_t) const { return 0; }} // namespace notadiff --git a/src/native/nota.engine/src/nota_engine_audio.cpp b/src/native/nota.engine/src/nota_engine_audio.cppindex bed76936..9712e710 100644--- a/src/native/nota.engine/src/nota_engine_audio.cpp+++ b/src/native/nota.engine/src/nota_engine_audio.cpp@@ -161,4 +161,9 @@ int32_t nota_gamepad_poll_events(NotaEngine* e, NotaGamepadButtonEvent* out, intreinterpret_cast<nota::GamepadInput::ButtonEvent*>(out), max);}+int32_t nota_gamepad_axis_values(NotaEngine* e, int32_t pad, int32_t* out, int32_t max) {+ if (!e || !out || max <= 0) return 0;+ return ENG(e)->gamepadAxisValues(pad, out, max);+}+} // extern "C"