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
(feat) Modular Scope: resize, pop-out window, time window, zoom, trigger and freeze (#266) (#359)
Chris Laupama6c9143dfd5b8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 051996d6..8b1b96f3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,6 +23,12 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.## [Unreleased]### Added+- **A bigger, more useful Modular Scope** (#266): drag the bar under the trace to make it+ taller (76–320 px), or open the Scope in its own resizable window. New controls: a time+ window in milliseconds (50 ms–8 s) or, with **Sync**, in beats (1/16 to 8 bars) at the+ current tempo; a 1×–8× vertical zoom; a **Rise** trigger that starts the trace where the+ input rises through 0, so a repeating shape holds still; and **Freeze**. The settings and+ the height are saved with the project; older projects open with a 1 s window, as before.- **Fold the piano roll** (nota-daw/nota#344, #345): **Fold** in the piano roll toolbar (⌥⇧F)shows only the scale's notes on a melodic track, or only the pads, each row named after itspad, on a Drum Rack. Pitches that hold notes keep their rows, so nothing is hidden. ↑/↓ anddiff --git a/FEATURES.md b/FEATURES.mdindex bd85ec3f..77cb121d 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -187,8 +187,10 @@ track count and closes with Escape.Modulators: **LFO** (with phase), an **envelope follower**, **MIDI→CV**(velocity/gate/note), **ADSR** (gated by notes), **Macro** (a manual control → CV) and**Math** (two CV inputs → one output); any parameter can also be a CV source- (param → param). A **CV Scope** oscilloscope reads any modulator signal, and CV ports are- drawn only where they actually work.+ (param → param). A **CV Scope** oscilloscope reads any modulator signal: drag its trace+ taller (76–320 px) or open it in its own window, set its time window in ms or in beats,+ zoom it 1–8×, hold a repeating shape still with a rising-edge trigger, or freeze it. CV+ ports are drawn only where they actually work.---diff --git a/specs/047-scope-view/plan.md b/specs/047-scope-view/plan.mdnew file mode 100644index 00000000..e79a424a--- /dev/null+++ b/specs/047-scope-view/plan.md@@ -0,0 +1,36 @@+# Plan: Scope view++## Engine++- `ScopeHistory` (Modulation.h): a ring of 8192 (value, dt) pairs and a 64-bit write count.+ 8192 blocks hold the longest window (8 s) down to 64-frame blocks at 48 kHz.+- A `Modulator` holds a `shared_ptr<ScopeHistory>`, allocated in `addModulator` for Scope+ nodes only (message thread). Snapshot copies of the track share it, so the trace carries on+ across a republish. The audio thread only writes values into it (`pushScope(v, dt)`, no+ allocation); the old snapshot drops its reference wherever it is retired today.+- `readScope(values, dts, cap)` returns the newest entries oldest → newest, at most the+ recorded count and at most `kScopeLen − 256` (a margin the writer may reach while the UI+ copies).+- Fields 13–18 on the generic modulator get/set: window ms, sync, window beats, zoom (snapped+ to 1/2/4/8), trigger, height. The engine only stores them.+- ABI: `nota_track_modulator_scope_timed`. The untimed `nota_track_modulator_scope` stays and+ now also returns the newest values.++## App++- `ScopeTrace` (Nota.Application): window seconds, knob maps, labels, and `Layout`, which lays+ the history into the window (free running, or from the latest rising crossing of 0 with a+ full window after it, interpolated between blocks).+- `ModularView.Scope.cs`: the Scope node (trace, resize grip, window/zoom knobs, Free / Rise /+ Freeze chips) and `ScopeViz`. A pop-out glyph in the node header opens `ScopeWindow`, which+ builds the same trace and controls. Both follow the engine fields every tick and rebuild+ when a chip changes on the other copy. Freeze lives in the Modular view (not saved).+- Persistence: `ModulatorDto` gains optional Scope fields with the defaults; Capture writes+ them, Apply sets them for Scope nodes. No format bump.++## Tests++`--scope` (`ScopeViewTests`): history per block with time steps, newest-first reads, a full+ring, untimed read, survives a republish; defaults, clamps, save/load, older-project defaults;+`ScopeTrace` cycles in a window, beat window, trigger stability, no-crossing fallback,+right-aligned short history, layout cost, labels.diff --git a/specs/047-scope-view/spec.md b/specs/047-scope-view/spec.mdnew file mode 100644index 00000000..52189f7c--- /dev/null+++ b/specs/047-scope-view/spec.md@@ -0,0 +1,127 @@+# Feature Specification: Scope view++**Feature Branch**: `feat/scope-view`++**Created**: 2026-10-28++**Status**: Draft++**Input**: User description: "Scope: resizable / pop-out view with basic controls+(nota-daw/nota#266). The Modular Scope node is too small to be useful and can't be made bigger.+It should be resizable inside the card, with a pop-out / full-width view, and have basic+controls: time window (ms or beat-synced), vertical zoom, trigger (free / rising edge), freeze."++## User Scenarios & Testing *(mandatory)*++### User Story 1 - See a modulator's shape at a useful size (Priority: P1)++A sound designer patches an LFO into a Scope node to see what it does. Today the trace is a+76 px strip that rolls past in about a second, whatever the LFO's rate. They drag the bottom+edge of the scope to make it taller, or open it in its own window, and set the time window so+one or two cycles fill it.++**Why this priority**: The issue's first complaint is size; without it the other controls have+nowhere to live.++**Independent Test**: Add a Scope, patch an LFO in, drag the scope's bottom edge down, and open+the pop-out. Both show the same live trace at the new size.++**Acceptance Scenarios**:++1. **Given** a Scope node, **When** the user drags the grip under its trace, **Then** the trace+ grows or shrinks between 76 px and 320 px tall, and the node's card grows with it.+2. **Given** a resized Scope, **When** the project is saved and reopened, **Then** it keeps its+ height.+3. **Given** a Scope node, **When** the user clicks its expand button, **Then** a separate,+ resizable window opens with the same live trace and the same controls, titled after the+ track and the node; closing it leaves the node as it was.+4. **Given** the pop-out is open, **When** the node is deleted or the track is removed, **Then**+ the window closes.++---++### User Story 2 - Time window, zoom, trigger, freeze (Priority: P1)++The user sets the window to 1 bar so an LFO synced to 1/4 shows four cycles that line up with+the beat. They raise the zoom on a shallow envelope, turn the trigger on so a repeating shape+holds still instead of rolling, and freeze the trace to look at one moment.++**Why this priority**: These are the "basic controls" the issue lists.++**Independent Test**: With an LFO at 1/4 synced, set the window to 1 bar and see four cycles;+turn Trigger on and see the trace stop rolling; Freeze and see it hold while the LFO keeps+running.++**Acceptance Scenarios**:++1. **Given** the time window in **ms**, **When** the user sets it between 50 ms and 8 s,+ **Then** the trace spans exactly that much time, newest at the right.+2. **Given** the time window in **beats** (**Sync** on), **When** the user picks 1/4 beat to+ 8 bars, **Then** the trace spans that many beats at the current tempo, and follows a tempo+ change.+3. **Given** a zoom of 1×, 2×, 4× or 8×, **Then** the vertical scale is ±1.15 divided by the zoom+ (a trace that leaves the scale is clipped at the edge).+4. **Given** Trigger on (rising edge), **When** the input crosses the trigger level (0) going up,+ **Then** the trace starts at the latest such crossing that leaves a full window after it, so+ a periodic signal holds still. With no crossing in the history the trace rolls as with+ Trigger off.+5. **Given** Freeze on, **Then** the trace stops updating while the input keeps running; Freeze+ off resumes the live trace.+6. **Given** these settings, **When** the project is saved and reopened, **Then** the window,+ Sync, zoom, trigger and trace height come back; Freeze always starts off.++### Edge Cases++- **Not enough history**: a window longer than what the scope has recorded (right after it is+ added, or at a very long window) draws what there is, right-aligned.+- **Transport stopped**: the scope keeps recording (modulators run while stopped), so an LFO+ stays visible.+- **Block-rate CV**: the scope records one value per audio block (a few ms). At the shortest+ window the trace is a few dozen points; it is drawn as straight segments between them.+- **Unwired scope**: the hint text stays as today; the controls stay usable.+- **Older projects**: a Scope saved before this change opens at 76 px, a 1 s window, 1×, free+ running.++## Requirements *(mandatory)*++### Functional Requirements++- **FR-001**: The engine MUST record a Scope's input with each value's time step, at least 4096+ values, written only by the audio thread and read lock-free by the UI. Only Scope nodes hold+ the buffer.+- **FR-002**: Reading the scope MUST return the newest values (oldest → newest) with their time+ steps.+- **FR-003**: A Scope MUST have saved settings: window in ms (50–8000, default 1000), Sync+ (off by default), window in beats (0.25–32, default 4), zoom (1, 2, 4 or 8, default 1) and+ trigger (free or rising, default free), readable and writable like its other fields.+- **FR-004**: The Scope node MUST show controls for window (ms or beats with a Sync switch),+ zoom, trigger and freeze, under the trace.+- **FR-005**: The trace MUST be resizable by a grip, 76–320 px, saved with the Scope (field 18).+- **FR-006**: An expand button MUST open the scope in its own resizable window with the same+ trace and controls.+- **FR-007**: Freeze MUST be a view state only (not saved).++### Key Entities++- **Scope history**: a ring of (value, time step) pairs owned by a Scope modulator.+- **Scope settings**: window (ms / beats, Sync), zoom, trigger — modulator fields saved with the+ project.++## Success Criteria *(mandatory)*++### Measurable Outcomes++- **SC-001**: With a 1 Hz LFO and a 2 s window, the trace shows two cycles (within 5 %).+- **SC-002**: With a synced LFO and Trigger on, the trace's start moves by less than one block+ between frames.+- **SC-003**: A Scope adds no audio-thread allocation and less than 1 % to the engine's+ per-block work (the perf gate passes without an override).+- **SC-004**: An older project with a Scope opens with the defaults and its wiring unchanged.++## Assumptions++- The trace is the Scope's CV input, as today; audio stays Lens's job (#261).+- There are no MCP modulator tools yet, so the Scope settings have no MCP surface; Duplicate+ Track does not copy modulators today (separate gap), so it does not copy Scope settings either.+- The trigger level is fixed at 0 (the CV centre); a level control can come later.+- #119 (tempo-synced oscilloscope and visualizer) builds on this.diff --git a/specs/047-scope-view/tasks.md b/specs/047-scope-view/tasks.mdnew file mode 100644index 00000000..b51dc772--- /dev/null+++ b/specs/047-scope-view/tasks.md@@ -0,0 +1,13 @@+# Tasks: Scope view++- [x] T001 Engine: `ScopeHistory` ring (value, dt), shared by snapshot copies, allocated for Scope nodes only+- [x] T002 Engine: `readScope` returns the newest entries; timed ABI `nota_track_modulator_scope_timed`+- [x] T003 Engine: modulator fields 13–18 (window ms, sync, beats, zoom, trigger, height) with clamps+- [x] T004 Interop + IAudioEngine `ModulatorScopeTimed`+- [x] T005 `ScopeTrace`: window, labels, knob maps, `Layout` (free / rising-edge trigger)+- [x] T006 Scope node: resize grip, window + Sync, zoom, Free / Rise / Freeze, pop-out glyph+- [x] T007 `ScopeWindow`: same trace and controls, closes when the Scope is gone+- [x] T008 Persistence: `ModulatorDto` Scope fields, Capture / Apply+- [x] T009 Smoke `--scope` (21 checks), in the full run+- [x] T010 CHANGELOG, FEATURES, nota-docs EN + RU (Modular → Scope)+- [ ] T011 Full smoke run, macOS check with before/after screenshots, perf gatediff --git a/src/managed/Nota.App/MainWindow.Files.cs b/src/managed/Nota.App/MainWindow.Files.csindex 6189a8d6..08be1e66 100644--- a/src/managed/Nota.App/MainWindow.Files.cs+++ b/src/managed/Nota.App/MainWindow.Files.cs@@ -451,6 +451,7 @@ public partial class MainWindow_blockMovesDone = 0;CloseDetail(); // collapse the docked row too, not just hide the panel_deviceChain?.ForgetCardState(); // per-track preset labels belong to the old project+ _modular?.ForgetScopes(); // so do frozen Scope traces and Scope windowsTrackArming.ForgetSelection(); // the arm-on-select memory tooTimeline.Refresh();_session?.Refresh();diff --git a/src/managed/Nota.App/ModularView.Scope.cs b/src/managed/Nota.App/ModularView.Scope.csnew file mode 100644index 00000000..2771a9ab--- /dev/null+++ b/src/managed/Nota.App/ModularView.Scope.cs@@ -0,0 +1,285 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// The Modular Scope node (specs/047): a CV monitor whose trace can be resized by the grip+// under it or popped out into its own window, with a time window (ms, or beats when+// synced), a vertical zoom, a rising-edge trigger and a freeze. The window, sync, zoom,+// trigger and trace height are modulator fields saved with the project; freeze is a view+// state shared by the node and its window. The maths lives in ScopeTrace.++using System;+using System.Collections.Generic;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Input;+using Avalonia.Layout;+using Avalonia.Media;+using Avalonia.Threading;+using Nota.Application;++namespace Nota.App;++public sealed partial class ModularView+{+ // A frozen Scope keeps the history it had when Freeze went on, so the node and its window+ // (rebuilt on every chip change) both draw the held trace.+ private readonly Dictionary<(int Track, int Mod), ScopeSnapshot> _scopeFrozen = new();+ internal sealed record ScopeSnapshot(float[] Values, float[] Dts, int Count);+ private readonly Dictionary<(int Track, int Mod), ScopeWindow> _scopeWindows = new();+ private bool _rebuildQueued;++ internal bool ScopeFrozen(int trackId, int modId) => _scopeFrozen.ContainsKey((trackId, modId));+ internal ScopeSnapshot? ScopeHeld(int trackId, int modId) => _scopeFrozen.GetValueOrDefault((trackId, modId));++ /// <summary>A new or reopened project reuses track and modulator ids: drop the held traces+ /// and close the Scope windows, which belong to the old project.</summary>+ public void ForgetScopes()+ {+ _scopeFrozen.Clear();+ foreach (var w in new List<ScopeWindow>(_scopeWindows.Values)) w.Close();+ _scopeWindows.Clear();+ }++ private void SetScopeFrozen(int trackId, int modId, bool on)+ {+ if (!on) { _scopeFrozen.Remove((trackId, modId)); return; }+ var v = new float[ScopeTrace.HistoryLength]; var dt = new float[ScopeTrace.HistoryLength];+ int n = _engine.ModulatorScopeTimed(trackId, modId, v, dt);+ _scopeFrozen[(trackId, modId)] = new ScopeSnapshot(v, dt, Math.Max(0, n));+ }++ // Rebuild on the next dispatcher turn: safe from inside a live-follow tick, which+ // Rebuild would otherwise clear while it runs.+ private void QueueRebuild()+ {+ if (_rebuildQueued) return;+ _rebuildQueued = true;+ Dispatcher.UIThread.Post(() => { _rebuildQueued = false; Rebuild(); });+ }++ // Scope: a CV monitor — one CV input (patch a cable in) drives an oscilloscope; the+ // incoming CV also passes straight through to CV-out.+ private void BuildScopeView(GNode n, int modId)+ {+ var col = new Grid { RowDefinitions = new RowDefinitions("3,32,Auto,Auto,Auto") };+ col.Children.Add(Row(new Border { Background = n.Stripe, CornerRadius = NotaRadius.Top(NotaRadius.TileValue) }, 0));+ var headBorder = NodeHeader(n);+ col.Children.Add(Row(headBorder, 1));++ int t = _trackId; var e = _engine;+ var viz = new ScopeViz(e, t, modId, () => ScopeHeld(t, modId));+ _liveKnobs.Add(viz.Update);+ // Unwired, the scope says what it can watch: a modulator's CV, patched into its input. It+ // doesn't tap audio — a first-time user tried to hang it off a filter's output (#261). The hint+ // stands in for the trace, which would only draw a flat line through it.+ Control body = viz;+ if ((int)Math.Round(e.ModulatorGet(t, modId, 10)) < 0)+ {+ body = new TextBlock+ {+ Text = "Watches CV. Drag a modulator's CV out onto this node. For audio, put Lens on the chain.",+ FontSize = 9, Foreground = Text3, TextWrapping = TextWrapping.Wrap, TextAlignment = TextAlignment.Center,+ HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(8, 0),+ };+ }+ double h0 = Math.Clamp(e.ModulatorGet(t, modId, ScopeTrace.FieldHeight), ScopeTrace.MinHeight, ScopeTrace.MaxHeight);+ var vizBox = new Border { Height = h0, Margin = new Thickness(9, 6, 9, 0), Child = body };+ col.Children.Add(Row(new StackPanel { Children = { vizBox, ScopeGrip(vizBox, t, modId) } }, 2));+ col.Children.Add(Row(ScopeControls(t, modId, _liveKnobs.Add, QueueRebuild), 3));+ col.Children.Add(Row(PortsBlock(n), 4));+ WrapFrame(n, col, headBorder);+ }++ // The bar under the trace: drag it to make the trace taller or shorter (76–320 px).+ private Control ScopeGrip(Border box, int t, int modId)+ {+ var line = new Border+ {+ Width = 28, Height = 2, CornerRadius = NotaRadius.Badge, Background = NotaPalette.Seam,+ HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center,+ };+ var grip = new Border { Height = 9, Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.SizeNorthSouth), Child = line };+ ToolTip.SetTip(grip, "Drag to resize the trace");+ bool drag = false; double y0 = 0, h0 = 0;+ grip.PointerEntered += (_, _) => line.Background = Text3;+ grip.PointerExited += (_, _) => { if (!drag) line.Background = NotaPalette.Seam; };+ grip.PointerPressed += (_, ev) =>+ {+ drag = true; y0 = ev.GetPosition(this).Y; h0 = box.Height;+ ev.Pointer.Capture(grip); ev.Handled = true;+ };+ grip.PointerMoved += (_, ev) =>+ {+ if (!drag) return;+ double dy = (ev.GetPosition(this).Y - y0) / Math.Max(0.05, _scale); // screen px → node px+ box.Height = Math.Round(Math.Clamp(h0 + dy, ScopeTrace.MinHeight, ScopeTrace.MaxHeight));+ ev.Handled = true;+ };+ grip.PointerReleased += (_, ev) =>+ {+ if (!drag) return;+ drag = false; ev.Pointer.Capture(null); line.Background = NotaPalette.Seam;+ _engine.ModulatorSet(t, modId, ScopeTrace.FieldHeight, (float)box.Height);+ Changed?.Invoke();+ ev.Handled = true;+ };+ return grip;+ }++ // Window + zoom knobs, then the trigger and freeze chips. Shared by the node and its+ // window: `addTick` registers the live follow, `refresh` rebuilds the host when a+ // chip changes (or the other copy changed one).+ internal Control ScopeControls(int t, int modId, Action<Action> addTick, Action refresh)+ {+ var e = _engine;+ bool sync = e.ModulatorGet(t, modId, ScopeTrace.FieldSync) > 0.5f;+ bool trig = e.ModulatorGet(t, modId, ScopeTrace.FieldTrigger) > 0.5f;+ bool frozen = ScopeFrozen(t, modId);+ int lastBeat = ScopeTrace.BeatSteps.Length - 1;++ // Window: milliseconds on a log knob, or musical steps when synced.+ int wField = sync ? ScopeTrace.FieldWindowBeats : ScopeTrace.FieldWindowMs;+ double ToFrac(float v) => sync ? ScopeTrace.BeatIndex(v) / (double)lastBeat : ScopeTrace.MsToKnob(v);+ float FromFrac(double f) => sync ? ScopeTrace.BeatSteps[(int)Math.Round(Math.Clamp(f, 0, 1) * lastBeat)] : (float)ScopeTrace.KnobToMs(f);+ string Fmt(float v) => sync ? ScopeTrace.BeatsLabel(v) : ScopeTrace.MsLabel(v);+ float w0 = e.ModulatorGet(t, modId, wField);+ var wValue = MonoValue(Fmt(w0));+ // Full travel either way; double-click goes back to 1 s (or 4 beats).+ var wKnob = new Knob(ToFrac(w0))+ {+ Accent = true, Width = 30, Height = 30,+ Default = sync ? ToFrac((float)ScopeTrace.DefaultWindowBeats) : ScopeTrace.MsToKnob(ScopeTrace.DefaultWindowMs),+ };+ wKnob.Format = f => Fmt(FromFrac(f));+ wKnob.ValueChanged += f => { float v = FromFrac(f); e.ModulatorSet(t, modId, wField, v); wValue.Text = Fmt(v); };+ ValueEntry.Attach(wKnob, "Window", wValue);+ var syncChip = ToggleLabel(sync ? "Sync" : "ms", sync ? "The window is in beats at the tempo. Click for milliseconds"+ : "The window is in milliseconds. Click to sync it to the beat",+ () => { e.ModulatorSet(t, modId, ScopeTrace.FieldSync, sync ? 0f : 1f); Changed?.Invoke(); refresh(); });+ var windowCell = new StackPanel+ {+ Spacing = 0, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center,+ Children = { syncChip, wKnob, wValue },+ };++ // Zoom: 1× / 2× / 4× / 8× on a stepped knob.+ int last = ScopeTrace.Zooms.Length - 1;+ int ZoomAt(double f) => ScopeTrace.Zooms[(int)Math.Round(Math.Clamp(f, 0, 1) * last)];+ float z0 = e.ModulatorGet(t, modId, ScopeTrace.FieldZoom);+ var zValue = MonoValue(ScopeTrace.ZoomLabel(ScopeTrace.Zooms[ScopeTrace.ZoomIndex(z0)]));+ var zKnob = new Knob(ScopeTrace.ZoomIndex(z0) / (double)last, 0) { Accent = true };+ zKnob.Format = f => ScopeTrace.ZoomLabel(ZoomAt(f));+ zKnob.ValueChanged += f => { int z = ZoomAt(f); e.ModulatorSet(t, modId, ScopeTrace.FieldZoom, z); zValue.Text = ScopeTrace.ZoomLabel(z); };+ ValueEntry.Attach(zKnob, "Zoom", zValue);+ var zoomCell = KnobCell("Zoom", zKnob, zValue);++ addTick(() =>+ {+ // Another copy (node ↔ window) switched a chip: rebuild to match.+ if ((e.ModulatorGet(t, modId, ScopeTrace.FieldSync) > 0.5f) != sync+ || (e.ModulatorGet(t, modId, ScopeTrace.FieldTrigger) > 0.5f) != trig+ || ScopeFrozen(t, modId) != frozen) { refresh(); return; }+ if (!wKnob.Dragging)+ {+ float cur = e.ModulatorGet(t, modId, wField); double f = ToFrac(cur);+ if (Math.Abs(f - wKnob.Value) > 1e-3) { wKnob.Value = f; wValue.Text = Fmt(cur); }+ }+ if (!zKnob.Dragging)+ {+ float cur = e.ModulatorGet(t, modId, ScopeTrace.FieldZoom); double f = ScopeTrace.ZoomIndex(cur) / (double)last;+ if (Math.Abs(f - zKnob.Value) > 1e-3) { zKnob.Value = f; zValue.Text = ScopeTrace.ZoomLabel(ScopeTrace.Zooms[ScopeTrace.ZoomIndex(cur)]); }+ }+ });++ var chips = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 3, Margin = new Thickness(9, 0), VerticalAlignment = VerticalAlignment.Center };+ void SetTrig(bool on) { e.ModulatorSet(t, modId, ScopeTrace.FieldTrigger, on ? 1f : 0f); Changed?.Invoke(); refresh(); }+ var free = SegChip("Free", !trig, () => SetTrig(false));+ ToolTip.SetTip(free, "Free running: the newest value is at the right");+ var rise = SegChip("Rise", trig, () => SetTrig(true));+ ToolTip.SetTip(rise, "Trigger: start the trace where the input rises through 0, so a repeating shape holds still");+ var freeze = SegChip("Freeze", frozen, () => { SetScopeFrozen(t, modId, !frozen); refresh(); });+ ToolTip.SetTip(freeze, frozen ? "Back to the live trace" : "Hold the trace while the input keeps running");+ freeze.Margin = new Thickness(8, 0, 0, 0);+ chips.Children.Add(free); chips.Children.Add(rise); chips.Children.Add(freeze);++ return new StackPanel+ {+ Margin = new Thickness(0, 4, 0, 0),+ Children =+ {+ KnobGrid(windowCell, zoomCell),+ new Border { Height = 34, Child = chips, BorderBrush = BorderInner, BorderThickness = new Thickness(0, 1, 0, 0) },+ },+ };+ }++ // Open (or bring forward) the Scope's own window.+ private void OpenScopeWindow(int t, int modId, Control anchor)+ {+ if (_scopeWindows.TryGetValue((t, modId), out var open)) { open.Activate(); return; }+ var w = new ScopeWindow(this, _engine, t, modId, $"Scope {modId} · {TrackName(t)}");+ _scopeWindows[(t, modId)] = w;+ w.Closed += (_, _) => _scopeWindows.Remove((t, modId));+ // After the click has finished (the button opens on release), owned by the window that+ // holds the node, so it stays in front of it.+ var owner = TopLevel.GetTopLevel(anchor) as Window;+ Dispatcher.UIThread.Post(() => { w.ShowOver(owner); w.Activate(); }, DispatcherPriority.Background);+ }++ internal sealed class ScopeViz : Control+ {+ private readonly IAudioEngine _e;+ private readonly int _t, _mod;+ private readonly Func<ScopeSnapshot?> _held;+ private readonly float[] _v = new float[ScopeTrace.HistoryLength], _dt = new float[ScopeTrace.HistoryLength];+ private readonly double[] _xs = new double[ScopeTrace.HistoryLength];+ private readonly float[] _ys = new float[ScopeTrace.HistoryLength];+ private int _n, _zoom = 1;+ private bool _triggered;++ public ScopeViz(IAudioEngine e, int trackId, int modId, Func<ScopeSnapshot?> held)+ {+ _e = e; _t = trackId; _mod = modId; _held = held;+ IsHitTestVisible = false; ClipToBounds = true;+ }++ public void Update()+ {+ _zoom = ScopeTrace.Zooms[ScopeTrace.ZoomIndex(_e.ModulatorGet(_t, _mod, ScopeTrace.FieldZoom))];+ // Frozen: lay out the held history, so window, zoom and trigger still apply to it.+ var held = _held();+ float[] v = held?.Values ?? _v, dt = held?.Dts ?? _dt;+ int m = held?.Count ?? _e.ModulatorScopeTimed(_t, _mod, _v, _dt);+ double win = ScopeTrace.WindowSeconds(_e.ModulatorGet(_t, _mod, ScopeTrace.FieldSync) > 0.5f,+ _e.ModulatorGet(_t, _mod, ScopeTrace.FieldWindowMs), _e.ModulatorGet(_t, _mod, ScopeTrace.FieldWindowBeats), _e.Bpm);+ bool trig = _e.ModulatorGet(_t, _mod, ScopeTrace.FieldTrigger) > 0.5f;+ _n = ScopeTrace.Layout(v.AsSpan(0, m), dt.AsSpan(0, m), win, trig, _xs, _ys, out _triggered);+ InvalidateVisual();+ }++ public override void Render(DrawingContext ctx)+ {+ double w = Bounds.Width, h = Bounds.Height;+ if (w <= 0 || h <= 0) return;+ ctx.DrawRectangle(ScopeBg, null, new Rect(0, 0, w, h), 4, 4);+ double mid = h / 2;+ var grid = new Pen(BorderInner, 1);+ for (int i = 1; i < 4; i++) { double x = Math.Round(w * i / 4) + 0.5; ctx.DrawLine(grid, new Point(x, 2), new Point(x, h - 2)); }+ ctx.DrawLine(grid, new Point(0, mid), new Point(w, mid));+ if (_triggered) ctx.DrawRectangle(Brass, null, new Rect(0, mid - 4, 2, 8)); // the trigger point+ if (_n < 2) return;+ double scale = _zoom / ScopeTrace.Range;+ var geo = new StreamGeometry();+ using (var g = geo.Open())+ {+ for (int i = 0; i < _n; i++)+ {+ double v = Math.Clamp(_ys[i] * scale, -1, 1);+ var p = new Point(_xs[i] * w, mid - v * (mid - 2));+ if (i == 0) g.BeginFigure(p, false); else g.LineTo(p);+ }+ }+ ctx.DrawGeometry(null, new Pen(Brass, 1.5), geo);+ }+ }+}diff --git a/src/managed/Nota.App/ModularView.cs b/src/managed/Nota.App/ModularView.csindex a67e1679..ce9f74f9 100644--- a/src/managed/Nota.App/ModularView.cs+++ b/src/managed/Nota.App/ModularView.cs@@ -27,7 +27,7 @@ using Nota.Presentation;namespace Nota.App;-public sealed class ModularView : UserControl+public sealed partial class ModularView : UserControl{// ---- palette --------------------------------------------------------private static readonly IBrush CanvasBg = NotaPalette.CanvasBg;@@ -1024,43 +1024,6 @@ public sealed class ModularView : UserControlreturn new Border { Child = stack, BorderBrush = BorderDef, BorderThickness = new Thickness(0, 1, 0, 0) };}- // Scope: a CV monitor — one CV input (patch a cable in) drives a rolling- // oscilloscope; the incoming CV also passes straight through to CV-out.- private void BuildScopeView(GNode n, int modId)- {- var col = new Grid { RowDefinitions = new RowDefinitions("3,32,Auto,Auto") };- col.Children.Add(Row(new Border { Background = n.Stripe, CornerRadius = NotaRadius.Top(NotaRadius.TileValue) }, 0));- var headBorder = NodeHeader(n);- col.Children.Add(Row(headBorder, 1));-- var viz = new ScopeViz();- int t = _trackId; var e = _engine;- var buf = new float[128];- _liveKnobs.Add(() =>- {- int m = e.ModulatorScope(t, modId, buf);- viz.Set(buf, m);- });- // Unwired, the scope says what it can watch: a modulator's CV, patched into its input. It- // doesn't tap audio — a first-time user tried to hang it off a filter's output (#261). The hint- // stands in for the trace, which would only draw a flat line through it.- Control body = viz;- if ((int)Math.Round(e.ModulatorGet(t, modId, 10)) < 0)- {- var hint = new TextBlock- {- Text = "Watches CV. Drag a modulator's CV out onto this node. For audio, put Lens on the chain.",- FontSize = 9, Foreground = Text3, TextWrapping = TextWrapping.Wrap, TextAlignment = TextAlignment.Center,- HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(8, 0),- };- body = hint;- }- var vizBox = new Border { Height = 76, Margin = new Thickness(9, 6), Child = body };- col.Children.Add(Row(vizBox, 2));- col.Children.Add(Row(PortsBlock(n), 3));- WrapFrame(n, col, headBorder);- }-private static Control MathLabeledRow(string label, Control field){var dock = new DockPanel { LastChildFill = true };@@ -1133,16 +1096,21 @@ public sealed class ModularView : UserControl}// A compact Sync/Free toggle used as the Rate cell's label (14px so it fits the knob row).- private Border SyncToggle(int modId, bool synced)+ private Border SyncToggle(int modId, bool synced) =>+ ToggleLabel(synced ? "Sync" : "Free", null, () => { _engine.ModulatorSet(_trackId, modId, 1, synced ? 0f : 1f); Rebuild(); });++ // A small clickable label chip over a knob (Sync/Free, the Scope's ms/Sync).+ private static Border ToggleLabel(string text, string? tip, Action onClick){var b = new Border{Height = 13, CornerRadius = NotaRadius.Badge, Padding = new Thickness(5, 0),Background = NotaPalette.SurfaceRaised, BorderBrush = NotaPalette.Seam, BorderThickness = new Thickness(1),Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Center,- Child = new TextBlock { Text = synced ? "Sync" : "Free", FontSize = 8, FontWeight = FontWeight.SemiBold, Foreground = NotaPalette.TextPrimary, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center },+ Child = new TextBlock { Text = text, FontSize = 8, FontWeight = FontWeight.SemiBold, Foreground = NotaPalette.TextPrimary, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center },};- b.PointerPressed += (_, e) => { _engine.ModulatorSet(_trackId, modId, 1, synced ? 0f : 1f); Rebuild(); e.Handled = true; };+ if (tip is not null) ToolTip.SetTip(b, tip);+ b.PointerPressed += (_, e) => { onClick(); e.Handled = true; };return b;}@@ -1461,6 +1429,15 @@ public sealed class ModularView : UserControl{var actions = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center };actions.Children.Add(new TextBlock { Text = string.IsNullOrEmpty(n.Badge) ? "LFO" : NotaText.Label(n.Badge), FontSize = 9, FontWeight = FontWeight.Medium, Foreground = Text3, VerticalAlignment = VerticalAlignment.Center });+ if (n.IsScopeNode)+ {+ int scopeTrack = _trackId, scopeMod = n.ModId;+ Control? pop = null;+ // Opens on release: opened on the press, the release raises the main window over it (macOS).+ pop = HeaderGlyph(GlyphKind.PopOut, Text3, "Open in a window", () => { });+ pop.PointerReleased += (_, e) => { OpenScopeWindow(scopeTrack, scopeMod, pop!); e.Handled = true; };+ actions.Children.Add(pop);+ }actions.Children.Add(HeaderGlyph(GlyphKind.Trash, Text3, "Delete (⌫)", () => RemoveModulatorNode(n)));DockPanel.SetDock(actions, Dock.Right);head.Children.Add(actions);@@ -2348,43 +2325,6 @@ public sealed class ModularView : UserControl// Rolling CV oscilloscope for a Scope node. Fed a snapshot (oldest→newest)// each Tick; draws a brass trace over a zero line in the -1..1 CV range.- private sealed class ScopeViz : Control- {- private float[] _buf = Array.Empty<float>();- private int _n;- public ScopeViz() { IsHitTestVisible = false; }- public void Set(float[] buf, int n)- {- if (_buf.Length < n) _buf = new float[n];- Array.Copy(buf, _buf, n);- _n = n;- InvalidateVisual();- }- public override void Render(DrawingContext ctx)- {- double w = Bounds.Width, h = Bounds.Height;- if (w <= 0 || h <= 0) return;- ctx.DrawRectangle(ScopeBg, null, new Rect(0, 0, w, h), 4, 4);- double mid = h / 2;- ctx.DrawLine(new Pen(BorderInner, 1), new Point(0, mid), new Point(w, mid));- if (_n < 2) return;- const double range = 1.15; // headroom past unity- var geo = new StreamGeometry();- using (var g = geo.Open())- {- for (int i = 0; i < _n; i++)- {- double x = _n == 1 ? 0 : i / (double)(_n - 1) * w;- double v = Math.Clamp(_buf[i] / range, -1, 1);- double y = mid - v * (mid - 2);- var p = new Point(x, y);- if (i == 0) g.BeginFigure(p, false); else g.LineTo(p);- }- }- ctx.DrawGeometry(null, new Pen(Brass, 1.5), geo);- }- }-private static readonly IBrush ScopeBg = NotaPalette.SurfaceDeep;private sealed class GridLayer : Controldiff --git a/src/managed/Nota.App/ScopeWindow.cs b/src/managed/Nota.App/ScopeWindow.csnew file mode 100644index 00000000..06bdd574--- /dev/null+++ b/src/managed/Nota.App/ScopeWindow.cs@@ -0,0 +1,85 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// A Modular Scope node popped out into its own resizable window (specs/047): the same live+// trace and the same controls as the node, the trace filling the window. It closes itself+// when its Scope (or its track) is gone. Settings changed here or on the node follow each+// other through the engine fields; freeze is shared through the Modular view.++using System;+using System.Collections.Generic;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Input;+using Avalonia.Interactivity;+using Avalonia.Threading;+using Nota.Application;++namespace Nota.App;++internal sealed class ScopeWindow : NotaWindow+{+ private readonly ModularView _view;+ private readonly IAudioEngine _engine;+ private readonly int _trackId, _modId;+ private readonly List<Action> _ticks = new();+ private readonly DispatcherTimer _timer = new() { Interval = TimeSpan.FromMilliseconds(33) };+ private bool _refillQueued;++ public ScopeWindow(ModularView view, IAudioEngine engine, int trackId, int modId, string title)+ {+ _view = view; _engine = engine; _trackId = trackId; _modId = modId;+ Title = title;+ Width = 720; Height = 340; MinWidth = 420; MinHeight = 220;+ CanResize = true;+ ShowInTaskbar = false;+ WindowStartupLocation = WindowStartupLocation.CenterOwner;+ _timer.Tick += (_, _) => Tick();+ Opened += (_, _) => _timer.Start();+ Closed += (_, _) => _timer.Stop();+ Refill();+ }++ private void Refill()+ {+ _ticks.Clear();+ var viz = new ModularView.ScopeViz(_engine, _trackId, _modId, () => _view.ScopeHeld(_trackId, _modId));+ _ticks.Add(viz.Update);+ var controls = _view.ScopeControls(_trackId, _modId, _ticks.Add, QueueRefill);+ var side = new Border { Width = 214, Child = controls, VerticalAlignment = Avalonia.Layout.VerticalAlignment.Top };+ DockPanel.SetDock(side, Dock.Right);+ var dock = new DockPanel { Margin = new Thickness(12) };+ dock.Children.Add(side);+ dock.Children.Add(new Border { Margin = new Thickness(0, 0, 12, 0), Child = viz });+ SetBody(dock);+ }++ private void QueueRefill()+ {+ if (_refillQueued) return;+ _refillQueued = true;+ Dispatcher.UIThread.Post(() => { _refillQueued = false; Refill(); });+ }++ private void Tick()+ {+ if (_engine.ModulatorKind(_trackId, _modId) != ScopeTrace.Kind) { Close(); return; } // deleted+ for (int i = 0; i < _ticks.Count; i++) _ticks[i]();+ }++ /// <summary>Show over <paramref name="owner"/> (the window that holds the node; the main+ /// window when that is gone), so it stays in front of it; over the main window, forward+ /// its keys (transport, undo …) as the device window does.</summary>+ public void ShowOver(Window? owner)+ {+ owner ??= (Avalonia.Application.Current?.ApplicationLifetime as Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime)?.MainWindow;+ if (owner is null) { Show(); return; }+ if (owner is MainWindow mw)+ {+ AddHandler(KeyDownEvent, (_, e) => mw.HandleTransportKeyTunnel(e), RoutingStrategies.Tunnel);+ KeyDown += (_, e) => { if (!e.Handled) mw.HandleFloatingKeyDown(e); };+ KeyUp += (_, e) => { if (!e.Handled) mw.HandleKeyUp(e); };+ }+ Show(owner);+ }+}diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.csindex 28665a6e..4883101d 100644--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs@@ -1275,8 +1275,11 @@ public interface IAudioEngine : IDisposablevoid ModulatorSet(int trackId, int modId, int field, float value);/// <summary>Live modulator output at the current transport position (for the node viz), -1..1×depth.</summary>float ModulatorValue(int trackId, int modId);- /// <summary>Rolling CV history for a Scope modulator; fills <paramref name="outv"/> oldest→newest, returns count.</summary>+ /// <summary>Rolling CV history for a Scope modulator: the newest values, oldest→newest; returns count.</summary>int ModulatorScope(int trackId, int modId, float[] outv);+ /// <summary>Scope history with time steps (specs/047): the newest entries oldest→newest, and the+ /// seconds each one follows the previous by (one audio block). Returns the count.</summary>+ int ModulatorScopeTimed(int trackId, int modId, float[] values, float[] dts);int CvLinkAdd(int trackId, int modId, int deviceIndex, int paramIndex);/// <summary>Cross-track link: modulator on trackId modulates a param on targetTrack (-1 = self).</summary>int CvLinkAddTo(int trackId, int modId, int targetTrack, int deviceIndex, int paramIndex);diff --git a/src/managed/Nota.Application/Instruments/ScopeTrace.cs b/src/managed/Nota.Application/Instruments/ScopeTrace.csnew file mode 100644index 00000000..ff7f3b75--- /dev/null+++ b/src/managed/Nota.Application/Instruments/ScopeTrace.cs@@ -0,0 +1,119 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// The Modular Scope node's view (specs/047): its saved settings (modulator fields 13..18),+// their labels, and how the engine's (value, time step) history is laid into the time+// window, free-running or held still on a rising edge. Pure, so the smoke test checks the+// same maths the node and its pop-out window draw.++using System;+using System.Globalization;++namespace Nota.Application;++public static class ScopeTrace+{+ public const int Kind = 6; // ModulatorKind::Scope+ public const int FieldWindowMs = 13, FieldSync = 14, FieldWindowBeats = 15, FieldZoom = 16,+ FieldTrigger = 17, FieldHeight = 18;+ public const int HistoryLength = 8192; // engine kScopeLen+ public const double MinWindowMs = 50, MaxWindowMs = 8000, DefaultWindowMs = 1000;+ public const double DefaultWindowBeats = 4;+ public const double MinHeight = 76, MaxHeight = 320;+ /// <summary>Vertical scale at 1×: ±1 CV with a little headroom.</summary>+ public const double Range = 1.15;++ /// <summary>The synced window steps, in beats (1/16 to 8 bars in 4/4).</summary>+ public static readonly float[] BeatSteps = { 0.25f, 0.5f, 1f, 2f, 4f, 8f, 16f, 32f };+ public static readonly int[] Zooms = { 1, 2, 4, 8 };++ /// <summary>The window in seconds: beats at the tempo when synced, else milliseconds.</summary>+ public static double WindowSeconds(bool sync, double ms, double beats, double bpm) =>+ sync ? beats * 60.0 / Math.Max(1.0, bpm) : Math.Clamp(ms, MinWindowMs, MaxWindowMs) / 1000.0;++ /// <summary>The window knob's position for a value (log in ms, stepped in beats).</summary>+ public static double MsToKnob(double ms) =>+ Math.Log(Math.Clamp(ms, MinWindowMs, MaxWindowMs) / MinWindowMs) / Math.Log(MaxWindowMs / MinWindowMs);+ public static double KnobToMs(double frac) => MinWindowMs * Math.Pow(MaxWindowMs / MinWindowMs, Math.Clamp(frac, 0, 1));+ public static int BeatIndex(double beats)+ {+ int best = 0;+ for (int i = 1; i < BeatSteps.Length; i++)+ if (Math.Abs(BeatSteps[i] - beats) < Math.Abs(BeatSteps[best] - beats)) best = i;+ return best;+ }+ public static int ZoomIndex(double zoom) => zoom >= 6 ? 3 : zoom >= 3 ? 2 : zoom >= 1.5 ? 1 : 0;++ public static string MsLabel(double ms) => ms >= 1000+ ? (ms / 1000).ToString(ms >= 10000 ? "0" : "0.0#", CultureInfo.InvariantCulture) + " s"+ : ms.ToString("0", CultureInfo.InvariantCulture) + " ms";++ public static string BeatsLabel(double beats)+ {+ if (beats >= 4) { int bars = (int)Math.Round(beats / 4); return bars == 1 ? "1 bar" : $"{bars} bars"; }+ return "1/" + (int)Math.Round(4 / Math.Max(0.25, beats));+ }++ public static string ZoomLabel(int zoom) => zoom.ToString(CultureInfo.InvariantCulture) + "×";++ /// <summary>+ /// Lay the history (oldest → newest; <paramref name="dt"/>[i] = seconds from entry i-1 to i)+ /// into a window of <paramref name="window"/> seconds. Writes each point's x (0 = left edge,+ /// 1 = right; the first point may sit just left of 0 so the line reaches the edge) and value,+ /// and returns the count. Free running, the newest value is at the right. With+ /// <paramref name="trigger"/>, the trace starts at the latest upward crossing of 0 that has+ /// a full window after it (interpolated between blocks), so a periodic signal holds still;+ /// <paramref name="triggered"/> says whether one was found (if not, it runs free).+ /// </summary>+ public static int Layout(ReadOnlySpan<float> v, ReadOnlySpan<float> dt, double window, bool trigger,+ Span<double> xs, Span<float> ys, out bool triggered)+ {+ triggered = false;+ int n = Math.Min(v.Length, dt.Length);+ if (n < 2 || window <= 0) return 0;+ int cap = Math.Min(xs.Length, ys.Length);++ // age[i] = seconds from entry i to the newest entry, walked back on the fly.+ if (trigger)+ {+ double ageI = 0; // age of entry i+ for (int i = n - 1; i >= 1; i--)+ {+ double agePrev = ageI + dt[i];+ if (v[i - 1] < 0 && v[i] >= 0)+ {+ double frac = -v[i - 1] / (double)(v[i] - v[i - 1]);+ double ageCross = agePrev - frac * dt[i];+ if (ageCross >= window)+ {+ triggered = true;+ int count = 0;+ double age = agePrev;+ for (int j = i - 1; j < n && count < cap; j++)+ {+ if (j > i - 1) age -= dt[j];+ double x = (ageCross - age) / window;+ xs[count] = x; ys[count] = v[j]; count++;+ if (x >= 1) break;+ }+ return count;+ }+ }+ ageI = agePrev;+ }+ }++ // Free running: walk back to the window's left edge (one point past it).+ int start = n - 1;+ double a = 0;+ while (start > 0 && a < window) { a += dt[start]; start--; }+ int written = 0;+ double ageJ = a;+ for (int j = start; j < n && written < cap; j++)+ {+ if (j > start) ageJ -= dt[j];+ xs[written] = 1 - ageJ / window; ys[written] = v[j]; written++;+ }+ return written;+ }+}diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Modulation.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Modulation.csindex a1b22b05..11fdf5a1 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Modulation.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Modulation.cs@@ -39,6 +39,9 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_track_modulator_scope")]internal static partial int ModulatorScope(IntPtr engine, int trackId, int modId, [Out] float[] outv, int cap);+ [LibraryImport(Lib, EntryPoint = "nota_track_modulator_scope_timed")]+ internal static partial int ModulatorScopeTimed(IntPtr engine, int trackId, int modId, [Out] float[] values, [Out] float[] dts, int cap);+[LibraryImport(Lib, EntryPoint = "nota_track_add_cv_link")]internal static partial int AddCvLink(IntPtr engine, int trackId, int modId, int deviceIndex, int paramIndex);diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Modulation.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Modulation.csindex 3ddfd69f..fe473cb9 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Modulation.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Modulation.cs@@ -27,6 +27,11 @@ public sealed partial class NotaEngine{ ThrowIfDisposed(); return NativeMethods.ModulatorValue(_handle, trackId, modId); }public int ModulatorScope(int trackId, int modId, float[] outv){ ThrowIfDisposed(); return NativeMethods.ModulatorScope(_handle, trackId, modId, outv, outv.Length); }+ public int ModulatorScopeTimed(int trackId, int modId, float[] values, float[] dts)+ {+ ThrowIfDisposed();+ return NativeMethods.ModulatorScopeTimed(_handle, trackId, modId, values, dts, Math.Min(values.Length, dts.Length));+ }public int CvLinkAdd(int trackId, int modId, int deviceIndex, int paramIndex){ ThrowIfDisposed(); return NativeMethods.AddCvLink(_handle, trackId, modId, deviceIndex, paramIndex); }diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.csindex 39dd1060..22651fa4 100644--- a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs@@ -170,6 +170,13 @@ public sealed class ModulatorDtopublic int InputA { get; set; } = -1; // Math: source modulator ids (remapped on load)public int InputB { get; set; } = -1;public float MathOffset { get; set; }+ // Scope view settings (specs/047); older projects read the defaults.+ public float ScopeWindowMs { get; set; } = 1000f;+ public bool ScopeSync { get; set; }+ public float ScopeWindowBeats { get; set; } = 4f;+ public int ScopeZoom { get; set; } = 1;+ public int ScopeTrigger { get; set; }+ public float ScopeHeight { get; set; } = 76f;[JsonExtensionData] public Dictionary<string, JsonElement>? Extra { get; set; }}diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.csindex 04e2ddcd..8d591208 100644--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs@@ -311,6 +311,12 @@ public sealed class ProjectServiceInputA = (int)engine.ModulatorGet(ti.Id, id, 10),InputB = (int)engine.ModulatorGet(ti.Id, id, 11),MathOffset = engine.ModulatorGet(ti.Id, id, 12),+ ScopeWindowMs = engine.ModulatorGet(ti.Id, id, 13),+ ScopeSync = engine.ModulatorGet(ti.Id, id, 14) > 0.5f,+ ScopeWindowBeats = engine.ModulatorGet(ti.Id, id, 15),+ ScopeZoom = (int)engine.ModulatorGet(ti.Id, id, 16),+ ScopeTrigger = (int)engine.ModulatorGet(ti.Id, id, 17),+ ScopeHeight = engine.ModulatorGet(ti.Id, id, 18),});}int cvCount = engine.CvLinkCount(ti.Id);@@ -821,6 +827,15 @@ public sealed class ProjectServiceengine.ModulatorSet(id, newId, 7, m.Release);engine.ModulatorSet(id, newId, 8, m.Decay);engine.ModulatorSet(id, newId, 9, m.Sustain);+ if (m.Kind == 6) // Scope view settings (specs/047)+ {+ engine.ModulatorSet(id, newId, 13, m.ScopeWindowMs);+ engine.ModulatorSet(id, newId, 14, m.ScopeSync ? 1f : 0f);+ engine.ModulatorSet(id, newId, 15, m.ScopeWindowBeats);+ engine.ModulatorSet(id, newId, 16, m.ScopeZoom);+ engine.ModulatorSet(id, newId, 17, m.ScopeTrigger);+ engine.ModulatorSet(id, newId, 18, m.ScopeHeight);+ }}// Math/Scope inputs reference other modulators by id → remap after all exist.foreach (var m in t.Modulators)diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.hindex 0b7c6044..16361d0c 100644--- a/src/native/nota.engine/include/nota/nota_engine.h+++ b/src/native/nota.engine/include/nota/nota_engine.h@@ -388,6 +388,11 @@ NOTA_API float nota_track_modulator_get(const NotaEngine* engine, int32_t tracNOTA_API NotaResult nota_track_modulator_set(NotaEngine* engine, int32_t track_id, int32_t mod_id, int32_t field, float value);NOTA_API float nota_track_modulator_value(const NotaEngine* engine, int32_t track_id, int32_t mod_id);NOTA_API int32_t nota_track_modulator_scope(const NotaEngine* engine, int32_t track_id, int32_t mod_id, float* out, int32_t cap);+/* Scope history with time steps (specs/047): the newest entries, oldest -> newest. dts[i] is+ * the seconds between entry i-1 and i (one audio block). Fields 13..18 hold the Scope view+ * settings: 13 window ms (50..8000), 14 sync, 15 window beats (0.25..32), 16 zoom (1/2/4/8),+ * 17 trigger (0 free, 1 rising), 18 trace height px (76..320). */+NOTA_API int32_t nota_track_modulator_scope_timed(const NotaEngine* engine, int32_t track_id, int32_t mod_id, float* values, float* dts, int32_t cap);NOTA_API int32_t nota_track_add_cv_link(NotaEngine* engine, int32_t track_id, int32_t mod_id, int32_t device_index, int32_t param_index);/* Cross-track: modulator on track_id modulates a param on target_track (-1 = self). */NOTA_API int32_t nota_track_add_cv_link_to(NotaEngine* engine, int32_t track_id, int32_t mod_id, int32_t target_track, int32_t device_index, int32_t param_index);diff --git a/src/native/nota.engine/src/abi/nota_engine_modulation.cpp b/src/native/nota.engine/src/abi/nota_engine_modulation.cppindex 52ed3157..85bb50da 100644--- a/src/native/nota.engine/src/abi/nota_engine_modulation.cpp+++ b/src/native/nota.engine/src/abi/nota_engine_modulation.cpp@@ -40,7 +40,11 @@ float nota_track_modulator_value(const NotaEngine* e, int32_t track_id, int32_treturn e ? CENG(e)->modulatorValue(track_id, mod_id) : 0.0f;}int32_t nota_track_modulator_scope(const NotaEngine* e, int32_t track_id, int32_t mod_id, float* out, int32_t cap) {- return e ? CENG(e)->modulatorScope(track_id, mod_id, out, cap) : 0;+ return e ? CENG(e)->modulatorScope(track_id, mod_id, out, nullptr, cap) : 0;+}+int32_t nota_track_modulator_scope_timed(+ const NotaEngine* e, int32_t track_id, int32_t mod_id, float* values, float* dts, int32_t cap) {+ return e && values && dts ? CENG(e)->modulatorScope(track_id, mod_id, values, dts, cap) : 0;}int32_t nota_track_add_cv_link(diff --git a/src/native/nota.engine/src/engine/Engine.h b/src/native/nota.engine/src/engine/Engine.hindex 6d742dff..8bda2bd4 100644--- a/src/native/nota.engine/src/engine/Engine.h+++ b/src/native/nota.engine/src/engine/Engine.h@@ -158,7 +158,7 @@ class Engine {float modulatorGet(int32_t trackId, int32_t modId, int32_t field) const;void modulatorSet(int32_t trackId, int32_t modId, int32_t field, float value);float modulatorValue(int32_t trackId, int32_t modId) const; // live output for viz- int32_t modulatorScope(int32_t trackId, int32_t modId, float* out, int32_t cap) const; // CV scope history+ int32_t modulatorScope(int32_t trackId, int32_t modId, float* values, float* dts, int32_t cap) const; // CV scope history, newest cap entriesint32_t addCvLink(int32_t trackId, int32_t modId, int32_t device, int32_t param);// Cross-track: the modulator lives on trackId; the target param is on targetTrack// (-1 = trackId itself). The link is owned by the modulator's track.diff --git a/src/native/nota.engine/src/engine/Engine_Modulation.cpp b/src/native/nota.engine/src/engine/Engine_Modulation.cppindex e5688cc7..7c472bcb 100644--- a/src/native/nota.engine/src/engine/Engine_Modulation.cpp+++ b/src/native/nota.engine/src/engine/Engine_Modulation.cpp@@ -34,6 +34,7 @@ int32_t Engine::addModulator(int32_t trackId, int32_t kind) {Modulator m;m.id = nt->nextModId++;m.kind = static_cast<ModulatorKind>(kind);+ if (m.kind == ModulatorKind::Scope) m.scope = std::make_shared<ScopeHistory>();const int32_t id = m.id;nt->modulators.push_back(m);republishWithTrack(trackId, nt);@@ -587,17 +588,17 @@ void Engine::updateModulators(Graph* g, double beat, double timeSec, double dt)} else if (m.kind == ModulatorKind::Scope) {const float v = modOutput(t, m.inputA.load(std::memory_order_relaxed), beat, timeSec);m.outValue.store(v, std::memory_order_relaxed); // pass-through- m.pushScope(v);+ m.pushScope(v, static_cast<float>(dt));}}}}-int32_t Engine::modulatorScope(int32_t trackId, int32_t modId, float* out, int32_t cap) const {+int32_t Engine::modulatorScope(int32_t trackId, int32_t modId, float* values, float* dts, int32_t cap) const {auto t = findTrackAuthoring(trackId);if (!t) return 0;for (auto& m : t->modulators)- if (m.id == modId) return m.readScope(out, cap);+ if (m.id == modId) return m.readScope(values, dts, cap);return 0;}diff --git a/src/native/nota.engine/src/engine/Modulation.cpp b/src/native/nota.engine/src/engine/Modulation.cppindex d7435181..21f2f1ae 100644--- a/src/native/nota.engine/src/engine/Modulation.cpp+++ b/src/native/nota.engine/src/engine/Modulation.cpp@@ -5,10 +5,17 @@namespace nota {-int32_t Modulator::readScope(float* out, int32_t cap) const {- const int32_t w = scopeWrite.load(std::memory_order_relaxed);- const int32_t n = cap < kScopeLen ? cap : kScopeLen;- for (int32_t i = 0; i < n; ++i) out[i] = scopeBuf[(w + i) & (kScopeLen - 1)];+int32_t Modulator::readScope(float* values, float* dts, int32_t cap) const {+ if (!scope || cap <= 0) return 0;+ const int64_t w = scope->write.load(std::memory_order_acquire);+ // Leave a margin the audio thread may overwrite while we copy (a few blocks per UI read).+ constexpr int64_t kReadable = kScopeLen - 256;+ const int32_t n = static_cast<int32_t>(std::min<int64_t>({(int64_t)cap, w, kReadable}));+ for (int32_t i = 0; i < n; ++i) {+ const int64_t at = (w - n + i) & (kScopeLen - 1);+ values[i] = scope->value[at];+ if (dts) dts[i] = scope->dt[at];+ }return n;}@@ -32,8 +39,13 @@ Modulator& Modulator::operator=(const Modulator& o) {inputB.store(o.inputB.load(std::memory_order_relaxed), std::memory_order_relaxed);mathOffset.store(o.mathOffset.load(std::memory_order_relaxed), std::memory_order_relaxed);outValue.store(o.outValue.load(std::memory_order_relaxed), std::memory_order_relaxed);- for (int i = 0; i < kScopeLen; ++i) scopeBuf[i] = o.scopeBuf[i];- scopeWrite.store(o.scopeWrite.load(std::memory_order_relaxed), std::memory_order_relaxed);+ scopeWindowMs.store(o.scopeWindowMs.load(std::memory_order_relaxed), std::memory_order_relaxed);+ scopeSync.store(o.scopeSync.load(std::memory_order_relaxed), std::memory_order_relaxed);+ scopeWindowBeats.store(o.scopeWindowBeats.load(std::memory_order_relaxed), std::memory_order_relaxed);+ scopeZoom.store(o.scopeZoom.load(std::memory_order_relaxed), std::memory_order_relaxed);+ scopeTrigger.store(o.scopeTrigger.load(std::memory_order_relaxed), std::memory_order_relaxed);+ scopeHeight.store(o.scopeHeight.load(std::memory_order_relaxed), std::memory_order_relaxed);+ scope = o.scope; // shared: snapshot copies keep recording into the same historyreturn *this;}@@ -52,6 +64,12 @@ float Modulator::get(ModField f) const {case ModField::InputA: return (float)inputA.load(std::memory_order_relaxed);case ModField::InputB: return (float)inputB.load(std::memory_order_relaxed);case ModField::MathOffset: return mathOffset.load(std::memory_order_relaxed);+ case ModField::ScopeWindowMs: return scopeWindowMs.load(std::memory_order_relaxed);+ case ModField::ScopeSync: return (float)scopeSync.load(std::memory_order_relaxed);+ case ModField::ScopeWindowBeats: return scopeWindowBeats.load(std::memory_order_relaxed);+ case ModField::ScopeZoom: return (float)scopeZoom.load(std::memory_order_relaxed);+ case ModField::ScopeTrigger: return (float)scopeTrigger.load(std::memory_order_relaxed);+ case ModField::ScopeHeight: return scopeHeight.load(std::memory_order_relaxed);}return 0.0f;}@@ -73,6 +91,16 @@ void Modulator::set(ModField f, float v) {case ModField::InputA: inputA.store((int32_t)std::lround(v), std::memory_order_relaxed); break;case ModField::InputB: inputB.store((int32_t)std::lround(v), std::memory_order_relaxed); break;case ModField::MathOffset: mathOffset.store(v, std::memory_order_relaxed); break;+ case ModField::ScopeWindowMs: scopeWindowMs.store(std::clamp(v, 50.0f, 8000.0f), std::memory_order_relaxed); break;+ case ModField::ScopeSync: scopeSync.store(v > 0.5f ? 1 : 0, std::memory_order_relaxed); break;+ case ModField::ScopeWindowBeats: scopeWindowBeats.store(std::clamp(v, 0.25f, 32.0f), std::memory_order_relaxed); break;+ case ModField::ScopeZoom: { // snap to 1 / 2 / 4 / 8+ const int z = v >= 6.0f ? 8 : v >= 3.0f ? 4 : v >= 1.5f ? 2 : 1;+ scopeZoom.store(z, std::memory_order_relaxed);+ break;+ }+ case ModField::ScopeTrigger: scopeTrigger.store(v > 0.5f ? 1 : 0, std::memory_order_relaxed); break;+ case ModField::ScopeHeight: scopeHeight.store(std::clamp(v, 76.0f, 320.0f), std::memory_order_relaxed); break;}}diff --git a/src/native/nota.engine/src/engine/Modulation.h b/src/native/nota.engine/src/engine/Modulation.hindex 4df826eb..b38ed6f9 100644--- a/src/native/nota.engine/src/engine/Modulation.h+++ b/src/native/nota.engine/src/engine/Modulation.h@@ -17,6 +17,7 @@#include <atomic>#include <cmath>#include <cstdint>+#include <memory>namespace nota {@@ -29,7 +30,14 @@ namespace nota {// the UI to draw; passes the input through as its output.enum class ModulatorKind : int32_t { LFO = 0, EnvFollower = 1, MidiToCv = 2, Adsr = 3, Macro = 4, Math = 5, Scope = 6 };-inline constexpr int kScopeLen = 128; // CV oscilloscope history length+// Scope history (specs/047): one (value, time step) pair per audio block. 8192 blocks hold+// the longest 8 s window down to 64-frame blocks at 48 kHz.+inline constexpr int kScopeLen = 8192;+struct ScopeHistory {+ float value[kScopeLen] = {};+ float dt[kScopeLen] = {}; // seconds since the previous entry (the block length)+ std::atomic<int64_t> write{0}; // entries written so far (audio thread)+};enum class CvMode : int32_t { Add = 0, Multiply = 1, Override = 2 };enum class MathOp : int32_t { Add = 0, Subtract = 1, Multiply = 2, Invert = 3, Scale = 4, Min = 5, Max = 6 };@@ -48,6 +56,13 @@ enum class ModField : int32_t {InputA = 10,InputB = 11,MathOffset = 12, // Math (op = Waveform field; gain = Depth field)+ // Scope view settings (specs/047): read by the UI only; the engine just stores them.+ ScopeWindowMs = 13, // 50..8000 ms+ ScopeSync = 14, // 1 = the window is ScopeWindowBeats at the tempo+ ScopeWindowBeats = 15, // 0.25..32 beats+ ScopeZoom = 16, // 1, 2, 4 or 8+ ScopeTrigger = 17, // 0 free · 1 rising edge through 0+ ScopeHeight = 18, // trace height in the node, 76..320 px};struct Modulator {@@ -70,16 +85,27 @@ struct Modulator {std::atomic<int32_t> inputB{-1};std::atomic<float> mathOffset{0.0f}; // Math: Scale offsetstd::atomic<float> outValue{0.0f}; // runtime: this block's output (read by links + Math)- float scopeBuf[kScopeLen] = {}; // Scope: rolling history (audio-thread write)- std::atomic<int32_t> scopeWrite{0};-- void pushScope(float v) {- const int32_t w = scopeWrite.load(std::memory_order_relaxed);- scopeBuf[w & (kScopeLen - 1)] = v;- scopeWrite.store(w + 1, std::memory_order_relaxed);+ std::atomic<float> scopeWindowMs{1000.0f}; // Scope view settings (UI-only, saved)+ std::atomic<int32_t> scopeSync{0};+ std::atomic<float> scopeWindowBeats{4.0f};+ std::atomic<int32_t> scopeZoom{1};+ std::atomic<int32_t> scopeTrigger{0};+ std::atomic<float> scopeHeight{76.0f};+ // Scope: rolling history, allocated on the message thread for Scope nodes only and+ // shared by the track's snapshot copies (so the trace survives a republish). The+ // audio thread only writes into it.+ std::shared_ptr<ScopeHistory> scope;++ void pushScope(float v, float dt) {+ if (!scope) return;+ const int64_t w = scope->write.load(std::memory_order_relaxed);+ scope->value[w & (kScopeLen - 1)] = v;+ scope->dt[w & (kScopeLen - 1)] = dt;+ scope->write.store(w + 1, std::memory_order_release);}- // Copy the history oldest→newest into `out`; returns the count written.- int32_t readScope(float* out, int32_t cap) const;+ // Copy the newest entries oldest→newest into `values` (and `dts` when non-null);+ // returns the count written (at most cap, and at most what has been recorded).+ int32_t readScope(float* values, float* dts, int32_t cap) const;Modulator() = default;Modulator(const Modulator& o) { *this = o; }diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 66da1c54..18e5428c 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -477,6 +477,14 @@ if (args.Length >= 1 && args[0] == "--fold")Console.WriteLine(failures == 0 ? "FOLD PASSED" : $"FOLD FAILED ({failures})");return failures == 0 ? 0 : 1;}+// The Modular Scope view alone: `--scope`. Also part of the full run.+if (args.Length >= 1 && args[0] == "--scope")+{+ Console.WriteLine("-- scope view --");+ foreach (var (ok, label) in ScopeViewTests.Run()) Check(ok, label);+ Console.WriteLine(failures == 0 ? "SCOPE PASSED" : $"SCOPE FAILED ({failures})");+ return failures == 0 ? 0 : 1;+}// The project pan law alone: `--panlaw`. Also part of the full run.if (args.Length >= 1 && args[0] == "--panlaw"){@@ -15176,6 +15184,9 @@ foreach (var (ok, label) in AuroraNullTests.Run()) Check(ok, label);Console.WriteLine("-- device fold --");foreach (var (ok, label) in DeviceFoldTests.Run()) Check(ok, label);+Console.WriteLine("-- scope view --");+foreach (var (ok, label) in ScopeViewTests.Run()) Check(ok, label);+// The Linux JUCE message pump (.specify/bugs/linux-plugin-black-window): exported on every// platform and a safe no-op before any hosted plugin exists (the app ticks it on Linux).Console.WriteLine("-- plugin host pump --");diff --git a/tests/Nota.SmokeTest/ScopeViewTests.cs b/tests/Nota.SmokeTest/ScopeViewTests.csnew file mode 100644index 00000000..da18a94f--- /dev/null+++ b/tests/Nota.SmokeTest/ScopeViewTests.cs@@ -0,0 +1,192 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// The Modular Scope view (specs/047): the engine records a Scope's input with each block's+// time step, reads back the newest entries, and keeps the view settings (window, sync, zoom,+// trigger, height) as modulator fields that clamp, save and default on older projects.+// ScopeTrace lays the history into the window: a 2 s window of a 1 Hz LFO shows two cycles,+// the rising-edge trigger holds a periodic trace still, and a short history right-aligns.+// Also runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --scope`.++using System.Diagnostics;+using System.Text.RegularExpressions;+using Nota.Application;+using Nota.Infrastructure;++namespace Nota.SmokeTest;++internal static class ScopeViewTests+{+ private const int Lfo = 0, Scope = 6, Block = 256;++ public static IEnumerable<(bool ok, string label)> Run()+ {+ foreach (var r in History()) yield return r;+ foreach (var r in Settings()) yield return r;+ foreach (var r in Trace()) yield return r;+ }++ private static int Rising(ReadOnlySpan<double> xs, ReadOnlySpan<float> ys, int n)+ {+ int c = 0;+ for (int i = 1; i < n; i++) if (ys[i - 1] < 0 && ys[i] >= 0 && xs[i] > 0 && xs[i] <= 1) c++;+ return c;+ }++ private static IEnumerable<(bool, string)> History()+ {+ using var e = new NotaEngine();+ int t = e.AddInstrumentTrack();+ int lfo = e.ModulatorAdd(t, Lfo);+ e.ModulatorSet(t, lfo, 1, 0f); // free running+ e.ModulatorSet(t, lfo, 2, 1f); // 1 Hz+ int sc = e.ModulatorAdd(t, Scope);+ e.ModulatorSet(t, sc, 10, lfo); // input = the LFO+ var v = new float[ScopeTrace.HistoryLength]; var dt = new float[ScopeTrace.HistoryLength];+ yield return (e.ModulatorScopeTimed(t, sc, v, dt) == 0, "scope: a new Scope has no history yet");++ var buf = new float[Block * 2];+ e.Seek(0); e.Play();+ const int blocks = 600; // ~3 s+ for (int b = 0; b < blocks; b++) e.RenderOffline(buf, Block);+ e.StopTransport();+ int n = e.ModulatorScopeTimed(t, sc, v, dt);+ double sr = n > 0 && dt[0] > 0 ? Math.Round(Block / dt[0]) : 0; // the render rate+ double sum = 0; float lo = 1, hi = -1; bool steps = true;+ for (int i = 0; i < n; i++)+ {+ sum += dt[i]; lo = Math.Min(lo, v[i]); hi = Math.Max(hi, v[i]);+ if (Math.Abs(dt[i] - Block / sr) > 1e-6) steps = false;+ }+ yield return (n == blocks && steps && (sr == 44100 || sr == 48000) && Math.Abs(sum - blocks * Block / sr) < 1e-3,+ $"scope: one entry per block with its time step ({n} entries for {blocks} blocks, {sum:F3} s at {sr:0} Hz, steps {(steps ? "= block" : "off")})");+ yield return (lo < -0.98f && hi > 0.98f, $"scope: the history is the LFO's swing ({lo:F2} … {hi:F2})");++ var v10 = new float[10]; var dt10 = new float[10];+ int m = e.ModulatorScopeTimed(t, sc, v10, dt10);+ yield return (m == 10 && v10.AsSpan().SequenceEqual(v.AsSpan(n - 10, 10)),+ "scope: a short read returns the newest entries, oldest → newest");++ // Past the ring's length the reader still gets the newest values, within the safe margin.+ for (int b = 0; b < ScopeTrace.HistoryLength; b++) e.RenderOffline(buf, Block);+ int full = e.ModulatorScopeTimed(t, sc, v, dt);+ float live = e.ModulatorValue(t, lfo);+ yield return (full > ScopeTrace.HistoryLength - 300 && full < ScopeTrace.HistoryLength,+ $"scope: a full ring reads {full} of {ScopeTrace.HistoryLength} (a margin the audio thread may be writing)");+ yield return (Math.Abs(v[full - 1] - e.ModulatorValue(t, sc)) < 0.2f || Math.Abs(v[full - 1] - live) < 0.2f,+ "scope: the last entry is the current value");++ var dummy = new float[16];+ yield return (e.ModulatorScopeTimed(t, lfo, dummy, dummy) == 0 && e.ModulatorScopeTimed(t, 999, dummy, dummy) == 0,+ "scope: an LFO or a missing id has no history");+ yield return (e.ModulatorScope(t, sc, dummy) == 16, "scope: the untimed read still works (newest values)");++ // The history survives a republish of the track (another node added).+ int before = e.ModulatorScopeTimed(t, sc, v, dt);+ e.ModulatorAdd(t, Lfo);+ yield return (e.ModulatorScopeTimed(t, sc, v, dt) == before, "scope: adding another node keeps the trace");+ }++ private static IEnumerable<(bool, string)> Settings()+ {+ using var e = new NotaEngine();+ int t = e.AddInstrumentTrack();+ int sc = e.ModulatorAdd(t, Scope);+ float F(int f) => e.ModulatorGet(t, sc, f);+ yield return (F(13) == 1000f && F(14) == 0f && F(15) == 4f && F(16) == 1f && F(17) == 0f && F(18) == 76f,+ "scope: defaults are a 1 s window, free, 4 beats, 1×, no trigger, 76 px");+ e.ModulatorSet(t, sc, 13, 20000f); bool msHi = F(13) == 8000f;+ e.ModulatorSet(t, sc, 13, 1f); bool msLo = F(13) == 50f;+ e.ModulatorSet(t, sc, 16, 3f); bool z4 = F(16) == 4f;+ e.ModulatorSet(t, sc, 16, 100f); bool z8 = F(16) == 8f;+ e.ModulatorSet(t, sc, 18, 500f); bool hHi = F(18) == 320f;+ e.ModulatorSet(t, sc, 15, 64f); bool bHi = F(15) == 32f;+ yield return (msHi && msLo && z4 && z8 && hHi && bHi, "scope: the window, zoom, beats and height clamp (8 s / 50 ms, 4× / 8×, 32 beats, 320 px)");++ e.ModulatorSet(t, sc, 13, 2500f); e.ModulatorSet(t, sc, 14, 1f); e.ModulatorSet(t, sc, 15, 2f);+ e.ModulatorSet(t, sc, 16, 2f); e.ModulatorSet(t, sc, 17, 1f); e.ModulatorSet(t, sc, 18, 180f);+ var w = new List<string>();+ var doc = ProjectService.Capture(e, new TransportState(120, 1, false, false), w);+ string dir = Path.Combine(Path.GetTempPath(), "nota-scope-" + Guid.NewGuid().ToString("N"));+ try+ {+ ProjectService.Save(doc, dir, e);+ using (var e2 = new NotaEngine())+ {+ ProjectService.Apply(ProjectService.Load(dir), e2, dir);+ e2.TryGetTrackInfo(0, out var ti);+ int id = e2.ModulatorIdAt(ti.Id, 0);+ float G(int f) => e2.ModulatorGet(ti.Id, id, f);+ yield return (G(13) == 2500f && G(14) == 1f && G(15) == 2f && G(16) == 2f && G(17) == 1f && G(18) == 180f,+ "scope: the settings survive save and reopen");+ }+ // An older project has no Scope fields: it opens with the defaults.+ string manifest = Path.Combine(dir, ProjectService.ManifestName);+ string json = File.ReadAllText(manifest);+ string stripped = Regex.Replace(json, ",\\s*\"Scope(WindowMs|Sync|WindowBeats|Zoom|Trigger|Height)\"\\s*:\\s*[^,}\\]\\s]+", "", RegexOptions.IgnoreCase);+ File.WriteAllText(manifest, stripped);+ using (var e3 = new NotaEngine())+ {+ ProjectService.Apply(ProjectService.Load(dir), e3, dir);+ e3.TryGetTrackInfo(0, out var ti);+ int id = e3.ModulatorIdAt(ti.Id, 0);+ float G(int f) => e3.ModulatorGet(ti.Id, id, f);+ yield return (stripped != json && e3.ModulatorKind(ti.Id, id) == Scope+ && G(13) == 1000f && G(14) == 0f && G(16) == 1f && G(17) == 0f && G(18) == 76f,+ "scope: an older project opens with the default settings");+ }+ }+ finally { try { Directory.Delete(dir, true); } catch (IOException) { } }+ }++ private static IEnumerable<(bool, string)> Trace()+ {+ const int N = ScopeTrace.HistoryLength;+ const float step = 0.00267f; // ~128 frames at 48 kHz+ var v = new float[N]; var dt = new float[N];+ var xs = new double[N]; var ys = new float[N];+ void Fill(int shift)+ {+ for (int i = 0; i < N; i++) { dt[i] = step; v[i] = (float)Math.Sin(2 * Math.PI * 1.0 * (i + shift) * step + 0.3); }+ }++ Fill(0);+ int n = ScopeTrace.Layout(v, dt, 2.0, false, xs, ys, out bool trig);+ int cycles = Rising(xs, ys, n);+ yield return (!trig && cycles == 2 && xs[0] <= 0 && Math.Abs(xs[n - 1] - 1) < 1e-9,+ $"trace: a 2 s window of a 1 Hz LFO shows two cycles, newest at the right ({cycles} rising crossings)");+ yield return (Math.Abs(ScopeTrace.WindowSeconds(true, 1000, 4, 120) - 2.0) < 1e-9 && Math.Abs(ScopeTrace.WindowSeconds(false, 250, 4, 120) - 0.25) < 1e-9,+ "trace: 4 beats at 120 BPM is 2 s; 250 ms is 0.25 s");++ // Trigger: across frames (the history moving on by 1..40 blocks) the trace starts at the+ // rising crossing each time, within a fraction of a block.+ double worst = 0; bool allTrig = true;+ for (int s = 1; s <= 40; s++)+ {+ Fill(s * 7);+ n = ScopeTrace.Layout(v, dt, 1.5, true, xs, ys, out trig);+ allTrig &= trig;+ // Where the drawn line crosses 0 between its first two points.+ double x0 = xs[0] + (xs[1] - xs[0]) * (-ys[0] / (double)(ys[1] - ys[0]));+ worst = Math.Max(worst, Math.Abs(x0) * 1.5);+ }+ yield return (allTrig && worst < step * 0.05, $"trace: the trigger holds a periodic shape still (start within {worst * 1000:F3} ms of the crossing)");++ var flat = Enumerable.Repeat(0.5f, 500).ToArray(); var fdt = Enumerable.Repeat(step, 500).ToArray();+ n = ScopeTrace.Layout(flat, fdt, 0.5, true, xs, ys, out trig);+ yield return (!trig && n > 2 && Math.Abs(xs[n - 1] - 1) < 1e-9, "trace: with no crossing the trigger runs free");++ n = ScopeTrace.Layout(flat.AsSpan(0, 100), fdt.AsSpan(0, 100), 8.0, false, xs, ys, out _);+ yield return (n == 100 && xs[0] > 0.9 && Math.Abs(xs[n - 1] - 1) < 1e-9, "trace: a short history draws right-aligned");++ Fill(0);+ var sw = Stopwatch.StartNew();+ for (int k = 0; k < 200; k++) ScopeTrace.Layout(v, dt, 8.0, true, xs, ys, out _);+ double ms = sw.Elapsed.TotalMilliseconds / 200;+ yield return (ms < 1.0, $"trace: laying out a full 8 s history takes {ms:F3} ms");++ yield return (ScopeTrace.BeatsLabel(0.25) == "1/16" && ScopeTrace.BeatsLabel(1) == "1/4" && ScopeTrace.BeatsLabel(4) == "1 bar"+ && ScopeTrace.BeatsLabel(32) == "8 bars" && ScopeTrace.MsLabel(1500) == "1.5\u2009s" && ScopeTrace.MsLabel(50) == "50\u2009ms",+ "trace: window labels (1/16 … 8 bars, 50 ms … 1.5 s)");+ }+}