Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,15 @@ jobs:
run: npm install

- name: Build Site
run: npm run build:site
run: npm run docs:build

- name: Setup Pages
uses: actions/configure-pages@v5

- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: "./dist-site"
path: "./docs/.vitepress/dist"

- name: Deploy to GitHub Pages
id: deployment
Expand Down
4 changes: 4 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,7 @@ jobs:

- name: Check
run: npm run check

# TypeDoc fails on an undocumented export, and VitePress on a dead link
- name: Build docs
run: npm run docs:build
9 changes: 6 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ node_modules

build/
dist/
dist-site/
documentation/
.vscode/
.vscode/

# The docs site's generated API pages and build
docs/api/
docs/.vitepress/dist/
docs/.vitepress/cache/
4 changes: 2 additions & 2 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
npm run document
git add ./
# Fails on an undocumented export or a broken {@link}, as the docs build does
npm run docs:api
89 changes: 89 additions & 0 deletions KNOWN-ISSUES.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# Known issues

Bugs and allocation problems found while documenting the library, to fix in later releases. The TSDoc comments describe what the code does today, and the guides avoid the broken parts. Fixing one is a behaviour change, so each needs a changeset, a test, and an update to the comment that describes the current behaviour.

## Rotation direction

- **`Mat2.fromAngle` and `Mat3.fromAngle` turn the wrong way.** They build the transpose of a rotation, so `fromAngle(r)` equals `identity().rotate(-r)`: clockwise, where `Vec2.rotate` and `Mat2`/`Mat3.rotate` turn counter-clockwise.
- **`Mat3.fromQuat` rotates by the inverse of the quaternion.** It returns the transpose of `Mat4.fromQuat`'s upper 3×3. `new Vec3(1, 0, 0).transformByMat3(Mat3.fromQuat(q))` disagrees with `transformByQuat(q)`.

## Swizzle setters

The getters are right; these setters write the wrong components.

- **`Vec3.yzx` and `Vec3.zxy` are swapped**, and so are `Vec4.yzx` and `Vec4.zxy`. `v.yzx = [a, b, c]` sets x = b, y = c, z = a, where it should set y = a, z = b, x = c.
- **`Vec3.zy` and `Vec4.zy` write in reverse**: z = v.y and y = v.x, where it should be z = v.x and y = v.y.
- **`xx`, `yy` and `zz` (Vec2, Vec3) take their value from the second component** (`v.y`). Using the first would match the other setters.

## Vectors

- **The `lengthSquared` setter sets the wrong length** (Vec2, Vec3, Vec4). It scales by `value / lengthSquared`, so the new squared length is `value² / old`. It should scale by `Math.sqrt(value / lengthSquared)`.
- **Setting `length` or `lengthSquared` on a zero vector stores NaN**, which the getters then hide by reading it as 0.
- **`Vec3.cross` and `Vec4.cross` don't change the vector in place**, unlike every other method without the `New` suffix, so `cross` and `crossNew` do the same thing.
- **`Vec4.getAngle` returns the angle between two rotations**, `acos(2·dot² − 1)`, not the angle between two 4D vectors. It can also return NaN when rounding pushes the dot product just past 1.
- **`inverse` has no divide-by-zero guard** (Vec2, Vec3, Vec4): a zero component becomes `Infinity`, where `divide` gives 0.
- **`Vec2.slope`'s setter flips vectors that point left**, because it sets the angle to `Math.atan(value)`, which is always between -90° and 90°.
- **The x, y, z and w setters accept NaN** and store it; the getters hide it as 0.
- `Vec2.rotateDegByNew` names its parameter `radian`, though it takes degrees.

## Matrices

- **`Mat4.transformToNew` adds to the translation instead of setting it.** It calls `transform` rather than `transformTo`.
- **`Mat4.rotation` is only right for a uniform scale.** It divides each row by a scale factor where it should divide each column by its own. The same bug is in gl-matrix.
- **`Mat2.columnArray` and `Mat3.columnArray` are row-major.** `array` is already column-major; `columnArray` returns the transpose.
- **`invert` leaves a singular matrix unchanged without saying so** (Mat2, Mat3, Mat4), where `Mat3.fromMat4` returns null for the same case.
- `Mat4.fromRotation` types its `axis` as `any` rather than `Vec3Like`, and `Mat3.translate` takes a `Vec2` rather than a `Vec2Like` and has no `translateNew`.

## Quaternions

- **`Quat.inverse()`, inherited from Vec4, takes the reciprocal of each component**, which is easy to confuse with `invert()`. `Quat.lerp`, `Quat.interpolate` and `cross` return a `Vec4` rather than a `Quat`.
- `Quat.rotateX`, `rotateY` and `rotateZ` ignore their `origin` argument, which is there only to match Vec4.

## Color

- **`Color.fromHSV` throws on a negative hue**: `i % 6` is negative, so the lookup is undefined.
- **`Color.fromHex` misreads 4- and 8-digit hex** rather than reading the alpha or rejecting it (`'#ff000080'` comes out bluish with alpha 1). Strings that aren't hex give black, and since `ColorLike` strings go through `fromHex`, CSS strings such as `'rgb(…)'` aren't supported.
- **`toHex` and `toCSS` don't clamp**, so a channel outside 0–1 gives a broken hex string or an out-of-range `rgb()` value.

## Plane and Ray

- **`Ray.intersectBox` returns null when the ray starts inside the box**, where `intersectSphere` returns the exit point. A ray with a zero component whose origin lies exactly on a slab plane gives 0/0 = NaN.
- `Plane`'s constructor doesn't normalise the normal, so `distanceTo` and `projectPoint` are wrong for a non-unit normal unless you call `normalize()`.

## Allocation in per-frame methods

Many methods documented as "in place" still allocate temporary objects, which adds garbage-collection pressure in render loops. wtc-gl works around this with its own allocation-free copies in `packages/wtc-gl/src/core/matrix.ts`; once these are fixed it can drop that file. Benchmark before and after (Vitest's `bench`) so the gains are measured, not assumed.

### Internal temporaries (no API change)

These can use local numbers instead of temporary objects, with identical results:

- **Scalar arithmetic** (Vec2, Vec3, Vec4): `addScalar`, `subtractScalar`, `multiplyScalar` and `divideScalar` each build a temporary vector, and `scale` and `normalise` go through them. `v.normalise().scale(10)` allocates two vectors.
- **`transformByMat2`, `transformByMat3`, `transformByMat4`** (Vec2, Vec3, Vec4) clone the vector and read the matrix's `.array`, which builds a new array of up to 16 numbers. Transforming 1,000 points allocates 2,000 objects. They can read the matrix's elements directly.
- **`transformByQuat`** (Vec3, Vec4) clones the vector and builds two temporary vectors.
- **`rotateX`, `rotateY` and `rotateZ`** (Vec3, Vec4) call `subtractNew`, and **`distance`** calls `subtractNew` to measure a length.
- **Matrix `multiply`, `rotate`, `invert` and `adjoint`** (Mat2, Mat3, Mat4) clone the matrix first. `Mat4.rotate` also builds a second Mat4. A clone runs the constructor and all 16 type-checked setters.
- **`Quat.multiply` and `Quat.rotateX`, `rotateY`, `rotateZ`** clone the quaternion.
- **`Plane` and `Ray`** run every point through `Vec3.interpolate`, which allocates a Vec3 even when given one, then use `subtractNew`, `addNew` and `multiplyScalarNew` along the way. They could read x, y and z from the `Vec3Like` directly.
- **`Vec2.getAngle`, `Vec3.getAngle` and `Vec4.getAngle`** clone both vectors to normalise them, where they could divide the dot product by the two lengths.

### New allocation-free API (additive)

The common per-frame operations need forms that write into an object you already have:

- **Writing to a typed array:** `toArray(out, offset = 0)` on vectors, quaternions, matrices and `Color`, so uniforms can be filled without making a new array each frame (wtc-gl's `writeMat4` and `writeMat3`).
- **Multiplying two matrices into this one:** `multiplyMatrices(a, b)` (or a static `Mat4.multiply(out, a, b)`), for model-view-projection and parent-child chains without `multiplyNew`.
- **Composing in place:** `Mat4.compose(q, position, scale)`, the in-place counterpart of `fromRotationTranslationScale` (wtc-gl's `composeMat4`).
- **Decomposing into existing objects:** `getTranslation(out)`, `getScaling(out)` and `getRotation(out)`, since the `translation`, `scaling` and `rotation` getters allocate.
- **In-place interpolation:** `lerp(v, t)` on vectors and `slerp(q, t)` on Quat, since `Vec*.lerp` and `Quat.slerp` are static and allocate. `Color` already has an in-place `lerp`.
- **Setting from loose values without allocating:** a `set(x, y, z)` / `copy(v)` pair (`reset` and `resetToVector` exist, but `resetToVector` silently ignores anything that isn't the same class), and `Quat.setFromAxisAngle` and `setFromEuler` (wtc-gl's `quatFromEuler`).
- **A normal matrix into an existing Mat3:** `Mat3.normalFromMat4(m)`, the in-place counterpart of `fromMat4` (wtc-gl's `normalMatrix`).

### Field access (measure first)

Every component read goes through a getter that does `this.#x || 0`, and every write through a setter that type-checks and can throw. That isn't allocation, but it is the cost on every operation. Plain public fields, or a `Float32Array`/`Float64Array` backing store (which would also make `toArray` a single `set`), would be faster. This changes behaviour, though: NaN would be visible, bad values wouldn't throw, and a typed array changes precision or what `.array` returns. It needs a benchmark and probably a major version.

## Scalar functions

- `pingpong` returns negative values for a negative `t`, because `%` keeps the sign.
- `map` divides by zero when `inMin === inMax`, and `smoothstep` and `smootherstep` return NaN when `edge0 === edge1`.
17 changes: 15 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# [wtc-math](https://github.com/wethegit/wtc-math#readme) _1.3.0_
# [wtc-math](https://github.com/wethegit/wtc-math#readme)

> A math library for JavaScript and TypeScript — vectors, matrices, quaternions, and utilities for 3D graphics and creative coding.

Expand Down Expand Up @@ -63,4 +63,17 @@ import type { Vec2Like, Vec3Like, Vec4Like, QuatLike, Mat2Like, Mat3Like, Mat4Li

## Documentation

Full API docs: [wethegit.github.io/wtc-math](https://wethegit.github.io/wtc-math/)
[The documentation](https://wethegit.github.io/wtc-math/) has guides, live examples and the API reference.

## Development

| Command | What it does |
| --- | --- |
| `npm run docs:dev` | Generates the API pages and starts the docs site. |
| `npm run docs:build` | Builds the docs for GitHub Pages. |
| `npm test` | Runs the tests. |
| `npm run check` | Type-checks, tests and builds. This is what CI runs. |

The docs are in `docs/`; [docs/README.md](docs/README.md) covers writing pages and examples. The API reference is generated from the TSDoc comments in `src/`, and the docs build (and the pre-commit hook) fail on an undocumented export.

Bugs found but not yet fixed are listed in [KNOWN-ISSUES.md](KNOWN-ISSUES.md), and planned work in [ROADMAP.md](ROADMAP.md).
90 changes: 90 additions & 0 deletions ROADMAP.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# Roadmap

Planned work on wtc-math, roughly in the order it should happen. Bugs and the allocation problems in existing methods are listed separately in [KNOWN-ISSUES.md](KNOWN-ISSUES.md).

## Order of work

1. **Tests first.** Add a failing regression test for each item in [KNOWN-ISSUES.md](KNOWN-ISSUES.md) before fixing it, and benchmarks (Vitest's `bench`) for the hot paths: `normalise`, transforming a batch of points, and a parent-child matrix chain.
2. **Bug fixes and allocation work** from [KNOWN-ISSUES.md](KNOWN-ISSUES.md).
3. **New features**, below. They should follow the allocation-free pattern from step 2: methods that change `this`, `New` variants that allocate, and statics that take an optional `out`.
4. **Package and tooling** updates can happen any time, each in its own PR.

Each change to the published package needs a changeset (`npm run changeset`) and docs: TSDoc on every new export (the docs build fails without it) and a guide page or section for anything a reader would look for.

## Package and tooling

### Package

- **Move `typescript` from `dependencies` to `devDependencies`.** It's published as a runtime dependency (1.4.0 lists `typescript: ^6.0.3`), so every install of wtc-math also installs TypeScript. Nothing uses it at runtime.
- **Add `"sideEffects": false`** to `package.json`. No module in `src/` runs anything when imported, so bundlers can drop what a project doesn't use.
- **Update the metadata.** The `description` only mentions vectors, matrices and quaternions; add colours, `Plane`, `Ray` and the scalar functions. Point `homepage` at the docs site, [wethegit.github.io/wtc-math](https://wethegit.github.io/wtc-math/), and add keywords such as colour, OKLCH, ray and plane.
- **Change `husky install` to `husky`** in the `prepare` script. `husky install` is deprecated in husky v9 and prints a warning.
- **Release a patch** for the above. npm only shows the new README after a release.

### Code style

- **Add Prettier and ESLint**, configured as in wtc-gl, with lint-staged in the pre-commit hook. `src/` mixes `var`, double quotes and tabs. Reformat everything in one PR of its own, before or after the bug fixes but not mixed in with them, so the fix diffs stay readable. Add the commit to `.git-blame-ignore-revs`.
- **Merge `src/common.ts` into `Utils.ts`.** It duplicates `degToRad` and `radToDeg` as `degreesToRadian` and `radianToDegrees`.
- **Trim `tsdoc.json`.** The `@chainable`, `@constructor` and `@static` tag definitions are no longer used.

### CI

- **Bring `docs.yml` in line with `release.yml`**: `npm ci` with the npm cache instead of `npm install`, and current versions of the checkout, setup-node and Pages actions.
- **Check `dependabot.yml`'s `reviewers` setting**, which GitHub may have deprecated in favour of a `CODEOWNERS` file, and switch to `CODEOWNERS` if so.

### wtc-gl

- **Point wtc-gl's API links at the new reference.** Its TypeDoc `externalSymbolLinkMappings` send every wtc-math type to the site root; map them to the class pages instead, such as `https://wethegit.github.io/wtc-math/api/wtc-math/classes/Vec3`. Its `api/wtc-math.md` page could link to the [conventions](https://wethegit.github.io/wtc-math/getting-started/conventions) guide.
- **Delete `core/matrix.ts`** once wtc-math's in-place methods stop allocating and it has `multiplyMatrices`, `compose`, `toArray` and the rest of the allocation-free API.

## New features

### From wtc-gl

wtc-gl implements these itself. Moving them here lets it delete the code, and makes them available to projects that don't use wtc-gl.

- **`Frustum`**: six planes from a view-projection matrix, with `setFromMatrix(m)`, `intersectsSphere(centre, radius)`, `intersectsBox(min, max)` and `containsPoint(p)`. Replaces `Camera.updateFrustum`, `setPlane`, `planeDistance` and `frustumIntersectsSphere` in wtc-gl.
- **`Box3` and `Sphere` bounds**: build from points, `expandByPoint`, `containsPoint`, `intersectsBox` and `intersectsSphere`, centre and size, and `applyMat4(m)`. Replaces wtc-gl's `core/bounds.ts` (`worldBoundingSphere`) and `Raycast`'s private `boxDistance`.
- **A fuller `Ray`**:
- Return the hit distance `t` as well as the point, or add `intersect…Distance` methods, since sorting hits needs the distance. wtc-gl's `Raycast` returns distances.
- `intersectTriangle(a, b, c, cullBackFaces)` using Möller–Trumbore, as wtc-gl's `Raycast` does.
- `applyMat4(m)`, to take a ray into a model's local space.
- `Ray.fromCamera(ndc, inverseViewProjection)`. The [Ray guide](docs/geometry/ray.md#picking-with-the-pointer) currently has readers write this by hand.
- **`Vec3.project(viewProjection)` and `Vec3.unproject(inverseViewProjection)`**, matching wtc-gl's `Camera.project` and `Camera.unproject`.
- **sRGB and linear colour**: `Color.toLinear()` and `Color.fromLinear(r, g, b, a)`. `Color` already converts internally for OKLab, and wtc-gl does it again in `loaders/gltf/colour.ts`. Lighting maths and shaders work in linear colour.
- **Curve evaluation**: point and derivative at `t` for quadratic and cubic Béziers and Catmull-Rom splines, as plain functions. wtc-gl's `path/segments.ts` has its own. Its `Path` class, with tilt and frames, is renderer-specific and stays in wtc-gl.

### Creative coding

- **Frame-rate-independent damping**: `damp(a, b, lambda, dt)`, with `Vec2`, `Vec3`, `Vec4` and `Quat` versions, and a critically damped spring like Unity's `SmoothDamp` that keeps a velocity. Once it exists, update the docs that suggest `lerp(x, target, 0.1)` each frame ([Vec2](docs/vectors/vec2.md#interpolation), [scalar functions](docs/utilities/scalars.md#lerp)), which settles faster on a 120 Hz screen than a 60 Hz one.
- **Noise**: seeded simplex noise in 2D, 3D and 4D, and fractal (fBm) noise built on it.
- **Seeded randomness**: a small seeded generator (such as mulberry32), `randomRange`, and random points in and on a circle and a sphere.
- **Easing functions**: in, out and in-out forms of quad, cubic, quart, expo, sine, back and elastic.
- **More scalar functions**:
- `inverseLerp(a, b, v)`.
- A `mod` that's always positive. Use it in `pingpong`, which fixes the negative `t` bug.
- `fract`, `step`, `wrap(v, min, max)` and `approxEqual(a, b, epsilon)`.
- `lerpAngle` and `angleDelta`, which take the shortest way around the circle, so a turn from 350° to 10° doesn't go the long way.
- **Vector operations GLSL has and wtc-math lacks**:
- `reflect(normal)` and `refract(normal, eta)`.
- Component-wise `min`, `max`, `clamp` and `abs`.
- `equals(v, epsilon)`.
- `projectOnto(v)` and `projectOnPlane(normal)`.
- `Vec2.fromAngle(angle, length)`.
- Spherical and cylindrical conversion. Today `radius`, `phi` and `theta` are only other names for x, y and z.
- **Quaternions**:
- `Quat.fromUnitVectors(a, b)`, the rotation that turns one direction into another, for aligning an object to a normal or a velocity.
- `Quat.lookRotation(forward, up)`.
- `toEuler(order)` and `toAxisAngle()`.
- `rotateTowards(q, maxAngle)`.

### Web

- **CSS transforms**: `Mat4.toCSS()` giving `matrix3d(…)` and `Mat3.toCSS()` giving `matrix(…)`, for driving DOM elements from a camera or a 2D transform.
- **CSS colours**:
- `toCSS('oklch')` and the other modern formats.
- `Color.fromCSS(string)` to parse `rgb()`, `hsl()`, `oklch()` and 3-, 4-, 6- and 8-digit hex. This also fixes `fromHex` misreading 8-digit hex, and lets `ColorLike` strings be any CSS colour.
- **Accessibility**: WCAG `luminance()` and `Color.contrastRatio(a, b)`, for checking text against a background.
- **Palette adjustments in OKLCH**: `lighten`, `darken`, `saturate`, `desaturate` and `withAlpha`.
- **Gamut mapping**: bring out-of-gamut OKLCH colours into sRGB by reducing chroma rather than clipping each channel, so `fromOklch` stops shifting hue at the extremes. The [colour spaces guide](docs/colour/colour-spaces.md#oklab-and-oklch) warns about this today.
- **Reading from typed arrays**: `fromArray(array, offset)` on vectors, quaternions, matrices and `Color`, the counterpart of the `toArray(out, offset)` planned in [KNOWN-ISSUES.md](KNOWN-ISSUES.md#new-allocation-free-api-additive). For reading geometry attributes and buffers.
Loading
Loading