FA2: param-domain Gate schematic + 8px node min-sep (all nodes grabbable at defaults); cross-mode drag guard; double-clamp px overflow fix

This commit is contained in:
2026-07-27 19:09:47 -04:00
parent d5d1902ea4
commit 99f377db28
6 changed files with 360 additions and 142 deletions
+43 -21
View File
@@ -23,13 +23,14 @@ double secondsPerPixel(const Rect& area, double totalSeconds) {
return totalSeconds / static_cast<double>(w); return totalSeconds / static_cast<double>(w);
} }
// Seconds per pixel in the GATE timed region (FA2): the Gate schematic maps A/H/D/R onto // Seconds per pixel for a GATE time-node drag (FA2): the reciprocal of the overlay's
// gateTimedWidth(area) px, not the full canvas, so a Gate time-node drag must use this scale for // param-domain gatePxPerSecond(area) scale — sample-length-free, matching
// the handle to track the cursor. Matches envelope_overlay::gatePolyline. // envelope_overlay::gatePolyline exactly so the dragged handle tracks the cursor 1:1 (each
double gateSecondsPerPixel(const Rect& area, double totalSeconds) { // node's x is affine in its own segment duration with slope gatePxPerSecond). Zero when the
const int w = gateTimedWidth(area); // area is degenerate.
if (w <= 0 || totalSeconds <= 0.0) return 0.0; double gateSecondsPerPixel(const Rect& area) {
return totalSeconds / static_cast<double>(w); const double pps = gatePxPerSecond(area);
return pps > 0.0 ? 1.0 / pps : 0.0;
} }
// Level (0..1) represented by one vertical pixel. levelToY spans (height-1) rows for [0,1], so one // Level (0..1) represented by one vertical pixel. levelToY spans (height-1) rows for [0,1], so one
@@ -51,20 +52,42 @@ bool isDraggable(EnvNode n) {
} }
} }
// True when the node belongs to the envelope's active mode. Guards the degenerate cross-mode
// write: the degenerate baseline polyline carries a ReleaseEnd vertex regardless of mode, so a
// zero-height Trigger-mode grab of it must not write releaseSeconds (and vice versa for Gate
// nodes vs Trigger fields). Applied by BOTH the hit-test and the drag resolver so they agree.
bool nodeInMode(EnvNode n, EnvMode m) {
switch (n) {
case EnvNode::AttackEnd:
case EnvNode::HoldEnd:
case EnvNode::DecayEnd:
case EnvNode::ReleaseEnd:
return m == EnvMode::Gate;
case EnvNode::FadeInEnd:
case EnvNode::FadeOutStart:
case EnvNode::LengthEnd:
return m == EnvMode::Trigger;
case EnvNode::Origin:
case EnvNode::ReleaseStart:
return false; // never draggable in any mode (isDraggable filters these anyway)
}
return false;
}
} // namespace } // namespace
NodeHit nodeAtPoint(const AmpEnvelope& env, const Rect& area, double totalSeconds, int x, int y) { NodeHit nodeAtPoint(const AmpEnvelope& env, const Rect& area, double totalSeconds, int x, int y) {
const std::vector<EnvVertex> poly = buildEnvelopePolyline(env, area, totalSeconds); const std::vector<EnvVertex> poly = buildEnvelopePolyline(env, area, totalSeconds);
// NEAREST draggable node within the pick radius wins (Chebyshev distance — the square grab // NEAREST draggable, mode-matching node within the pick radius wins (Chebyshev distance —
// box); ties break to the earlier draw-order node (FA2). Nearest-wins keeps every handle // the square grab box); ties break to the earlier draw-order node (FA2). Gate nodes never
// grabbable when nodes sit close (e.g. a short hold), while the draw-order tie-break makes // coincide (the forward map enforces kGateNodeSepPx separation), so the tie-break only
// exactly-coincident nodes deterministic: at zero fade-out, FadeOutStart overlays LengthEnd // matters for Trigger's zero-fade-out coincidence: FadeOutStart overlays LengthEnd, WINS the
// and WINS the tie, so the fade-out handle is grabbable at the right edge and can be dragged // tie, and can be dragged inward from the right edge. The mode filter keeps the degenerate
// inward from zero. // baseline's ReleaseEnd vertex from registering as a grabbable node in Trigger mode.
NodeHit best; NodeHit best;
int bestDist = kNodeGrabRadius + 1; int bestDist = kNodeGrabRadius + 1;
for (const EnvVertex& v : poly) { for (const EnvVertex& v : poly) {
if (!isDraggable(v.node)) continue; if (!isDraggable(v.node) || !nodeInMode(v.node, env.mode)) continue;
const int dist = std::max(std::abs(x - v.x), std::abs(y - v.y)); const int dist = std::max(std::abs(x - v.x), std::abs(y - v.y));
if (dist < bestDist) { // strictly closer only: earlier draw order keeps ties if (dist < bestDist) { // strictly closer only: earlier draw order keeps ties
bestDist = dist; bestDist = dist;
@@ -78,17 +101,16 @@ AmpEnvelope resolveNodeDrag(const AmpEnvelope& grabEnv, EnvNode node, const Rect
double totalSeconds, const EnvClampBounds& bounds, double totalSeconds, const EnvClampBounds& bounds,
int dxPixels, int dyPixels) { int dxPixels, int dyPixels) {
AmpEnvelope out = grabEnv; AmpEnvelope out = grabEnv;
if (!isDraggable(node)) return out; if (!isDraggable(node) || !nodeInMode(node, grabEnv.mode)) return out;
const double secPerPx = secondsPerPixel(area, totalSeconds); const double secPerPx = secondsPerPixel(area, totalSeconds);
if (secPerPx <= 0.0) return out; // degenerate area / duration — no motion if (secPerPx <= 0.0) return out; // degenerate area / duration — no motion
const double dSec = static_cast<double>(dxPixels) * secPerPx; const double dSec = static_cast<double>(dxPixels) * secPerPx;
// Gate time nodes live in the TIMED region of the Gate schematic (FA2), which is narrower // Gate time nodes use the schematic's PARAM-DOMAIN px->seconds scale (FA2) — the reciprocal
// than the canvas by the sustain-plateau reserve — their px->seconds scale differs so the // of the overlay's gatePxPerSecond, sample-length-free — so the dragged handle tracks the
// dragged handle tracks the cursor 1:1. gateTimedWidth >= 1 whenever the area is non-empty, // cursor 1:1. gateTimedWidth >= 1 whenever the area is non-empty, so gateDSec is
// so gateDSec is well-defined past the degenerate guard above. // well-defined past the degenerate guard above.
const double gateDSec = const double gateDSec = static_cast<double>(dxPixels) * gateSecondsPerPixel(area);
static_cast<double>(dxPixels) * gateSecondsPerPixel(area, totalSeconds);
switch (node) { switch (node) {
// --- Gate: each cumulative-time node edits its OWN segment duration. Non-negative // --- Gate: each cumulative-time node edits its OWN segment duration. Non-negative
+17 -10
View File
@@ -25,10 +25,13 @@
// decay time, its Y sets the sustain level (the standard ADSR-editor grammar). Origin and the // decay time, its Y sets the sustain level (the standard ADSR-editor grammar). Origin and the
// drawing-only ReleaseStart vertex are NOT draggable. // drawing-only ReleaseStart vertex are NOT draggable.
// //
// GATE DRAG SCALE (FA2). Gate time nodes live in the Gate schematic's TIMED region // GATE DRAG SCALE (FA2). Gate time nodes convert px->seconds via the reciprocal of the
// (gateTimedWidth(area) px — the canvas minus the sustain-plateau reserve), so their px->seconds // schematic's PARAM-DOMAIN scale (envelope_overlay's gatePxPerSecond — sample-length-free), so
// conversion uses that width, not the full canvas; Trigger nodes keep the full-canvas scale. // a dragged handle tracks the cursor exactly 1:1 for stages within the schematic domain (each
// Both match the forward map in envelope_overlay, so a dragged handle tracks the cursor 1:1. // node's x is affine in its own segment duration). Trigger nodes keep the full-canvas
// PCM-aligned scale. Both match the forward map in envelope_overlay. A node is only editable in
// its OWN mode: Gate nodes ignore drags while the envelope is in Trigger mode and vice versa
// (guards the degenerate baseline's cross-mode ReleaseEnd vertex from writing releaseSeconds).
// //
// Reuses editor_geometry's Rect + the EnvNode / AmpEnvelope / EnvMode types from // Reuses editor_geometry's Rect + the EnvNode / AmpEnvelope / EnvMode types from
// envelope_overlay (one shared node vocabulary across draw + edit), and the shared timeToX / // envelope_overlay (one shared node vocabulary across draw + edit), and the shared timeToX /
@@ -69,11 +72,14 @@ struct EnvClampBounds {
// Which node a grab at (x, y) lands on, given the CURRENT envelope + overlay rect + sample // Which node a grab at (x, y) lands on, given the CURRENT envelope + overlay rect + sample
// duration (the same inputs buildEnvelopePolyline drew from, so the grab tests the drawn handles). // duration (the same inputs buildEnvelopePolyline drew from, so the grab tests the drawn handles).
// Returns EnvNode::Origin's NON-membership as a miss via the bool return: `hit` is false for a // Returns EnvNode::Origin's NON-membership as a miss via the bool return: `hit` is false for a
// point off every DRAGGABLE node. Origin and ReleaseStart are never returned (not draggable). // point off every DRAGGABLE node. Origin and ReleaseStart are never returned (not draggable),
// The NEAREST node within the radius wins (Chebyshev distance); an exact tie goes to the earlier // and a node from the OTHER mode is never returned (the degenerate baseline's ReleaseEnd vertex
// draw-order node (FA2 — deterministic, and it makes coincident nodes grabbable: at zero // is not grabbable in Trigger mode). The NEAREST node within the radius wins (Chebyshev
// fade-out, FadeOutStart overlays LengthEnd, wins the tie, and can be dragged inward from the // distance); an exact tie goes to the earlier draw-order node (FA2 — deterministic). Gate nodes
// right edge; at zero hold, AttackEnd wins over HoldEnd). Pure. // never coincide (the forward map enforces kGateNodeSepPx separation, so every Gate handle is
// individually grabbable in every state); the tie-break matters only for Trigger's zero-fade-out
// coincidence, where FadeOutStart overlays LengthEnd, wins the tie, and can be dragged inward
// from the right edge. Pure.
struct NodeHit { struct NodeHit {
bool hit = false; bool hit = false;
EnvNode node = EnvNode::Origin; // meaningful only when hit == true EnvNode node = EnvNode::Origin; // meaningful only when hit == true
@@ -90,7 +96,8 @@ NodeHit nodeAtPoint(const AmpEnvelope& env, const Rect& area, double totalSecond
// duration (e.g. dragging HoldEnd changes holdSeconds, not attack). // duration (e.g. dragging HoldEnd changes holdSeconds, not attack).
// * Y delta -> the LEVEL param, but ONLY for the sustain node (DecayEnd); clamped to [0,1]. // * Y delta -> the LEVEL param, but ONLY for the sustain node (DecayEnd); clamped to [0,1].
// dyPixels is IGNORED for every time-only node. // dyPixels is IGNORED for every time-only node.
// * Non-draggable node (Origin / ReleaseStart) or a zero-width/zero-height area or // * Non-draggable node (Origin / ReleaseStart), a node from the OTHER mode (a Gate node while
// grabEnv.mode is Trigger, or vice versa), a zero-width/zero-height area, or
// totalSeconds <= 0 -> `grabEnv` returned unchanged (no motion). // totalSeconds <= 0 -> `grabEnv` returned unchanged (no motion).
// Only the dragged node's param(s) change; every other field carries through from `grabEnv`. Pure // Only the dragged node's param(s) change; every other field carries through from `grabEnv`. Pure
// — rounding is to the param's continuous value (no snapping, matching the sliders' resolution). // — rounding is to the param's continuous value (no snapping, matching the sliders' resolution).
+62 -28
View File
@@ -11,11 +11,11 @@ int timeToX(const Rect& area, double totalSeconds, double t) {
if (w <= 0 || totalSeconds <= 0.0) return area.left; if (w <= 0 || totalSeconds <= 0.0) return area.left;
if (t < 0.0) t = 0.0; if (t < 0.0) t = 0.0;
// Linear map, clamped on BOTH sides (FA2 bounds invariant): t past totalSeconds pins to the // Linear map, clamped on BOTH sides (FA2 bounds invariant): t past totalSeconds pins to the
// last in-bounds column area.right-1. Round to the nearest pixel. // last in-bounds column area.right-1. Clamp in DOUBLE space BEFORE the integer cast — a huge
const double frac = t / totalSeconds; // t would overflow a 32-bit long (Windows) and wrap to the WRONG edge — then round.
long xi = static_cast<long>(frac * static_cast<double>(w) + 0.5); double px = (t / totalSeconds) * static_cast<double>(w);
if (xi > w - 1) xi = w - 1; if (px > static_cast<double>(w - 1)) px = static_cast<double>(w - 1);
return area.left + static_cast<int>(xi); return area.left + static_cast<int>(px + 0.5);
} }
int gateTimedWidth(const Rect& area) { int gateTimedWidth(const Rect& area) {
@@ -26,6 +26,17 @@ int gateTimedWidth(const Rect& area) {
return std::max(1, w - sustainPx); return std::max(1, w - sustainPx);
} }
double gatePxPerSecond(const Rect& area) {
const int timedW = gateTimedWidth(area);
if (timedW <= 0) return 0.0;
// Usable width = timed region minus the four per-segment separation bases and the last
// in-bounds column, floored at 1 px so the scale never degenerates; the domain is the four
// stages end-to-end at their schematic maxima (param-domain scale — sample-length-free).
const double usable =
std::max(1.0, static_cast<double>(timedW - 1 - 4 * kGateNodeSepPx));
return usable / (4.0 * kGateStageMaxSeconds);
}
int levelToY(const Rect& area, double level) { int levelToY(const Rect& area, double level) {
const int h = std::max(0, area.height()); const int h = std::max(0, area.height());
if (h <= 0) return area.top; if (h <= 0) return area.top;
@@ -56,22 +67,22 @@ EnvVertex vtx(EnvNode node, const Rect& area, double totalSeconds, double t, dou
} }
// One Gate vertex from a pixel offset inside the area (the Gate schematic works in px space — // One Gate vertex from a pixel offset inside the area (the Gate schematic works in px space —
// timed px + the fixed sustain-plateau reserve — not through the plain timeToX map). Clamps x to // timed px + the fixed sustain-plateau reserve — not through the plain timeToX map). Clamps x in
// the last in-bounds column (FA2 bounds invariant). // DOUBLE space to the last in-bounds column BEFORE the integer cast (FA2 bounds invariant; a
// huge px would overflow a 32-bit long on Windows and wrap to the WRONG edge).
EnvVertex gateVtx(EnvNode node, const Rect& area, double px, double level) { EnvVertex gateVtx(EnvNode node, const Rect& area, double px, double level) {
const int w = std::max(1, area.width()); const int w = std::max(1, area.width());
long xi = static_cast<long>(px + 0.5); if (px < 0.0) px = 0.0;
if (xi < 0) xi = 0; if (px > static_cast<double>(w - 1)) px = static_cast<double>(w - 1);
if (xi > w - 1) xi = w - 1;
EnvVertex v; EnvVertex v;
v.node = node; v.node = node;
v.x = area.left + static_cast<int>(xi); v.x = area.left + static_cast<int>(px + 0.5);
v.y = levelToY(area, level); v.y = levelToY(area, level);
v.level = level; v.level = level;
return v; return v;
} }
std::vector<EnvVertex> gatePolyline(const AmpEnvelope& env, const Rect& area, double totalSeconds) { std::vector<EnvVertex> gatePolyline(const AmpEnvelope& env, const Rect& area) {
// Non-negative segment durations (a stored negative would be an upstream bug; clamp defensively). // Non-negative segment durations (a stored negative would be an upstream bug; clamp defensively).
const double a = std::max(0.0, env.attackSeconds); const double a = std::max(0.0, env.attackSeconds);
const double h = std::max(0.0, env.holdSeconds); const double h = std::max(0.0, env.holdSeconds);
@@ -80,26 +91,47 @@ std::vector<EnvVertex> gatePolyline(const AmpEnvelope& env, const Rect& area, do
const double sus = clamp01(env.sustainLevel); const double sus = clamp01(env.sustainLevel);
// BOUNDED SCHEMATIC (FA2): A/H/D and R map onto the TIMED region (canvas minus the reserved // BOUNDED SCHEMATIC (FA2): A/H/D and R map onto the TIMED region (canvas minus the reserved
// sustain-plateau width) at the sample's time scale; the sustain plateau is the fixed reserve // sustain-plateau width) at the PARAM-DOMAIN scale — sample-length-free — and every segment
// between DecayEnd and ReleaseStart. Cumulative px, clamped in gateVtx, stay monotonic. // gets a kGateNodeSepPx base so consecutive nodes never coincide (every node individually
const int timedW = gateTimedWidth(area); // grabbable at any params, incl. the tier-0 zero-hold/zero-decay defaults). The sustain
const int sustainPx = std::max(0, area.width()) - timedW; // plateau is the fixed reserve between DecayEnd and ReleaseStart.
const double pxPerSec = static_cast<double>(timedW) / totalSeconds; const int W = std::max(1, area.width());
const double sustainPx = static_cast<double>(W - gateTimedWidth(area));
const double sep = static_cast<double>(kGateNodeSepPx);
const double pps = gatePxPerSecond(area);
const double pxAttack = a * pxPerSec; double xAttack = sep + a * pps; // AttackEnd
const double pxHold = (a + h) * pxPerSec; double xHold = xAttack + sep + h * pps; // HoldEnd
const double pxDecay = (a + h + d) * pxPerSec; double xDecay = xHold + sep + d * pps; // DecayEnd (sustain node)
const double pxPlateau = pxDecay + static_cast<double>(sustainPx); // schematic note-off double xPlateau = xDecay + sustainPx; // ReleaseStart (schematic note-off)
const double pxRelease = pxPlateau + r * pxPerSec; double xRelease = xPlateau + sep + r * pps; // ReleaseEnd
// Right-edge overrun (a stored stage beyond the schematic domain): compress from the RIGHT
// preserving the minimum gaps, so trailing nodes stay individually separated instead of
// piling on the last column. The re-floor pass only bites when the canvas is too narrow to
// hold the minimum gaps at all — then gateVtx's [0, W-1] clamp wins (in-bounds > separation).
const double xMax = static_cast<double>(W - 1);
if (xRelease > xMax) {
xRelease = xMax;
xPlateau = std::min(xPlateau, xRelease - sep);
xDecay = std::min(xDecay, xPlateau - sustainPx);
xHold = std::min(xHold, xDecay - sep);
xAttack = std::min(xAttack, xHold - sep);
xAttack = std::max(xAttack, sep);
xHold = std::max(xHold, xAttack + sep);
xDecay = std::max(xDecay, xHold + sep);
xPlateau = std::max(xPlateau, xDecay + sustainPx);
xRelease = std::max(xRelease, xPlateau + sep);
}
std::vector<EnvVertex> pts; std::vector<EnvVertex> pts;
pts.reserve(6); pts.reserve(6);
pts.push_back(gateVtx(EnvNode::Origin, area, 0.0, 0.0)); pts.push_back(gateVtx(EnvNode::Origin, area, 0.0, 0.0));
pts.push_back(gateVtx(EnvNode::AttackEnd, area, pxAttack, 1.0)); pts.push_back(gateVtx(EnvNode::AttackEnd, area, xAttack, 1.0));
pts.push_back(gateVtx(EnvNode::HoldEnd, area, pxHold, 1.0)); pts.push_back(gateVtx(EnvNode::HoldEnd, area, xHold, 1.0));
pts.push_back(gateVtx(EnvNode::DecayEnd, area, pxDecay, sus)); // sustain node pts.push_back(gateVtx(EnvNode::DecayEnd, area, xDecay, sus)); // sustain node
pts.push_back(gateVtx(EnvNode::ReleaseStart, area, pxPlateau, sus)); // plateau end pts.push_back(gateVtx(EnvNode::ReleaseStart, area, xPlateau, sus)); // plateau end
pts.push_back(gateVtx(EnvNode::ReleaseEnd, area, pxRelease, 0.0)); pts.push_back(gateVtx(EnvNode::ReleaseEnd, area, xRelease, 0.0));
return pts; return pts;
} }
@@ -135,7 +167,9 @@ std::vector<EnvVertex> buildEnvelopePolyline(const AmpEnvelope& env, const Rect&
return {vtx(EnvNode::Origin, area, 1.0, 0.0, 0.0), return {vtx(EnvNode::Origin, area, 1.0, 0.0, 0.0),
vtx(EnvNode::ReleaseEnd, area, 1.0, 1.0, 0.0)}; vtx(EnvNode::ReleaseEnd, area, 1.0, 1.0, 0.0)};
} }
return env.mode == EnvMode::Gate ? gatePolyline(env, area, totalSeconds) // Gate is a param-domain schematic — totalSeconds only gates the degenerate branch above
// (no loaded duration -> baseline); Trigger is PCM-aligned and consumes it.
return env.mode == EnvMode::Gate ? gatePolyline(env, area)
: triggerPolyline(env, area, totalSeconds); : triggerPolyline(env, area, totalSeconds);
} }
+50 -16
View File
@@ -10,9 +10,14 @@
// sustain plateau, release sustain->0. Since there is no held note-off to draw // sustain plateau, release sustain->0. Since there is no held note-off to draw
// against, Gate is a BOUNDED SCHEMATIC (FA2): a fixed fraction of the canvas // against, Gate is a BOUNDED SCHEMATIC (FA2): a fixed fraction of the canvas
// width (kGateSustainDisplayFraction) is RESERVED for the sustain plateau, and // width (kGateSustainDisplayFraction) is RESERVED for the sustain plateau, and
// the remaining "timed" width carries A/H/D AND the release at the sample's time // the remaining "timed" width carries A/H/D AND the release at the PARAM-DOMAIN
// scale — so A -> (H) -> D -> S-plateau -> R all render INSIDE the canvas and the // scale — the timed width represents 4 x kGateStageMaxSeconds (the four stage
// release is a visible, draggable segment (it no longer trails past area.right). // sliders end-to-end at their maxima), NOT the sample's duration, so the layout
// is identical for a 0.3s and a 10s capture. Each segment additionally gets a
// kGateNodeSepPx pixel base, so consecutive nodes NEVER coincide: every Gate
// node is individually grabbable at ANY param values, including the tier-0
// defaults (hold 0 / decay 0). A -> (H) -> D -> S-plateau -> R all render INSIDE
// the canvas and the release is a visible, draggable segment.
// * Trigger -> the fade/%-length shape: fade-in 0->1, unity plateau, fade-out 1->0 anchored // * Trigger -> the fade/%-length shape: fade-in 0->1, unity plateau, fade-out 1->0 anchored
// to playEnd (= lengthFraction of the post-start span). Trigger keeps the // to playEnd (= lengthFraction of the post-start span). Trigger keeps the
// waveform's exact time base so the shape lines up with the PCM under it. // waveform's exact time base so the shape lines up with the PCM under it.
@@ -30,11 +35,15 @@
// * ALL vertices are now in-bounds (see above). The shell's previous "skip handle when // * ALL vertices are now in-bounds (see above). The shell's previous "skip handle when
// v.x >= waveArea.right" clip is dead code: ReleaseEnd (Gate) and FadeOutStart/LengthEnd // v.x >= waveArea.right" clip is dead code: ReleaseEnd (Gate) and FadeOutStart/LengthEnd
// (Trigger, at full length / zero fade-out) now land at area.right-1 and MUST get handles. // (Trigger, at full length / zero fade-out) now land at area.right-1 and MUST get handles.
// * Gate's x-axis is schematic, not PCM-aligned (the sustain reserve compresses the timed // * Gate's x-axis is SCHEMATIC, not PCM-aligned: the timed region is scaled to the param
// region); Trigger's x-axis is still PCM-aligned. // domain (4 x kGateStageMaxSeconds), the sustain reserve is a fixed width, and every
// * nodeAtPoint (envelope_edit) now resolves to the NEAREST node within the grab radius, // segment carries a kGateNodeSepPx pixel base. The Gate curve does NOT line up with the
// draw-order tie-break — coincident nodes (zero fade-out at the right edge, zero hold) are // waveform under it — do not label it as if it did. Trigger's x-axis IS still PCM-aligned.
// deterministically grabbable. // * Gate nodes never coincide (min-separation, above), so every Gate handle is individually
// grabbable in every state. nodeAtPoint (envelope_edit) resolves to the NEAREST node within
// the grab radius with a draw-order tie-break; the tie-break only matters for the one
// remaining coincidence, Trigger's zero-fade-out (FadeOutStart overlays LengthEnd at the
// right edge and wins the tie, so the fade can be dragged open from zero).
// //
// DELIBERATELY ENGINE-FREE (house pattern — param_slider does the same). It does NOT depend on // DELIBERATELY ENGINE-FREE (house pattern — param_slider does the same). It does NOT depend on
// sample_map / sampler_core (which would drag bank_book / wav_trim in). The shell reads the // sample_map / sampler_core (which would drag bank_book / wav_trim in). The shell reads the
@@ -146,27 +155,52 @@ struct EnvVertex {
// The fraction of the canvas width RESERVED for the Gate sustain-plateau display (FA2). The // The fraction of the canvas width RESERVED for the Gate sustain-plateau display (FA2). The
// plateau is a fixed-width schematic region between DecayEnd and ReleaseStart; the remaining // plateau is a fixed-width schematic region between DecayEnd and ReleaseStart; the remaining
// width is the "timed" region A/H/D/R map onto at the sample's time scale. One constant shared // width is the "timed" region A/H/D/R map onto at the schematic param-domain scale. One
// by the forward map (here) and the inverse map (envelope_edit) so a drag tracks the cursor. // constant shared by the forward map (here) and the inverse map (envelope_edit).
inline constexpr double kGateSustainDisplayFraction = 0.15; inline constexpr double kGateSustainDisplayFraction = 0.15;
// The minimum pixel separation between consecutive Gate polyline nodes: every Gate segment gets
// this many px as a base, PLUS its time-proportional extent, so zero-duration stages (tier-0
// defaults: hold 0, decay 0) still render as distinct, individually grabbable handles. Chosen
// larger than envelope_edit's kNodeGrabRadius (6) so a click dead-on a node can never tie with
// its neighbour. Shared by the forward map and the drag inverse.
inline constexpr int kGateNodeSepPx = 8;
// The Gate schematic's per-stage time domain (seconds): the timed region represents the four
// stages end-to-end at this maximum each (4 x this total). MIRRORS the shell's stage-slider
// ceiling (kEnvTimeMaxSeconds in reasampler_editor.cpp) — keep the two equal so a stage at its
// slider max lands exactly at the canvas edge. Drag safety does NOT depend on this constant
// (param clamps are caller-supplied in envelope_edit); only layout does.
inline constexpr double kGateStageMaxSeconds = 2.0;
// The pixel width of the Gate timed region: area.width() minus the sustain-plateau reserve, // The pixel width of the Gate timed region: area.width() minus the sustain-plateau reserve,
// floored at 1 px so the px<->seconds scale never degenerates for a non-empty area. Returns 0 // floored at 1 px so the px<->seconds scale never degenerates for a non-empty area. Returns 0
// for a zero/negative-width area. Shared by gatePolyline and envelope_edit's gate drag scale. // for a zero/negative-width area. Shared by gatePolyline and envelope_edit's gate drag scale.
int gateTimedWidth(const Rect& area); int gateTimedWidth(const Rect& area);
// Pixels per second of the Gate timed region under the PARAM-DOMAIN scale: the timed width,
// minus the four per-segment kGateNodeSepPx bases and the last in-bounds column, spread over
// 4 x kGateStageMaxSeconds. Independent of the sample's duration. Returns 0 for a
// zero/negative-width area; otherwise > 0 (the usable width floors at 1 px). The ONE px<->sec
// scale shared by the forward map (gatePolyline) and the drag inverse (envelope_edit), so a
// dragged handle tracks the cursor 1:1.
double gatePxPerSecond(const Rect& area);
// Map an amp envelope to its polyline vertices inside `area`, over a sample of `totalSeconds` // Map an amp envelope to its polyline vertices inside `area`, over a sample of `totalSeconds`
// wall-clock duration. `area` is the waveform rect (left/top inclusive, right/bottom exclusive); // wall-clock duration. `area` is the waveform rect (left/top inclusive, right/bottom exclusive);
// y maps level 0..1 across [area.bottom-1 .. area.top] (level 1 at the TOP). The polyline reads // y maps level 0..1 across [area.bottom-1 .. area.top] (level 1 at the TOP). The polyline reads
// left-to-right in draw order, Origin first. // left-to-right in draw order, Origin first.
// //
// TIME BASE (FA2). // TIME BASE (FA2).
// * Gate: a bounded schematic. The canvas splits into a TIMED region of gateTimedWidth(area) // * Gate: a bounded schematic, INDEPENDENT of totalSeconds. The canvas splits into a TIMED
// px — where attack/hold/decay run from t=0 and the release ramp runs after the plateau, all // region of gateTimedWidth(area) px — where attack/hold/decay run from t=0 and the release
// at totalSeconds-over-timed-width scale — plus a FIXED sustain plateau of // ramp runs after the plateau, at the gatePxPerSecond(area) PARAM-DOMAIN scale, each segment
// (width - timedWidth) px between DecayEnd and ReleaseStart (the schematic note-off). Every // carrying a kGateNodeSepPx base so consecutive nodes never coincide — plus a FIXED sustain
// vertex x clamps to area.right-1, so when the stages overrun the visible span the trailing // plateau of (width - timedWidth) px between DecayEnd and ReleaseStart (the schematic
// nodes pile up (still monotonic, still in-bounds, still draggable back left). // note-off). Stages beyond the schematic domain (a stored stage > kGateStageMaxSeconds)
// compress from the RIGHT preserving the minimum gaps, so trailing nodes stay individually
// separated instead of piling on the last column; only a canvas too narrow to hold the
// minimum gaps at all sacrifices separation (in-bounds wins).
// * Trigger: the waveform's exact time base (PCM-aligned). The played span is // * Trigger: the waveform's exact time base (PCM-aligned). The played span is
// lengthFraction * totalSeconds; fade-in/out are fractions OF that played span. Nodes past // lengthFraction * totalSeconds; fade-in/out are fractions OF that played span. Nodes past
// the played span never appear (FadeOutStart/LengthEnd sit at the played span's right edge). // the played span never appear (FadeOutStart/LengthEnd sit at the played span's right edge).
+100 -35
View File
@@ -4,19 +4,22 @@
// boundaries (the load-bearing "a drag can never produce a param a slider couldn't" invariant). // boundaries (the load-bearing "a drag can never produce a param a slider couldn't" invariant).
// //
// Covers: nodeAtPoint (grabs a drawn handle within the pick radius; misses off every node; skips // Covers: nodeAtPoint (grabs a drawn handle within the pick radius; misses off every node; skips
// the non-draggable Origin/ReleaseStart anchors; NEAREST-node-wins with draw-order tie-break — // the non-draggable Origin/ReleaseStart anchors AND other-mode nodes; NEAREST-node-wins with
// FA2); resolveNodeDrag Gate (each cumulative node edits its OWN segment at the TIMED-region px // draw-order tie-break; EVERY Gate node individually grabbable at the tier-0 defaults — FA2);
// scale; X->time, sustain node's Y->level; lower clamp at 0; upper clamp at the caller's max; // resolveNodeDrag Gate (each cumulative node edits its OWN segment at the PARAM-DOMAIN px scale;
// only the dragged param changes; ReleaseEnd grabbable + draggable — FA2); resolveNodeDrag // X->time, sustain node's Y->level; lower clamp at 0; upper clamp at the caller's max; only the
// Trigger (fades as fractions of the played span; fadeIn/fadeOut mutual clamp so they never // dragged param changes; ReleaseEnd grabbable + draggable; per-node drag round-trip tracks the
// cross; length clamp; FadeOutStart moves OPPOSITE the pixel delta; zero-fade-out node grabbable // cursor ~1:1 — FA2); resolveNodeDrag Trigger (fades as fractions of the played span;
// at the right edge and draggable inward — FA2); degenerate area/duration + non-draggable node // fadeIn/fadeOut mutual clamp so they never cross; length clamp; FadeOutStart moves OPPOSITE the
// -> no motion. // pixel delta; zero-fade-out node grabbable at the right edge and draggable inward — FA2);
// degenerate area/duration + non-draggable node + cross-mode node -> no motion.
#include "../src/vst/envelope_edit.h" #include "../src/vst/envelope_edit.h"
#include <cmath> #include <cmath>
#include <cstdio> #include <cstdio>
#include <cstdlib>
#include <vector>
using namespace reasampler::vst; using namespace reasampler::vst;
@@ -26,12 +29,21 @@ static int g_fail = 0;
static bool near(double a, double b, double eps = 1e-9) { return std::fabs(a - b) <= eps; } static bool near(double a, double b, double eps = 1e-9) { return std::fabs(a - b) <= eps; }
// Find the first vertex with a given node in a polyline; asserts presence via the returned bool.
static bool findNode(const std::vector<EnvVertex>& poly, EnvNode node, EnvVertex& out) {
for (const EnvVertex& v : poly) {
if (v.node == node) { out = v; return true; }
}
return false;
}
// 1000px wide, 100px tall, offset origin. Trigger scale: 2.0s over 1000px => 0.002 s/px. Gate // 1000px wide, 100px tall, offset origin. Trigger scale: 2.0s over 1000px => 0.002 s/px. Gate
// scale (FA2 schematic): 2.0s over the 850px TIMED region (150px sustain-plateau reserve) => // scale (FA2 param-domain schematic — sample-length-free): (850-1-32)px over the 8.0s schematic
// 2/850 s/px, and the gateEnv() nodes draw at A x@85, H x@128, D x@255, RS x@405, RE x@575. // domain => 102.125 px/s, each segment prefixed by the 8px separation base; the gateEnv() nodes
// draw at A x@28, H x@47, D x@85, RS x@235, RE x@284.
static Rect wideArea() { return Rect{20, 10, 1020, 110}; } static Rect wideArea() { return Rect{20, 10, 1020, 110}; }
static constexpr double kTotal = 2.0; static constexpr double kTotal = 2.0;
static constexpr double kGateSecPerPx = kTotal / 850.0; static const double kGateSecPerPx = 1.0 / gatePxPerSecond(wideArea());
static AmpEnvelope gateEnv() { static AmpEnvelope gateEnv() {
AmpEnvelope e; AmpEnvelope e;
@@ -58,11 +70,11 @@ static AmpEnvelope triggerEnv() {
static void testHitGrabsDrawnHandle() { static void testHitGrabsDrawnHandle() {
const AmpEnvelope e = gateEnv(); const AmpEnvelope e = gateEnv();
const Rect a = wideArea(); const Rect a = wideArea();
// AttackEnd draws at x = left+85 (0.2s * 425 px/s in the timed region), y = top (level 1). // 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.left + 85, a.top); NodeHit h = nodeAtPoint(e, a, kTotal, a.left + 28, a.top);
CHECK(h.hit && h.node == EnvNode::AttackEnd); CHECK(h.hit && h.node == EnvNode::AttackEnd);
// The sustain node (DecayEnd) at 0.6s -> left+255, level 0.5 -> ~top+50. // The sustain node (DecayEnd) at left+85, level 0.5 -> ~top+50.
NodeHit s = nodeAtPoint(e, a, kTotal, a.left + 255, a.top + 50); NodeHit s = nodeAtPoint(e, a, kTotal, a.left + 85, a.top + 50);
CHECK(s.hit && s.node == EnvNode::DecayEnd); CHECK(s.hit && s.node == EnvNode::DecayEnd);
} }
@@ -80,31 +92,39 @@ static void testHitSkipsNonDraggableAnchors() {
// Origin draws at (left, bottom-1). Even a pixel-perfect grab there is NOT a draggable node. // Origin draws at (left, bottom-1). Even a pixel-perfect grab there is NOT a draggable node.
NodeHit o = nodeAtPoint(e, a, kTotal, a.left, a.bottom - 1); NodeHit o = nodeAtPoint(e, a, kTotal, a.left, a.bottom - 1);
CHECK(!o.hit); CHECK(!o.hit);
// ReleaseStart draws at (left+405, sustain level ~top+50) — the fixed plateau end. It is // 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. // drawing-only -> not grabbable; no other node is within the radius, so this grab misses.
NodeHit rs = nodeAtPoint(e, a, kTotal, a.left + 405, a.top + 50); NodeHit rs = nodeAtPoint(e, a, kTotal, a.left + 235, a.top + 50);
CHECK(!rs.hit); CHECK(!rs.hit);
} }
static void testHitNearestNodeWinsOverDrawOrder() { static void testHitNearestNodeWinsOverDrawOrder() {
// FA2 nearest-wins: with a SHORT hold, AttackEnd (x@85) and HoldEnd (x@89) both fall within // FA2 nearest-wins: with a SHORT hold, AttackEnd (x@28) and HoldEnd (x@37 — the 8px base
// the grab radius of a point at x@90 — the NEAREST (HoldEnd, 1px) must win, not the earlier // plus 0.01s ~= 1px) both fall within the grab radius of a point at x@33 — the NEAREST
// draw-order AttackEnd (5px), so tightly packed handles stay individually grabbable. // (HoldEnd, 4px) must win, not the earlier draw-order AttackEnd (5px), so tightly packed
// handles stay individually grabbable.
AmpEnvelope e = gateEnv(); AmpEnvelope e = gateEnv();
e.holdSeconds = 0.01; // hold end at 0.21s -> x@round(89.25)=89 e.holdSeconds = 0.01;
const Rect a = wideArea(); const Rect a = wideArea();
NodeHit h = nodeAtPoint(e, a, kTotal, a.left + 90, a.top); NodeHit h = nodeAtPoint(e, a, kTotal, a.left + 33, a.top);
CHECK(h.hit && h.node == EnvNode::HoldEnd); CHECK(h.hit && h.node == EnvNode::HoldEnd);
} }
static void testHitCoincidentNodesTieToEarlierDrawOrder() { static void testGateDefaultsEveryNodeGrabbable() {
// Zero hold: AttackEnd and HoldEnd draw at the SAME pixel. The tie goes to the earlier // THE FA2 headline regression: at the tier-0 Gate defaults (attack 3ms, hold 0, decay 0,
// draw-order node (AttackEnd) — deterministic, mirroring the pre-FA2 first-match rule. // sustain 1.0, release 60ms) the forward map's kGateNodeSepPx separation keeps every
AmpEnvelope e = gateEnv(); // draggable node distinct, and a grab AT each drawn vertex resolves to THAT node — HoldEnd
e.holdSeconds = 0.0; // and DecayEnd are no longer shadowed by AttackEnd (pre-fix they were permanently
// ungrabbable in the default state).
const AmpEnvelope e; // struct defaults ARE the tier-0 Gate defaults
const Rect a = wideArea(); const Rect a = wideArea();
NodeHit h = nodeAtPoint(e, a, kTotal, a.left + 85, a.top); const std::vector<EnvVertex> poly = buildEnvelopePolyline(e, a, kTotal);
CHECK(h.hit && h.node == EnvNode::AttackEnd); 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);
CHECK(h.hit && h.node == v.node);
}
} }
// --- resolveNodeDrag Gate ----------------------------------------------------- // --- resolveNodeDrag Gate -----------------------------------------------------
@@ -113,7 +133,7 @@ static void testGateAttackDragMovesOnlyAttack() {
const AmpEnvelope e = gateEnv(); const AmpEnvelope e = gateEnv();
const Rect a = wideArea(); const Rect a = wideArea();
EnvClampBounds b; // default maxima 4.0s EnvClampBounds b; // default maxima 4.0s
// +50px at the GATE timed-region scale (2/850 s/px) on attack. Nothing else moves. // +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, a, kTotal, b, 50, 0);
CHECK(near(out.attackSeconds, 0.2 + 50.0 * kGateSecPerPx)); CHECK(near(out.attackSeconds, 0.2 + 50.0 * kGateSecPerPx));
CHECK(near(out.holdSeconds, e.holdSeconds)); CHECK(near(out.holdSeconds, e.holdSeconds));
@@ -126,7 +146,7 @@ static void testGateTimeLowerClampAtZero() {
const AmpEnvelope e = gateEnv(); const AmpEnvelope e = gateEnv();
const Rect a = wideArea(); const Rect a = wideArea();
EnvClampBounds b; EnvClampBounds b;
// Drag attack far LEFT (-500px ~= -1.18s at the gate scale) from 0.2s: clamps to 0, never // 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). // 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, a, kTotal, b, -500, 0);
CHECK(near(out.attackSeconds, 0.0)); CHECK(near(out.attackSeconds, 0.0));
@@ -137,7 +157,7 @@ static void testGateTimeUpperClampAtSliderMax() {
const Rect a = wideArea(); const Rect a = wideArea();
EnvClampBounds b; EnvClampBounds b;
b.maxDecaySeconds = 1.0; // the shell's decay slider tops out at 1.0s b.maxDecaySeconds = 1.0; // the shell's decay slider tops out at 1.0s
// Drag decay far RIGHT (+2000px ~= +4.7s at the gate scale) from 0.3s: clamps to the slider // 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). // 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, a, kTotal, b, 2000, 0);
CHECK(near(out.decaySeconds, 1.0)); CHECK(near(out.decaySeconds, 1.0));
@@ -179,11 +199,11 @@ static void testGateTimeOnlyNodeIgnoresY() {
static void testGateReleaseEndGrabAndDrag() { static void testGateReleaseEndGrabAndDrag() {
// The FA2 fix: ReleaseEnd is a drawn, IN-BOUNDS, grabbable handle (pre-FA2 it mapped past // The FA2 fix: ReleaseEnd is a drawn, IN-BOUNDS, grabbable handle (pre-FA2 it mapped past
// area.right and could never be grabbed). gateEnv() draws it at x@575, level 0 (bottom row). // area.right and could never be grabbed). gateEnv() draws it at x@284, level 0 (bottom row).
const AmpEnvelope e = gateEnv(); const AmpEnvelope e = gateEnv();
const Rect a = wideArea(); const Rect a = wideArea();
EnvClampBounds b; EnvClampBounds b;
NodeHit h = nodeAtPoint(e, a, kTotal, a.left + 575, a.bottom - 1); NodeHit h = nodeAtPoint(e, a, kTotal, a.left + 284, a.bottom - 1);
CHECK(h.hit && h.node == EnvNode::ReleaseEnd); CHECK(h.hit && h.node == EnvNode::ReleaseEnd);
// Dragging it RIGHT lengthens the release at the gate timed scale; only release changes. // 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, a, kTotal, b, 85, 0);
@@ -197,6 +217,31 @@ static void testGateReleaseEndGrabAndDrag() {
CHECK(near(hi.releaseSeconds, b.maxReleaseSeconds)); CHECK(near(hi.releaseSeconds, b.maxReleaseSeconds));
} }
static void testGateDragRoundTripTracksPixels() {
// 1:1 tracking (FA2): drag a Gate node by N px, rebuild the polyline from the edited params,
// and the node's drawn vertex has moved by ~N px (rounding may shift the landing by 1). The
// forward map is affine in each node's own segment duration with slope gatePxPerSecond and
// the inverse uses exactly the reciprocal, so the handle follows the cursor.
const AmpEnvelope e = gateEnv();
const Rect a = wideArea();
EnvClampBounds b;
const int dx = 25;
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(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(std::abs((after.y - before.y) - 10) <= 1);
}
// --- resolveNodeDrag Trigger -------------------------------------------------- // --- resolveNodeDrag Trigger --------------------------------------------------
static void testTriggerFadeInIsFractionOfPlaySpan() { static void testTriggerFadeInIsFractionOfPlaySpan() {
@@ -289,12 +334,30 @@ static void testDegenerateAreaNoMotion() {
CHECK(near(o2.attackSeconds, e.attackSeconds)); CHECK(near(o2.attackSeconds, e.attackSeconds));
} }
static void testCrossModeNodeNoMotion() {
// A node from the OTHER mode never writes (FA2 guard): the degenerate baseline polyline
// carries a ReleaseEnd vertex regardless of mode, so a Trigger-mode grab of it (e.g. over a
// zero-height canvas) must NOT write releaseSeconds — and symmetrically a Trigger node is
// inert on a Gate envelope.
EnvClampBounds b;
const AmpEnvelope t = triggerEnv();
AmpEnvelope out = resolveNodeDrag(t, EnvNode::ReleaseEnd, 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);
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{0, 0, 100, 0};
const NodeHit h = nodeAtPoint(t, flat, kTotal, 99, 0);
CHECK(!h.hit);
}
int main() { int main() {
testHitGrabsDrawnHandle(); testHitGrabsDrawnHandle();
testHitMissesOffEveryNode(); testHitMissesOffEveryNode();
testHitSkipsNonDraggableAnchors(); testHitSkipsNonDraggableAnchors();
testHitNearestNodeWinsOverDrawOrder(); testHitNearestNodeWinsOverDrawOrder();
testHitCoincidentNodesTieToEarlierDrawOrder(); testGateDefaultsEveryNodeGrabbable();
testGateAttackDragMovesOnlyAttack(); testGateAttackDragMovesOnlyAttack();
testGateTimeLowerClampAtZero(); testGateTimeLowerClampAtZero();
@@ -303,6 +366,7 @@ int main() {
testGateSustainLevelClamps01(); testGateSustainLevelClamps01();
testGateTimeOnlyNodeIgnoresY(); testGateTimeOnlyNodeIgnoresY();
testGateReleaseEndGrabAndDrag(); testGateReleaseEndGrabAndDrag();
testGateDragRoundTripTracksPixels();
testTriggerFadeInIsFractionOfPlaySpan(); testTriggerFadeInIsFractionOfPlaySpan();
testTriggerFadesCannotCross(); testTriggerFadesCannotCross();
@@ -312,6 +376,7 @@ int main() {
testNonDraggableNodeNoMotion(); testNonDraggableNodeNoMotion();
testDegenerateAreaNoMotion(); testDegenerateAreaNoMotion();
testCrossModeNodeNoMotion();
if (g_fail == 0) std::printf("envelope_edit: all tests passed\n"); if (g_fail == 0) std::printf("envelope_edit: all tests passed\n");
else std::printf("envelope_edit: %d FAILED\n", g_fail); else std::printf("envelope_edit: %d FAILED\n", g_fail);
+87 -31
View File
@@ -5,11 +5,14 @@
// fade/%-length shape at the waveform time base. // fade/%-length shape at the waveform time base.
// //
// Covers: timeToX / levelToY (linear maps, edge clamps, past-end CLAMPED to right-1 — the FA2 // Covers: timeToX / levelToY (linear maps, edge clamps, past-end CLAMPED to right-1 — the FA2
// bounds invariant, degenerate area/duration); gateTimedWidth; buildEnvelopePolyline Gate (node // bounds invariant, no 32-bit overflow on huge times, degenerate area/duration); gateTimedWidth
// order, levels, timed-region placement, fixed sustain-plateau reserve, release visible // + gatePxPerSecond; buildEnvelopePolyline Gate (node order, levels, PARAM-DOMAIN timed-region
// in-bounds, overrun pile-up clamped at the right edge, every vertex in-bounds); // placement independent of sample duration, per-segment kGateNodeSepPx separation — every node
// buildEnvelopePolyline Trigger (fade-in/unity/fade-out at fractions of the played span, overlap // distinct even at the tier-0 zero-hold/zero-decay defaults, fixed sustain-plateau reserve,
// clamp, full-length/zero-fade-out nodes in-bounds at right-1); degenerate flat baseline. // release visible in-bounds, overrun compressed from the right preserving the minimum gaps,
// every vertex in-bounds); buildEnvelopePolyline Trigger (fade-in/unity/fade-out at fractions of
// the played span, overlap clamp, full-length/zero-fade-out nodes in-bounds at right-1);
// degenerate flat baseline.
#include "../src/vst/envelope_overlay.h" #include "../src/vst/envelope_overlay.h"
@@ -53,6 +56,9 @@ static void testTimeToXPastEndClamps() {
const Rect a = wideArea(); const Rect a = wideArea();
CHECK(timeToX(a, 2.0, 3.0) == a.right - 1); CHECK(timeToX(a, 2.0, 3.0) == a.right - 1);
CHECK(timeToX(a, 2.0, 1000.0) == a.right - 1); CHECK(timeToX(a, 2.0, 1000.0) == a.right - 1);
// A HUGE t must clamp in double space, not overflow the integer cast (32-bit long on
// Windows would wrap to LONG_MIN and pin to the WRONG edge).
CHECK(timeToX(a, 2.0, 1e15) == a.right - 1);
} }
static void testGateTimedWidth() { static void testGateTimedWidth() {
@@ -63,6 +69,15 @@ static void testGateTimedWidth() {
CHECK(gateTimedWidth(Rect{0, 0, 1, 10}) == 1); CHECK(gateTimedWidth(Rect{0, 0, 1, 10}) == 1);
} }
static void testGatePxPerSecond() {
// PARAM-DOMAIN scale: (timedW - 1 - 4*sep) px spread over 4 x kGateStageMaxSeconds. For the
// 1000px canvas: (850 - 1 - 32) / 8.0s = 817/8 px/s. Independent of any sample duration.
const double expected = 817.0 / (4.0 * kGateStageMaxSeconds);
CHECK(gatePxPerSecond(wideArea()) == expected);
CHECK(gatePxPerSecond(Rect{5, 5, 5, 45}) == 0.0); // zero-width area -> 0
CHECK(gatePxPerSecond(Rect{0, 0, 10, 10}) > 0.0); // tiny area: usable floors at 1px, > 0
}
static void testTimeToXDegenerate() { static void testTimeToXDegenerate() {
const Rect a = wideArea(); const Rect a = wideArea();
CHECK(timeToX(a, 0.0, 1.0) == a.left); // no duration -> left CHECK(timeToX(a, 0.0, 1.0) == a.left); // no duration -> left
@@ -118,26 +133,55 @@ static void testGateNodeOrderAndLevels() {
} }
static void testGateSchematicPlacement() { static void testGateSchematicPlacement() {
// FA2 bounded schematic: timed region = 850px (150px reserved plateau), total 2.0s => // FA2 bounded schematic at the PARAM-DOMAIN scale: timed region = 850px (150px reserved
// 425 px/s in the timed region. attack .2 -> x@85, hold end .3 -> x@round(127.5)=128, decay // plateau), pps = (850-1-32)/8s = 102.125 px/s, each segment prefixed by the 8px separation
// end .6 -> x@255. Plateau is the FIXED 150px reserve -> ReleaseStart x@405. Release .4 -> // base. attack .2 -> x@round(8+20.425)=28; hold .1 -> x@round(28.425+8+10.2125)=47; decay
// 170px ramp -> ReleaseEnd x@575, well inside the canvas. // .3 -> x@round(46.6375+8+30.6375)=85; plateau is the FIXED 150px reserve -> ReleaseStart
// x@235; release .4 -> x@round(235.275+8+40.85)=284, well inside the canvas.
AmpEnvelope env; AmpEnvelope env;
env.mode = EnvMode::Gate; env.mode = EnvMode::Gate;
env.attackSeconds = 0.2; env.attackSeconds = 0.2;
env.holdSeconds = 0.1; // hold end at 0.3s env.holdSeconds = 0.1;
env.decaySeconds = 0.3; // decay end at 0.6s env.decaySeconds = 0.3;
env.sustainLevel = 0.5; env.sustainLevel = 0.5;
env.releaseSeconds = 0.4; env.releaseSeconds = 0.4;
const Rect a = wideArea(); const Rect a = wideArea();
const std::vector<EnvVertex> poly = buildEnvelopePolyline(env, a, 2.0); const std::vector<EnvVertex> poly = buildEnvelopePolyline(env, a, 2.0);
EnvVertex v; EnvVertex v;
CHECK(findNode(poly, EnvNode::AttackEnd, v) && v.x == a.left + 85); CHECK(findNode(poly, EnvNode::AttackEnd, v) && v.x == a.left + 28);
CHECK(findNode(poly, EnvNode::HoldEnd, v) && v.x == a.left + 128); CHECK(findNode(poly, EnvNode::HoldEnd, v) && v.x == a.left + 47);
CHECK(findNode(poly, EnvNode::DecayEnd, v) && v.x == a.left + 255); CHECK(findNode(poly, EnvNode::DecayEnd, v) && v.x == a.left + 85);
CHECK(findNode(poly, EnvNode::ReleaseStart, v) && v.x == a.left + 405); CHECK(findNode(poly, EnvNode::ReleaseStart, v) && v.x == a.left + 235);
CHECK(findNode(poly, EnvNode::ReleaseEnd, v) && v.x == a.left + 575); CHECK(findNode(poly, EnvNode::ReleaseEnd, v) && v.x == a.left + 284);
}
static void testGateLayoutIndependentOfSampleDuration() {
// The Gate schematic is scaled by the PARAM domain, NOT the capture length: the same params
// produce the SAME polyline over a 0.3s and a 10s sample (pre-fix, a 60ms release on a 10s
// capture collapsed to ~5px while 2s stages on a 0.3s capture pinned to the right edge).
AmpEnvelope env;
env.mode = EnvMode::Gate;
env.attackSeconds = 0.2;
env.holdSeconds = 0.1;
env.decaySeconds = 0.3;
env.sustainLevel = 0.5;
env.releaseSeconds = 0.06;
const Rect a = wideArea();
CHECK(buildEnvelopePolyline(env, a, 0.3) == buildEnvelopePolyline(env, a, 10.0));
}
static void testGateMinSeparationAtDefaults() {
// THE FA2 headline: at the tier-0 Gate defaults (attack 3ms, hold 0, decay 0, sustain 1.0,
// release 60ms) every consecutive node pair is at least kGateNodeSepPx apart — no node ever
// 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<EnvVertex> poly = buildEnvelopePolyline(env, 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);
}
} }
static void testGateSustainPlateauFixedWidth() { static void testGateSustainPlateauFixedWidth() {
@@ -183,28 +227,32 @@ static void testGateReleaseVisibleInBounds() {
CHECK(rel.level == 0.0); CHECK(rel.level == 0.0);
} }
static void testGateOverrunClampsToCanvas() { static void testGateOverrunCompressesFromRight() {
// A/H/D/R overrun the visible span (sum 3.5s > 2.0s total): the trailing nodes pile up at // Stages BEYOND the schematic domain (4.0s each > kGateStageMaxSeconds): the layout
// the last in-bounds column — monotonic, in-bounds, still individually draggable back left. // compresses from the right preserving the minimum gaps — ReleaseEnd pins to the last
// NOTHING maps past area.right (the pre-FA2 release tail is gone). // in-bounds column, but the trailing nodes stay strictly increasing and individually
// separated (>= kGateNodeSepPx), NOT piled on one pixel. NOTHING maps past area.right.
AmpEnvelope env; AmpEnvelope env;
env.mode = EnvMode::Gate; env.mode = EnvMode::Gate;
env.attackSeconds = 1.0; env.attackSeconds = 4.0;
env.holdSeconds = 1.0; env.holdSeconds = 4.0;
env.decaySeconds = 1.0; // decay end at 3.0s -> already past the timed span env.decaySeconds = 4.0;
env.sustainLevel = 0.7; env.sustainLevel = 0.7;
env.releaseSeconds = 0.5; env.releaseSeconds = 4.0;
const Rect a = wideArea(); const Rect a = wideArea();
const std::vector<EnvVertex> poly = buildEnvelopePolyline(env, a, 2.0); const std::vector<EnvVertex> poly = buildEnvelopePolyline(env, a, 2.0);
CHECK(poly.size() == 6);
EnvVertex decay, plateauEnd, rel; EnvVertex plateauEnd, rel;
CHECK(findNode(poly, EnvNode::DecayEnd, decay));
CHECK(findNode(poly, EnvNode::ReleaseStart, plateauEnd)); CHECK(findNode(poly, EnvNode::ReleaseStart, plateauEnd));
CHECK(findNode(poly, EnvNode::ReleaseEnd, rel)); CHECK(findNode(poly, EnvNode::ReleaseEnd, rel));
CHECK(decay.x == a.right - 1); // pinned to the last in-bounds column CHECK(rel.x == a.right - 1); // pinned to the last in-bounds column
CHECK(plateauEnd.x == a.right - 1);
CHECK(rel.x == a.right - 1);
CHECK(plateauEnd.level == 0.7); // still at sustain CHECK(plateauEnd.level == 0.7); // still at sustain
for (size_t i = 1; i < poly.size(); ++i) {
CHECK(poly[i].x > poly[i - 1].x); // strictly monotonic
CHECK(poly[i].x - poly[i - 1].x >= kGateNodeSepPx - 1); // min gaps survive compression
CHECK(poly[i].x >= a.left && poly[i].x < a.right); // in-bounds
}
} }
static void testGateAllVerticesInBounds() { static void testGateAllVerticesInBounds() {
@@ -223,8 +271,13 @@ static void testGateAllVerticesInBounds() {
AmpEnvelope trig = base; AmpEnvelope trig = base;
trig.mode = EnvMode::Trigger; trig.mode = EnvMode::Trigger;
trig.lengthFraction = 1.0; trig.fadeInFraction = 0.0; trig.fadeOutFraction = 0.0; trig.lengthFraction = 1.0; trig.fadeInFraction = 0.0; trig.fadeOutFraction = 0.0;
// ABSURD stage values must clamp in double space, not overflow the integer cast (32-bit
// long on Windows would wrap negative and land on the WRONG edge).
AmpEnvelope huge = base;
huge.mode = EnvMode::Gate;
huge.releaseSeconds = 1e12;
for (const AmpEnvelope& env : {base, big, zero, trig}) { for (const AmpEnvelope& env : {base, big, zero, trig, huge}) {
for (const EnvVertex& v : buildEnvelopePolyline(env, a, 2.0)) { for (const EnvVertex& v : buildEnvelopePolyline(env, a, 2.0)) {
CHECK(v.x >= a.left && v.x < a.right); CHECK(v.x >= a.left && v.x < a.right);
CHECK(v.y >= a.top && v.y < a.bottom); CHECK(v.y >= a.top && v.y < a.bottom);
@@ -316,14 +369,17 @@ int main() {
testTimeToXPastEndClamps(); testTimeToXPastEndClamps();
testTimeToXDegenerate(); testTimeToXDegenerate();
testGateTimedWidth(); testGateTimedWidth();
testGatePxPerSecond();
testLevelToYEndpoints(); testLevelToYEndpoints();
testLevelToYClamps(); testLevelToYClamps();
testGateNodeOrderAndLevels(); testGateNodeOrderAndLevels();
testGateSchematicPlacement(); testGateSchematicPlacement();
testGateLayoutIndependentOfSampleDuration();
testGateMinSeparationAtDefaults();
testGateSustainPlateauFixedWidth(); testGateSustainPlateauFixedWidth();
testGateReleaseVisibleInBounds(); testGateReleaseVisibleInBounds();
testGateOverrunClampsToCanvas(); testGateOverrunCompressesFromRight();
testGateAllVerticesInBounds(); testGateAllVerticesInBounds();
testTriggerShape(); testTriggerShape();