fix(instrument): bound the waveform zero-crossing snap to a pixel radius so single-cycle loop marks stop teleporting

Ctrl during a marker drag defeats the snap outright. nearestZeroCrossing keeps its
unbounded contract; snapToZeroCrossing is the decision a drag applies.
This commit is contained in:
2026-08-03 15:15:25 -04:00
parent 1159d364c2
commit b7b7e88195
5 changed files with 205 additions and 24 deletions
+1 -1
View File
@@ -340,7 +340,7 @@ anything for a trigger shape.
- `sample_chrome` — the CHROME band's interior: the toolbar row (title + the whole right-anchored control run — bake Hold cell, bake, preview, velocity knob cell, loop enable, channel toggle, Browse) over the strip row, which the piano strip owns outright. The title takes what the run leaves; the strip takes its whole row, inset only by the shared band pad so it lines up with the waveform band beneath. Every run member's width is RESERVED unconditionally, the Hold cell included — the only conditionally-drawn one, and the leftmost, so what its reservation buys is a title slot that does not re-measure when a loop is dialled in or out (`sample_chrome.h` records the cost). Also `previewGlyph`, the preview button's play triangle — three vertices for one filled-triangle draw, so the button's label needs no font metric and no image asset.
- `bake_hold` — the Hold knob's value domain and nothing else: the knob's normalized [0,1] mapped onto the note-length ladder and back, ordered by LENGTH rather than by the ladder's presentation order. Split from `sample_chrome` on the same axis `deck_values` was split from `knob_deck` — that says where the cell is, this says what its position means.
- `keyboard_strip` — piano-keyboard strip: true white/black key geometry (whites tiled at one width, blacks overlaid at one width and height, straddling their boundary), hit-test resolving black-over-white by zone, root-marker rect, the absolute-position drag resolver, and MIDI note naming under the C4 convention. **Same-class keys are one integer width by construction; the residue of an indivisible band width (`w % 75`, up to 74 px) lands in symmetric end margins, never in a key** — uniform widths and gap-free edge-to-edge tiling cannot both hold, and uniformity wins.
- `waveform_view` — the WAVEFORM band's interior: `resolveLaneSplit` is THE lane-split decision (two lanes 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), free of any pixel geometry so the meter's bar count can ask the same question without a band rect; `waveformSurface` folds it and then measures it against the band, which is why its `laneCount` can still report 1 for a Stereo split on a band too thin to divide. It also yields **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, plus `markerHandleRect` — a top-strip grab tab distinct from a marker's full-height column, so two markers that share a frame stay independently grabbable (the column goes to the first in draw order; the tab, asked first, resolves the other).
- `waveform_view` — the WAVEFORM band's interior: `resolveLaneSplit` is THE lane-split decision (two lanes 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), free of any pixel geometry so the meter's bar count can ask the same question without a band rect; `waveformSurface` folds it and then measures it against the band, which is why its `laneCount` can still report 1 for a Stereo split on a band too thin to divide. It also yields **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 the zero-crossing snap — RADIUS-BOUNDED (`snapToZeroCrossing`), the radius denominated in PIXELS and converted through `xToFrame`; `nearestZeroCrossing` beside it is the unbounded primitive and is NOT what a drag applies — plus `markerHandleRect` — a top-strip grab tab distinct from a marker's full-height column, so two markers that share a frame stay independently grabbable (the column goes to the first in draw order; the tab, asked first, resolves the other).
- **Overlay contract (consumed by later waveform work).** `WaveformSurface::overlay` — equivalently the standalone `waveformOverlayArea(band)` — is the band's DRAWN COLUMN SPAN at the band's full height, in both modes: same inset and same width as `component_geometry`'s `waveformColumnCount`, so overlay pixel and waveform column are one pixel and every overlay lands on the column that draws the frame it names. Deriving that width instead of restating the inset is what keeps the two chains from drifting apart again. 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.
- **The four marks.** One grammar — line + shaped cap + label — over START / LOOP / END / XFADE. Which of them are PRESENT is the mode's answer, and drawn iff grabbable: Trigger carries START alone (the loop pair and the fade are absent, not dim), Gate always carries the pair so the drag-to-set-loop gesture survives the enable being off, and the fade needs an active loop to have a seam. `markerHandleRect` IS the cap: every mark's is the same rect shape, only the glyph inside differs, which is what keeps the claim arbitration seeing one nominal cap area. `capAtPoint` resolves caps in the REVERSE of the column order, so any coincident PAIR stays separable (one answers its cap, the other its column) and the crossfade — the one mark with no column — can never be shadowed. `layoutMarkLabels` places the promoted (grabbed/hovered) mark first and suppresses any box that would overlap one already placed. `crossfadeWedgeHeight` is the ONE ramp both the audible region and the ingredient ghost draw, because they are the same fade weight over the two spans it mixes.
- `loop_marks` — the loop enable's state machine, split from the geometry above on the axis the surface already has: that says where a mark is, this says what the loop IS. `SampleLoop::hasLoop` is the single authority and `resolveLoopMarks`/`applyLoopMarks` are its only two folds — the resolve re-parks on `defaultLoopBounds` only when the span is one `resolveLoop` would refuse (so a user's off keeps its positions and `parked` separates the two OFF states), and the write folds collapse-to-off in and ties the crossfade to the SPAN rather than to the enable. Links `loop_span` so the span the user is offered and the span the engine accepts stay one definition.
+38 -11
View File
@@ -178,17 +178,15 @@ std::int64_t resolveDragFrame(const OverlayArea& area, std::int64_t frameCount,
return xToFrame(area, frameCount, grabX + dxPixels);
}
std::int64_t nearestZeroCrossing(const AudioSample* pcm, std::int64_t frames,
std::int64_t target) {
if (pcm == nullptr || frames < 2) return clampFrame(target, frames > 0 ? frames - 1 : 0);
// Clamp target into a valid sample index [0, frames).
std::int64_t t = target;
if (t < 0) t = 0;
if (t > frames - 1) t = frames - 1;
namespace {
// The fan-out both entry points below share, so the two cannot grow two search orders: at each
// distance d probe t-d before t+d, which is what resolves an equidistant tie to the LOWER frame.
// Answers -1 when no crossing lies within `maxDistance` — the caller decides what that means.
std::int64_t crossingWithin(const AudioSample* pcm, std::int64_t frames, std::int64_t t,
std::int64_t maxDistance) {
// A crossing lives at frame i (1 <= i < frames) when sign(pcm[i-1]) != sign(pcm[i]) OR
// pcm[i] == 0. isCrossing(i) tests exactly that. We fan out from t: at each distance d we
// probe t-d before t+d, so an equidistant tie resolves to the LOWER frame (deterministic).
// pcm[i] == 0.
auto isCrossing = [&](std::int64_t i) -> bool {
if (i < 1 || i >= frames) return false;
const AudioSample a = pcm[i - 1];
@@ -198,7 +196,7 @@ std::int64_t nearestZeroCrossing(const AudioSample* pcm, std::int64_t frames,
};
if (isCrossing(t)) return t;
for (std::int64_t d = 1; d < frames; ++d) {
for (std::int64_t d = 1; d <= maxDistance; ++d) {
const std::int64_t lo = t - d;
if (lo >= 1 && isCrossing(lo)) return lo; // lower side wins the tie
const std::int64_t hi = t + d;
@@ -206,7 +204,36 @@ std::int64_t nearestZeroCrossing(const AudioSample* pcm, std::int64_t frames,
// Stop once both probes have run off both ends — no crossing anywhere.
if (lo < 1 && hi >= frames) break;
}
return t; // no sign change in the whole buffer -> keep the raw (clamped) target
return -1;
}
// Clamp into a valid sample index [0, frames).
std::int64_t clampSampleIndex(std::int64_t target, std::int64_t frames) {
return clampFrame(target, frames > 0 ? frames - 1 : 0);
}
} // namespace
std::int64_t nearestZeroCrossing(const AudioSample* pcm, std::int64_t frames,
std::int64_t target) {
const std::int64_t t = clampSampleIndex(target, frames);
if (pcm == nullptr || frames < 2) return t;
// `frames` bounds every reachable distance from any t in [0, frames), so this is the whole
// buffer.
const std::int64_t c = crossingWithin(pcm, frames, t, frames);
return c >= 0 ? c : t; // no sign change anywhere -> keep the raw (clamped) target
}
std::int64_t zeroCrossingSnapFrames(const OverlayArea& area, std::int64_t frameCount) {
return xToFrame(area, frameCount, area.rect.x + kZeroCrossingSnapPx);
}
std::int64_t snapToZeroCrossing(const AudioSample* pcm, std::int64_t frames, std::int64_t target,
std::int64_t maxDistanceFrames) {
const std::int64_t t = clampSampleIndex(target, frames);
if (pcm == nullptr || frames < 2 || maxDistanceFrames < 0) return t;
const std::int64_t c = crossingWithin(pcm, frames, t, maxDistanceFrames);
return c >= 0 ? c : t; // nothing that near -> the mark stays where it was dropped
}
} // namespace reasampler::instrument::ui
+36 -5
View File
@@ -185,12 +185,43 @@ int markerAtPoint(const OverlayArea& area, std::int64_t frameCount, const std::i
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).
// Search fans out symmetrically from the clamped target; an equidistant tie resolves to the
// lower frame. No sign change anywhere (or fewer than 2 frames) returns the clamped target
// unchanged.
// --- The zero-crossing snap ----------------------------------------------------------------
// Nearest zero-crossing frame to `target` in the mono PCM. 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). Search
// fans out symmetrically from the clamped target; an equidistant tie resolves to the lower
// frame. No sign change anywhere (or fewer than 2 frames) returns the clamped target unchanged.
//
// This answers WHERE the nearest crossing is, over the whole buffer. It is not what a drag
// should apply — see snapToZeroCrossing.
std::int64_t nearestZeroCrossing(const AudioSample* pcm, std::int64_t frames,
std::int64_t target);
// How far, in PIXELS, a mark may be pulled to reach a crossing. Aliases the mark's own grab band
// on purpose: the snap may move a mark only as far as the pointer could have been from it and
// still have grabbed it — a displacement inside the neighbourhood the user was already pointing
// at is one they cannot see.
//
// PIXELS rather than frames because the drag itself resolves in pixels — resolveDragFrame answers
// the column's own first frame, so a frame radius under one column's span would be unreachable on
// a long capture, and a fixed frame radius means a different VISIBLE distance at every sample
// length.
inline constexpr int kZeroCrossingSnapPx = kMarkerGrabWidth;
// That radius in frames for this overlay, read off THE mapping rather than a second ratio.
// Answers 0 below one frame per pixel, which is right: at that zoom the user is placing
// individual frames, and only a mark dropped exactly on a crossing snaps.
std::int64_t zeroCrossingSnapFrames(const OverlayArea& area, std::int64_t frameCount);
// THE snap a marker drag applies: the nearest crossing WITHIN maxDistanceFrames of the clamped
// target, or the target itself when none is that near. Same fan-out and same tie rule as
// nearestZeroCrossing.
//
// The radius is what makes this a snap rather than a constraint. Unbounded, the search always
// finds something: on single-cycle material, whose whole ~800-frame buffer holds one or two
// crossings, it pinned the loop marks hundreds of frames from where they were dropped — halving
// the loop and doubling the pitch. Do not remove the bound.
std::int64_t snapToZeroCrossing(const AudioSample* pcm, std::int64_t frames, std::int64_t target,
std::int64_t maxDistanceFrames);
} // namespace reasampler::instrument::ui
@@ -282,13 +282,15 @@ void ReaSamplerEditor::dragWaveform(const FaceLayout& fl, int x, int y) {
dragStartMarkers_.crossfade};
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. The crossfade handle is exempt: it sets a fade
// LENGTH, and the whole point of the fade is that its edges need no zero crossing.
// Snap to a zero crossing in the decoded PCM, but only one within kZeroCrossingSnapPx of
// where the mark was dropped. Pure over the cached mono frames — no host types, no file I/O.
// The crossfade handle is exempt: it sets a fade LENGTH, and the whole point of the fade is
// that its edges need no zero crossing. Ctrl defeats the snap outright, the same "get out of
// the way, I want exactness" role it plays as the knobs' fine drag.
const std::vector<AudioSample>& pcm = monoPcmFor(selectedId_);
if (!pcm.empty() && waveMarker_ != WaveMarker::kCrossfade) {
newFrame = nearestZeroCrossing(pcm.data(), static_cast<std::int64_t>(pcm.size()),
newFrame);
if (!pcm.empty() && waveMarker_ != WaveMarker::kCrossfade && !dragModifiers().ctrl) {
newFrame = snapToZeroCrossing(pcm.data(), static_cast<std::int64_t>(pcm.size()), newFrame,
zeroCrossingSnapFrames(overlay, frames));
}
// Build the edited marker set from the snapshot, moving only the grabbed marker, then