diff --git a/CMakeLists.txt b/CMakeLists.txt index 91d5899..2f45f00 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -905,13 +905,16 @@ target_include_directories(keyboard_strip PUBLIC src) target_link_libraries(keyboard_strip PUBLIC editor_geometry) # waveform_view (Phase S11) — PURE frame<->pixel mapping, marker grab regions, drag-delta -# frame resolver, and the zero-crossing snap for the capture-first editor's waveform surface -# (draggable start + loop markers over the picked capture's decoded PCM). The mirror of -# keyboard_strip; links editor_geometry for the shared Rect and peaks for the AudioSample -# alias the snap scans. NEITHER SDK. +# frame resolver, the zero-crossing snap, and the WAVEFORM band's drawn surface (channel +# lanes + the overlay area — see waveform_view.h) for the capture-first editor. The mirror of +# keyboard_strip; links editor_geometry for the shared Rect/OverlayArea, peaks for the +# AudioSample alias the snap scans + the per-lane Envelope split. sample_bands is a PRIVATE +# implementation dep (waveformLanes, used internally) — nothing in the public header needs it. +# NEITHER SDK. add_library(waveform_view STATIC src/core/instrument/ui/waveform_view.cpp) target_include_directories(waveform_view PUBLIC src) target_link_libraries(waveform_view PUBLIC editor_geometry peaks) +target_link_libraries(waveform_view PRIVATE sample_bands) # bank_sync (Phase S9/S8 reader) — PURE decision logic for the instrument's off-audio-thread # poll: parse/compare the S9 bank-generation stamp, and the S8 assignment-request CONSUME @@ -1034,10 +1037,11 @@ add_executable(keyboard_strip_tests tests/test_keyboard_strip.cpp) target_link_libraries(keyboard_strip_tests PRIVATE keyboard_strip) add_test(NAME keyboard_strip_tests COMMAND keyboard_strip_tests) -# waveform_view (S11): the pure marker geometry + zero-crossing snap. Links ONLY waveform_view -# (+ its pure editor_geometry/peaks deps) — NEITHER SDK — the same plain-data-boundary proof. +# waveform_view (S11): the pure marker geometry + zero-crossing snap. Links waveform_view (+ +# its pure editor_geometry/peaks deps) plus sample_bands directly, since the test exercises +# waveformLanes/kWaveformMinHeight/kLaneGap, which waveform_view no longer re-exports. NEITHER SDK. add_executable(waveform_view_tests tests/test_waveform_view.cpp) -target_link_libraries(waveform_view_tests PRIVATE waveform_view) +target_link_libraries(waveform_view_tests PRIVATE waveform_view sample_bands) add_test(NAME waveform_view_tests COMMAND waveform_view_tests) # bank_sync (S9/S8 reader): the pure generation-parse + assignment-consume decision. Links diff --git a/src/core/instrument/CLAUDE.md b/src/core/instrument/CLAUDE.md index 3ae371f..766cb03 100644 --- a/src/core/instrument/CLAUDE.md +++ b/src/core/instrument/CLAUDE.md @@ -216,11 +216,12 @@ slider couldn't. Two pure modules split the forward (draw) and inverse (edit) ma ### `ui/` -- `editor_geometry` (`core/instrument/ui`) — the shared geometry VOCABULARY every instrument UI module speaks: the `core::ui::Rect` alias + `contains()`, nothing else. Header-only (an INTERFACE CMake target), so it carries no layout of its own. -- `sample_bands` — **THE band-stack allocator**, and the only module that owns the Sample face's vertical inventory: three bands top-to-bottom (CHROME toolbar+control row / WAVEFORM elastic, floored at two stacked lanes / DECKS bottom-anchored at the knob deck's own wrapped height), plus the waveform band's lane split. A shared READ-ONLY surface for every band owner — a band's interior module lays out inside the rect it is handed and never re-allocates the stack. +- `editor_geometry` (`core/instrument/ui`) — the shared geometry VOCABULARY every instrument UI module speaks: the `core::ui::Rect` alias, `contains()`, and `OverlayArea` (a one-field `Rect` wrapper, no implicit conversion from `Rect`). Header-only (an INTERFACE CMake target), so it carries no layout of its own. +- `sample_bands` — **THE band-stack allocator**, and the only module that owns the Sample face's vertical inventory: three bands top-to-bottom (CHROME toolbar+control row / WAVEFORM elastic, floored at two stacked lanes / DECKS bottom-anchored at the knob deck's own wrapped height), plus the waveform band's lane split (`waveformLanes` takes a resolved `LaneSplit`, not a raw bool — only `waveformSurface` folds the source-channel-count decision in). A shared READ-ONLY surface for every band owner — a band's interior module lays out inside the rect it is handed and never re-allocates the stack. - `sample_chrome` — the CHROME band's interior: the toolbar row (title + Browse) over the control row (root strip, preview, velocity knob cell, curve button, channel toggle). The fixed run is right-anchored; the root strip takes the remainder. - `keyboard_strip` — piano-keyboard strip: MIDI-note→key rect mapping, black/white key layout, hit-test, root-marker rect, and the drag-delta note resolver. -- `waveform_view` — waveform/marker geometry: maps frame span linearly across a rect; generic named draggable markers with drag-delta resolver, clamp, and zero-crossing snap. +- `waveform_view` — the WAVEFORM band's interior: `waveformSurface` resolves the drawn lane(s) (two stacked lanes, L over R, only when the mode is stereo AND the source has a second channel — a mono source under stereo mode is dual-mono and draws one lane) plus **the** overlay area, and `laneEnvelope` splits one multi-channel envelope pass per lane. Also maps frame span linearly across a rect; generic named draggable markers with drag-delta resolver, clamp, and zero-crossing snap. + - **Overlay contract (consumed by later waveform work).** `WaveformSurface::overlay` — equivalently the standalone `waveformOverlayArea(band)` — is the FULL band in both modes. Everything riding the waveform (the amp-envelope trace and its node handles, the start/loop markers, the loop region) draws ONCE into it, spanning both stacked lanes; hit-testing resolves against the same area so a grab in the lower lane reaches them. Anything drawn or hit-tested per lane is a duplicate and a defect — structurally enforced: `overlay` is the distinct `OverlayArea` type (`editor_geometry`), not `Rect`, so every overlay-consuming API (`frameToX`/`markerAtPoint`/`resolveDragFrame`, `envelope_edit`'s `nodeAtPoint`/`resolveNodeDrag`, `envelope_overlay`'s `buildEnvelopePolyline`) rejects a lane rect at compile time rather than silently accepting one. - `capture_browser` — capture browser: card-grid layout + bank-filter tab strip geometry and hit-test; knows only counts and rects, draws nothing. - `browser_scroll` — scroll + type-to-filter layered over `capture_browser`: vertical scroll offset, scrollbar thumb, thumb-drag mapping, and name-substring search. - `param_slider` — parameter control-panel: vertical stack of TOGGLE (two-segment selector) and SLIDER (horizontal track) rows; maps normalized value to/from handle pixel. diff --git a/src/core/instrument/ui/editor_geometry.h b/src/core/instrument/ui/editor_geometry.h index 08f5cdb..fbd88f3 100644 --- a/src/core/instrument/ui/editor_geometry.h +++ b/src/core/instrument/ui/editor_geometry.h @@ -1,9 +1,10 @@ #pragma once // editor_geometry.h — the shared geometry vocabulary for the VST3 editor's pure modules: -// the one concrete `Rect` (aliased from core/ui) and its half-open `contains()`. Every -// instrument UI module speaks these types, so they live in one place rather than each -// module reaching into core/ui separately. The Sample face's own layout lives in -// sample_bands (the band-stack allocator) and the per-band modules. +// the one concrete `Rect` (aliased from core/ui), its half-open `contains()`, and +// `OverlayArea` (the waveform band's shared overlay rect — see the contract in +// waveform_view.h). Every instrument UI module speaks these types, so they live in one +// place rather than each module reaching into core/ui separately. The Sample face's own +// layout lives in sample_bands (the band-stack allocator) and the per-band modules. #include "core/ui/rect.h" @@ -12,4 +13,13 @@ namespace reasampler::instrument::ui { using Rect = ::reasampler::ui::Rect; using ::reasampler::ui::contains; +// Distinct from Rect on purpose (no implicit Rect->OverlayArea conversion): only +// waveformOverlayArea/WaveformSurface::overlay construct one, so an overlay-only API can +// require this type and reject a lane rect at compile time instead of silently accepting it. +struct OverlayArea { + Rect rect; + bool operator==(const OverlayArea& o) const { return rect == o.rect; } + bool operator!=(const OverlayArea& o) const { return !(*this == o); } +}; + } // namespace reasampler::instrument::ui diff --git a/src/core/instrument/ui/envelope_edit.cpp b/src/core/instrument/ui/envelope_edit.cpp index cb0c742..8f11bc1 100644 --- a/src/core/instrument/ui/envelope_edit.cpp +++ b/src/core/instrument/ui/envelope_edit.cpp @@ -63,7 +63,8 @@ bool nodeInMode(EnvNode n, EnvMode m) { } // namespace -NodeHit nodeAtPoint(const AmpEnvelope& env, const Rect& area, double totalSeconds, int x, int y) { +NodeHit nodeAtPoint(const AmpEnvelope& env, const OverlayArea& area, double totalSeconds, int x, + int y) { const std::vector poly = buildEnvelopePolyline(env, area, totalSeconds); // Nearest draggable, mode-matching node within the pick radius wins (Chebyshev distance); // ties go to the earlier draw-order node. Only matters for Trigger's zero-fade-out @@ -81,16 +82,17 @@ NodeHit nodeAtPoint(const AmpEnvelope& env, const Rect& area, double totalSecond return best; } -AmpEnvelope resolveNodeDrag(const AmpEnvelope& grabEnv, EnvNode node, const Rect& area, +AmpEnvelope resolveNodeDrag(const AmpEnvelope& grabEnv, EnvNode node, const OverlayArea& area, double totalSeconds, const EnvClampBounds& bounds, int dxPixels, int dyPixels) { AmpEnvelope out = grabEnv; if (!isDraggable(node) || !nodeInMode(node, grabEnv.mode)) return out; - const double secPerPx = secondsPerPixel(area, totalSeconds); + const Rect& rect = area.rect; + const double secPerPx = secondsPerPixel(rect, totalSeconds); if (secPerPx <= 0.0) return out; // degenerate area / duration — no motion const double dSec = static_cast(dxPixels) * secPerPx; - const double gateDSec = static_cast(dxPixels) * gateSecondsPerPixel(area); + const double gateDSec = static_cast(dxPixels) * gateSecondsPerPixel(rect); switch (node) { // Gate: each cumulative-time node edits its own segment duration. Non-negative durations @@ -106,7 +108,7 @@ AmpEnvelope resolveNodeDrag(const AmpEnvelope& grabEnv, EnvNode node, const Rect case EnvNode::DecayEnd: { // X sets decay time, Y sets sustain level (drag down = higher y = lower level). out.decaySeconds = std::clamp(grabEnv.decaySeconds + gateDSec, 0.0, bounds.maxDecaySeconds); - const double lvlPerPx = levelPerPixel(area); + const double lvlPerPx = levelPerPixel(rect); const double dLevel = -static_cast(dyPixels) * lvlPerPx; out.sustainLevel = std::clamp(grabEnv.sustainLevel + dLevel, 0.0, 1.0); break; diff --git a/src/core/instrument/ui/envelope_edit.h b/src/core/instrument/ui/envelope_edit.h index 55a48a7..c9b5e06 100644 --- a/src/core/instrument/ui/envelope_edit.h +++ b/src/core/instrument/ui/envelope_edit.h @@ -54,7 +54,9 @@ struct NodeHit { bool hit = false; EnvNode node = EnvNode::Origin; // meaningful only when hit == true }; -NodeHit nodeAtPoint(const AmpEnvelope& env, const Rect& area, double totalSeconds, int x, int y); +// Takes the waveform overlay (not a lane) — see waveform_view.h's overlay contract. +NodeHit nodeAtPoint(const AmpEnvelope& env, const OverlayArea& area, double totalSeconds, int x, + int y); // Resolves a drag of `node` to a new AmpEnvelope. `grabEnv` is the envelope as of grab time (the // shell snapshots it on button-down so the delta is absolute, not accumulated); `dxPixels`/ @@ -65,7 +67,7 @@ NodeHit nodeAtPoint(const AmpEnvelope& env, const Rect& area, double totalSecond // * A non-draggable node, an other-mode node, a zero-size area, or totalSeconds <= 0 returns // `grabEnv` unchanged. // Only the dragged node's param(s) change. Pure. -AmpEnvelope resolveNodeDrag(const AmpEnvelope& grabEnv, EnvNode node, const Rect& area, +AmpEnvelope resolveNodeDrag(const AmpEnvelope& grabEnv, EnvNode node, const OverlayArea& area, double totalSeconds, const EnvClampBounds& bounds, int dxPixels, int dyPixels); diff --git a/src/core/instrument/ui/envelope_overlay.cpp b/src/core/instrument/ui/envelope_overlay.cpp index b5e0ffa..30f4ee3 100644 --- a/src/core/instrument/ui/envelope_overlay.cpp +++ b/src/core/instrument/ui/envelope_overlay.cpp @@ -149,15 +149,16 @@ std::vector triggerPolyline(const AmpEnvelope& env, const Rect& area, } // namespace -std::vector buildEnvelopePolyline(const AmpEnvelope& env, const Rect& area, +std::vector buildEnvelopePolyline(const AmpEnvelope& env, const OverlayArea& area, double totalSeconds) { - if (area.width <= 0 || area.height <= 0 || totalSeconds <= 0.0) { + const Rect& rect = area.rect; + if (rect.width <= 0 || rect.height <= 0 || totalSeconds <= 0.0) { // Degenerate surface: flat two-point baseline so the shell always has a line. - return {vtx(EnvNode::Origin, area, 1.0, 0.0, 0.0), - vtx(EnvNode::ReleaseEnd, area, 1.0, 1.0, 0.0)}; + return {vtx(EnvNode::Origin, rect, 1.0, 0.0, 0.0), + vtx(EnvNode::ReleaseEnd, rect, 1.0, 1.0, 0.0)}; } - return env.mode == EnvMode::Gate ? gatePolyline(env, area) - : triggerPolyline(env, area, totalSeconds); + return env.mode == EnvMode::Gate ? gatePolyline(env, rect) + : triggerPolyline(env, rect, totalSeconds); } } // namespace reasampler::instrument::ui diff --git a/src/core/instrument/ui/envelope_overlay.h b/src/core/instrument/ui/envelope_overlay.h index 0b88197..e764f8f 100644 --- a/src/core/instrument/ui/envelope_overlay.h +++ b/src/core/instrument/ui/envelope_overlay.h @@ -93,8 +93,9 @@ double gatePxPerSecond(const Rect& area); // Gate's x-axis is a bounded schematic independent of totalSeconds (does NOT line up with the // waveform under it); Trigger's x-axis is PCM-aligned wall-clock. Every vertex is clamped inside // the canvas: x in [area.x, area.right()-1], y in [area.y, area.bottom()-1]. A degenerate area -// or totalSeconds <= 0 yields the flat two-point baseline [Origin, end at level 0]. -std::vector buildEnvelopePolyline(const AmpEnvelope& env, const Rect& area, +// or totalSeconds <= 0 yields the flat two-point baseline [Origin, end at level 0]. Takes the +// waveform overlay (not a lane) — see waveform_view.h's overlay contract. +std::vector buildEnvelopePolyline(const AmpEnvelope& env, const OverlayArea& area, double totalSeconds); // Maps a time (seconds) to a pixel x inside `area`, linear and clamped at both ends. Shared diff --git a/src/core/instrument/ui/sample_bands.cpp b/src/core/instrument/ui/sample_bands.cpp index f0b54c4..4500b5f 100644 --- a/src/core/instrument/ui/sample_bands.cpp +++ b/src/core/instrument/ui/sample_bands.cpp @@ -32,10 +32,10 @@ SampleBands computeSampleBands(int w, int h, int deckHeight) { return b; } -WaveformLanes waveformLanes(const Rect& waveform, bool stereo) { +WaveformLanes waveformLanes(const Rect& waveform, LaneSplit split) { WaveformLanes lanes; if (waveform.empty()) return lanes; - if (!stereo) { + if (split == LaneSplit::Single) { lanes.upper = waveform; // one lane; `lower` stays empty return lanes; } diff --git a/src/core/instrument/ui/sample_bands.h b/src/core/instrument/ui/sample_bands.h index 6049d75..fe6c80e 100644 --- a/src/core/instrument/ui/sample_bands.h +++ b/src/core/instrument/ui/sample_bands.h @@ -48,6 +48,12 @@ struct WaveformLanes { Rect upper; Rect lower; // empty() in mono }; -WaveformLanes waveformLanes(const Rect& waveform, bool stereo); + +// A RESOLVED lane-split decision, not "is the instrument in stereo mode" — a mono source +// stays Single even in stereo mode (dual-mono, no second channel to draw). Only +// waveformSurface (waveform_view) folds the source channel count in; a bare bool here would +// let a caller pass isStereoMode straight through and skip that check. +enum class LaneSplit { Single, Stereo }; +WaveformLanes waveformLanes(const Rect& waveform, LaneSplit split); } // namespace reasampler::instrument::ui diff --git a/src/core/instrument/ui/waveform_view.cpp b/src/core/instrument/ui/waveform_view.cpp index 324a1a6..2fbf2d7 100644 --- a/src/core/instrument/ui/waveform_view.cpp +++ b/src/core/instrument/ui/waveform_view.cpp @@ -3,8 +3,11 @@ #include "core/instrument/ui/waveform_view.h" #include +#include #include // std::abs (int overload) +#include "core/instrument/ui/sample_bands.h" // waveformLanes (the band's lane inventory) + namespace reasampler::instrument::ui { namespace { @@ -17,30 +20,57 @@ std::int64_t clampFrame(std::int64_t f, std::int64_t frameCount) { } // namespace -int frameToX(const Rect& area, std::int64_t frameCount, std::int64_t frame) { - const int w = std::max(0, area.width); - if (frameCount <= 0 || w <= 0) return area.x; +OverlayArea waveformOverlayArea(const Rect& band) { + return OverlayArea{band.empty() ? Rect{} : band}; +} + +WaveformSurface waveformSurface(const Rect& band, bool stereoMode, int sourceChannels) { + WaveformSurface s; + if (band.empty()) return s; + s.overlay = waveformOverlayArea(band); + const bool twoLanes = stereoMode && sourceChannels >= 2; + const WaveformLanes lanes = + waveformLanes(band, twoLanes ? LaneSplit::Stereo : LaneSplit::Single); + s.upper = lanes.upper; + s.lower = lanes.lower; + // Derived from the resolved lanes, not `twoLanes` — a stereo split's integer division + // rounds the lower lane to empty for a band this thin (height <= 3), far below the + // allocator's kWaveformMinHeight floor but reachable if this is called directly with an + // arbitrary rect (as tests do). + s.laneCount = lanes.lower.empty() ? 1 : 2; + return s; +} + +audio::Envelope laneEnvelope(const audio::Envelope& env, int lane) { + if (lane < 0 || static_cast(lane) >= env.size()) return {}; + return audio::Envelope{env[static_cast(lane)]}; +} + +int frameToX(const OverlayArea& area, std::int64_t frameCount, std::int64_t frame) { + const int w = std::max(0, area.rect.width); + if (frameCount <= 0 || w <= 0) return area.rect.x; const std::int64_t f = clampFrame(frame, frameCount); // x = left + round(f * w / frameCount); multiply before divide to keep this exact. const std::int64_t num = f * static_cast(w) + frameCount / 2; - return area.x + static_cast(num / frameCount); + return area.rect.x + static_cast(num / frameCount); } -std::int64_t xToFrame(const Rect& area, std::int64_t frameCount, int x) { - const int w = std::max(0, area.width); +std::int64_t xToFrame(const OverlayArea& area, std::int64_t frameCount, int x) { + const Rect& r = area.rect; + const int w = std::max(0, r.width); if (frameCount <= 0 || w <= 0) return 0; - if (x <= area.x) return 0; - if (x >= area.right()) return frameCount; - const std::int64_t dx = static_cast(x - area.x); + if (x <= r.x) return 0; + if (x >= r.right()) return frameCount; + const std::int64_t dx = static_cast(x - r.x); // Inverse of frameToX: frame = round(dx * frameCount / w). const std::int64_t num = dx * frameCount + static_cast(w) / 2; return clampFrame(num / static_cast(w), frameCount); } -int markerAtPoint(const Rect& area, std::int64_t frameCount, const std::int64_t* frames, +int markerAtPoint(const OverlayArea& area, std::int64_t frameCount, const std::int64_t* frames, int count, int x, int y) { if (count <= 0 || frames == nullptr) return -1; - if (!contains(area, x, y)) return -1; + if (!contains(area.rect, x, y)) return -1; for (int i = 0; i < count; ++i) { const int mx = frameToX(area, frameCount, frames[i]); if (x >= mx - kMarkerGrabWidth && x <= mx + kMarkerGrabWidth) return i; @@ -48,11 +78,11 @@ int markerAtPoint(const Rect& area, std::int64_t frameCount, const std::int64_t* return -1; } -std::int64_t resolveDragFrame(const Rect& area, std::int64_t frameCount, std::int64_t startFrame, - int dxPixels) { +std::int64_t resolveDragFrame(const OverlayArea& area, std::int64_t frameCount, + std::int64_t startFrame, int dxPixels) { const std::int64_t start = clampFrame(startFrame, frameCount); if (dxPixels == 0) return start; - const int w = std::max(0, area.width); + const int w = std::max(0, area.rect.width); if (frameCount <= 0 || w <= 0) return start; // no room to move // Proportional shift, rounded to the nearest frame (same linear map as frameToX/xToFrame). const std::int64_t magnitude = diff --git a/src/core/instrument/ui/waveform_view.h b/src/core/instrument/ui/waveform_view.h index 3dc58a9..b3b8efc 100644 --- a/src/core/instrument/ui/waveform_view.h +++ b/src/core/instrument/ui/waveform_view.h @@ -1,46 +1,81 @@ -// waveform_view.h — waveform/marker geometry + zero-crossing snap. Mirror of keyboard_strip/ -// editor_geometry: frame<->pixel + marker hit-test + snap arithmetic lives here, unit-tested -// outside the DAW; the shell draws and marshals mouse events into it. +// waveform_view.h — the WAVEFORM band's interior: the drawn lane/overlay surface, plus +// frame<->pixel mapping, marker hit-test and zero-crossing snap. Unit-tested outside the +// DAW; the shell draws and marshals mouse events into it. // -// The surface maps a sample's full frame span [0, frameCount] linearly across a horizontal -// waveform rect. Markers are a generic N-named-marker set (not hardcoded specials), so a -// different mode (e.g. start + %-length end + fades) can repurpose the same machinery. +// The band maps a sample's full frame span [0, frameCount] linearly across its width. +// Markers are a generic N-named-marker set (not hardcoded specials), so a different mode +// (e.g. start + %-length end + fades) can repurpose the same machinery. #pragma once #include -#include "core/instrument/ui/editor_geometry.h" // Rect, contains -#include "core/audio/peaks.h" // AudioSample (float) +#include "core/instrument/ui/editor_geometry.h" // Rect, OverlayArea, contains +#include "core/audio/peaks.h" // AudioSample (float), Envelope namespace reasampler::instrument::ui { using audio::AudioSample; +// What the waveform band actually draws: the channel lane(s), and THE rect every overlay +// riding the waveform occupies. +// +// OVERLAY CONTRACT — `overlay` is the whole band in BOTH modes, never a lane. The amp +// envelope trace and its node handles, the start/loop markers, and the loop region draw +// ONCE into `overlay`, spanning both stacked lanes in stereo. Hit-testing reads the same +// rect, so a grab in the lower lane resolves to the same overlay item as one in the upper. +// Anything that draws per lane is a duplicate and a defect. +struct WaveformSurface { + Rect upper; // lane 0 -> channel 0 (LEFT); the whole band when single-lane + Rect lower; // lane 1 -> channel 1 (RIGHT); empty() when single-lane + OverlayArea overlay; // the full band, both modes + int laneCount = 0; // 0 on a degenerate band, else 1 or 2 — matches `lower`'s emptiness + // (2 iff lower non-empty). For a non-empty band <= 2px tall, `upper` + // can be empty too while this still reports 1 — unreachable through + // the band-stack allocator's kWaveformMinHeight floor. +}; + +// Resolves the surface for a waveform band. Two lanes need BOTH stereo mode and a source +// that has a second channel to show: a mono source under stereo mode is dual-mono, so a +// second lane would be the redundant duplicate single-lane mode exists to avoid. +WaveformSurface waveformSurface(const Rect& band, bool stereoMode, int sourceChannels); + +// THE overlay area, standalone — same value as WaveformSurface::overlay, for the hit-test +// paths that have no channel count to hand. An overlay's rect never depends on the lane +// split, which is exactly the contract. +OverlayArea waveformOverlayArea(const Rect& band); + +// The single-channel envelope lane `lane` draws, taken from a multi-channel envelope +// computed in ONE computeEnvelope pass (it already envelopes channels independently, so a +// second lane costs no second scan of the PCM). Lane 0 is the upper lane and takes channel +// 0, lane 1 the lower and channel 1 — the L-above-R order. An out-of-range lane yields an +// empty envelope, which draws as a bare midline. +audio::Envelope laneEnvelope(const audio::Envelope& env, int lane); + // Pixel width of a marker's grab region either side of its x line. Mirrors keyboard_strip's // edge-grab idiom. inline constexpr int kMarkerGrabWidth = 5; // x pixel of `frame` under the linear map: frame 0 -> area.x, frame frameCount -> area.right(). // Frame is clamped to [0, frameCount] before mapping. frameCount <= 0 or a zero-width area pins -// every frame to area.x. -int frameToX(const Rect& area, std::int64_t frameCount, std::int64_t frame); +// every frame to area.x. Takes the overlay (not a lane) — see the OVERLAY CONTRACT above. +int frameToX(const OverlayArea& area, std::int64_t frameCount, std::int64_t frame); // Inverse of frameToX: the frame a point x maps to, clamped to [0, frameCount]. A point left of // area.x yields 0; right of area.right() yields frameCount. -std::int64_t xToFrame(const Rect& area, std::int64_t frameCount, int x); +std::int64_t xToFrame(const OverlayArea& area, std::int64_t frameCount, int x); // Which marker (index into the caller's parallel `frames` array, in draw order) a grab at // (x, y) lands on, or -1 for a miss. A marker is grabbed when x is within kMarkerGrabWidth of // its drawn x and y is inside `area`. First marker in draw order wins an overlapping tie. -int markerAtPoint(const Rect& area, std::int64_t frameCount, const std::int64_t* frames, +int markerAtPoint(const OverlayArea& area, std::int64_t frameCount, const std::int64_t* frames, int count, int x, int y); // Resolves a drag to a new frame: `startFrame` shifted by round(dxPixels * frameCount / // areaWidth), clamped to [0, frameCount]. The shell applies between-marker clamps (e.g. // start <= loopEnd) after this per-marker resolve. -std::int64_t resolveDragFrame(const Rect& area, std::int64_t frameCount, std::int64_t startFrame, - int dxPixels); +std::int64_t resolveDragFrame(const OverlayArea& area, std::int64_t frameCount, + std::int64_t startFrame, int dxPixels); // Nearest zero-crossing frame to `target` in the mono PCM, for loop/start snap. A crossing is a // frame i (1 <= i < frames) where pcm[i-1] and pcm[i] differ in sign (pcm[i] == 0 snaps to i). diff --git a/src/shell/instrument/editor_input_waveform.cpp b/src/shell/instrument/editor_input_waveform.cpp index 1918dc1..0fa86c2 100644 --- a/src/shell/instrument/editor_input_waveform.cpp +++ b/src/shell/instrument/editor_input_waveform.cpp @@ -1,6 +1,8 @@ // editor_input_waveform.cpp — the WAVEFORM band's input: grabbing an envelope node or a // start/loop marker, and resolving both drags live against the pure inverse maps // (envelope_edit, waveform_view). Windows-only. +// +// Overlay contract: see waveform_view.h's WaveformSurface. #include "shell/instrument/reasampler_editor.h" @@ -11,7 +13,7 @@ #include #include "core/instrument/ui/envelope_edit.h" // nodeAtPoint / resolveNodeDrag -#include "core/instrument/ui/waveform_view.h" // markerAtPoint / resolveDragFrame / snap +#include "core/instrument/ui/waveform_view.h" // waveformOverlayArea / markerAtPoint / snap #include "shell/instrument/editor_internal.h" #include "shell/instrument/reasampler_processor.h" @@ -21,10 +23,10 @@ using namespace reasampler::ui; using namespace reasampler::instrument::ui; bool ReaSamplerEditor::mouseDownWaveform(const FaceLayout& fl, int x, int y) { - const Rect& band = fl.bands.waveform; const std::vector& pcm = monoPcmFor(selectedId_); const std::int64_t frames = static_cast(pcm.size()); if (frames <= 0) return false; + const OverlayArea overlay = waveformOverlayArea(fl.bands.waveform); // Envelope nodes first (they sit on top of the markers), then the wave markers. const double rate = liveSampleRate(); @@ -32,7 +34,7 @@ bool ReaSamplerEditor::mouseDownWaveform(const FaceLayout& fl, int x, int y) { const std::int64_t startFrame = params_.startPoint.value_or(0); const AmpEnvelope env = packEnvelope(params_.play, frames, startFrame); const double totalSeconds = static_cast(frames) / rate; - const NodeHit nh = nodeAtPoint(env, band, totalSeconds, x, y); + const NodeHit nh = nodeAtPoint(env, overlay, totalSeconds, x, y); if (nh.hit) { drag_ = DragKind::kEnvNode; envNode_ = nh.node; @@ -47,7 +49,7 @@ bool ReaSamplerEditor::mouseDownWaveform(const FaceLayout& fl, int x, int y) { } const SetupMarkers m = pickedMarkers(frames); const std::int64_t markerFrames[3] = {m.start, m.loopStart, m.loopEnd}; - const int hit = markerAtPoint(band, frames, markerFrames, 3, x, y); + const int hit = markerAtPoint(overlay, frames, markerFrames, 3, x, y); if (hit >= 0) { drag_ = DragKind::kWaveMarker; waveMarker_ = static_cast(hit); @@ -61,7 +63,7 @@ bool ReaSamplerEditor::mouseDownWaveform(const FaceLayout& fl, int x, int y) { } void ReaSamplerEditor::dragWaveform(const FaceLayout& fl, int x, int y) { - const Rect& band = fl.bands.waveform; + const OverlayArea overlay = waveformOverlayArea(fl.bands.waveform); const int dx = x - dragStartX_; if (drag_ == DragKind::kEnvNode) { @@ -73,7 +75,7 @@ void ReaSamplerEditor::dragWaveform(const FaceLayout& fl, int x, int y) { const double rate = liveSampleRate(); if (frames <= 0 || rate <= 0.0) return; const double totalSeconds = static_cast(frames) / rate; - const AmpEnvelope edited = resolveNodeDrag(dragStartEnv_, envNode_, band, totalSeconds, + const AmpEnvelope edited = resolveNodeDrag(dragStartEnv_, envNode_, overlay, totalSeconds, envClampBounds(), dx, y - dragStartY_); unpackEnvelope(edited, frames, dragStartFrame_, params_.play); invalidate(); // live feedback; commit on WM_LBUTTONUP @@ -90,7 +92,7 @@ void ReaSamplerEditor::dragWaveform(const FaceLayout& fl, int x, int y) { const int idx = static_cast(waveMarker_); const std::int64_t startVals[3] = {dragStartMarkers_.start, dragStartMarkers_.loopStart, dragStartMarkers_.loopEnd}; - std::int64_t newFrame = resolveDragFrame(band, frames, startVals[idx], dx); + std::int64_t newFrame = resolveDragFrame(overlay, frames, startVals[idx], dx); // Snap to the nearest zero crossing in the decoded PCM. Pure over the cached mono // frames — no host types, no file I/O. diff --git a/src/shell/instrument/editor_paint_waveform.cpp b/src/shell/instrument/editor_paint_waveform.cpp index 7b48fc0..75ce070 100644 --- a/src/shell/instrument/editor_paint_waveform.cpp +++ b/src/shell/instrument/editor_paint_waveform.cpp @@ -1,21 +1,19 @@ // editor_paint_waveform.cpp — the WAVEFORM band's painter: the channel lane(s), the loop // span + start/loop markers, and the amp-envelope overlay. Windows-only. // -// Overlays that ride the waveform (the envelope trace, its node handles, the markers) draw -// ONCE across the full band height, never per lane — the landed contract the stacked-lane -// work consumes. +// Overlay contract: see waveform_view.h's WaveformSurface. #include "shell/instrument/reasampler_editor.h" #ifdef _WIN32 #include +#include #include #include #include "core/audio/peaks.h" // computeEnvelope (waveform binning) -#include "core/instrument/ui/sample_bands.h" // waveformLanes (the band's lane inventory) -#include "core/instrument/ui/waveform_view.h" // frameToX (waveform markers) +#include "core/instrument/ui/waveform_view.h" // waveformSurface / laneEnvelope / frameToX #include "shell/instrument/editor_internal.h" // kit adapters #include "shell/instrument/reasampler_processor.h" @@ -36,57 +34,74 @@ void ReaSamplerEditor::paintWaveform(LICE_IBitmap* bmp, const Rect& band) { fillSurface(bmp, toKitBox(band), Role::BgBase, InteractionState::Rest); if (band.empty()) return; - const std::vector& pcm = monoPcmFor(selectedId_); - const std::int64_t frames = static_cast(pcm.size()); + const std::vector& mono = monoPcmFor(selectedId_); + const std::int64_t frames = static_cast(mono.size()); if (frames <= 0) { kitTextCentered(bmp, band, "(decoding...)", Font::Label, Role::TextDim); return; } - // One lane today: the cached PCM is a mono downmix, so there is no second channel to - // draw. The band is already sized for two, and the second lane lights up when the - // per-channel decode lands. - const WaveformLanes lanes = waveformLanes(band, /*stereo=*/false); - const Rect& lane = lanes.upper; - if (lane.width > 0) { + const ChannelPcm& src = channelPcmFor(selectedId_); + const WaveformSurface surface = waveformSurface( + band, channelMode_ == ChannelMode::Stereo, src.channelCount); + + if (!surface.upper.empty()) { // Gap-free: one bin per drawn pixel column (kWaveformOversample == 1, so this // multiplies by 1). The gap-free draw comes from peaks::columnMinMax's exact // partition — extra bins produce no visible change. Clamped to frame count below. + // Both lanes share a width, so one bin count serves both. const std::int64_t wantBins = - static_cast((std::max)(1, waveformColumnCount(toKitBox(lane)))) * + static_cast( + (std::max)(1, waveformColumnCount(toKitBox(surface.upper)))) * kWaveformOversample; const std::size_t bins = static_cast(wantBins < frames ? wantBins : frames); - drawEnvelope(bmp, lane, computeEnvelope(pcm, 1, pcm.size(), bins)); + + if (surface.laneCount == 2) { + // ONE pass over the interleaved source: computeEnvelope already envelopes each + // channel independently, so the second lane costs no second scan of the PCM. + const Envelope env = + computeEnvelope(src.interleaved, static_cast(src.channelCount), + static_cast(src.frameCount()), bins); + drawEnvelope(bmp, surface.upper, laneEnvelope(env, 0)); + drawEnvelope(bmp, surface.lower, laneEnvelope(env, 1)); + } else { + // One lane draws what one lane plays: the downmix, not channel 0 of a stereo + // source. + drawEnvelope(bmp, surface.upper, computeEnvelope(mono, 1, mono.size(), bins)); + } } - // Markers and the loop span run the FULL band height (both lanes), so a stacked view - // reads one loop region rather than two. + // Markers and the loop span are overlays: ONE draw across the full stacked height, so a + // stereo view reads one loop region rather than two. + const OverlayArea& overlay = surface.overlay; + const Rect& overlayRect = overlay.rect; const SetupMarkers m = pickedMarkers(frames); if (m.hasLoop && m.loopEnd > m.loopStart) { - const int lx = frameToX(band, frames, m.loopStart); - const int rx = frameToX(band, frames, m.loopEnd); + const int lx = frameToX(overlay, frames, m.loopStart); + const int rx = frameToX(overlay, frames, m.loopEnd); if (rx > lx) { - LICE_FillRect(bmp, lx, band.y, rx - lx, band.height, + LICE_FillRect(bmp, lx, overlayRect.y, rx - lx, overlayRect.height, toLice(roleColor(kRoleLoopMarker)), 0.20f, 0); } } const std::int64_t markerFrames[3] = {m.start, m.loopStart, m.loopEnd}; const Role markerRoles[3] = {kRoleStartMarker, kRoleLoopMarker, kRoleLoopMarker}; for (int i = 0; i < 3; ++i) { - const int mx = frameToX(band, frames, markerFrames[i]); + const int mx = frameToX(overlay, frames, markerFrames[i]); const bool loopMarker = (i != 0); const float alpha = (loopMarker && !m.hasLoop) ? 0.4f : 1.0f; - LICE_FillRect(bmp, mx - 1, band.y, 2, band.height, + LICE_FillRect(bmp, mx - 1, overlayRect.y, 2, overlayRect.height, toLice(roleColor(markerRoles[i])), alpha, 0); } - paintEnvelopeOverlay(bmp, band, frames); + paintEnvelopeOverlay(bmp, overlay, frames); } -void ReaSamplerEditor::paintEnvelopeOverlay(LICE_IBitmap* bmp, const Rect& waveArea, +void ReaSamplerEditor::paintEnvelopeOverlay(LICE_IBitmap* bmp, const OverlayArea& waveArea, std::int64_t frames) { - if (frames <= 0 || waveArea.width <= 0 || waveArea.height <= 0) return; + const Rect& area = waveArea.rect; + if (frames <= 0 || area.width <= 0 || area.height <= 0) return; const double rate = liveSampleRate(); if (rate <= 0.0) return; const double totalSeconds = static_cast(frames) / rate; @@ -98,8 +113,8 @@ void ReaSamplerEditor::paintEnvelopeOverlay(LICE_IBitmap* bmp, const Rect& waveA // curve over the waveform. Clip x to the wave rect (a Gate release tail maps past the right). const LICE_pixel line = toLice(roleColor(Role::AccentSecondary)); for (std::size_t i = 1; i < poly.size(); ++i) { - const int x0 = (std::max)(waveArea.x, (std::min)(waveArea.right() - 1, poly[i - 1].x)); - const int x1 = (std::max)(waveArea.x, (std::min)(waveArea.right() - 1, poly[i].x)); + const int x0 = (std::max)(area.x, (std::min)(area.right() - 1, poly[i - 1].x)); + const int x1 = (std::max)(area.x, (std::min)(area.right() - 1, poly[i].x)); LICE_Line(bmp, x0, poly[i - 1].y, x1, poly[i].y, line, 1.0f, 0, true); } // Draggable node handles: a small square per draggable node (Origin + ReleaseStart are @@ -113,8 +128,8 @@ void ReaSamplerEditor::paintEnvelopeOverlay(LICE_IBitmap* bmp, const Rect& waveA if (v.node == EnvNode::Origin || v.node == EnvNode::ReleaseStart) continue; const bool grabbed = (drag_ == DragKind::kEnvNode && envNode_ == v.node); const int r = 3; - const int hx = (std::max)(waveArea.x + r, (std::min)(waveArea.right() - 1 - r, v.x)); - const int hy = (std::max)(waveArea.y + r, (std::min)(waveArea.bottom() - 1 - r, v.y)); + const int hx = (std::max)(area.x + r, (std::min)(area.right() - 1 - r, v.x)); + const int hy = (std::max)(area.y + r, (std::min)(area.bottom() - 1 - r, v.y)); LICE_FillRect(bmp, hx - r, hy - r, 2 * r, 2 * r, grabbed ? handleHot : handle, 1.0f, 0); } } diff --git a/src/shell/instrument/editor_session.cpp b/src/shell/instrument/editor_session.cpp index 2f32519..8137f03 100644 --- a/src/shell/instrument/editor_session.cpp +++ b/src/shell/instrument/editor_session.cpp @@ -48,6 +48,8 @@ void ReaSamplerEditor::refreshFromBank() { // Main/UI thread only — reads the live bank over the bridge (allocates, calls REAPER). thumbCache_.clear(); // a bank edit may have re-captured/removed a sample; drop stale peaks pcmCache_.clear(); // and its decoded PCM (the waveform + snap source) + channelPcmId_.clear(); + channelPcm_ = ChannelPcm{}; if (!processor_) { samples_.clear(); banks_.clear(); @@ -202,42 +204,66 @@ int ReaSamplerEditor::effectiveRoot() const { return 60; } +std::string ReaSamplerEditor::samplePathFor(const std::string& sampleId) const { + // SampleChoice is the browser's metadata projection and does not carry the WAV path, so + // resolve it from the live bank blob (selectSample). + if (!processor_) return {}; + auto banksJson = processor_->bridge().readReasamplerExtState(reasampler::kProjExtBanksKey); + if (banksJson) { + // An empty relativePath (found the entry, but it carries no path) falls through to + // the refs fallback below rather than short-circuiting on it. + if (auto sel = selectSample(*banksJson, sampleId); sel && !sel->relativePath.empty()) { + return sel->relativePath; + } + } + // Fallback: the bank blob is not readable (extension absent / not yet parsed) or the id + // went stale there — the instance-owned ref still carries the path, so a self-contained + // instance draws its loaded sound's waveform regardless. + const SampleRefs refs = processor_->sampleRefs(); + if (const SelectedSample* r = findRef(refs, sampleId)) return r->relativePath; + return {}; +} + +const ReaSamplerEditor::ChannelPcm& ReaSamplerEditor::channelPcmFor( + const std::string& sampleId) { + if (channelPcmId_ == sampleId) return channelPcm_; + + // A failed decode is still cached (channelCount stays 0) so a broken/missing file is not + // re-read on every paint. + channelPcmId_ = sampleId; + channelPcm_ = ChannelPcm{}; + const std::string relativePath = samplePathFor(sampleId); + if (relativePath.empty()) return channelPcm_; + + const std::string projectDir = processor_->bridge().activeProjectDir(); + const std::vector bytes = + readFileBytes(resolveBankFile(projectDir, relativePath)); // empty on any failure + const WavLayout layout = parseWavLayout(bytes); + if (layout.valid) { + channelPcm_.interleaved = extractFloatFrames(bytes, layout, 0, layout.frameCount()); + channelPcm_.channelCount = static_cast(layout.channelCount); + } + return channelPcm_; +} + const std::vector& ReaSamplerEditor::monoPcmFor(const std::string& sampleId) { auto it = pcmCache_.find(sampleId); if (it != pcmCache_.end()) return it->second; - // SampleChoice is the browser's metadata projection and does not carry the WAV path, so - // resolve the path from the live bank blob (selectSample) and decode via the shared WAV - // parse. Every failure path caches an empty vector so a broken/missing file is not - // re-decoded on every paint. Keyed by id (width-independent) — the thumbnail bins this at - // whatever width, the snap scans it directly. - std::string relativePath; + // Every failure path caches an empty vector so a broken/missing file is not re-decoded on + // every paint. Keyed by id (width-independent) — the thumbnail bins this at whatever + // width, the snap scans it directly. std::vector mono; - if (processor_) { - auto banksJson = - processor_->bridge().readReasamplerExtState(reasampler::kProjExtBanksKey); - if (banksJson) { - if (auto sel = selectSample(*banksJson, sampleId)) relativePath = sel->relativePath; - } - if (relativePath.empty()) { - // Fallback: the bank blob is not readable (extension absent / not yet parsed) or - // the id went stale there — the instance-owned ref still carries the path, so a - // self-contained instance draws its loaded sound's waveform regardless. - const SampleRefs refs = processor_->sampleRefs(); - if (const SelectedSample* r = findRef(refs, sampleId)) { - relativePath = r->relativePath; - } - } - if (!relativePath.empty()) { - const std::string projectDir = processor_->bridge().activeProjectDir(); - const std::string abs = resolveBankFile(projectDir, relativePath); - const std::vector bytes = readFileBytes(abs); // empty on any failure - const WavLayout layout = parseWavLayout(bytes); - if (layout.valid) { - std::vector interleaved = - extractFloatFrames(bytes, layout, 0, layout.frameCount()); - mono = downmixToMono(interleaved, layout.channelCount); - } + const std::string relativePath = samplePathFor(sampleId); + if (!relativePath.empty()) { + const std::string projectDir = processor_->bridge().activeProjectDir(); + const std::string abs = resolveBankFile(projectDir, relativePath); + const std::vector bytes = readFileBytes(abs); // empty on any failure + const WavLayout layout = parseWavLayout(bytes); + if (layout.valid) { + std::vector interleaved = + extractFloatFrames(bytes, layout, 0, layout.frameCount()); + mono = downmixToMono(interleaved, layout.channelCount); } } auto ins = pcmCache_.emplace(sampleId, std::move(mono)); diff --git a/src/shell/instrument/reasampler_editor.h b/src/shell/instrument/reasampler_editor.h index ef7360b..9c09a32 100644 --- a/src/shell/instrument/reasampler_editor.h +++ b/src/shell/instrument/reasampler_editor.h @@ -45,6 +45,7 @@ using instrument::ui::ChromeRects; using instrument::ui::DeckGroupDesc; using instrument::ui::EnvClampBounds; using instrument::ui::EnvNode; +using instrument::ui::OverlayArea; using instrument::ui::Rect; using instrument::ui::SampleBands; @@ -173,7 +174,7 @@ private: void paintVelocityCurve(LICE_IBitmap* bmp, const Rect& r); // Traces the amp-envelope overlay + its draggable node handles over `waveArea`, ONCE at // full band height (never per lane). - void paintEnvelopeOverlay(LICE_IBitmap* bmp, const Rect& waveArea, std::int64_t frames); + void paintEnvelopeOverlay(LICE_IBitmap* bmp, const OverlayArea& waveArea, std::int64_t frames); // --- Input: the mouse-down dispatch and its per-band branches --- void onMouseDown(int x, int y); @@ -262,6 +263,28 @@ private: // thread only (file I/O); cleared with the thumbnail cache on refresh. const std::vector& monoPcmFor(const std::string& sampleId); + // The interleaved source PCM behind the stereo waveform lanes. + struct ChannelPcm { + std::vector interleaved; // frame-interleaved source frames + int channelCount = 0; // 0 = nothing decoded + std::int64_t frameCount() const { + return channelCount > 0 + ? static_cast(interleaved.size()) / channelCount + : 0; + } + }; + + // The interleaved PCM + channel count for a bank sample id. SINGLE-SLOT by design: the + // waveform band draws one capture at a time, while monoPcmFor's cache spans every + // browsed card — holding interleaved PCM there would pin a whole bank at multi-channel + // size. A miss re-decodes (only on selection change or a bank refresh; an edit commit + // does not clear it). UI thread only (file I/O). + const ChannelPcm& channelPcmFor(const std::string& sampleId); + + // The project-relative WAV path for a bank sample id: the live bank blob first, the + // instance's own SampleRefs as the self-contained fallback. "" when unresolvable. + std::string samplePathFor(const std::string& sampleId) const; + // The effective loop + start markers for the loaded capture: the parameter set's // override when one is set, else the bank's loop intrinsic / frame 0. Absent loop -> // loopStart==loopEnd==0. `frames` defaults loopEnd when the bank left the loop empty. @@ -434,6 +457,11 @@ private: // Decoded mono-PCM cache, keyed by id (width-independent). Feeds the waveform envelope // binning + zero-crossing snap. Cleared alongside thumbCache_ on refresh. std::unordered_map> pcmCache_; + + // The single-slot interleaved-PCM cache behind channelPcmFor (see its note on why this + // is not keyed into pcmCache_). Cleared alongside pcmCache_ on refresh. + std::string channelPcmId_; + ChannelPcm channelPcm_; }; } // namespace reasampler::vst diff --git a/tests/test_envelope_edit.cpp b/tests/test_envelope_edit.cpp index 37f92a3..f4a77e2 100644 --- a/tests/test_envelope_edit.cpp +++ b/tests/test_envelope_edit.cpp @@ -44,6 +44,8 @@ static bool findNode(const std::vector& poly, EnvNode node, EnvVertex // draw at A x@28, H x@47, D x@85, RS x@235, RE x@284. static Rect wideArea() { return Rect::ltrb(20, 10, 1020, 110); } static constexpr double kTotal = 2.0; + +static OverlayArea overlayOf(const Rect& r) { return OverlayArea{r}; } static const double kGateSecPerPx = 1.0 / gatePxPerSecond(wideArea()); static AmpEnvelope gateEnv() { @@ -72,10 +74,10 @@ static void testHitGrabsDrawnHandle() { const AmpEnvelope e = gateEnv(); const Rect a = wideArea(); // AttackEnd draws at x = left+28 (8px base + 0.2s * 102.125 px/s), y = top (level 1). - NodeHit h = nodeAtPoint(e, a, kTotal, a.x + 28, a.y); + NodeHit h = nodeAtPoint(e, overlayOf(a), kTotal, a.x + 28, a.y); CHECK(h.hit && h.node == EnvNode::AttackEnd); // The sustain node (DecayEnd) at left+85, level 0.5 -> ~top+50. - NodeHit s = nodeAtPoint(e, a, kTotal, a.x + 85, a.y + 50); + NodeHit s = nodeAtPoint(e, overlayOf(a), kTotal, a.x + 85, a.y + 50); CHECK(s.hit && s.node == EnvNode::DecayEnd); } @@ -83,7 +85,7 @@ static void testHitMissesOffEveryNode() { const AmpEnvelope e = gateEnv(); const Rect a = wideArea(); // A point far from any drawn handle (right of the release ramp, well away from a node). - NodeHit h = nodeAtPoint(e, a, kTotal, a.x + 700, a.y + 5); + NodeHit h = nodeAtPoint(e, overlayOf(a), kTotal, a.x + 700, a.y + 5); CHECK(!h.hit); } @@ -91,11 +93,11 @@ static void testHitSkipsNonDraggableAnchors() { const AmpEnvelope e = gateEnv(); const Rect a = wideArea(); // Origin draws at (left, bottom-1). Even a pixel-perfect grab there is NOT a draggable node. - NodeHit o = nodeAtPoint(e, a, kTotal, a.x, a.bottom() - 1); + NodeHit o = nodeAtPoint(e, overlayOf(a), kTotal, a.x, a.bottom() - 1); CHECK(!o.hit); // ReleaseStart draws at (left+235, sustain level ~top+50) — the fixed plateau end. It is // drawing-only -> not grabbable; no other node is within the radius, so this grab misses. - NodeHit rs = nodeAtPoint(e, a, kTotal, a.x + 235, a.y + 50); + NodeHit rs = nodeAtPoint(e, overlayOf(a), kTotal, a.x + 235, a.y + 50); CHECK(!rs.hit); } @@ -107,7 +109,7 @@ static void testHitNearestNodeWinsOverDrawOrder() { AmpEnvelope e = gateEnv(); e.holdSeconds = 0.01; const Rect a = wideArea(); - NodeHit h = nodeAtPoint(e, a, kTotal, a.x + 33, a.y); + NodeHit h = nodeAtPoint(e, overlayOf(a), kTotal, a.x + 33, a.y); CHECK(h.hit && h.node == EnvNode::HoldEnd); } @@ -119,11 +121,11 @@ static void testGateDefaultsEveryNodeGrabbable() { // ungrabbable in the default state). const AmpEnvelope e; // struct defaults ARE the tier-0 Gate defaults const Rect a = wideArea(); - const std::vector poly = buildEnvelopePolyline(e, a, kTotal); + const std::vector poly = buildEnvelopePolyline(e, overlayOf(a), kTotal); CHECK(poly.size() == 6); for (const EnvVertex& v : poly) { if (v.node == EnvNode::Origin || v.node == EnvNode::ReleaseStart) continue; - const NodeHit h = nodeAtPoint(e, a, kTotal, v.x, v.y); + const NodeHit h = nodeAtPoint(e, overlayOf(a), kTotal, v.x, v.y); CHECK(h.hit && h.node == v.node); } } @@ -135,7 +137,7 @@ static void testGateAttackDragMovesOnlyAttack() { const Rect a = wideArea(); EnvClampBounds b; // default maxima 4.0s // +50px at the GATE param-domain scale (~0.0098 s/px) on attack. Nothing else moves. - AmpEnvelope out = resolveNodeDrag(e, EnvNode::AttackEnd, a, kTotal, b, 50, 0); + AmpEnvelope out = resolveNodeDrag(e, EnvNode::AttackEnd, overlayOf(a), kTotal, b, 50, 0); CHECK(near(out.attackSeconds, 0.2 + 50.0 * kGateSecPerPx)); CHECK(near(out.holdSeconds, e.holdSeconds)); CHECK(near(out.decaySeconds, e.decaySeconds)); @@ -149,7 +151,7 @@ static void testGateTimeLowerClampAtZero() { EnvClampBounds b; // Drag attack far LEFT (-500px ~= -4.9s at the gate scale) from 0.2s: clamps to 0, never // negative (monotonic: the segment cannot go below zero). - AmpEnvelope out = resolveNodeDrag(e, EnvNode::AttackEnd, a, kTotal, b, -500, 0); + AmpEnvelope out = resolveNodeDrag(e, EnvNode::AttackEnd, overlayOf(a), kTotal, b, -500, 0); CHECK(near(out.attackSeconds, 0.0)); } @@ -160,7 +162,7 @@ static void testGateTimeUpperClampAtSliderMax() { b.maxDecaySeconds = 1.0; // the shell's decay slider tops out at 1.0s // Drag decay far RIGHT (+2000px ~= +19.6s at the gate scale) from 0.3s: clamps to the slider // max 1.0, NOT beyond (the drag can't produce a param the slider couldn't). - AmpEnvelope out = resolveNodeDrag(e, EnvNode::DecayEnd, a, kTotal, b, 2000, 0); + AmpEnvelope out = resolveNodeDrag(e, EnvNode::DecayEnd, overlayOf(a), kTotal, b, 2000, 0); CHECK(near(out.decaySeconds, 1.0)); } @@ -170,7 +172,7 @@ static void testGateSustainNodeBothAxes() { EnvClampBounds b; // DecayEnd: +100px X at the gate timed scale on decay; +bottom-ward Y LOWERS the level. Level // span is 99 px for [0,1]; drag DOWN by ~10px (positive dy) lowers sustain by ~10/99 ~= 0.101. - AmpEnvelope out = resolveNodeDrag(e, EnvNode::DecayEnd, a, kTotal, b, 100, 10); + AmpEnvelope out = resolveNodeDrag(e, EnvNode::DecayEnd, overlayOf(a), kTotal, b, 100, 10); CHECK(near(out.decaySeconds, 0.3 + 100.0 * kGateSecPerPx)); CHECK(out.sustainLevel < e.sustainLevel); // dragged DOWN -> lower sustain CHECK(near(out.sustainLevel, 0.5 - 10.0 / 99.0, 1e-6)); @@ -181,10 +183,10 @@ static void testGateSustainLevelClamps01() { const Rect a = wideArea(); EnvClampBounds b; // Drag sustain UP hard (dy very negative): clamps to 1.0. - AmpEnvelope up = resolveNodeDrag(e, EnvNode::DecayEnd, a, kTotal, b, 0, -10000); + AmpEnvelope up = resolveNodeDrag(e, EnvNode::DecayEnd, overlayOf(a), kTotal, b, 0, -10000); CHECK(near(up.sustainLevel, 1.0)); // Drag sustain DOWN hard (dy very positive): clamps to 0.0. - AmpEnvelope dn = resolveNodeDrag(e, EnvNode::DecayEnd, a, kTotal, b, 0, 10000); + AmpEnvelope dn = resolveNodeDrag(e, EnvNode::DecayEnd, overlayOf(a), kTotal, b, 0, 10000); CHECK(near(dn.sustainLevel, 0.0)); } @@ -193,7 +195,7 @@ static void testGateTimeOnlyNodeIgnoresY() { const Rect a = wideArea(); EnvClampBounds b; // HoldEnd is time-only: a big Y delta must NOT change any level (there is no level to change). - AmpEnvelope out = resolveNodeDrag(e, EnvNode::HoldEnd, a, kTotal, b, 0, 500); + AmpEnvelope out = resolveNodeDrag(e, EnvNode::HoldEnd, overlayOf(a), kTotal, b, 0, 500); CHECK(near(out.holdSeconds, e.holdSeconds)); // dx 0 -> no time change either CHECK(near(out.sustainLevel, e.sustainLevel)); // Y ignored for a time-only node } @@ -204,17 +206,17 @@ static void testGateReleaseEndGrabAndDrag() { const AmpEnvelope e = gateEnv(); const Rect a = wideArea(); EnvClampBounds b; - NodeHit h = nodeAtPoint(e, a, kTotal, a.x + 284, a.bottom() - 1); + NodeHit h = nodeAtPoint(e, overlayOf(a), kTotal, a.x + 284, a.bottom() - 1); CHECK(h.hit && h.node == EnvNode::ReleaseEnd); // Dragging it RIGHT lengthens the release at the gate timed scale; only release changes. - AmpEnvelope out = resolveNodeDrag(e, EnvNode::ReleaseEnd, a, kTotal, b, 85, 0); + AmpEnvelope out = resolveNodeDrag(e, EnvNode::ReleaseEnd, overlayOf(a), kTotal, b, 85, 0); CHECK(near(out.releaseSeconds, 0.4 + 85.0 * kGateSecPerPx)); CHECK(near(out.sustainLevel, e.sustainLevel)); CHECK(near(out.decaySeconds, e.decaySeconds)); // Far LEFT clamps to 0; far RIGHT clamps to the slider max. - AmpEnvelope lo = resolveNodeDrag(e, EnvNode::ReleaseEnd, a, kTotal, b, -2000, 0); + AmpEnvelope lo = resolveNodeDrag(e, EnvNode::ReleaseEnd, overlayOf(a), kTotal, b, -2000, 0); CHECK(near(lo.releaseSeconds, 0.0)); - AmpEnvelope hi = resolveNodeDrag(e, EnvNode::ReleaseEnd, a, kTotal, b, 5000, 0); + AmpEnvelope hi = resolveNodeDrag(e, EnvNode::ReleaseEnd, overlayOf(a), kTotal, b, 5000, 0); CHECK(near(hi.releaseSeconds, b.maxReleaseSeconds)); } @@ -230,16 +232,16 @@ static void testGateDragRoundTripTracksPixels() { for (EnvNode n : {EnvNode::AttackEnd, EnvNode::HoldEnd, EnvNode::DecayEnd, EnvNode::ReleaseEnd}) { EnvVertex before, after; - CHECK(findNode(buildEnvelopePolyline(e, a, kTotal), n, before)); - const AmpEnvelope edited = resolveNodeDrag(e, n, a, kTotal, b, dx, 0); - CHECK(findNode(buildEnvelopePolyline(edited, a, kTotal), n, after)); + CHECK(findNode(buildEnvelopePolyline(e, overlayOf(a), kTotal), n, before)); + const AmpEnvelope edited = resolveNodeDrag(e, n, overlayOf(a), kTotal, b, dx, 0); + CHECK(findNode(buildEnvelopePolyline(edited, overlayOf(a), kTotal), n, after)); CHECK(std::abs((after.x - before.x) - dx) <= 1); } // The sustain node's Y axis tracks too: +10px down moves the drawn vertex ~10px down. EnvVertex before, after; - CHECK(findNode(buildEnvelopePolyline(e, a, kTotal), EnvNode::DecayEnd, before)); - const AmpEnvelope edited = resolveNodeDrag(e, EnvNode::DecayEnd, a, kTotal, b, 0, 10); - CHECK(findNode(buildEnvelopePolyline(edited, a, kTotal), EnvNode::DecayEnd, after)); + CHECK(findNode(buildEnvelopePolyline(e, overlayOf(a), kTotal), EnvNode::DecayEnd, before)); + const AmpEnvelope edited = resolveNodeDrag(e, EnvNode::DecayEnd, overlayOf(a), kTotal, b, 0, 10); + CHECK(findNode(buildEnvelopePolyline(edited, overlayOf(a), kTotal), EnvNode::DecayEnd, after)); CHECK(std::abs((after.y - before.y) - 10) <= 1); } @@ -250,7 +252,7 @@ static void testTriggerFadeInIsFractionOfPlaySpan() { const Rect a = wideArea(); EnvClampBounds b; // +50px = +0.1s on the play timeline = +0.1/1.0 = +0.1 fraction. fadeIn 0.2 -> 0.3. - AmpEnvelope out = resolveNodeDrag(e, EnvNode::FadeInEnd, a, kTotal, b, 50, 0); + AmpEnvelope out = resolveNodeDrag(e, EnvNode::FadeInEnd, overlayOf(a), kTotal, b, 50, 0); CHECK(near(out.fadeInFraction, 0.3)); CHECK(near(out.fadeOutFraction, e.fadeOutFraction)); // unchanged } @@ -263,7 +265,7 @@ static void testTriggerFadesCannotCross() { EnvClampBounds b; // Drag fade-in far RIGHT (+2000px): would push fadeIn well past 1-fadeOut=0.7, but the mutual // clamp caps it at 0.7 so the fade nodes never cross (monotonic on the play timeline). - AmpEnvelope out = resolveNodeDrag(e, EnvNode::FadeInEnd, a, kTotal, b, 2000, 0); + AmpEnvelope out = resolveNodeDrag(e, EnvNode::FadeInEnd, overlayOf(a), kTotal, b, 2000, 0); CHECK(near(out.fadeInFraction, 0.7)); CHECK(near(out.fadeOutFraction, 0.3)); } @@ -274,7 +276,7 @@ static void testTriggerFadeOutMovesOppositePixelDelta() { EnvClampBounds b; // FadeOutStart sits at (1-fadeOut) of the span; dragging it LEFT (-50px) LENGTHENS the fade-out. // -50px = -0.1s = -0.1 fraction on the span, applied OPPOSITE -> fadeOut 0.2 -> 0.3. - AmpEnvelope out = resolveNodeDrag(e, EnvNode::FadeOutStart, a, kTotal, b, -50, 0); + AmpEnvelope out = resolveNodeDrag(e, EnvNode::FadeOutStart, overlayOf(a), kTotal, b, -50, 0); CHECK(near(out.fadeOutFraction, 0.3)); CHECK(near(out.fadeInFraction, e.fadeInFraction)); } @@ -290,14 +292,14 @@ static void testTriggerZeroFadeOutGrabbableAtRightEdge() { e.fadeOutFraction = 0.0; const Rect a = wideArea(); EnvClampBounds b; - NodeHit h = nodeAtPoint(e, a, kTotal, a.right() - 1, a.y); + NodeHit h = nodeAtPoint(e, overlayOf(a), kTotal, a.right() - 1, a.y); CHECK(h.hit && h.node == EnvNode::FadeOutStart); // -100px = -0.2s on the 2.0s played span, applied OPPOSITE -> fadeOut 0.0 -> 0.1. - AmpEnvelope out = resolveNodeDrag(e, EnvNode::FadeOutStart, a, kTotal, b, -100, 0); + AmpEnvelope out = resolveNodeDrag(e, EnvNode::FadeOutStart, overlayOf(a), kTotal, b, -100, 0); CHECK(near(out.fadeOutFraction, 0.1)); CHECK(near(out.lengthFraction, e.lengthFraction)); // length untouched // LengthEnd sits at the same x but level 0 (bottom row) — grabbable at ITS drawn point. - NodeHit le = nodeAtPoint(e, a, kTotal, a.right() - 1, a.bottom() - 1); + NodeHit le = nodeAtPoint(e, overlayOf(a), kTotal, a.right() - 1, a.bottom() - 1); CHECK(le.hit && le.node == EnvNode::LengthEnd); } @@ -306,10 +308,10 @@ static void testTriggerLengthClampsAtMax() { const Rect a = wideArea(); EnvClampBounds b; // maxLengthFraction 1.0 // LengthEnd maps to a fraction of the WHOLE sample: +2000px = +4.0s = +2.0 fraction, clamps 1.0. - AmpEnvelope out = resolveNodeDrag(e, EnvNode::LengthEnd, a, kTotal, b, 2000, 0); + AmpEnvelope out = resolveNodeDrag(e, EnvNode::LengthEnd, overlayOf(a), kTotal, b, 2000, 0); CHECK(near(out.lengthFraction, 1.0)); // Drag far LEFT clamps to 0. - AmpEnvelope lo = resolveNodeDrag(e, EnvNode::LengthEnd, a, kTotal, b, -2000, 0); + AmpEnvelope lo = resolveNodeDrag(e, EnvNode::LengthEnd, overlayOf(a), kTotal, b, -2000, 0); CHECK(near(lo.lengthFraction, 0.0)); } @@ -319,9 +321,9 @@ static void testNonDraggableNodeNoMotion() { const AmpEnvelope e = gateEnv(); const Rect a = wideArea(); EnvClampBounds b; - AmpEnvelope o = resolveNodeDrag(e, EnvNode::Origin, a, kTotal, b, 500, 500); + AmpEnvelope o = resolveNodeDrag(e, EnvNode::Origin, overlayOf(a), kTotal, b, 500, 500); CHECK(near(o.attackSeconds, e.attackSeconds) && near(o.sustainLevel, e.sustainLevel)); - AmpEnvelope rs = resolveNodeDrag(e, EnvNode::ReleaseStart, a, kTotal, b, 500, 500); + AmpEnvelope rs = resolveNodeDrag(e, EnvNode::ReleaseStart, overlayOf(a), kTotal, b, 500, 500); CHECK(near(rs.releaseSeconds, e.releaseSeconds)); } @@ -329,9 +331,9 @@ static void testDegenerateAreaNoMotion() { const AmpEnvelope e = gateEnv(); EnvClampBounds b; const Rect zeroW = Rect::ltrb(0, 0, 0, 100); - AmpEnvelope o1 = resolveNodeDrag(e, EnvNode::AttackEnd, zeroW, kTotal, b, 500, 0); + AmpEnvelope o1 = resolveNodeDrag(e, EnvNode::AttackEnd, overlayOf(zeroW), kTotal, b, 500, 0); CHECK(near(o1.attackSeconds, e.attackSeconds)); - AmpEnvelope o2 = resolveNodeDrag(e, EnvNode::AttackEnd, wideArea(), 0.0, b, 500, 0); // no time + AmpEnvelope o2 = resolveNodeDrag(e, EnvNode::AttackEnd, overlayOf(wideArea()), 0.0, b, 500, 0); // no time CHECK(near(o2.attackSeconds, e.attackSeconds)); } @@ -342,14 +344,14 @@ static void testCrossModeNodeNoMotion() { // inert on a Gate envelope. EnvClampBounds b; const AmpEnvelope t = triggerEnv(); - AmpEnvelope out = resolveNodeDrag(t, EnvNode::ReleaseEnd, wideArea(), kTotal, b, 50, 0); + AmpEnvelope out = resolveNodeDrag(t, EnvNode::ReleaseEnd, overlayOf(wideArea()), kTotal, b, 50, 0); CHECK(near(out.releaseSeconds, t.releaseSeconds)); const AmpEnvelope g = gateEnv(); - out = resolveNodeDrag(g, EnvNode::FadeInEnd, wideArea(), kTotal, b, 50, 0); + out = resolveNodeDrag(g, EnvNode::FadeInEnd, overlayOf(wideArea()), kTotal, b, 50, 0); CHECK(near(out.fadeInFraction, g.fadeInFraction)); // And the zero-height baseline's ReleaseEnd is not even reported grabbable in Trigger mode. const Rect flat = Rect::ltrb(0, 0, 100, 0); - const NodeHit h = nodeAtPoint(t, flat, kTotal, 99, 0); + const NodeHit h = nodeAtPoint(t, overlayOf(flat), kTotal, 99, 0); CHECK(!h.hit); } diff --git a/tests/test_envelope_overlay.cpp b/tests/test_envelope_overlay.cpp index 6839bec..e32e018 100644 --- a/tests/test_envelope_overlay.cpp +++ b/tests/test_envelope_overlay.cpp @@ -26,6 +26,8 @@ static int g_fail = 0; #define CHECK(cond) do { if(!(cond)) { \ std::printf("FAIL line %d: %s\n", __LINE__, #cond); ++g_fail; } } while(0) +static OverlayArea overlayOf(const Rect& r) { return OverlayArea{r}; } + // A comfortable overlay area: 1000px wide, 100px tall, offset so left/top != 0 (catches origin // bugs). Under levelToY the level span is height-1 = 99 rows. static Rect wideArea() { return Rect::ltrb(20, 10, 1020, 110); } // width 1000, height 100 @@ -112,7 +114,7 @@ static void testGateNodeOrderAndLevels() { env.sustainLevel = 0.5; env.releaseSeconds = 0.4; const Rect a = wideArea(); - const std::vector poly = buildEnvelopePolyline(env, a, 2.0); + const std::vector poly = buildEnvelopePolyline(env, overlayOf(a), 2.0); // Six vertices, in draw order. CHECK(poly.size() == 6); @@ -147,7 +149,7 @@ static void testGateSchematicPlacement() { env.sustainLevel = 0.5; env.releaseSeconds = 0.4; const Rect a = wideArea(); - const std::vector poly = buildEnvelopePolyline(env, a, 2.0); + const std::vector poly = buildEnvelopePolyline(env, overlayOf(a), 2.0); EnvVertex v; CHECK(findNode(poly, EnvNode::AttackEnd, v) && v.x == a.x + 28); @@ -169,7 +171,7 @@ static void testGateLayoutIndependentOfSampleDuration() { env.sustainLevel = 0.5; env.releaseSeconds = 0.06; const Rect a = wideArea(); - CHECK(buildEnvelopePolyline(env, a, 0.3) == buildEnvelopePolyline(env, a, 10.0)); + CHECK(buildEnvelopePolyline(env, overlayOf(a), 0.3) == buildEnvelopePolyline(env, overlayOf(a), 10.0)); } static void testGateMinSeparationAtDefaults() { @@ -178,7 +180,7 @@ static void testGateMinSeparationAtDefaults() { // renders on top of its neighbour, so each is individually grabbable. const AmpEnvelope env; // struct defaults ARE the tier-0 Gate defaults const Rect a = wideArea(); - const std::vector poly = buildEnvelopePolyline(env, a, 2.0); + const std::vector poly = buildEnvelopePolyline(env, overlayOf(a), 2.0); CHECK(poly.size() == 6); for (size_t i = 1; i < poly.size(); ++i) { CHECK(poly[i].x - poly[i - 1].x >= kGateNodeSepPx); @@ -197,7 +199,7 @@ static void testGateSustainPlateauFixedWidth() { env.releaseSeconds = 0.3; const Rect a = wideArea(); const int plateauPx = a.width - gateTimedWidth(a); // 150 - const std::vector poly = buildEnvelopePolyline(env, a, 2.0); + const std::vector poly = buildEnvelopePolyline(env, overlayOf(a), 2.0); EnvVertex decay, plateauEnd; CHECK(findNode(poly, EnvNode::DecayEnd, decay)); @@ -218,7 +220,7 @@ static void testGateReleaseVisibleInBounds() { env.sustainLevel = 0.5; env.releaseSeconds = 0.4; const Rect a = wideArea(); - const std::vector poly = buildEnvelopePolyline(env, a, 2.0); + const std::vector poly = buildEnvelopePolyline(env, overlayOf(a), 2.0); EnvVertex plateauEnd, rel; CHECK(findNode(poly, EnvNode::ReleaseStart, plateauEnd)); @@ -241,7 +243,7 @@ static void testGateOverrunCompressesFromRight() { env.sustainLevel = 0.7; env.releaseSeconds = 4.0; const Rect a = wideArea(); - const std::vector poly = buildEnvelopePolyline(env, a, 2.0); + const std::vector poly = buildEnvelopePolyline(env, overlayOf(a), 2.0); CHECK(poly.size() == 6); EnvVertex plateauEnd, rel; @@ -279,7 +281,7 @@ static void testGateAllVerticesInBounds() { huge.releaseSeconds = 1e12; for (const AmpEnvelope& env : {base, big, zero, trig, huge}) { - for (const EnvVertex& v : buildEnvelopePolyline(env, a, 2.0)) { + for (const EnvVertex& v : buildEnvelopePolyline(env, overlayOf(a), 2.0)) { CHECK(v.x >= a.x && v.x < a.right()); CHECK(v.y >= a.y && v.y < a.bottom()); } @@ -297,7 +299,7 @@ static void testTriggerShape() { env.fadeInFraction = 0.2; env.fadeOutFraction = 0.3; const Rect a = wideArea(); - const std::vector poly = buildEnvelopePolyline(env, a, 2.0); + const std::vector poly = buildEnvelopePolyline(env, overlayOf(a), 2.0); CHECK(poly.size() == 4); CHECK(poly[0].node == EnvNode::Origin); @@ -319,7 +321,7 @@ static void testTriggerFadeOverlapClamp() { env.fadeInFraction = 0.8; // fade-in end at 0.8*2.0 = 1.6s -> x@800 env.fadeOutFraction = 0.6; // would be 1.4s -> clamped to 1-0.8=0.2 -> begins at 0.8*2.0 too const Rect a = wideArea(); - const std::vector poly = buildEnvelopePolyline(env, a, 2.0); + const std::vector poly = buildEnvelopePolyline(env, overlayOf(a), 2.0); EnvVertex fin, fout; CHECK(findNode(poly, EnvNode::FadeInEnd, fin)); @@ -338,7 +340,7 @@ static void testTriggerFullLengthZeroFadeOutInBounds() { env.fadeInFraction = 0.1; env.fadeOutFraction = 0.0; const Rect a = wideArea(); - const std::vector poly = buildEnvelopePolyline(env, a, 2.0); + const std::vector poly = buildEnvelopePolyline(env, overlayOf(a), 2.0); EnvVertex fout, lend; CHECK(findNode(poly, EnvNode::FadeOutStart, fout)); @@ -353,12 +355,12 @@ static void testTriggerFullLengthZeroFadeOutInBounds() { static void testDegenerateFlatBaseline() { AmpEnvelope env; // any params const Rect zeroW = Rect::ltrb(0, 0, 0, 100); - const std::vector p1 = buildEnvelopePolyline(env, zeroW, 2.0); + const std::vector p1 = buildEnvelopePolyline(env, overlayOf(zeroW), 2.0); CHECK(p1.size() == 2); // always a drawable line CHECK(p1.front().level == 0.0 && p1.back().level == 0.0); const Rect ok = wideArea(); - const std::vector p2 = buildEnvelopePolyline(env, ok, 0.0); // no duration + const std::vector p2 = buildEnvelopePolyline(env, overlayOf(ok), 0.0); // no duration CHECK(p2.size() == 2); CHECK(p2.front().level == 0.0 && p2.back().level == 0.0); CHECK(p2.front().x == ok.x && p2.back().x == ok.right() - 1); // spans the area, in-bounds diff --git a/tests/test_sample_bands.cpp b/tests/test_sample_bands.cpp index 881f8c9..4bb286f 100644 --- a/tests/test_sample_bands.cpp +++ b/tests/test_sample_bands.cpp @@ -88,7 +88,7 @@ static void testTwoLaneFloorHoldsTwoUsableLanes() { // number, so a lane can never be allocated below its own minimum. CHECK(kWaveformMinHeight == 2 * kLaneMinHeight + kLaneGap); const SampleBands b = computeSampleBands(840, 160, 120); - const WaveformLanes lanes = waveformLanes(b.waveform, /*stereo=*/true); + const WaveformLanes lanes = waveformLanes(b.waveform, LaneSplit::Stereo); CHECK(lanes.upper.height >= kLaneMinHeight); CHECK(lanes.lower.height >= kLaneMinHeight); } @@ -108,14 +108,14 @@ static void testDegenerateWindowYieldsNoInvertedRects() { static void testMonoUsesOneFullBandLane() { const Rect band = Rect::ltrb(8, 100, 832, 300); - const WaveformLanes lanes = waveformLanes(band, /*stereo=*/false); + const WaveformLanes lanes = waveformLanes(band, LaneSplit::Single); CHECK(lanes.upper == band); CHECK(lanes.lower.empty()); // no redundant duplicate lane in mono } static void testStereoSplitsIntoTwoLanesWithTheSeamGap() { const Rect band = Rect::ltrb(8, 100, 832, 300); // height 200 - const WaveformLanes lanes = waveformLanes(band, /*stereo=*/true); + const WaveformLanes lanes = waveformLanes(band, LaneSplit::Stereo); CHECK(lanes.upper.y == band.y); CHECK(lanes.lower.bottom() == band.bottom()); // Full width each, seam exactly kLaneGap, no overlap. @@ -127,14 +127,14 @@ static void testStereoSplitsIntoTwoLanesWithTheSeamGap() { static void testStereoOddRemainderGoesToTheUpperLane() { const Rect band = Rect::ltrb(0, 0, 100, 201); // usable 199 -> 100 / 99 - const WaveformLanes lanes = waveformLanes(band, /*stereo=*/true); + const WaveformLanes lanes = waveformLanes(band, LaneSplit::Stereo); CHECK(lanes.upper.height == 100); CHECK(lanes.lower.height == 99); CHECK(lanes.lower.bottom() == band.bottom()); } static void testEmptyBandYieldsEmptyLanes() { - const WaveformLanes lanes = waveformLanes(Rect{}, /*stereo=*/true); + const WaveformLanes lanes = waveformLanes(Rect{}, LaneSplit::Stereo); CHECK(lanes.upper.empty()); CHECK(lanes.lower.empty()); } diff --git a/tests/test_waveform_view.cpp b/tests/test_waveform_view.cpp index d5cfd60..e4cb1c6 100644 --- a/tests/test_waveform_view.cpp +++ b/tests/test_waveform_view.cpp @@ -1,16 +1,20 @@ // Standalone tests for reasampler::instrument::ui::waveform_view — no VST3, no REAPER, no framework. -// Same fast assert loop as the sibling pure tests. Assert the S11 waveform surface's -// frame<->pixel mapping, marker grab regions, drag-delta frame resolver (with clamps), and -// the zero-crossing snap — the geometry + snap that back the draggable start/loop markers. +// Same fast assert loop as the sibling pure tests. Assert the waveform band's drawn surface +// (lane split + the full-height overlay contract) and its frame<->pixel mapping, marker grab +// regions, drag-delta frame resolver (with clamps), and zero-crossing snap. // // Covers: frameToX / xToFrame (linear map + inverse, edge clamps, degenerate frameCount/width); // markerAtPoint (grab band, first-match on overlap, off-area + null-array rejection); // resolveDragFrame (round-to-nearest-frame, clamp to [0,frameCount], zero-delta/zero-width // no-ops); nearestZeroCrossing (nearest sign-change, sample-on-zero, equidistant-tie-to-lower, -// no-crossing keeps target, target clamp, degenerate buffers). +// no-crossing keeps target, target clamp, degenerate buffers); waveformSurface (two stacked +// lanes L-over-R in stereo, one lane in mono AND for a mono source, overlay always the full +// stacked height, grabs reaching the lower lane); laneEnvelope (per-lane channel split). #include "../src/core/instrument/ui/waveform_view.h" +#include "../src/core/instrument/ui/sample_bands.h" // kWaveformMinHeight, kLaneGap +#include #include #include @@ -22,6 +26,8 @@ static int g_fail = 0; #define CHECK(cond) do { if(!(cond)) { \ std::printf("FAIL line %d: %s\n", __LINE__, #cond); ++g_fail; } } while(0) +static OverlayArea overlayOf(const Rect& r) { return OverlayArea{r}; } + // A comfortable waveform area: 1000px wide, offset so left != 0 (catches origin bugs). static Rect wideArea() { return Rect::ltrb(20, 10, 1020, 90); } // width 1000 @@ -29,36 +35,36 @@ static Rect wideArea() { return Rect::ltrb(20, 10, 1020, 90); } // width 1000 static void testFrameToXEndpoints() { const Rect a = wideArea(); - CHECK(frameToX(a, 1000, 0) == a.x); // frame 0 -> left edge - CHECK(frameToX(a, 1000, 1000) == a.right()); // frameCount -> right edge - CHECK(frameToX(a, 1000, 500) == a.x + 500); // midpoint (1:1 here) + CHECK(frameToX(overlayOf(a), 1000, 0) == a.x); // frame 0 -> left edge + CHECK(frameToX(overlayOf(a), 1000, 1000) == a.right()); // frameCount -> right edge + CHECK(frameToX(overlayOf(a), 1000, 500) == a.x + 500); // midpoint (1:1 here) } static void testFrameToXClampsOutOfRange() { const Rect a = wideArea(); - CHECK(frameToX(a, 1000, -50) == a.x); // below 0 pins left - CHECK(frameToX(a, 1000, 5000) == a.right()); // above count pins right + CHECK(frameToX(overlayOf(a), 1000, -50) == a.x); // below 0 pins left + CHECK(frameToX(overlayOf(a), 1000, 5000) == a.right()); // above count pins right } static void testFrameToXDegenerate() { const Rect a = wideArea(); - CHECK(frameToX(a, 0, 100) == a.x); // no frames -> left + CHECK(frameToX(overlayOf(a), 0, 100) == a.x); // no frames -> left const Rect z = Rect::ltrb(5, 5, 5, 45); // zero width - CHECK(frameToX(z, 1000, 500) == z.x); + CHECK(frameToX(overlayOf(z), 1000, 500) == z.x); } static void testXToFrameInverse() { const Rect a = wideArea(); - CHECK(xToFrame(a, 1000, a.x) == 0); - CHECK(xToFrame(a, 1000, a.right()) == 1000); - CHECK(xToFrame(a, 1000, a.x + 250) == 250); // 1:1 map here + CHECK(xToFrame(overlayOf(a), 1000, a.x) == 0); + CHECK(xToFrame(overlayOf(a), 1000, a.right()) == 1000); + CHECK(xToFrame(overlayOf(a), 1000, a.x + 250) == 250); // 1:1 map here } static void testXToFrameClampsOutside() { const Rect a = wideArea(); - CHECK(xToFrame(a, 1000, a.x - 100) == 0); // left of area -> 0 - CHECK(xToFrame(a, 1000, a.right() + 100) == 1000); // right of area -> frameCount - CHECK(xToFrame(a, 0, a.x + 10) == 0); // no frames -> 0 + CHECK(xToFrame(overlayOf(a), 1000, a.x - 100) == 0); // left of area -> 0 + CHECK(xToFrame(overlayOf(a), 1000, a.right() + 100) == 1000); // right of area -> frameCount + CHECK(xToFrame(overlayOf(a), 0, a.x + 10) == 0); // no frames -> 0 } static void testFrameToXRoundTrip() { @@ -66,8 +72,8 @@ static void testFrameToXRoundTrip() { // xToFrame should land within a couple frames (rounding both directions). const Rect a = Rect::ltrb(0, 0, 800, 60); for (std::int64_t f = 0; f <= 2000; f += 137) { - const int x = frameToX(a, 2000, f); - const std::int64_t back = xToFrame(a, 2000, x); + const int x = frameToX(overlayOf(a), 2000, f); + const std::int64_t back = xToFrame(overlayOf(a), 2000, x); CHECK(back >= f - 3 && back <= f + 3); } } @@ -76,75 +82,82 @@ static void testFrameToXRoundTrip() { static void testMarkerAtPointGrabsWithinBand() { const Rect a = wideArea(); + const OverlayArea ov = overlayOf(a); // Markers at frames 100, 500, 900 -> x = left+100, left+500, left+900. const std::int64_t frames[3] = {100, 500, 900}; const int midY = a.y + a.height / 2; - CHECK(markerAtPoint(a, 1000, frames, 3, a.x + 100, midY) == 0); - CHECK(markerAtPoint(a, 1000, frames, 3, a.x + 500, midY) == 1); - CHECK(markerAtPoint(a, 1000, frames, 3, a.x + 900, midY) == 2); + CHECK(markerAtPoint(ov, 1000, frames, 3, a.x + 100, midY) == 0); + CHECK(markerAtPoint(ov, 1000, frames, 3, a.x + 500, midY) == 1); + CHECK(markerAtPoint(ov, 1000, frames, 3, a.x + 900, midY) == 2); // Within the grab band on either side of the line. - CHECK(markerAtPoint(a, 1000, frames, 3, a.x + 500 + kMarkerGrabWidth, midY) == 1); - CHECK(markerAtPoint(a, 1000, frames, 3, a.x + 500 - kMarkerGrabWidth, midY) == 1); + CHECK(markerAtPoint(ov, 1000, frames, 3, a.x + 500 + kMarkerGrabWidth, midY) == 1); + CHECK(markerAtPoint(ov, 1000, frames, 3, a.x + 500 - kMarkerGrabWidth, midY) == 1); } static void testMarkerAtPointMissesBetween() { const Rect a = wideArea(); + const OverlayArea ov = overlayOf(a); const std::int64_t frames[3] = {100, 500, 900}; const int midY = a.y + a.height / 2; // Well away from any marker line. - CHECK(markerAtPoint(a, 1000, frames, 3, a.x + 300, midY) == -1); + CHECK(markerAtPoint(ov, 1000, frames, 3, a.x + 300, midY) == -1); // Off the area vertically. - CHECK(markerAtPoint(a, 1000, frames, 3, a.x + 500, a.y - 5) == -1); + CHECK(markerAtPoint(ov, 1000, frames, 3, a.x + 500, a.y - 5) == -1); } static void testMarkerAtPointFirstMatchOnOverlap() { const Rect a = wideArea(); + const OverlayArea ov = overlayOf(a); // Two markers at the same frame -> first in order wins. const std::int64_t frames[2] = {400, 400}; const int midY = a.y + a.height / 2; - CHECK(markerAtPoint(a, 1000, frames, 2, a.x + 400, midY) == 0); + CHECK(markerAtPoint(ov, 1000, frames, 2, a.x + 400, midY) == 0); } static void testMarkerAtPointRejectsNullEmpty() { const Rect a = wideArea(); + const OverlayArea ov = overlayOf(a); const int midY = a.y + a.height / 2; - CHECK(markerAtPoint(a, 1000, nullptr, 3, a.x + 100, midY) == -1); + CHECK(markerAtPoint(ov, 1000, nullptr, 3, a.x + 100, midY) == -1); const std::int64_t frames[1] = {100}; - CHECK(markerAtPoint(a, 1000, frames, 0, a.x + 100, midY) == -1); + CHECK(markerAtPoint(ov, 1000, frames, 0, a.x + 100, midY) == -1); } // --- resolveDragFrame --------------------------------------------------------- static void testResolveDragFrameShift() { const Rect a = wideArea(); // 1:1 (1000px / 1000 frames) - CHECK(resolveDragFrame(a, 1000, 300, 0) == 300); // zero delta -> unchanged - CHECK(resolveDragFrame(a, 1000, 300, 100) == 400); // +100px -> +100 frames - CHECK(resolveDragFrame(a, 1000, 300, -50) == 250); // -50px -> -50 frames + const OverlayArea ov = overlayOf(a); + CHECK(resolveDragFrame(ov, 1000, 300, 0) == 300); // zero delta -> unchanged + CHECK(resolveDragFrame(ov, 1000, 300, 100) == 400); // +100px -> +100 frames + CHECK(resolveDragFrame(ov, 1000, 300, -50) == 250); // -50px -> -50 frames } static void testResolveDragFrameClamps() { const Rect a = wideArea(); - CHECK(resolveDragFrame(a, 1000, 50, -500) == 0); // clamp low - CHECK(resolveDragFrame(a, 1000, 950, 500) == 1000); // clamp high (== frameCount) + const OverlayArea ov = overlayOf(a); + CHECK(resolveDragFrame(ov, 1000, 50, -500) == 0); // clamp low + CHECK(resolveDragFrame(ov, 1000, 950, 500) == 1000); // clamp high (== frameCount) } static void testResolveDragFrameRounds() { // 500px area over 1000 frames -> 2 frames/px. A +3px drag -> round(6.0)=6; the rounding is // at the frame centre. Use a scale where a fractional result appears. - const Rect a = Rect::ltrb(0, 0, 300, 60); // 1000 frames / 300px = 3.33 frames/px + const OverlayArea ov = overlayOf(Rect::ltrb(0, 0, 300, 60)); // 1000 frames / 300px = 3.33 frames/px // +3px -> 3*1000/300 = 10.0 -> 10 frames. - CHECK(resolveDragFrame(a, 1000, 100, 3) == 110); + CHECK(resolveDragFrame(ov, 1000, 100, 3) == 110); // +1px -> 1000/300 = 3.33 -> rounds to 3. - CHECK(resolveDragFrame(a, 1000, 100, 1) == 103); + CHECK(resolveDragFrame(ov, 1000, 100, 1) == 103); } static void testResolveDragFrameDegenerate() { const Rect z = Rect::ltrb(0, 0, 0, 60); // zero width - CHECK(resolveDragFrame(z, 1000, 300, 100) == 300); // pinned to start + CHECK(resolveDragFrame(overlayOf(z), 1000, 300, 100) == 300); // pinned to start const Rect a = wideArea(); - CHECK(resolveDragFrame(a, 0, 300, 100) == 0); // no frames -> clamp(start)=0 + const OverlayArea ov = overlayOf(a); + CHECK(resolveDragFrame(ov, 0, 300, 100) == 0); // no frames -> clamp(start)=0 // startFrame out of range is clamped first. - CHECK(resolveDragFrame(a, 1000, 5000, 0) == 1000); + CHECK(resolveDragFrame(ov, 1000, 5000, 0) == 1000); } // --- nearestZeroCrossing ------------------------------------------------------ @@ -193,6 +206,144 @@ static void testZeroCrossingDegenerate() { CHECK(nearestZeroCrossing(one.data(), 1, 0) == 0); // <2 frames -> clamped target } +// --- waveformSurface: the lane split + the overlay contract -------------------- + +// A realistic waveform band: full-width, taller than the two-lane floor. +static Rect band() { return Rect::ltrb(8, 90, 832, 90 + kWaveformMinHeight); } + +static void testSurfaceStereoStacksTwoLanes() { + const Rect b = band(); + const WaveformSurface s = waveformSurface(b, /*stereoMode=*/true, /*sourceChannels=*/2); + CHECK(s.laneCount == 2); + CHECK(!s.upper.empty() && !s.lower.empty()); + CHECK(s.upper.y == b.y); // L on top + CHECK(s.lower.y > s.upper.bottom()); // R below, seam between them + CHECK(s.lower.bottom() == b.bottom()); // together they reach the band's floor + CHECK(s.upper.x == b.x && s.upper.width == b.width); + CHECK(s.lower.x == b.x && s.lower.width == b.width); + // Non-overlapping, and the band is exactly lanes + the one seam gap. + CHECK(s.lower.y - s.upper.bottom() == kLaneGap); + CHECK(s.upper.height + kLaneGap + s.lower.height == b.height); +} + +static void testSurfaceMonoIsOneLane() { + const Rect b = band(); + const WaveformSurface s = waveformSurface(b, /*stereoMode=*/false, /*sourceChannels=*/2); + CHECK(s.laneCount == 1); + CHECK(s.upper == b); // the single lane spans the whole band + CHECK(s.lower.empty()); // no second lane to draw +} + +static void testSurfaceMonoSourceInStereoModeStaysOneLane() { + // Dual-mono: a mono source under stereo mode has no second channel, so a second lane + // would be a redundant duplicate. + const Rect b = band(); + const WaveformSurface s = waveformSurface(b, /*stereoMode=*/true, /*sourceChannels=*/1); + CHECK(s.laneCount == 1); + CHECK(s.upper == b); + CHECK(s.lower.empty()); +} + +static void testSurfaceOverlayIsFullStackedHeightInBothModes() { + const Rect b = band(); + const WaveformSurface st = waveformSurface(b, /*stereoMode=*/true, 2); + const WaveformSurface mo = waveformSurface(b, /*stereoMode=*/false, 2); + // Stereo: ONE overlay rect spanning both lanes, not either lane. + CHECK(st.overlay.rect == b); + CHECK(st.overlay.rect.height == st.upper.height + kLaneGap + st.lower.height); + CHECK(st.overlay.rect != st.upper && st.overlay.rect != st.lower); + // Mono: the same rect, which is also the single lane. + CHECK(mo.overlay.rect == b); + CHECK(mo.overlay.rect == mo.upper); + // The standalone accessor the hit-test paths use agrees with the resolved surface. + CHECK(waveformOverlayArea(b) == st.overlay); + CHECK(waveformOverlayArea(b) == mo.overlay); +} + +static void testSurfaceDegenerateBandDrawsNothing() { + const WaveformSurface s = waveformSurface(Rect{10, 10, 0, 0}, true, 2); + CHECK(s.laneCount == 0); + CHECK(s.upper.empty() && s.lower.empty() && s.overlay.rect.empty()); + CHECK(waveformOverlayArea(Rect{10, 10, 0, 0}).rect.empty()); +} + +static void testSurfaceThinBandRoundsLowerLaneEmpty() { + // Height 3 is the edge where the stereo split's integer division rounds the lower lane to + // empty even though the band itself isn't degenerate — pins the laneCount derivation. + const WaveformSurface s = waveformSurface(Rect{0, 0, 100, 3}, true, 2); + CHECK(s.laneCount == 1); + CHECK(!s.upper.empty()); + CHECK(s.lower.empty()); +} + +// --- Hit-testing across the stacked lanes ------------------------------------- + +static void testMarkerGrabReachesTheLowerStereoLane() { + const Rect b = band(); + const WaveformSurface s = waveformSurface(b, /*stereoMode=*/true, 2); + const std::int64_t frames = 1000; + const std::int64_t markers[1] = {500}; + const int mx = frameToX(s.overlay, frames, 500); + // The same marker answers a grab in either lane — overlays span the full stack. + const int upperY = s.upper.y + s.upper.height / 2; + const int lowerY = s.lower.y + s.lower.height / 2; + CHECK(markerAtPoint(s.overlay, frames, markers, 1, mx, upperY) == 0); + CHECK(markerAtPoint(s.overlay, frames, markers, 1, mx, lowerY) == 0); + // A lower-lane grab hit-tested against the UPPER LANE would be lost — the miss this + // contract exists to prevent. (Explicit OverlayArea{} wrap: production code can't do + // this by accident — markerAtPoint won't accept a bare lane Rect — but the geometry + // claim still needs proving.) + CHECK(markerAtPoint(overlayOf(s.upper), frames, markers, 1, mx, lowerY) == -1); + // Off the marker's x is still a miss at either height. + CHECK(markerAtPoint(s.overlay, frames, markers, 1, mx + 40, lowerY) == -1); +} + +static void testMarkerGrabInMonoSpansTheBand() { + const Rect b = band(); + const WaveformSurface s = waveformSurface(b, /*stereoMode=*/false, 2); + const std::int64_t frames = 1000; + const std::int64_t markers[1] = {250}; + const int mx = frameToX(s.overlay, frames, 250); + CHECK(markerAtPoint(s.overlay, frames, markers, 1, mx, b.y) == 0); + CHECK(markerAtPoint(s.overlay, frames, markers, 1, mx, b.bottom() - 1) == 0); + CHECK(markerAtPoint(s.overlay, frames, markers, 1, mx, b.bottom() + 5) == -1); +} + +// --- Per-lane envelope content ------------------------------------------------- + +static void testAsymmetricStereoLanesCarryDifferentContent() { + // Left is full-scale, right is a tenth of it — the lanes must look materially different. + const std::size_t frames = 400; + std::vector interleaved(frames * 2); + for (std::size_t f = 0; f < frames; ++f) { + const AudioSample v = (f % 2 == 0) ? 1.0f : -1.0f; + interleaved[f * 2 + 0] = v; + interleaved[f * 2 + 1] = v * 0.1f; + } + // ONE pass over the interleaved source, split per lane — what the painter does. + const reasampler::audio::Envelope env = + reasampler::audio::computeEnvelope(interleaved, 2, frames, 20); + const reasampler::audio::Envelope upper = laneEnvelope(env, 0); + const reasampler::audio::Envelope lower = laneEnvelope(env, 1); + CHECK(upper.size() == 1 && lower.size() == 1); + CHECK(upper[0].size() == 20 && lower[0].size() == 20); + for (std::size_t i = 0; i < 20; ++i) { + CHECK(upper[0][i].max > 0.9f); // left near full scale + CHECK(lower[0][i].max < 0.2f); // right an order of magnitude down + CHECK(!(upper[0][i] == lower[0][i])); // and materially different, bin for bin + } +} + +static void testLaneEnvelopeRejectsOutOfRangeLane() { + const std::size_t frames = 16; + std::vector mono(frames, 0.5f); + const reasampler::audio::Envelope env = + reasampler::audio::computeEnvelope(mono, 1, frames, 4); + CHECK(laneEnvelope(env, 0).size() == 1); + CHECK(laneEnvelope(env, 1).empty()); // a mono source has no lower lane + CHECK(laneEnvelope(env, -1).empty()); +} + int main() { testFrameToXEndpoints(); testFrameToXClampsOutOfRange(); @@ -218,6 +369,19 @@ int main() { testZeroCrossingClampsTarget(); testZeroCrossingDegenerate(); + testSurfaceStereoStacksTwoLanes(); + testSurfaceMonoIsOneLane(); + testSurfaceMonoSourceInStereoModeStaysOneLane(); + testSurfaceOverlayIsFullStackedHeightInBothModes(); + testSurfaceDegenerateBandDrawsNothing(); + testSurfaceThinBandRoundsLowerLaneEmpty(); + + testMarkerGrabReachesTheLowerStereoLane(); + testMarkerGrabInMonoSpansTheBand(); + + testAsymmetricStereoLanesCarryDifferentContent(); + testLaneEnvelopeRejectsOutOfRangeLane(); + if (g_fail == 0) std::printf("waveform_view: all tests passed\n"); else std::printf("waveform_view: %d FAILED\n", g_fail); return g_fail == 0 ? 0 : 1;