export interface ActivationEnvelopeOptions { attack?: number; hold?: number; release?: number; } export function clamp01(value: number) { return Math.min(1, Math.max(0, value)); } export function interpolate(from: number, to: number, progress: number) { return from + (to - from) * clamp01(progress); } export function smoothstep(start: number, end: number, value: number) { if (start === end) { return value < start ? 0 : 1; } const progress = clamp01((value - start) / (end - start)); return progress * progress * (3 - 2 * progress); } export function smootherstep(start: number, end: number, value: number) { if (start === end) { return value < start ? 0 : 1; } const progress = clamp01((value - start) / (end - start)); return progress * progress * progress * (progress * (progress * 6 - 15) + 10); } export function easeOutCubic(progress: number) { const normalized = clamp01(progress); return 1 - (1 - normalized) ** 3; } export function getActivationEnvelope( offset: number, { attack = 0.65, hold = 0, release = 2, }: ActivationEnvelopeOptions = {}, ) { const attackWidth = Math.max(0, attack); const holdWidth = Math.max(0, hold); const releaseWidth = Math.max(0, release); const attackIntensity = attackWidth === 0 ? Number(offset >= 0) : smootherstep(-attackWidth, 0, offset); const releaseIntensity = releaseWidth === 0 ? Number(offset <= holdWidth) : 1 - smootherstep(holdWidth, holdWidth + releaseWidth, offset); return clamp01(attackIntensity * releaseIntensity); } export function getCrossfadeWeights(progress: number) { const incoming = smootherstep(0, 1, progress); return { outgoing: 1 - incoming, incoming, }; } export interface MotionCycleOptions { elapsed: number; units: number; millisecondsPerUnit: number; settleDuration?: number; } export interface MotionCycle { position: number; progress: number; settling: boolean; cycleElapsed: number; duration: number; } export function getMotionCycle({ elapsed, units, millisecondsPerUnit, settleDuration = 650, }: MotionCycleOptions): MotionCycle { const normalizedUnits = Math.max(1, units); const unitDuration = Math.max(1, millisecondsPerUnit); const motionDuration = normalizedUnits * unitDuration; const quietDuration = Math.max(0, settleDuration); const duration = motionDuration + quietDuration; const cycleElapsed = ((elapsed % duration) + duration) % duration; const settling = cycleElapsed >= motionDuration; const position = settling ? normalizedUnits - 0.001 : cycleElapsed / unitDuration; return { position, progress: settling ? 1 : clamp01(cycleElapsed / motionDuration), settling, cycleElapsed, duration, }; }