Search by

sugarcraft / sugar-spring

detain

Damped spring physics for PHP — spring core mirrors charmbracelet/harmonica, extended with projectile simulation, easing/Bezier timing curves, spring chains, collections and reduced-motion snapping for spring-driven types; pure math, no terminal dependency.

Package info

github.com/sugarcraft/sugar-spring

Documentation

pkg:composer/sugarcraft/sugar-spring

Statistics

Installs: 2 581

Dependents: 5

Suggesters: 0

Stars: 1

Open Issues: 0

dev-master 2026-11-16 21:04 UTC

This package is auto-updated.

Last update: 2026-11-20 01:04:12 UTC


README

sugar-spring

SugarSpring

Formerly published as sugarcraft/honey-bounce (renamed 2026-10). Namespace changed: SugarCraft\Bounce\ → SugarCraft\Spring\.

CI codecov Packagist Version License PHP

sugar-spring — damped-spring physics, projectile simulation, and easing/timing curves for animation in PHP 8.3+. Pure math; no terminal dependency.

composer require sugarcraft/sugar-spring

I want to…

Goal Reach for
Move a value to a target with physical feel Spring
Know when an animation is actually done Spring::settled() / SpringChain::isComplete() / SpringCollection::settled()
Sequence staggered animations SpringChain
Animate many values at once SpringCollection
Skip the math, pick a feel Spring::fromPreset()
Use physical units (tension/friction/mass) SpringConfig
Arcs, bouncing balls, particles Projectile + Vector / Point
CSS-compatible timing curves CubicBezier
Named easing curves without control points Easing enum
Honour reduced-motion automatic for spring-driven types (see Reduced motion)

Spring

Damped harmonic oscillator (Ryan-Juckett's algorithm, spring physics part 1 / part 2). The dampingRatio regimes are tabulated under Damping-ratio regimes.

The constructor refuses a spring that cannot converge: angularFrequency must be at least 1e-9 and dampingRatio greater than 0 (a zero-damping spring oscillates forever, a negative one diverges), and deltaTime must be positive (zero freezes the state, a negative value integrates backwards). These are refusals, not slowdowns — a non-converging spring would otherwise spin your frame loop until the user closes the window.

One entry vocabulary: every class in this library ships both the plain new X(...) form and the house factory shape X::new(...) — Spring, SpringConfig, Vector, Point, CubicBezier, Projectile, SpringChain. Same door, same guarantees; the mirror is not a semantics fork.

use SugarCraft\Spring\Spring;

$spring = new Spring(
    deltaTime:        Spring::fps(60),  // 1/60 of a second
    angularFrequency: 6.0,              // rad/sec
    dampingRatio:     1.0,             // critical
);
$pos = 0.0;
$vel = 0.0;
$target = 100.0;

$frame = 0;
while (!Spring::settled($pos, $vel, $target) && $frame < 600) {
    [$pos, $vel] = $spring->update($pos, $vel, $target);
    printf("frame %2d  pos=%.2f  vel=%.2f\n", $frame, $pos, $vel);
    $frame++;
}

Spring::fps(float $n) returns 1.0 / $n for the deltaTime — refusing non-finite and non-positive rates, and rates so small their reciprocal overflows to INF (fps(1e-310) throws rather than handing out a frozen step) — then tick the simulation $n times per second. Spring::settled($pos, $vel, $target, $threshold) is the stop predicate: position within the threshold (default Spring::SETTLING_THRESHOLD = 1e-4) and velocity below it. Drive loops by settled() rather than by a fixed frame count — a frame budget that completes one preset can be nowhere near enough for another: Molasses alone needs 439 frames (~7.3 s) at 60 fps (see Spring presets).

Driving a frame loop

A spring bakes its deltaTime in at construction, so the simulation only matches wall-clock when you actually call update() at that rate. Two honest patterns:

  • Fixed cadence (terminals, replays). Build one spring with Spring::fps(60) and advance it by exactly one step per frame — with sugar-core programs, once per tick command your Program::subscriptions() emits (Subscriptions::withTick() / Cmd::tick()):

    use SugarCraft\Spring\Spring;
    
    $spring = new Spring(Spring::fps(60), 6.0, 1.0);
    $targets = [10.0, 60.0, 100.0];
    $index = 0;
    $pos = 0.0;
    $vel = 0.0;
    
    while ($index < count($targets)) {
        [$pos, $vel] = $spring->update($pos, $vel, $targets[$index]);
        // render $pos — exactly one update and one paint per frame
        if (Spring::settled($pos, $vel, $targets[$index])) {
            $index++;   // the NEXT frame starts the next stage
        }
    }

    Every pass of this loop is one frame: one update(), one render, never a run-to-settled burst inside a single iteration. Motion then advances per frame, so a loop that drifts slower than 60 Hz stretches the animation — replays stay deterministic by recording tick counts; for wall-clock motion measure the real frame time instead:

    use SugarCraft\Spring\Spring;
    
    // A real loop measures with hrtime(true); the scripted array keeps the
    // example deterministic. Clamping bounds a stall instead of teleporting.
    $frameTimes = [0.016, 0.033, 0.017, 0.021, 0.016];
    $targets    = [10.0, 60.0, 100.0, 100.0, 100.0];
    $pos = 0.0;
    $vel = 0.0;
    
    foreach ($frameTimes as $index => $deltaTime) {
        $deltaTime = min($deltaTime, 0.05);           // cap a stall: never a teleport
        $spring = new Spring($deltaTime, 6.0, 1.0);   // coeffs are cheap (~1 µs)
        [$pos, $vel] = $spring->update($pos, $vel, $targets[$index]);
        // render $pos this frame
    }

    Rebuilding the spring per frame (above) keeps wall-clock motion honest under jitter; if the integer-rendered position is unchanged from last frame, skip the repaint — animating a value that rounds to the same cell means the repaint carries no information.

Spring presets

Spring::fromPreset(SpringPreset $preset, ?float $deltaTime = null, ?bool $reducedMotionOverride = null) constructs a spring from a named preset at 60 fps (override the frame time as needed; reducedMotionOverride pins the snap-to-target behaviour — see Reduced motion). Five presets are available, tuned by hand against the react-spring-era folk tables (the presets are not literal UIKit values — UIViewPropertyAnimator documents duration/damping, not tension triples):

Preset Tension Friction Mass ζ Overshoot Settle at 60 fps
Gentle 100 10 1 0.50 ~16% 174 frames (~2.9 s)
Wobbly 180 12 1 0.45 ~21% 141 frames (~2.4 s)
Stiff 500 20 1 0.45 ~21% 94 frames (~1.6 s)
Slow 50 6 1 0.42 ~23% 292 frames (~4.9 s)
Molasses 30 4 1 0.37 ~29% 439 frames (~7.3 s)

Every preset is under-damped (ζ < 1) — they all overshoot a little; that is the family's character. Settle frames are measured for a 0 → 100 move at the default 1e-4 threshold; under reduced motion every preset instead snaps to target in one tick (see Reduced motion). No critical-by-construction preset ships (none was tuned); build one with dampingRatio: 1.0 (the critically damped example above) or new SpringConfig(...) with friction 2 * sqrt(tension * mass).

use SugarCraft\Spring\{Spring, SpringPreset};

$spring = Spring::fromPreset(SpringPreset::Wobbly);
// With custom frame rate
$spring60 = Spring::fromPreset(SpringPreset::Stiff, Spring::fps(60));
$spring30 = Spring::fromPreset(SpringPreset::Gentle, Spring::fps(30));

SpringConfig

SpringConfig accepts physical parameters (tension / friction / mass — all finite and greater than zero) and derives the angularFrequency and dampingRatio consumed by Spring. Extreme-but-finite triples are refused when the derived ω/ζ are non-finite, non-positive, or numerically degenerate. Past ζ ≈ 2^26.5 the float sum ζ² − 1 rounds back to ζ² and both over-damped roots collapse to one number — the spring would freeze, and that is illegal, not merely slow. The derivation:

angularFrequency = sqrt(tension / mass)
dampingRatio     = friction / (2 * sqrt(tension * mass))
use SugarCraft\Spring\{SpringConfig, Spring};

$config = new SpringConfig(tension: 180.0, friction: 12.0, mass: 1.0);
$spring = $config->spring();  // 1/60 default; pass $deltaTime for another frame rate
$snapped = $config->spring(reducedMotionOverride: true);  // pin the snap, ignore the env
echo $config->angularFrequency;     // 13.416... (public readonly)

SpringConfig::spring() returns a pre-wired Spring instance ready to drive update() calls and accept the optional reducedMotionOverride — see Reduced motion. Its default frame time is 1/60 s, one frame at 60 fps.

Damping-ratio regimes

The dampingRatio argument to Spring picks one of three classical behaviours:

  • Under-damped (0 < ζ < 1) — oscillates around the target, amplitudes decaying each cycle. Reach for this when the feel should read as bouncy.
  • Critically damped (ζ = 1) — fastest convergence with no overshoot. The default for "snap to value" animations.
  • Over-damped (ζ > 1) — converges without overshoot but slower than critical. Reach for this for slow, weighty motion.

ζ <= 0 is refused at construction: zero damping is a pure oscillator that never settles, and negative damping diverges — neither belongs in a frame loop, so the constructor throws instead of hanging it.

Reduced motion

Spring-driven animation honours a reduced-motion request automatically: Spring::update() — and everything built from springs, SpringChain and SpringCollection — snaps to $target (returning [<target>, 0.0]) when the signal is on. The signal is environment-only: REDUCE_MOTION or PREFERS_REDUCED_MOTION, looked up through SugarCraft\ColorProfile\Probe::reducedMotion(). The lookup treats 0, false, no and off (case-insensitively) as off; any other non-empty value — 1 among them — as on. Both variables are consulted — REDUCE_MOTION first, then PREFERS_REDUCED_MOTION — and either reading on snaps, so an off value in one never suppresses an on value in the other, and the per-spring reducedMotionOverride (below) is the only opt-back-in path when the environment is set. There is no terminal query or accessibility-daemon channel, and the value is read once per process: the first spring update() that needs it probes the environment and remembers the answer, so flipping the env var mid-session does NOT change behaviour on the next frame (a CLI/TUI run's a11y setting is fixed for its lifetime — that is the whole point of the memo, and why a frame loop of springs no longer pays an environment scan per spring per frame). Spring::resetReducedMotionProbe() is the documented seam for processes that genuinely hot-swap the signal (and for tests); the per-spring reducedMotionOverride remains evaluated per call and always beats the memo. When the host sets one of the variables this supports the WCAG 2.3.3 (Animation from Interactions) reduced-motion guideline; for the auto-running uses advertised above, WCAG 2.2.2 (Pause, Stop, Hide), Level A still applies to anything that moves for longer than five seconds — a math library can support conformance, not satisfy it for your whole app. Snap-to-target is an accessible substitute only when the end state carries the information of the movement; where motion itself carries information, pin the spring to keep animating (override below).

No terminal, desktop environment or accessibility tooling populates these variables on its own — they are opt-in conventions — so host apps are expected to expose their own reduce-motion toggle and gate it through Probe::reducedMotion() as the single read point; the fleet-wide hub for these variables is docs/GETTING-STARTED.md § Accessibility & reduced motion.

Projectile, the Easing curves and CubicBezier deliberately ignore the signal: they are pure functions of time with no target to snap to. Gate them in your app — when the signal is on, jump straight to the motion's end instead of animating it:

use SugarCraft\ColorProfile\Probe;
use SugarCraft\Spring\Easing\Easing;

$frame = 12;                                                               // 12th frame of a 60-frame motion
$t = Probe::reducedMotion() ? 1.0 : $frame / 60.0;  // t = 1.0 is "already there"
$progress = Easing::CubicOut->ease($t);

Two more knobs: the constructor's fourth parameter ?bool $reducedMotionOverride pins the behaviour for one spring — pass false to animate even when the env var is set, true to snap even when it is not (null, the default, defers to the environment). Spring::fromPreset() and SpringConfig::spring() take the same override as their final optional parameter.

use SugarCraft\Spring\Spring;

// With REDUCE_MOTION=1 at the first probe the spring skips animation:
putenv('REDUCE_MOTION=1');
Spring::resetReducedMotionProbe(); // only needed if this process already probed
$spring = new Spring(deltaTime: Spring::fps(60), angularFrequency: 6.0, dampingRatio: 1.0);
[$pos, $vel] = $spring->update(0.0, 0.0, 100.0);  // returns [100.0, 0.0]

// Pin one spring to ignore the environment (e.g. a required progress cue —
// motion whose information is not in the end state):
$alwaysAnimates = new Spring(
    deltaTime: Spring::fps(60),
    angularFrequency: 6.0,
    dampingRatio: 1.0,
    reducedMotionOverride: false,
);

Projectile

Newtonian-physics simulator for arcs / bouncing balls / particle effects.

use SugarCraft\Spring\{Point, Projectile, Spring, Vector};

$p = Projectile::new(
    deltaTime:    Spring::fps(60),
    position:     Point::zero(),
    velocity:     new Vector(5.0, 10.0),          // up-and-to-the-right (Y-up)
    acceleration: Projectile::gravity(),          // (0, -9.81) — pulls down
);
for ($i = 0; $i < 60; $i++) {
    $p = $p->update();
    echo sprintf("t=%2d  pos=(%.1f, %.1f)\n", $i, $p->position->x, $p->position->y);
}

Gravity constants: Projectile::GRAVITY (9.81) and Projectile::TERMINAL_GRAVITY (53.0). Helper factories Projectile::gravity() and Projectile::terminalGravity() return Y-up Vector instances ((0, -9.81, 0) / (0, -53, 0)) ready to drop into the constructor; gravityYDown() / terminalGravityYDown() keep the legacy Y-down sign reachable.

The Projectile statics are the only gravity presets. The package-level SugarCraft\Spring\Gravity façade (Gravity::standard() etc.) forwarded to them and was removed in 2.0.0; see Removed aliases. The presets return a SHARED immutable Vector (readonly by type — no caller can mutate what they did not build).

Coordinate systems

Both Vector and Point are 3D (x, y, z) — the constructor's $z defaults to 0.0 so existing 2D call sites still compile unchanged. Use the third dimension when a scene needs a Z axis (parallax / depth-shaded particle systems). Both types refuse non-finite components with InvalidArgumentException, and Vector::normalize() refuses zero-band and overflowed (INF) lengths with a RuntimeException — a different class on purpose (constructor: bad input; normalize: no honest answer — catch what you mean, a catch (InvalidArgumentException) around normalize() is an uncaught fatal on a zero vector). length(), lengthSquared() and distance() can overflow to INF (components ~1e154 and up), so compare magnitudes through normalize() on extreme inputs — normalize() refuses the overflow loudly, where a raw length() comparison would silently see INF against INF.

The Y-axis convention is Y-up by default: Projectile::gravity() returns (0, -9.81, 0) so increasing Y means "up the screen". Terminal renderers usually grow downward — flip to Projectile::gravityYDown() when you want gravity to pull toward the bottom of the grid without manually negating every coordinate.

Projectile::update() returns a new Projectile instance each call — update() never mutates the receiver. The hazard is discarding the result: read state from whatever you last assigned ($p = $p->update();), not from the pre-update $p. The position / velocity / acceleration properties and their identically-named accessor methods expose the same Vectors; pick either spelling — just be consistent. Each step builds fresh Point/Vector instances; a state component that overflows to INF mid-simulation is refused by their constructors (InvalidArgumentException, naming the component), so bound your accelerations and velocities. A deltaTime of 0 is accepted and freezes the integrator — every Euler term is multiplied by it, so update() keeps handing back an identical state.

Re-aiming a projectile between frames is fluent like the rest of the library: withPosition() / withVelocity() / withAcceleration() / withDeltaTime() each return a new Projectile with only that field swapped — no four-argument rebuild, and the construction door validates every swap (so withDeltaTime(0.0) freezes legally, withDeltaTime(INF) refuses loudly).

When is it done? (the completion contract)

A spring has finished when Spring::settled($pos, $vel, $target, $threshold) says so — position near the target and velocity near zero, both required: a position-only check gives false positives on under-damped presets, which cross the target at full speed and come back. Chain and collection expose the same contract at their own level: SpringChain::isComplete() and SpringCollection::settled(). Loops in this README stop on those predicates, not on frame counts; the $frame < 600 guards shown are escape hatches for paths you can't otherwise bound, and presets are documented so you can size them (Molasses alone needs 439).

For terminal grids the default 1e-4 threshold is finer than one cell: a spring has usually stopped changing the frame long before it has stopped settling. Pass a cell-sized threshold (0.5) to settled() when the consumer renders at cell resolution, and skip the repaint when the rounded cell value is unchanged from last frame. There is no built-in value→cell helper; 0.5 is the working rule of thumb when one unit maps to one cell.

SpringChain

Sequence multiple springs so that one spring's settle triggers the next. Useful for staggered animations where each stage must complete before the next begins.

use SugarCraft\Spring\Spring;
use SugarCraft\Spring\SpringChain;
use SugarCraft\Spring\SpringPreset;

$chain = (new SpringChain([]))
    ->withStage(Spring::fromPreset(SpringPreset::Gentle), 0.0, 0.0, 50.0)
    ->withStage(Spring::fromPreset(SpringPreset::Wobbly), 0.0, 0.0, 100.0)
    ->withStage(Spring::fromPreset(SpringPreset::Stiff),  0.0, 0.0, 75.0);

while (!$chain->isComplete()) {
    $chain = $chain->tick();
    $positions = $chain->currentPositions();   // this frame's positions
    // render $positions
}

tick() returns the advanced chain — reassign it, or the run replays the same frame forever. Positions are read back with currentPositions(), which always reflects the chain you call it on (the previous three-tuple return carried a copy that lagged one frame behind; that shape is gone). Each tick() advances only the active stage. When that stage reaches its target — position within SpringChain::SETTLING_THRESHOLD (5e-4) and velocity within it — the chain activates the next stage. The threshold is deliberately looser than a lone spring's Spring::SETTLING_THRESHOLD (1e-4) so stages hand off while still visually moving; a settled stage hands off up to 5e-4 short of its target by that design. isComplete() returns true when all stages have settled. Under reduced motion every stage still snaps, but each hand-off costs its own tick: with n unsettled stages the final positions are in place after 2n−1 ticks and isComplete() turns true on tick 2n. Note withStage() restarts the new chain at stage 0: build the full stage list before the first tick(). The constructor accepts [Spring, float, float, float] stages and refuses malformed shapes and an out-of-range active index at the boundary.

SpringCollection

Keep many named springs animating at once. Like every other type here, the collection is immutable: withSpring(), without(), withTarget() and tick() each return a new collection, so the carry-the-result assignment is mandatory:

use SugarCraft\Spring\Spring;
use SugarCraft\Spring\SpringCollection;

$group = (new SpringCollection())
    ->withSpring('menu',  Spring::fromPreset(\SugarCraft\Spring\SpringPreset::Stiff),    0.0, 0.0, 40.0)
    ->withSpring('panel', Spring::fromPreset(\SugarCraft\Spring\SpringPreset::Molasses), 0.0, 0.0, 90.0);

$frame = 0;
while (!$group->settled() && $frame < 600) {   // settled(): every member's position AND velocity within Spring::SETTLING_THRESHOLD
    $group = $group->tick();                   // tick(): self — NOT a position map
    $frame++;
}

echo sprintf("menu=%.2f panel=%.2f\n", $group->position('menu'), $group->position('panel'));

Read with position($id) / all() / target($id) / velocity($id) / allVelocities() / has($id); ask "still animating?" with settled($threshold = Spring::SETTLING_THRESHOLD) (it needs velocities, which is why they are exposed). Unknown ids are refused by position() / target() / velocity() / withTarget() with an OutOfBoundsException naming the id, and the constructor refuses misaligned or orphaned per-id maps (the position, velocity and target maps are keyed by id and must hold the same ids). The pre-2.0 add() / remove() / setTarget() mutators were removed in 2.0.0. Use the with*() forms above: withSpring(), without() and withTarget() are copy-on-write, so the return value is the new collection.

Easing

SugarCraft\Spring\Easing\Easing provides named easing curves via their ease(float $t): float method — apply to any normalized time value in [0.0, 1.0]:

use SugarCraft\Spring\Easing\Easing;

$ease = Easing::ElasticOut;
for ($f = 0; $f <= 60; $f++) {
    $t = $f / 60.0;
    echo sprintf("frame %2d  t=%.3f  eased=%.3f\n", $f, $t, $ease->ease($t));
}

Honesty about the range: ease() assumes t in [0, 1] but does not enforce it (out-of-domain t extrapolates), and several curves intentionally leave [0, 1] in the output — Elastic* and Back* overshoot, Bounce* stays inside. One naming caveat: the shipped BackIn/BackOut/BackInOut are the sin-modulated family (t³ ∓ sin shaping), not Penner's classic c1 = 1.70158 polynomial — the overshoot is real, but the dip shape differs from the canonical Penner tables. Six of the sixteen cases leave the [0, 1] range somewhere, by design. If you map an eased value to cells ((int) round($eased * $cols)), clamp before indexing — a rubber-band curve is one frame away from a negative index. Non-finite t flows through ease() unguarded: NAN returns NAN from every case, INF survives the polynomial curves (returning +INF or -INF depending on the signs of the terms) but flips to NAN inside the trig of every Elastic* and Back* case — clamp upstream. The solver-backed CubicBezier::ease() takes the opposite policy: it refuses a non-finite t outright, because a Newton iteration has nothing honest to answer with.

Both easing kinds — the analytic Easing enum (16 cases) and the solver-backed CubicBezier curves (26 named presets plus any custom cubic-bezier() tuple) — implement SugarCraft\Spring\Easing\EasingFunction, the extension seam: write your own ease() and pass it anywhere an easing function is consumed (the same name does not make same-named enum cases and presets value-twins: CubicIn is literally t³, its Bezier fit is not). Two kinds is ONE palette, not a palette plus a fallback: reaching for the enum's simplicity caps nothing about where the value can be consumed, and it never pushes you across to the solver to get a legitimately-missing curve — the enum carries the analytic family, CubicBezier carries the easings.net table fits, and a curve absent from the 16 (Sine, Quart, Quint, Expo, Circ — by name) ships today as CubicBezier presets while expanding the analytic enum stays a gated ruling, not an oversight.

CubicBezier

CubicBezier implements the CSS cubic-bezier() easing algorithm (Newton-Raphson root-finding with a bounded binary-search fallback). Construct via static factory methods, 26 named presets in two families:

  • the five CSS transition-timing-function keywords — linear, ease, ease-in, ease-out, ease-in-out (each is expressible as cubic-bezier(), which generalizes them);
  • 21 Penner-style curves — Sine, Quad, Cubic, Quart, Quint, Expo and Circ, each in In/Out/InOut — approximated with the easings.net table expressed as Bezier control points. The Penner rows are named for the easing family, not for a CSS standard list:
use SugarCraft\Spring\Easing\CubicBezier;

// CSS named easings
$ease       = CubicBezier::cssEase();    // 0.25, 0.10, 0.25, 1.00
$easeIn     = CubicBezier::easeIn();     // 0.42, 0.00, 1.00, 1.00
$easeOut    = CubicBezier::easeOut();    // 0.00, 0.00, 0.58, 1.00
$easeInOut  = CubicBezier::easeInOut();  // 0.42, 0.00, 0.58, 1.00
$linear     = CubicBezier::linear();     // 0.00, 0.00, 1.00, 1.00

// Sine
$easeInSine      = CubicBezier::easeInSine();
$easeOutSine     = CubicBezier::easeOutSine();
$easeInOutSine   = CubicBezier::easeInOutSine();

// Quadratic
$easeInQuad      = CubicBezier::easeInQuad();
$easeOutQuad     = CubicBezier::easeOutQuad();
$easeInOutQuad   = CubicBezier::easeInOutQuad();

// Cubic
$easeInCubic     = CubicBezier::easeInCubic();
$easeOutCubic    = CubicBezier::easeOutCubic();
$easeInOutCubic  = CubicBezier::easeInOutCubic();

// Quartic / Quintic / Exponential / Circular
$easeInQuart     = CubicBezier::easeInQuart();
$easeOutQuart    = CubicBezier::easeOutQuart();
$easeInOutQuart  = CubicBezier::easeInOutQuart();

$easeInQuint     = CubicBezier::easeInQuint();
$easeOutQuint    = CubicBezier::easeOutQuint();
$easeInOutQuint  = CubicBezier::easeInOutQuint();

$easeInExpo      = CubicBezier::easeInExpo();
$easeOutExpo     = CubicBezier::easeOutExpo();
$easeInOutExpo   = CubicBezier::easeInOutExpo();

$easeInCirc      = CubicBezier::easeInCirc();
$easeOutCirc     = CubicBezier::easeOutCirc();
$easeInOutCirc  = CubicBezier::easeInOutCirc();

for ($f = 0; $f <= 60; $f++) {
    $t = $f / 60.0;
    echo sprintf("frame %2d  eased=%.4f\n", $f, $easeInOutCubic->ease($t));
}

CubicBezier::ease(float $t): float takes a finite t and returns the eased progress. A non-finite t throws. A finite out-of-range t is neither refused nor clamped — but past roughly 1e2 the solver saturates to an endpoint, so ease(1e3) on cssEase() is exactly 1.0. The x-mapping is solved so the curve is monotonic within [0, 1] (control x-values are range-checked). The y-output of every one of the 26 named presets lands on exactly 0 and 1 at the endpoints, and none overshoots the interval — each named curve's control y-values sit inside [0, 1], which keeps the whole Bezier curve inside it. Overshoot between endpoints arises only from user-supplied elastic- or back-flavoured control points — same honesty rule as Easing.

Public API

  • Spring — __construct($deltaTime, $angularFrequency, $dampingRatio, ?bool $reducedMotionOverride = null) (the classic $dt/ω/ζ triple; refuses non-finite inputs, dt <= 0, ω < 1e-9, ζ <= 0 and coefficient overflow) / update($pos, $vel, $target) (returns ONE shape carrying both views — named position/velocity plus positional 0/1, so existing [$pos, $vel] = destructures stay valid verbatim while transposed reads are statically flaggable) / bare tuning accessors deltaTime() / angularFrequency() / dampingRatio() / reducedMotionOverride() (the constructor inputs remembered on the object) / fps(float $n) (refuses rates whose reciprocal is not finite) / fromPreset(SpringPreset, ?float $deltaTime = null, ?bool $reducedMotionOverride = null) / static settled($pos, $vel, $target, $threshold = SETTLING_THRESHOLD). const SETTLING_THRESHOLD = 1e-4. update() rejects non-finite state and short-circuits to position = $target, velocity = 0.0 when the env-driven reduced-motion lookup — or the per-instance override — resolves to true.
  • SpringChain — __construct($stages, int $activeIndex = 0) / new($stages) / withStage(Spring, $pos, $vel, $target) (build-time only; returns a chain restarted at stage 0) / tick(): self (reassign or the run never advances) / currentPositions(): list<float> / isComplete(): bool / activeStage(): int / const SETTLING_THRESHOLD = 5e-4. Under reduced motion every stage snaps, but hand-offs still cost a tick (n stages carry their final positions after 2n−1 ticks and complete on tick 2n).
  • SpringCollection — __construct($springs, $positions, $velocities, $targets) / withSpring($id, Spring, $pos, $vel, $target) / without($id) / withTarget($id, $target) (unknown ids refused, named in the error) / tick(): self (new collection; positions map via all()) / position($id): float / has($id): bool / all(): array<string,float> / target($id): float / velocity($id): float / allVelocities() / settled($threshold = Spring::SETTLING_THRESHOLD): bool. The pre-2.0 add() / remove() / setTarget() mutators were removed in 2.0.0 — use the with*() forms.
  • SpringPreset — Gentle / Wobbly / Stiff / Slow / Molasses. resolve() returns a SpringConfig.
  • SpringConfig — __construct(tension, friction, mass) (all finite and positive; extreme-but-finite triples are refused when the derived ω/ζ are non-finite, non-positive, or numerically degenerate) with public readonly $angularFrequency / $dampingRatio / spring(float $deltaTime = 1/60, ?bool $reducedMotionOverride = null).
  • Projectile — Projectile::new(...) / update() / position() / velocity() / acceleration() (identical ->position etc. properties exist) / withPosition() / withVelocity() / withAcceleration() / withDeltaTime() (fluent: each returns a new Projectile preserving the other three fields; the construction door still refuses poisoned values) / gravity() / terminalGravity() / gravityYDown() / terminalGravityYDown() (canonical gravity presets, shared immutable vectors) / GRAVITY / TERMINAL_GRAVITY.
  • Vector — immutable 3D vector (finite components enforced) with add / sub / scale / length / lengthSquared / dot / cross / lerp / normalize (throws RuntimeException — zero-band and overflowed lengths; NOT the constructors' InvalidArgumentException) / jsonSerialize / Vector::fromArray / __toString / Vector::zero().
  • Point — immutable 3D point (finite components enforced) with add(Vector) / delta(Point) (the $to − $from motion primitive, returns a Vector) / distance / __toString / jsonSerialize / Point::fromArray / Point::zero().

Both types implement JsonSerializable as a positional [x, y, z] list and fromArray() decodes exactly that shape — the pair is the wire format, the index order is contractual, and an int component from json_decode is widened to float at the door (wrong arity, non-numeric entries, and non-finite values are refused with InvalidArgumentException).

  • Easing — enum implementing EasingFunction (the extension seam) with ease(float $t): float. Cases: Linear, QuadraticIn/Out/InOut, CubicIn/Out/InOut, ElasticIn/Out/InOut, BounceIn/Out/InOut, BackIn/Out/InOut.
  • CubicBezier — ease(float $t): float (implements the EasingFunction seam). 26 static factories: the five CSS timing keywords (linear, ease as cssEase(), easeIn, easeOut, easeInOut) and 21 Penner-style curves (easeIn/Out/InOut × Sine, Quad, Cubic, Quart, Quint, Expo, Circ) expressed as Bezier control points.

Exception messages are translated through SugarCraft\Spring\Lang (the sugarcraft i18n registry, lang/<code>.php files, 16 locales). Set the locale with the shared core machinery — SugarCraft\Core\I18n\T::setLocale():

use SugarCraft\Core\I18n\T;

T::setLocale('de');   // every Lang::t() lookup, this lib's messages included,
                      // now resolves German (exact → base → en fallback).

Test

cd sugar-spring && composer install && vendor/bin/phpunit

Snapshot tests

Numeric trajectory output is pinned as golden files (JSON) in tests/fixtures/, using sugar-testing's GoldenFile::save()/load() with plain assertEquals in tests/GoldenRenderTest.php — sugar-testing's assertGolden* helper family is ANSI/cell-grid specific and not used here. The golden tests clear REDUCE_MOTION / PREFERS_REDUCED_MOTION and pin serialize_precision in setUp(), so host accessibility settings and ini defaults cannot change the comparison. Any change to the physics output must be intentional — re-record the fixtures with:

UPDATE_GOLDENS=1 vendor/bin/phpunit

(there is no --update-golden phpunit flag).

Demos

Projectile motion

Projectile tracing a gravity arc and bouncing off the floor

Spring physics

Damped spring easing smoothly to its target value

Particle field

Projectile-driven particle field falling under terminal gravity

Removed aliases (2.0.0)

The pre-rename and pre-2.0 aliases below were deleted in 2.0.0. Each one forwarded to the canonical method shown; migrate call sites to it.

Class Removed Use instead
SpringCollection add() withSpring()
SpringCollection remove() without()
SpringCollection setTarget() withTarget()
SpringCollection get() position()
SpringCollection getTarget() target()
SpringConfig springAt60Fps() spring()
Easing\CubicBezier evaluate() ease()
Gravity standard() Projectile::gravity()
Gravity terminal() Projectile::terminalGravity()
Gravity standardYDown() Projectile::gravityYDown()
Gravity terminalYDown() Projectile::terminalGravityYDown()

The Gravity façade class itself is gone. tests/AccessorDeprecationTest.php pins this table against the code.

Used by

  • sugar-widgets — AnimatedProgress caches one Spring across the widget's lifetime and drives it per tick.
  • sugar-overlay — the Animation layer types (Fade / Slide / Scale) consume the easing seam, CubicBezier presets included.
  • candy-flappy — Bird.php integrates Projectile (gravity, terminal velocity) for its flap-and-fall arc.

Credits & inspiration

The spring core mirrors charmbracelet/harmonica after Ryan Juckett's spring physics articles; preset values descend from the react-spring-era folk tables and are tuned by hand; the Bezier control points follow easings.net. The reduced-motion lookup rides sugar-colorprofile's Probe. Originally inspired by the Go Charm ecosystem; SugarCraft is developed as a native PHP project.