Skip to content

@carrot/maths ​

ts

Core maths utilities, easing curves, and procedural noise. Pure TypeScript, zero dependencies, works in browser and Node.

Installation ​

ts
import { clamp, lerp, perlin2, EasingCurve } from '@carrot/maths';

Architecture ​

Utilities ​

Standard numerical functions - clamp, lerp, inverseLerp, remap, smoothStep, approximate comparison, and angle helpers. These are the foundation used by @carrot/maths-geometry and other packages.

Easing ​

EasingCurve wraps a normalised (t: number) => number function with a uniform API. Seven built-in curves are available as static singletons (EasingCurve.easeInOut, etc.) and can also be created from a type string via EasingCurve.from(). Custom functions are supported via EasingCurve.custom(). The standalone evaluateEasing() function provides a class-free path for one-shot calls.

Noise ​

Four noise algorithm families, all returning values in approximately [-1, 1]:

AlgorithmVariantsCharacter
Perlin1D, 2D, 3D, 4DSmooth gradient noise
Simplex2D, 3D, 4DFaster, fewer directional artifacts
Worley2D (F1, F1F2), 3DCellular / Voronoi patterns
Higher-orderFBM, domain warp, curl, ridgedComposite noise utilities

All noise functions share a permutation table and gradient arrays from noiseCommon.ts. The higher-order utilities (fbm2, domainWarp2, curl2, ridged2) accept any NoiseFn2/NoiseFn3, so they compose freely with any base algorithm.

File Structure ​

src/
├── index.ts                 # Public API barrel
├── utils.ts                 # clamp, lerp, angles, constants
├── easing/
│   └── easing.ts            # EasingCurve class + built-in curves
└── noise/
    ├── noiseCommon.ts        # Shared permutation table + gradients
    ├── perlin.ts             # Perlin 1D–4D
    ├── simplex.ts            # Simplex 2D–4D
    ├── worley.ts             # Worley/Voronoi 2D–3D
    └── noiseUtils.ts         # FBM, domain warp, curl, ridged

Dependencies ​

None.

Build ​

bash
npm run build

Compiles TypeScript to ESM via tsc. Output lands in dist/.


Using @carrot/maths ​

Core maths utilities, easing curves, and procedural noise for real-time applications.

Import ​

ts
import { clamp, lerp, EasingCurve, perlin2, fbm2 } from '@carrot/maths';

Common Patterns ​

1. Interpolation and clamping ​

ts
clamp(1.5);                         // 1 (default 0–1)
clamp(value, 0, 100);               // clamp to range

lerp(0, 100, 0.5);                  // 50
inverseLerp(0, 100, 50);            // 0.5
remap(50, 0, 100, -1, 1);           // 0

smoothStep(0, 1, 0.5);              // ~0.5 (Hermite curve)

2. Angle utilities ​

ts
toRadians(90);                       // π/2
toDegrees(Math.PI);                  // 180

wrapAngle(-0.5);                     // TAU - 0.5
angleInRange(angle, startAngle, endAngle);  // handles wrapping

3. Approximate comparison ​

ts
approximately(0.1 + 0.2, 0.3);      // true (within EPSILON)
isZero(0.0000001);                   // true

4. Easing curves ​

ts
// Static singletons
const curve = EasingCurve.easeInOut;
curve.evaluate(0.5);                 // ~0.5

// From type string
const bounce = EasingCurve.from('bounce');
bounce.evaluate(0.7);

// Custom function
const custom = EasingCurve.custom(t => t * t * t);
custom.evaluate(0.5);               // 0.125

// Standalone (no class)
evaluateEasing('easeOut', 0.5);

5. Perlin noise ​

ts
const value = perlin2(x * 0.05, y * 0.05);  // scale controls frequency

6. Simplex noise ​

ts
const value = simplex3(x * 0.1, y * 0.1, time * 0.5);  // animated noise

7. FBM (layered noise) ​

ts
const terrain = fbm2(perlin2, x * 0.01, y * 0.01, 6);  // 6 octaves
const clouds  = fbm2(simplex2, x * 0.005, y * 0.005, 4, 2, 0.5);

8. Domain warping ​

ts
const warped = domainWarp2(perlin2, x * 0.02, y * 0.02, 2.0, 2);
// strength=2, passes=2 → heavily distorted organic shapes

9. Curl noise (fluid-like flow) ​

ts
const [dx, dy] = curl2(perlin2, x * 0.05, y * 0.05);
// Use dx, dy as velocity for particle advection

10. Worley noise (cell patterns) ​

ts
const cellDist = worley2(x * 0.1, y * 0.1);

// Cell edges via F2 - F1
const { f1, f2 } = worley2F1F2(x * 0.1, y * 0.1);
const edges = f2 - f1;

11. Ridged noise (terrain ridges) ​

ts
const ridges = ridged2(perlin2, x * 0.01, y * 0.01, 6);

Tips ​

  • Scale your inputs - noise functions repeat every integer, so multiply coordinates by a small factor (0.01–0.1) for natural-looking results.
  • FBM octaves - 4–6 octaves is typical. More octaves = more detail but more computation.
  • Compose freely - all higher-order functions accept any NoiseFn2/NoiseFn3, so you can mix Perlin, Simplex, and Worley as base functions.

Package Contents ​

@carrot/maths-geometry ​

Import: import { ... } from '@carrot/maths-geometry';

Vectors ​

ClassInterfaceComponents
Vector2 · MutableVector2Vector2Likex, y
Vector3 · MutableVector3Vector3Likex, y, z
Vector4 · MutableVector4Vector4Likex, y, z, w

Union aliases: Vector2Any · Vector3Any · Vector4Any · VectorAny

Common operations: add · subtract · multiply · divide · scale · negate · normalize · dot · cross · lerp · clamp · distance · distanceSquared · length · lengthSquared · angle · perpendicular · reflect

Static constants (Vector3): zero · one · up · down · left · right · forwards · backwards

Matrices ​

ClassInterfaceSizeUse
Matrix3x2 · MutableMatrix3x2Matrix3x2Like3×2 (6 elements)2D affine (translate, rotate, scale, skew)
Matrix3x3 · MutableMatrix3x3Matrix3x3Like3×3 (9 elements)2D projective (perspective-correct transforms)
Matrix4x4 · MutableMatrix4x4Matrix4x4Like4×4 (16 elements)3D transforms (perspective, lookAt, orthographic)

Common operations: multiply · inverse · determinant · transformPoint · transformDirection · isIdentity

Matrix - generic interface: Matrix<TVector, TMatrix>

Quaternions ​

Quaternion - QuaternionLike - x, y, z, w

Factory: identity · fromEuler(pitch, yaw, roll) · fromAxisAngle(axis, angle) · lookRotation(forward, up?)

Operations: multiply · normalize · inverse · conjugate · dot · slerp · nlerp · rotateVector · toEuler · toRotationMatrix

Direction getters: forward · backward · up · down · left · right

Transforms ​

Transform2D - abstract with three concrete variants picked by createChild:

  • Transform2DNone - identity (zero cost)
  • Transform2DOffset - translation only
  • Transform2DAffine - full position + scale + rotation

Transform3D - position + quaternion rotation + scale, parent/child hierarchy, dirty-flag world matrix caching

Interfaces: Transform2DLike · Transform3DLike

Config types: TransformConfig2D · TransformConfig3D · TransformConfig

Sizes ​

Size2 · MutableSize2 - Size2Like - width, height, area, aspectRatio

Size3 · MutableSize3 - Size3Like - width, height, depth, volume

AspectRatio - fitInside, getWidth, getHeight, static square and none

Resolution - type alias for Size2 with resolution() factory

Bounds (AABB) ​

Bounds2 - center + extents, fromMinMax, fromPositionSize, enclosing, contains, intersects, intersection, union, expand

Bounds3 - 3D equivalent

Interfaces: Bounds2Like · Bounds3Like

Shapes (implement Geometry2) ​

Circle2 - center + radius, fromThreePoints, contains, closestPoint, SDF distanceTo, pointAtAngle, samplePoints

Ellipse2 - center + radiusX/radiusY, Newton-projection closestPoint, Ramanujan perimeter

Rect2 - fromMinMax, fromMinSize, fromCenterSize, corners, contains, closestPoint, SDF

Triangle2 - barycentric contains, signedArea, centroid, isDegenerate

Lines ​

InfiniteLine2 · InfiniteLine3 - origin + direction, closestPoint, distanceTo, project, reflect, side, intersect, parallelTo, coincidentWith

Ray2 · Ray3 - origin + direction + maxDistance, clamped intersection

LineSegment2 · LineSegment3 - start + end, midpoint, at(t), closestPoint, intersect

Curves ​

Arc2 - center + radius + startAngle/endAngle, pointAtAngle, closestPoint, bounds with cardinal crossing

Bezier2 - linear, quadratic, cubic factories, solve(t), derivative, tessellate, subdivide (De Casteljau), offset, exact bounds via root finding

Paths ​

Path2<T> - generic path (segments, bounds, perimeter, closestPoint, isClosed, iterable)

LineStrip2 - open polyline from LineSegment2 segments

LineLoop2 - closed polyline, ray-casting contains, signed area (shoelace)

BezierStrip2 - open bezier path, toLineStrip, samplePoints

BezierLoop2 - closed bezier path, toLineLoop, contains, signed area

Interfaces ​

Scalar: HasLength · HasRadius

Spatial 2D: HasCenter2 · HasDirection2 · HasOrigin2 · HasSize2 · HasMin2 · HasMax2 · HasStart2 · HasEnd2 · HasStartEnd2 · HasBounds2

Spatial 3D: HasCenter3 · HasDirection3 · HasOrigin3 · HasSize3 · HasMin3 · HasMax3 · HasStart3 · HasEnd3 · HasStartEnd3 · HasBounds3

Geometry: Geometry2 (extends HasBounds2: contains, closestPoint, distanceTo) · Geometry3

Carrot