diff --git a/.changeset/matrix-fixes.md b/.changeset/matrix-fixes.md new file mode 100644 index 0000000..5c0e899 --- /dev/null +++ b/.changeset/matrix-fixes.md @@ -0,0 +1,14 @@ +--- +"wtc-math": minor +--- + +Fix matrix and quaternion bugs listed in KNOWN-ISSUES.md: + +- **Behaviour change:** `Mat2.fromAngle` and `Mat3.fromAngle` now turn counter-clockwise, the same way as `rotate` and `Vec2.rotate`. They used to turn clockwise. Negate the angle to keep the old result. +- **Behaviour change:** `Mat3.fromQuat` now rotates the same way as the quaternion, and equals the upper 3×3 of `Mat4.fromQuat`. It used to rotate by the inverse. +- **Behaviour change:** `Mat2.columnArray` and `Mat3.columnArray` now return column-major order, the same as `array`, and are deprecated. The new `rowArray` gives the row-major order they used to return. +- **Behaviour change:** `Quat.inverse` and `Quat.inverseNew` are now the quaternion inverse, the same as `invert` and `invertNew`, instead of the reciprocal of each component. +- `Mat4.transformToNew` sets the translation instead of adding to it. +- `Mat4.rotation` is right for a non-uniform scale. +- `Quat.lerp` and `Quat.interpolate` return a `Quat` instead of a `Vec4`. +- `Mat3.translate` accepts a `Vec2Like`, and there's a new `Mat3.translateNew`. `Mat4.fromRotation` types its axis as `Vec3Like`. diff --git a/KNOWN-ISSUES.md b/KNOWN-ISSUES.md index 3f1bf94..523afa2 100644 --- a/KNOWN-ISSUES.md +++ b/KNOWN-ISSUES.md @@ -2,22 +2,12 @@ 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)`. - ## 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` and `Quat.interpolate` return a `Vec4` rather than a `Quat`. - `Quat.rotateX`, `rotateY` and `rotateZ` ignore their `origin` argument, which is there only to match Vec4. ## Color diff --git a/docs/rotation/quaternions.md b/docs/rotation/quaternions.md index 9b4abae..8c10566 100644 --- a/docs/rotation/quaternions.md +++ b/docs/rotation/quaternions.md @@ -74,9 +74,7 @@ orientation.multiply(step).normalise() const difference = to.multiplyNew(from.invertNew()) ``` -::: warning -`inverse()`, inherited from `Vec4`, takes `1 / x` of each component. It isn't the inverse rotation; that's `invert()`. -::: +`inverse()` and `inverseNew()` are other names for `invert()` and `invertNew()`. On a `Vec4` they take `1 / x` of each component instead. ## Interpolating @@ -86,7 +84,7 @@ const difference = to.multiplyNew(from.invertNew()) const halfway = Quat.slerp(from, to, 0.5) ``` -Don't interpolate quaternions with `Vec4.lerp`; it doesn't keep a steady speed or a unit length. +Don't interpolate rotations with `Quat.lerp`; it doesn't keep a steady speed or a unit length. ## Related diff --git a/src/Mat2.ts b/src/Mat2.ts index ce7efa5..0c64027 100644 --- a/src/Mat2.ts +++ b/src/Mat2.ts @@ -424,29 +424,36 @@ class Mat2 { } /** - * A new array of the elements in row-major order (`[a11, a21, a12, a22]`), - * which is the transpose of {@link Mat2.array}. Despite the name, this is - * not the column-major order WebGL expects; use `array` for that. + * A new array of the elements in column-major order, the same as + * {@link Mat2.array}. + * + * @deprecated Use {@link Mat2.array}, or {@link Mat2.rowArray} for + * row-major order. Older versions of this getter returned the row-major order that `rowArray` now gives. */ get columnArray(): number[] { + return this.array; + } + + /** + * A new array of the elements in row-major order (`[a11, a21, a12, a22]`), + * the transpose of {@link Mat2.array}. + */ + get rowArray(): number[] { return [this.a11, this.a21, this.a12, this.a22]; } /** - * Create a rotation matrix from an angle in radians. - * - * Note: the result is `[cos r, -sin r, sin r, cos r]` in column-major - * order, which rotates clockwise by `r`. This is the opposite direction to - * {@link Mat2.rotate}, so `Mat2.fromAngle(r)` equals - * `Mat2.identity().rotate(-r)`. + * Create a matrix that rotates counter-clockwise by an angle in radians, + * the same direction as {@link Mat2.rotate}: `Mat2.fromAngle(r)` equals + * `Mat2.identity().rotate(r)`. * * @param r The angle, in radians. */ static fromAngle(r: number): Mat2 { - let s = Math.sin(r); - let c = Math.cos(r); + const s = Math.sin(r); + const c = Math.cos(r); - return new Mat2(c, -s, s, c); + return new Mat2(c, s, -s, c); } /** diff --git a/src/Mat3.ts b/src/Mat3.ts index b5ad675..4a527a0 100644 --- a/src/Mat3.ts +++ b/src/Mat3.ts @@ -387,15 +387,26 @@ class Mat3 { * the translation is applied to a vector before this matrix. Returns this * matrix, for chaining. * - * @param v The x and y offsets. + * @param v The x and y offsets, as a vector or `[x, y]` array. */ - translate(v: Vec2): Mat3 { - this.a31 += v.x * this.a11 + v.y * this.a21; - this.a32 += v.x * this.a12 + v.y * this.a22; - this.a33 += v.x * this.a13 + v.y * this.a23; + translate(v: Vec2Like): Mat3 { + const [x, y] = Array.isArray(v) ? v : [v.x, v.y]; + this.a31 += x * this.a11 + y * this.a21; + this.a32 += x * this.a12 + y * this.a22; + this.a33 += x * this.a13 + y * this.a23; return this; } + /** + * Like {@link Mat3.translate}, but returns a new matrix and leaves this one + * unchanged. + * + * @param v The x and y offsets, as a vector or `[x, y]` array. + */ + translateNew(v: Vec2Like): Mat3 { + return this.clone().translate(v); + } + /** * Apply a 2D rotation of `r` radians anticlockwise (about the z axis), in * place. This is this × a rotation matrix, so the rotation is applied to a @@ -700,12 +711,21 @@ class Mat3 { } /** - * A new array of the elements in row-major order - * (`[a11, a21, a31, a12, …, a33]`), which is the transpose of - * {@link Mat3.array}. Despite the name, this is not the column-major order - * WebGL expects; use `array` for that. + * A new array of the elements in column-major order, the same as + * {@link Mat3.array}. + * + * @deprecated Use {@link Mat3.array}, or {@link Mat3.rowArray} for + * row-major order. Older versions of this getter returned the row-major order that `rowArray` now gives. */ get columnArray(): number[] { + return this.array; + } + + /** + * A new array of the elements in row-major order + * (`[a11, a21, a31, a12, …, a33]`), the transpose of {@link Mat3.array}. + */ + get rowArray(): number[] { return [ this.a11, this.a21, @@ -742,20 +762,17 @@ class Mat3 { } /** - * Create a 2D rotation matrix from an angle in radians. - * - * Note: the upper-left 2×2 is `[cos r, -sin r, sin r, cos r]` in - * column-major order, which rotates clockwise by `r`. This is the opposite - * direction to {@link Mat3.rotate}, so `Mat3.fromAngle(r)` equals - * `Mat3.identity().rotate(-r)`. + * Create a 2D matrix that rotates counter-clockwise by an angle in + * radians, the same direction as {@link Mat3.rotate}: `Mat3.fromAngle(r)` + * equals `Mat3.identity().rotate(r)`. * * @param r The angle, in radians. */ static fromAngle(r: number): Mat3 { - let s = Math.sin(r); - let c = Math.cos(r); + const s = Math.sin(r); + const c = Math.cos(r); - return new Mat3(c, -s, 0, s, c, 0, 0, 0, 1); + return new Mat3(c, s, 0, -s, c, 0, 0, 0, 1); } /** @@ -770,11 +787,9 @@ class Mat3 { /** * Create a rotation matrix from a quaternion. The quaternion is assumed to - * be normalised. - * - * Note: the result is the transpose of the usual column-major rotation - * matrix (the one `Mat4.fromQuat` builds), so it rotates by the inverse of - * `q`. + * be normalised. The result is the upper-left 3×3 of + * {@link Mat4.fromQuat}, and rotates a vector the same way as + * `transformByQuat`. * * @param q The quaternion, as an object or `[x, y, z, w]` array. */ @@ -795,13 +810,13 @@ class Mat3 { return new Mat3( 1 - yy - zz, - yx - wz, - zx + wy, yx + wz, - 1 - xx - zz, - zy - wx, zx - wy, + yx - wz, + 1 - xx - zz, zy + wx, + zx + wy, + zy - wx, 1 - xx - yy ); } diff --git a/src/Mat4.ts b/src/Mat4.ts index 65db72d..02c46b3 100644 --- a/src/Mat4.ts +++ b/src/Mat4.ts @@ -482,15 +482,14 @@ class Mat4 { return this; } /** - * Meant to be like {@link Mat4.transformTo}, returning a new matrix and - * leaving this one unchanged. It currently calls {@link Mat4.transform}, so - * it adds `v` to the translation rather than setting it. + * Like {@link Mat4.transformTo}, but returns a new matrix and leaves this + * one unchanged. * - * @param v The translation. + * @param v The new translation. * @returns A new matrix. */ transformToNew(v: Vec3Like): Mat4 { - return this.clone().transform(v); + return this.clone().transformTo(v); } /** @@ -925,23 +924,24 @@ class Mat4 { } /** - * The rotation, as a new {@link Quat}, found by removing {@link Mat4.scaling} - * from the upper 3×3 part. Only reliable when the scale is uniform. + * The rotation, as a new {@link Quat}, found by dividing each of the first + * three columns by its length ({@link Mat4.scaling}). Works for any + * positive scale, uniform or not, as long as there is no shear. */ get rotation(): Quat { const scale = this.scaling.inverse(); - let sm11 = this.a11 * scale.x; - let sm12 = this.a12 * scale.y; - let sm13 = this.a13 * scale.z; + const sm11 = this.a11 * scale.x; + const sm12 = this.a12 * scale.x; + const sm13 = this.a13 * scale.x; - let sm21 = this.a21 * scale.x; - let sm22 = this.a22 * scale.y; - let sm23 = this.a23 * scale.z; + const sm21 = this.a21 * scale.y; + const sm22 = this.a22 * scale.y; + const sm23 = this.a23 * scale.y; - let sm31 = this.a31 * scale.x; - let sm32 = this.a32 * scale.y; - let sm33 = this.a33 * scale.z; + const sm31 = this.a31 * scale.z; + const sm32 = this.a32 * scale.z; + const sm33 = this.a33 * scale.z; const trace = sm11 + sm22 + sm33; let S = 0; @@ -1038,10 +1038,10 @@ class Mat4 { * Create a rotation matrix around an axis. See {@link Mat4.rotate}. * * @param r The angle, in radians. - * @param axis The axis to rotate around, as a {@link Vec3Like}. It is normalised for you; if its length is close to zero you get the identity matrix. + * @param axis The axis to rotate around, as a Vec3 or `[x, y, z]` array. It is normalised for you; if its length is close to zero you get the identity matrix. * @returns A new matrix. */ - static fromRotation(r: number, axis: any) { + static fromRotation(r: number, axis: Vec3Like): Mat4 { return new Mat4().rotate(r, axis); } diff --git a/src/Quat.ts b/src/Quat.ts index 48f68eb..beb63f1 100644 --- a/src/Quat.ts +++ b/src/Quat.ts @@ -1,7 +1,7 @@ import { Mat3 } from "./Mat3.js"; import { Vec3 } from "./Vec3.js"; import { Vec4, V4Q } from "./Vec4.js"; -import type { Vec3Like } from "./types.js"; +import type { Vec3Like, Vec4Like } from "./types.js"; const identity: number[] = [0, 0, 0, 1]; @@ -20,8 +20,8 @@ const orDefault = function (v: any, ident: string): number { * Quat extends {@link Vec4}, so it inherits the component-wise vector methods * (`add`, `scale`, `normalise`, swizzles and so on). Multiplication, the axis * rotations, `dot`, `clone` and `reset` are overridden with quaternion - * behaviour. Note that the inherited `inverse` is the component-wise - * reciprocal; use {@link Quat.invert} for the quaternion inverse. + * behaviour. `inverse` is the quaternion inverse, the same as + * {@link Quat.invert}, not the component-wise reciprocal it is on Vec4. */ class Quat extends Vec4 implements V4Q { /** @@ -246,6 +246,26 @@ class Quat extends Vec4 implements V4Q { return (this.clone() as Quat).invert(); } + /** + * Alias of {@link Quat.invert}: the quaternion inverse, in place. Unlike + * `Vec4.inverse`, this is not the reciprocal of each component. + * + * @returns This quaternion, for chaining. + */ + inverse(): Quat { + return this.invert(); + } + + /** + * Alias of {@link Quat.invertNew}: returns the quaternion inverse as a new + * quaternion and leaves this one unchanged. + * + * @returns A new, inverted Quat. + */ + inverseNew(): Quat { + return this.invertNew(); + } + // Getters and setters /** @@ -313,6 +333,38 @@ class Quat extends Vec4 implements V4Q { ); } + /** + * Create a new Quat from a loosely typed value, as {@link Vec4.interpolate} + * does: a number for all four components, a comma-separated string, an + * `[x, y, z, w]` array, or any object with x, y, z and w. + * + * @param v The value to convert. + * @returns A new Quat. + */ + static interpolate(v: Vec4Like | number | string): Quat { + const r = Vec4.interpolate(v); + return new Quat(r.x, r.y, r.z, r.w); + } + + /** + * Linearly interpolate between two quaternions, component by component. + * The result isn't normalised; use {@link Quat.slerp} for an even rotation, + * or normalise the result. + * + * @param q1 The start quaternion, returned when `t` is 0. + * @param q2 The end quaternion, returned when `t` is 1. + * @param t The interpolation amount, usually from 0 to 1. + * @returns A new Quat. + */ + static lerp(q1: V4Q, q2: V4Q, t: number): Quat { + return new Quat( + q1.x + t * (q2.x - q1.x), + q1.y + t * (q2.y - q1.y), + q1.z + t * (q2.z - q1.z), + q1.w + t * (q2.w - q1.w) + ); + } + /** * The angle of the rotation that takes one unit quaternion to another, in * radians, from 0 to π. Computed as `acos(2 * dot(a, b)² - 1)`, so `q` and diff --git a/src/Vec4.ts b/src/Vec4.ts index 1af2653..ef8d49f 100644 --- a/src/Vec4.ts +++ b/src/Vec4.ts @@ -1285,7 +1285,7 @@ class Vec4 implements V4Q { * @param v1 The start vector, returned when `d` is 0. * @param v2 The end vector, returned when `d` is 1. * @param d The interpolation amount, usually from 0 to 1. - * @returns A new Vec4 (also when called as `Quat.lerp`). + * @returns A new Vec4. */ static lerp(v1: Vec4, v2: Vec4, d: number) { return new Vec4( diff --git a/test/matrices.regressions.test.ts b/test/matrices.regressions.test.ts new file mode 100644 index 0000000..8793df3 --- /dev/null +++ b/test/matrices.regressions.test.ts @@ -0,0 +1,92 @@ +// Regression tests for the matrix and quaternion items in KNOWN-ISSUES.md +import { describe, expect, it } from "vitest"; +import { Mat2, Mat3, Mat4, Quat, Vec2, Vec3, Vec4 } from "../src/index.js"; +import { expectArrayClose } from "./helpers.js"; + +describe("rotation direction", () => { + it("Mat2.fromAngle turns counter-clockwise, like rotate", () => { + const r = 0.7; + expectArrayClose(Mat2.fromAngle(r).array, Mat2.identity().rotate(r).array); + expectArrayClose(new Vec2(1, 0).transformByMat2(Mat2.fromAngle(Math.PI / 2)).array, [0, 1]); + }); + + it("Mat3.fromAngle turns counter-clockwise, like rotate", () => { + const r = -1.3; + expectArrayClose(Mat3.fromAngle(r).array, Mat3.identity().rotate(r).array); + expectArrayClose(new Vec2(1, 0).transformByMat3(Mat3.fromAngle(Math.PI / 2)).array, [0, 1]); + }); + + it("Mat3.fromQuat rotates the same way as the quaternion", () => { + const q = Quat.fromAxisAngle(new Vec3(0.2, -0.5, 0.8).normalise(), 1.1); + const v = new Vec3(1, 2, -3); + expectArrayClose(v.transformByMat3New(Mat3.fromQuat(q)).array, v.transformByQuatNew(q).array); + + const m4 = Mat4.fromQuat(q).array; + const upper = [m4[0], m4[1], m4[2], m4[4], m4[5], m4[6], m4[8], m4[9], m4[10]]; + expectArrayClose(Mat3.fromQuat(q).array, upper); + }); +}); + +describe("Mat4", () => { + it("transformToNew sets the translation and leaves the original alone", () => { + const m = new Mat4().transformTo([1, 2, 3]); + const n = m.transformToNew([10, 20, 30]); + expectArrayClose(n.translation.array, [10, 20, 30]); + expectArrayClose(m.translation.array, [1, 2, 3]); + }); + + it("rotation is right for a non-uniform scale", () => { + const q = Quat.fromAxisAngle(new Vec3(0.3, 0.9, -0.2).normalise(), 0.8); + const m = Mat4.fromRotationTranslationScale(q, [1, 2, 3], [1, 4, 0.5]); + const r = m.rotation; + // q and -q are the same rotation + const sign = Math.sign(r.dot(q)) || 1; + expectArrayClose(r.array.map((n) => n * sign), q.array); + }); + + it("fromRotation accepts any Vec3Like axis", () => { + expectArrayClose(Mat4.fromRotation(Math.PI / 2, [0, 0, 1]).array, Mat4.fromZRotation(Math.PI / 2).array); + expectArrayClose(Mat4.fromRotation(Math.PI / 2, new Vec3(0, 0, 1)).array, Mat4.fromZRotation(Math.PI / 2).array); + }); +}); + +describe("columnArray", () => { + it("is column-major, the same as array, on Mat2 and Mat3", () => { + const m2 = new Mat2(1, 2, 3, 4); + expect(m2.columnArray).toEqual(m2.array); + expect(m2.rowArray).toEqual([1, 3, 2, 4]); + + const m3 = new Mat3(1, 2, 3, 4, 5, 6, 7, 8, 9); + expect(m3.columnArray).toEqual(m3.array); + expect(m3.rowArray).toEqual([1, 4, 7, 2, 5, 8, 3, 6, 9]); + }); +}); + +describe("Mat3.translate", () => { + it("accepts an array and has a New form", () => { + const m = new Mat3(); + const n = m.translateNew([2, 3]); + expectArrayClose(m.array, Mat3.identity().array); + expectArrayClose(new Vec2(1, 1).transformByMat3(n).array, [3, 4]); + m.translate([2, 3]); + expectArrayClose(m.array, n.array); + }); +}); + +describe("Quat", () => { + it("inverse is the quaternion inverse, not the component-wise reciprocal", () => { + const q = new Quat(1, 2, 3, 4); + const expected = q.invertNew(); + expectArrayClose(q.inverseNew().array, expected.array); + expectArrayClose(q.inverse().array, expected.array); + }); + + it("lerp and interpolate return a Quat", () => { + const a = new Quat(); + const b = Quat.fromAxisAngle(new Vec3(0, 1, 0), 1); + expect(Quat.lerp(a, b, 0.5) instanceof Quat).toBe(true); + expect(Quat.interpolate([0, 0, 0, 1]) instanceof Quat).toBe(true); + expect(Quat.interpolate(new Vec4(0, 0, 0, 1)) instanceof Quat).toBe(true); + expectArrayClose(Quat.interpolate([1, 2, 3, 4]).array, [1, 2, 3, 4]); + }); +});