Smoothing

Four laws that move a value towards a goal, step by step, at the same pace at any frame rate.

Easing runs from a start to an end over a fixed time. Smoothing has no end time: it follows a goal that may move, like a gauge needle following a reading. Each law is a pure step, testable without a clock; the streams operator smooth() runs one on a FrameClock (animation frames on JS).

The laws

Law Moves like
Exponential(keepPer10Ms) keeps a share of the way left per 10 ms: a quick start, a gentle arrival, no overshoot
Linear(unitsPerSecond) constant speed, never past the goal: a slew limit
AttackRelease(up, down) exponential, with one share for rising and one for falling: a VU meter rises fast, falls slowly
Spring(stiffness, damping) a damped spring with inertia; below critical damping (2 * sqrt(stiffness)) it overshoots and settles like an analog needle
import io.peekandpoke.ultra.maths.Smoothing
import io.peekandpoke.ultra.maths.Smoothing.Motion

val needle = Smoothing.Spring(stiffness = 200.0, damping = 10.0)

var motion = Motion(position = 0.0)
motion = needle.step(motion, goal = 1.0, elapsedMs = 16.7)  // position and velocity (units per second)

needle.isSettled(motion, goal = 1.0, near = 0.001)  // false: still on its way

Each step is exact for any elapsed time, so two 10 ms steps land where one 20 ms step does. isSettled is the minimum delta: within near of the goal (in the value's units) the motion may land exactly on it. A spring is settled only once its energy is too small to leave near again, so it does not stop while swinging through the goal. Keep near above 0. Parameters that make no sense (0, negative, NaN) land on the goal at once; an Exponential share of 1 or more counts as 0.999, the slowest.

quantize

Snaps a value to the nearest offset + k * size. The offset shifts the grid, not the value; halfway goes up:

import io.peekandpoke.ultra.maths.quantize

0.26.quantize(0.1)                 // 0.3 (with the usual floating-point error: 0.30000000000000004)
0.26.quantize(0.1, offset = 0.05)  // 0.25
0.25.quantize(0.5)                 // 0.5

A size of 0 or less, a size or offset that is not finite, and a value that is not finite return the value as it is.