Skip to content

Visualize Your Ideas With Code

feat(core): add spring interpolation (#356)

Gustav Neustadt1463b1592e22
diff --git a/packages/core/src/tweening/index.ts b/packages/core/src/tweening/index.ts
index 85d0f5ea..90c25ea2 100644
--- a/packages/core/src/tweening/index.ts
+++ b/packages/core/src/tweening/index.ts
@@ -7,3 +7,4 @@
export * from './interpolationFunctions';
export * from './timingFunctions';
export * from './tween';
+export * from './spring';
diff --git a/packages/core/src/tweening/spring.test.ts b/packages/core/src/tweening/spring.test.ts
new file mode 100644
index 00000000..acb4b89d
--- /dev/null
+++ b/packages/core/src/tweening/spring.test.ts
@@ -0,0 +1,121 @@
+/* eslint-disable @typescript-eslint/no-unused-vars */
+
+import {describe, test, beforeEach, expect} from 'vitest';
+import {Project} from '../Project';
+import {setProject, useProject, useTime} from '../utils';
+import {threads} from '../threading';
+import {spring, Spring} from './spring';
+
+describe('spring()', () => {
+ beforeEach(() => {
+ setProject(new Project({name: 'tests', scenes: []}));
+ });
+
+ test('Framerate-independent spring duration', () => {
+ const project = useProject();
+
+ let timeA;
+ // should be around 1.13333333 seconds
+ const taskA = threads(function* () {
+ yield* spring(
+ {
+ mass: 0.1,
+ stiffness: 20,
+ damping: 1.5,
+ },
+ 0,
+ 300,
+ x => {
+ // do nothing
+ },
+ );
+ timeA = useTime();
+ });
+
+ let timeB;
+ const taskB = threads(function* () {
+ yield* spring(
+ {
+ mass: 0.1,
+ stiffness: 20,
+ damping: 1.5,
+ },
+ 0,
+ 300,
+ x => {
+ // do nothing
+ },
+ );
+ timeB = useTime();
+ });
+
+ let timeC;
+ const taskC = threads(function* () {
+ yield* spring(
+ {
+ mass: 0.1,
+ stiffness: 20,
+ damping: 1.5,
+ },
+ 0,
+ 300,
+ x => {
+ // do nothing
+ },
+ );
+ timeC = useTime();
+ });
+
+ project.framerate = 60;
+ project.frame = 0;
+ for (const _ of taskA) {
+ project.frame++;
+ }
+
+ project.framerate = 24;
+ project.frame = 0;
+ for (const _ of taskB) {
+ project.frame++;
+ }
+
+ project.framerate = 120;
+ project.frame = 0;
+ for (const _ of taskC) {
+ project.frame++;
+ }
+
+ expect(timeA).toBeCloseTo(1.5, 0);
+ expect(timeB).toBeCloseTo(1.5, 0);
+ expect(timeC).toBeCloseTo(1.5, 0);
+ });
+
+ test('Accumulated time offset', () => {
+ const project = useProject();
+
+ let time;
+ const task = threads(function* () {
+ yield* spring(
+ {
+ mass: 0.1,
+ stiffness: 20,
+ damping: 1.5,
+ },
+ 0,
+ 300,
+ x => {
+ // do nothing
+ },
+ );
+ time = useTime();
+ });
+
+ project.framerate = 10;
+ project.frame = 0;
+ for (const _ of task) {
+ project.frame++;
+ }
+
+ expect(project.frame).toBe(18);
+ expect(time).toBeCloseTo(1.5, 0);
+ });
+});
diff --git a/packages/core/src/tweening/spring.ts b/packages/core/src/tweening/spring.ts
new file mode 100644
index 00000000..3cc220dd
--- /dev/null
+++ b/packages/core/src/tweening/spring.ts
@@ -0,0 +1,169 @@
+import {decorate, threadable} from '../decorators';
+import {ThreadGenerator} from '../threading';
+import {useProject, useThread, useLogger} from '../utils';
+
+type ProgressFunction = (value: number, time: number) => void;
+
+decorate(spring, threadable());
+export function spring(
+ spring: Spring | null,
+ from: number,
+ to: number,
+ settleTolerance: number,
+ onProgress: ProgressFunction,
+ onEnd?: ProgressFunction,
+): ThreadGenerator;
+
+export function spring(
+ spring: Spring | null,
+ from: number,
+ to: number,
+ onProgress: ProgressFunction,
+ onEnd?: ProgressFunction,
+): ThreadGenerator;
+
+export function* spring(
+ spring: Spring | null,
+ from: number,
+ to: number,
+ settleToleranceOrOnProgress: number | ProgressFunction,
+ onProgressOrOnEnd?: ProgressFunction,
+ onEnd?: ProgressFunction,
+): ThreadGenerator {
+ const settleTolerance =
+ typeof settleToleranceOrOnProgress === 'number'
+ ? settleToleranceOrOnProgress
+ : 0.001;
+
+ onEnd =
+ typeof settleToleranceOrOnProgress === 'number' ? onEnd : onProgressOrOnEnd;
+
+ const onProgress: ProgressFunction = (value: number, time: number) => {
+ if (typeof settleToleranceOrOnProgress === 'function') {
+ settleToleranceOrOnProgress(value, time);
+ } else if (typeof onProgressOrOnEnd === 'function') {
+ onProgressOrOnEnd(value, time);
+ }
+ };
+
+ spring = spring ?? {
+ mass: 0.05,
+ stiffness: 10,
+ damping: 0.5,
+ };
+
+ if (spring.mass <= 0) {
+ useLogger().error(new Error('Spring mass must be greater than 0.'));
+ return;
+ }
+ if (spring.stiffness < 0) {
+ useLogger().error(
+ new Error('Spring stiffness must be greater or equal to 0.'),
+ );
+ return;
+ }
+ if (spring.damping < 0) {
+ useLogger().error(
+ new Error('Spring damping must be greater or equal to 0.'),
+ );
+ return;
+ }
+
+ const project = useProject();
+ const thread = useThread();
+
+ let position = from;
+ let velocity = spring.initialVelocity ?? 0;
+
+ const update = (dt: number) => {
+ if (spring === null) {
+ return;
+ }
+ const positionDelta = position - to;
+
+ // Using hooks law: F=-kx; with k being the spring constant and x the offset
+ // to the settling position
+ const force = -spring.stiffness * positionDelta - spring.damping * velocity;
+
+ // Update the velocity based on the given timestep
+ velocity += (force / spring.mass) * dt;
+
+ position += velocity * dt;
+ };
+
+ // Set simulation constant framerate
+ const simulationFrames = 120;
+
+ // Calculate a timestep based on on the simulation framerate
+ const timeStep = 1 / simulationFrames;
+
+ onProgress(from, 0);
+
+ const startTime = thread.time();
+ let simulationTime = startTime;
+
+ let settled = false;
+ while (!settled) {
+ while (simulationTime < project.time) {
+ const difference = project.time - simulationTime;
+
+ if (timeStep > difference) {
+ update(difference);
+ simulationTime = project.time;
+ } else {
+ update(timeStep);
+ simulationTime += timeStep;
+ }
+
+ // Perform the check during every iteration:
+ if (
+ Math.abs(to - position) < settleTolerance &&
+ Math.abs(velocity) < settleTolerance
+ ) {
+ // Set the thread time to simulation time:
+ thread.time(simulationTime);
+ settled = true;
+ // Break out when settled
+ break;
+ }
+ }
+
+ // Only yield if we haven't settled yet.
+ if (!settled) {
+ onProgress(position, project.time - startTime);
+ yield;
+ }
+ }
+
+ onProgress(to, project.time - startTime);
+ onEnd?.(to, project.time - startTime);
+}
+
+export interface Spring {
+ mass: number;
+ stiffness: number;
+ damping: number;
+ initialVelocity?: number;
+}
+
+export function makeSpring(
+ mass: number,
+ stiffness: number,
+ damping: number,
+ initialVelocity?: number,
+): Spring {
+ return {
+ mass,
+ stiffness,
+ damping,
+ initialVelocity,
+ };
+}
+
+export const BeatSpring: Spring = makeSpring(0.13, 5.7, 1.2, 10.0);
+export const PlopSpring: Spring = makeSpring(0.2, 20.0, 0.68, 0.0);
+export const BounceSpring: Spring = makeSpring(0.08, 4.75, 0.05, 0.0);
+export const SwingSpring: Spring = makeSpring(0.39, 19.85, 2.82, 0.0);
+export const JumpSpring: Spring = makeSpring(0.04, 10.0, 0.7, 8.0);
+export const StrikeSpring: Spring = makeSpring(0.03, 20.0, 0.9, 4.8);
+export const SmoothSpring: Spring = makeSpring(0.16, 15.35, 1.88, 0.0);