Files
sakurac/docs/linear.md
T
2026-10-28 22:13:49 -05:00

32 KiB
Raw Blame History

Plan: vectors, matrices and quaternions

Written 2026-10-14, and brought up to date 2026-10-20 for what was built since (method bounds, std::math, simd and the optimizer's passes), probed and measured again. This is a proposal. std is yours, so the decisions at the end are yours to make. Nothing in std is built yet. Two compiler bugs the first probes found are fixed already (see "Fixed along the way").

Comes after the ffi plan, now built: std::sys is system, and @foreign and @link are extern sections.

Built in the rebuild alone (roadmap.md, decision 1). Where this plan says both compilers, C's half is left out. What was measured in C stays as measured.

What it is: the objects of 2D and 3D math, with their operators:

  • vectors of two, three and four numbers;
  • square matrices of two, three and four columns;
  • quaternions, for rotations;
  • transforms of a position, a rotation and a scale;
  • the camera's matrices, as Vulkan, OpenGL and Direct3D want them.

Its users:

  • programs drawing through Vulkan, whose vertices, uniforms and push constants hold these;
  • games and simulations: movement, collision, physics and cameras;
  • tools reading 3D formats, such as glTF, whose nodes are transforms;
  • grids and screens, with vectors of integers as keys and positions.

It builds on what's built:

  • Operators by method (the README's "Operators"). a + b, m * v and q * r are methods.
  • std::math (std/math/, built 2026-10-14). A length needs its sqrt, a rotation its sin and cos, and slerp its acos. Its real trait says which types those apply to. Its constants are f64s, so f32 code writes math::pi as f32.
  • Bounds on a generic type's methods (built 2026-10-19), so length is where T: real.
  • simd (std/simd.sakura, built 2026-10-14), which vec4 may work through (decision 11).

Probed: again on 2026-10-20 (plans/linear/ in the scratchpad), under both compilers, in the VM and as executables at -O2. Every result here was the same everywhere. Two that weren't are under "Found along the way".

  • struct vec3<T> : additive, indexable<u64, T> where T: numeric with add, sub, negate, mul and equals gave +, -, -v, *, == and +=:
    • for f32, f64 and i32;
    • with v * 2.0 taking the constant as the vector's own number;
    • with a vector times a vector, and a vector times a number, as overloads of mul.
  • A number on the left, as 2.0f * v, through def f32::mul(&this, v: &vec3<f32>). But 2.0 * v is still refused for an f32 vector: an untyped 2.0 is an f64, which asks for f64::mul (decision 2).
  • A matrix times a vector, as columns times components, summed, and mat3f::identity() through the alias.
  • Indexing: v[1] = 9, through indexable and the fields read as an array, and v[3] stopping the program.
  • A swizzle, a.xy, as a property.
  • Methods for reals alone, as def vec3<T>::length(&this): T where T: real, now in both compilers. Asking it of a vec3<i32> is an error where it's written, naming the bound.
  • Hashing integers alone, as def vec2<T>::hash(&this): u64 where T: integer, so a vec2<i32> keys a dict.
  • Constants made by cross and length, and a Vulkan projection through math::tan with its clip_space defaulted, in both compilers.
  • One type of any length, struct vec<T, const N: u64> holding a T[N], with its operators, length, and cross refusing other lengths by if const N != 3 { compile_error(...) } (decision 3).

Measured on 2026-10-20, the best of five, pinned to a performance core of a busy machine: ten million steps of total = total + step * half on vec3<f32>, against the same written as three fields. The 2026-10-14 times are in parentheses.

Where Operators Fields
The rebuild, -O2 166 ms (400) 67 ms (60)
C, -O2 417 ms, the same with 0.5 written in place of half (430, and 2.1 s) 159 ms (126)
  • Inlining is done. Both compilers inline add and mul at -O2 now, with a dozen callers too. The rebuild moves step * half out of the loop, and zeroes nothing and checks no pointers in it.
  • What's left is the rebuild's, for f32 and other 4-byte numbers:
    • each f32 operation is still done in double precision. An add is addsd, then cvtsd2ss and cvtss2sd: three instructions for one addss. The fields pay it too, and take twice what f64's do: 67 ms against 31;
    • the vector's fields are written to the stack and read back each step: 36 instructions a step, against the fields' 12. A vec3<i32> does the same, 23 ms against 11, while a vec3<f64> stays in registers, its operators as fast as its fields: 29 ms and 31.
  • C no longer boxes an f32 lent by reference. step * 0.5 and step.mul(0.5) cost what they cost with a variable. Its code is still about 2.5 times as slow as the rebuild's, and does f32 in double precision too.
  • Lanes: a vec4<f32> whose add and mul read its fields as one f32x4 where lanes_held() took 73 ms, against 67 written as four fields, and 182 where its operators work field by field. The bits were the same.

So the types can be built today. Vectors of f64 are as fast as written out already. Those of f32 need the rebuild's code generator, or lanes for vec4 (decision 11).

What's there now

  • Operators by method (the README's "Operators"), chosen by the right operand, with a number on the left asking its own type, and a += b as a = a + b.
  • Numbers' methods beside the compiler's: a program may declare f32::mul taking a vector.
  • Bounds on a generic type's methods, in both compilers since 2026-10-19, as def vec3<T>::length(&this): T where T: real. Only the instances meeting them have the method.
  • Constant parameters and for const, so vec<T, 3> can be written, one body for every length (decision 3).
  • indexable, properties, if const, and static methods through an alias, as mat3f::identity(). Generic types have no associated variables, so vec3<T>::zero is a function.
  • std::math (the README's "Math"): sqrt, sin, cos, tan, acos, atan2 and fma of any real, with the same bits in the VM, in executables and in constants. It has no radians, degrees, lerp, smoothstep or remap yet.
  • simd<L[N]> (the README's "Vectors"): f32x4 and the rest, held in registers by the rebuild's -O2 executables, which lanes_held() says while compiling. An f32x4 is 16 bytes aligned to 4, as a packed vec4f is.
  • f32 is rounded after every operation, in the VM and in executables, so the two agree. Both compilers' executables work it in double precision.

What it needs

  1. Vectors of 2, 3 and 4, of any number: f32 and f64 for geometry, and integers for grids and pixels.
  2. Their arithmetic as operators: with each other component by component, with a number on either side, and negation.
  3. Their geometry: dot and cross products, length, distance, normalizing, interpolating, reflecting and projecting.
  4. Matrices of 2, 3 and 4:
    • products with each other and with vectors;
    • transposing, the determinant and the inverse;
    • translating, scaling and rotating;
    • looking at a point;
    • perspective and orthographic projections.
  5. Quaternions:
    • from an axis and an angle, from Euler angles, from one direction to another, and from a matrix;
    • composing and rotating vectors;
    • interpolating;
    • to a matrix and back.
  6. Transforms: a position, a rotation and a scale, combined, inverted, applied and interpolated.
  7. Layouts C and the GPU read, so a vec3<f32> is three floats one after another.
  8. The same bits in the VM, in executables, and in constants.
  9. As fast as written out, at -O2.

How it fits the rules

  • Plain data. Vectors, matrices and quaternions copy freely, hold nothing, close nothing, and are equatable. Vectors of integers are hashable, by a hash bounded where T: integer, so they key a dict.
  • Arithmetic is operators, by method. A vector is additive. It isn't numeric, since * between two vectors isn't a ring's product, and there's no %.
  • Nothing stops the program.
    • Normalizing a zero vector gives NaNs, as IEEE 754 does, and normalize_or gives a fallback.
    • An inverse is a maybe, which is nothing where the determinant is zero.
    • So nothing calls contract, and every function runs in a constant in C too, which refuses constants that could reach contract.
  • Methods for reals alone are bounded where T: real, so asking one of a vec3i is an error where it's written. Quaternions and transforms are of reals alone, bounded so on the type.
  • The same bits everywhere:
    • each operation rounds as its type does, and nothing fuses a multiply and an add but math::fma;
    • the functions are std::math's, which agree by construction;
    • simd's lanes give the bits the fields would, so vec4 may take either way.

The types (decisions 1 to 5)

module std::math;

pub struct vec2<T> : additive, indexable<u64, T> where T: numeric { pub var x: T; pub var y: T; }
pub struct vec3<T> : additive, indexable<u64, T> where T: numeric { pub var x: T; pub var y: T; pub var z: T; }
pub struct vec4<T> : additive, indexable<u64, T> where T: numeric { pub var x: T; pub var y: T; pub var z: T; pub var w: T; }

#! Column by column, as GLSL, SPIR-V and Vulkan lay them out (decision 5).
pub struct mat2<T> where T: numeric { pub var columns: vec2<T>[2]; }
pub struct mat3<T> where T: numeric { pub var columns: vec3<T>[3]; }
pub struct mat4<T> where T: numeric { pub var columns: vec4<T>[4]; }

#! A rotation, `w` last, as glm, Eigen and glTF hold it.
pub struct quat<T> where T: real { pub var x: T; pub var y: T; pub var z: T; pub var w: T; }

#! Where something is, how it's turned, and how large, applied scale first.
pub struct transform<T> where T: real {
  pub var translation: vec3<T>;
  pub var rotation:    quat<T>;
  pub var scale:       vec3<T>;
}

pub type vec2f = vec2<f32>;   pub type vec3f = vec3<f32>;   pub type vec4f = vec4<f32>;
pub type vec2d = vec2<f64>;   pub type vec3d = vec3<f64>;   pub type vec4d = vec4<f64>;
pub type vec2i = vec2<i32>;   pub type vec3i = vec3<i32>;   pub type vec4i = vec4<i32>;
pub type mat3f = mat3<f32>;   pub type mat4f = mat4<f32>;   pub type quatf = quat<f32>;
# and mat2f, the f64 ones, and transformf

The operations

Vectors, for any T:

a + b    a - b    -a    a += b               # component by component
a * b    a / b                                # component by component
v * s    v / s    s * v                       # by a number; s * v for f32, f64 and i32
a == b                                        # every component equal
v[i]                                          # a component, read or written

pub def vec3<T>::dot(&this, other: &vec3<T>): T;
pub def vec3<T>::cross(&this, other: &vec3<T>): vec3<T>;    # vec3 alone
pub def vec3<T>::length_squared(&this): T;
pub def vec3<T>::min(&this, other: &vec3<T>): vec3<T>;      # also max, clamp, abs
pub def vec3<T>::sum(&this): T;
pub def vec3<T>::cast<U>(&this): vec3<U>;                   # each as `as` converts it
pub def vec3<T>::hash(&this): u64 where T: integer;         # so integers key a dict
pub def vec3<T>::of(xy: vec2<T>, z: T): vec3<T>;            # and vec4::of(xyz, w)
pub val vec3<T>::xy: vec2<T>;                               # a property; the other swizzles (decision 9)
pub def vec3<T>::zero(): vec3<T>;   # also one, x_axis, y_axis, z_axis, as vec3f::zero()

Vectors, where T is f32 or f64:

pub def vec3<T>::length(&this): T where T: real;           # and so is each below
pub def vec3<T>::distance(&this, other: &vec3<T>): T;
pub def vec3<T>::normalize(&this): vec3<T>;                 # NaNs for a zero vector
pub def vec3<T>::normalize_or(&this, fallback: vec3<T>): vec3<T>;
pub def vec3<T>::lerp(&this, to: &vec3<T>, t: T): vec3<T>;
pub def vec3<T>::reflect(&this, normal: &vec3<T>): vec3<T>;
pub def vec3<T>::project_onto(&this, onto: &vec3<T>): vec3<T>;
pub def vec3<T>::angle_to(&this, other: &vec3<T>): T;       # radians
pub def vec3<T>::near(&this, other: &vec3<T>, tolerance: T): bool;

Matrices:

m * n    m * v    m * s    m + n    m - n    m == n    m[c]   # m[c] is column c

pub def mat4<T>::identity(): mat4<T>;
pub def mat4<T>::of_rows(rows: vec4<T>[4]): mat4<T>;
pub def mat4<T>::transpose(&this): mat4<T>;
pub def mat4<T>::determinant(&this): T;
pub def mat4<T>::row(&this, index: u64): vec4<T>;
pub def mat4<T>::translation(by: vec3<T>): mat4<T>;
pub def mat4<T>::scaling(by: vec3<T>): mat4<T>;

# Each of these is `where T: real`.
pub def mat4<T>::inverse(&this): maybe<mat4<T>>;
pub def mat4<T>::rotation(axis: vec3<T>, angle: T): mat4<T>;      # also rotation_x, _y, _z
pub def mat4<T>::look_at(eye: vec3<T>, target: vec3<T>, up: vec3<T>): mat4<T>;
pub def mat4<T>::perspective(fov_y: T, aspect: T, near: T, far: T, clip: clip_space = clip_space::vulkan): mat4<T>;
pub def mat4<T>::orthographic(left: T, right: T, bottom: T, top: T, near: T, far: T, clip: clip_space = clip_space::vulkan): mat4<T>;
pub def mat4<T>::transform_point(&this, point: vec3<T>): vec3<T>;      # w of 1, divided through
pub def mat4<T>::transform_direction(&this, direction: vec3<T>): vec3<T>;  # w of 0
pub def mat4<T>::normal_matrix(&this): maybe<mat3<T>>;   # the inverse transposed

#! Where depth runs and which way y points after projecting (decision 6).
pub enum clip_space: u8 {
  vulkan,    #! depth 0 to 1, y down
  opengl,    #! depth -1 to 1, y up
  direct3d,  #! depth 0 to 1, y up, as Metal and WebGPU too
}

Quaternions:

q * r    q * v    q == r    -q

pub def quat<T>::identity(): quat<T>;
pub def quat<T>::of_axis_angle(axis: vec3<T>, angle: T): quat<T>;
pub def quat<T>::of_euler(yaw: T, pitch: T, roll: T): quat<T>;     # decision 8
pub def quat<T>::between(from: vec3<T>, to: vec3<T>): quat<T>;     # the shortest arc
pub def quat<T>::look_rotation(forward: vec3<T>, up: vec3<T>): quat<T>;
pub def quat<T>::of_matrix(m: mat3<T>): quat<T>;
pub def quat<T>::conjugate(&this): quat<T>;        # also inverse, normalize, dot, length
pub def quat<T>::slerp(&this, to: &quat<T>, t: T): quat<T>;
pub def quat<T>::nlerp(&this, to: &quat<T>, t: T): quat<T>;
pub def quat<T>::matrix(&this): mat3<T>;           # also matrix4
pub def quat<T>::axis(&this): vec3<T>;             # also angle, euler

Transforms and helpers:

a * b                                              # b, then a
pub def transform<T>::identity(): transform<T>;
pub def transform<T>::inverse(&this): transform<T>;
pub def transform<T>::matrix(&this): mat4<T>;
pub def transform<T>::apply(&this, point: vec3<T>): vec3<T>;      # also apply_direction
pub def transform<T>::lerp(&this, to: &transform<T>, t: T): transform<T>;

pub def radians<T>(degrees: T): T where T: real;   # also degrees
pub def lerp<T>(from: T, to: T, t: T): T where T: real;
pub def smoothstep<T>(edge0: T, edge1: T, x: T): T where T: real;
pub def remap<T>(x: T, from_low: T, from_high: T, to_low: T, to_high: T): T where T: real;

Using it

A camera's matrices for Vulkan:

import std;
import std::math;

val view := mat4f::look_at(eye, vec3f::zero(), vec3f::y_axis());
val projection := mat4f::perspective(math::radians(60.0f), width / height, 0.1, 100);
val model := transform::<f32>{ translation = at, rotation = facing, scale = vec3f::one() }.matrix();
push.mvp = projection * view * model;            # a mat4f, as the shader's mat4 reads it

Turning, and easing between two turns:

val quarter := quatf::of_axis_angle(vec3f::y_axis(), math::pi as f32 / 2);
val ahead := quarter * vec3f{ x = 0, y = 0, z = -1 };    # now (-1, 0, 0)
val halfway := facing.slerp(&target, 0.5);

A grid:

var tiles := dict::<vec2i, tile>::new();
val east := vec2i{ x = 1, y = 0 };
tiles.set(position + east, tile::grass);

How each part works

  • Layout (decision 4):
    • Each type is its fields one after another, as C's arrays are. A vec3<f32> is 12 bytes, and a mat4<f32> 64, as Vulkan's vertex formats, glm and SPIR-V's storage buffers take them.
    • std140 uniform blocks align a vec3 to 16. Matching that is the program's to do, as with any struct a shader reads.
    • A vec4f is laid out as an f32x4 is, so it can be read as one (decision 11).
  • Indexing reads the fields as a fixed array, through a pointer to the first, &this.x, so an index out of range stops the program as any array's does, and needs no contract. (&this is a &&vec3<T>, a reference to the reference, so it isn't the vector's address.)
  • A number on the left is a method on that number: f32::mul, f64::mul and i32::mul, each taking a vector, matrix or quaternion, for the aliases above. Other number types put the number on the right.
  • Reals alone:
    • length, normalize and the rest are bounded where T: real, so asking them of a vec3i is a mistake where it's written, naming the bound.
    • Matrices' inverses, rotations and projections do the same. quat and transform are bounded real on the type, since a turn of integers means nothing.
  • Named vectors are static functions, as vec3f::zero() and vec3f::y_axis(), since a generic type has no associated variables.
  • Matrices (decision 5):
    • Column c is m[c], and the element in row r of it is m[c][r], as in GLSL.
    • m * v treats v as a column, and m * n applies n first. So projection * view * model reads right to left, as shaders do.
    • inverse is by cofactors, giving nothing where the determinant is exactly zero.
  • Projections (decision 6):
    • View space is right-handed: the camera looks down -Z, with +Y up, in every case.
    • Only the projection differs by clip_space:
      • vulkan maps near to 0 and far to 1, and negates y, since Vulkan's y points down;
      • opengl maps them to -1 and 1;
      • direct3d maps them to 0 and 1, with y up.
  • Quaternions (decision 8):
    • Hamilton's: i * j is k.
    • q * r rotates by r first, as matrices compose.
    • q * v rotates v by q, as v + 2w(u × v) + 2u × (u × v), where u is (x, y, z). That needs no matrix.
    • slerp takes the shorter way, negating one where their dot is negative. It falls back to nlerp where they're nearly the same, where acos loses precision.
    • of_euler(yaw, pitch, roll) turns by roll about Z, then pitch about X, then yaw about Y, for +Y up. euler gives them back, with pitch from -π/2 to π/2.
  • Transforms apply scale, then rotation, then translation. a * b applies b first.
    • inverse is exact where the scale is the same on every axis.
    • Otherwise the true inverse shears, which a transform can't hold. So inverse gives the nearest transform, and matrix().inverse() the exact matrix.
  • Equality is exact, so a vector holding a NaN equals nothing, itself included. near compares within a tolerance.
  • Printing: interpolation shows the fields, as vec3<f32>{x = 1, y = 2, z = 3}. describe gives (1, 2, 3).

Performance (decision 11)

What 2026-10-14 asked of the rebuild's code generator is half done, after its optimizer's passes of 2026-10-18 (performance.md): small methods returning a struct are inlined, and nothing in the probe's loop is zeroed or checked for null. What's left is for f32 and other 4-byte numbers:

  • f32 arithmetic in single precision (built 2026-10-28, see the CHANGELOG):
    • addss, subss, mulss, divss and sqrtss round exactly as computing in double and rounding does, since a double holds more than twice a float's bits.
    • So the results are the same bits, and the VM needn't change.
    • That's 1 instruction for 3, and removes the conversions' latency from every chain. It speeds every f32, not only vectors: written as fields, f32 took twice f64's time.
  • Vectors of 4-byte numbers in registers, as those of 8-byte ones are. A vec3<f32>'s and a vec3<i32>'s fields go to the stack and back each step, where a vec3<f64>'s stay in registers. This phase finds what keeps them in memory.
  • Lanes for vec4, in std:
    • Where lanes_held(), add, sub, mul and the rest of a vec4 of 4-byte numbers read its fields as one simd<T[4]>, through &this.x, since an f32x4 is laid out as a packed vec4f is. Elsewhere, in the VM, constants and C's executables, they take the fields.
    • The probe's vec4<f32> took 73 ms so, against 67 written as fields.
    • A mat4's columns are vec4s, so its products would be four lanes' multiplies and adds.
    • vec2 and vec3 of f32 aren't 16 or 32 bytes, and wait for the code generator.
  • The target: vector arithmetic within 1.5 times the same written as fields, at -O2, measured by the probe.

C's code isn't sped up here. The rebuild is the compiler that's going forward, and C's results are already right.

Testing

  • test/std/linear.sakura, written with std::testing, covers:
    • vectors: every operator for f32, f64 and i32, a number on each side, indexing past the end stopping a forked copy, swizzles, cast, hash in a dict, and the identities: a × b perpendicular to both, a · a its length squared, and normalize of zero giving NaNs;
    • matrices: products against values worked out by hand, inverse round trips to within a tolerance, a singular matrix's nothing, and determinant of rotations being 1;
    • projections: for each clip_space, a point on the near plane mapping to its near depth and one on the far plane to its far depth, and y's direction;
    • quaternions: rotating a vector agreeing with matrix() doing it, of_matrix back again, slerp at 0, 1 and halfway, the shorter way, Euler angles round trips away from the poles, and between of opposite vectors;
    • transforms: matrix() agreeing with apply, and inverse undoing it;
    • constants: const forward := vec3f::x_axis().cross(&vec3f::y_axis()) and a constant projection, the same in both compilers.
  • A program of the corpus prints the bits of many results, so the VM, executables and both compilers are compared exactly.
  • Where they run: in the VM, as executables at -O0 and -O2, and with run --checks. The rebuild's analyzer must check them with 0 notes.
  • The probe's timings are run before and after decision 11's work.

Phases

About 1,700 lines of std and 900 of tests. Every program's check would grow by about 5%: a copy of std/simd.sakura's 1,075 lines of generic methods, added to std, cost 3% of a one-line program's check in both compilers (2026-10-20, a busy machine). Decision 11 is work in the rebuild's code generator, sized once its first part, finding what keeps 4-byte fields in memory, is done.

  1. Vectors, with everything that needs no sqrt: operators, dot, cross, indexing, swizzles, min and max, and hashing.
  2. Matrices, with products, transpose, determinant, inverse, translation and scaling.
  3. What needs std::math: lengths, normalizing, interpolating, look_at, rotations, projections, quaternions and transforms, and the helpers.
  4. Lanes for vec4 and mat4, and the rebuild's code generator (decision 11).
  5. A "Vectors and matrices" section in the README, beside its "Vectors" of simd.

Each can begin now: std::math was built the day this was written.

Fixed along the way

These were found by the probes and fixed on 2026-10-14. Both compilers passed every check after. Both fixes still hold: the corpus program below gave its expected output under both compilers, in the VM and at -O2, on 2026-10-20.

  • C passed 0 for a constant on the right of an operator whose method takes &f32. v * 2.0 on a vec3<f32> gave a zero vector, since the constant was lent as the f64 it is alone. It's now lent as an f32, as a call's argument is, in *, in *=, and in *= on a property. The rebuild was right already.
  • The rebuild called def f32::mul(&this, v: &vec3<f32>) a cycle. That happened where vec3's bound asks for mul, since deciding that f32 is numeric worked out the program's methods on f32 first, this one among them. It now asks the compiler's own methods on a number first, as C does.
  • A program of the corpus covers both: operators_lend_constants_as_their_methods_take_them_1.

Found along the way

  • 2.0 * v is refused for an f32 vector, still, in both, since an untyped constant on the left asks its own type, f64. 2.0f * v and v * 2.0 work. Letting a constant on the left take the type of a method that fits would change the README's rule for a number on the left (decision 2 here).
  • The rebuild does f32 arithmetic in double precision, rounding after each operation, as C's executables do too: three instructions for one addss.
  • The rebuild keeps a struct of 4-byte numbers in memory through a loop, where one of 8-byte numbers stays in registers (Performance).
  • Generic types have no associated variables, and the compilers differ in how they say so. C refuses val vec3<T>::zero := .... The rebuild takes the declaration, but reading it gives a vec3<T> no instance made: val z: vec3f = vec3f::zero is a mismatch, and interpolating it prints nothing. An alias's own, val vec3f::zero := ..., works in both.
  • The rebuild doesn't report compile_error in a property's getter while checking. For vec<T, N>'s z, guarded by if const N < 3 { compile_error(...) }, C reports the error where a vec2's z is read. The rebuild checks it clean, and run stops with "Checking an instance lowering asked for made notes.", without the note. In a method, as cross, both report it while checking.
  • "Vector" now names three things: vector<T>, the README's "Vectors" of simd, and these.
  • No longer so (2026-10-20):
    • Neither compiler inlined a small method returning a struct at -O2. Both do.
    • C boxed an f32 temporary lent by reference, five times the cost of lending a variable. It costs what a variable does.
    • C refused bounds on a generic type's methods, where the rebuild took them, which is why reals were checked inside the methods by if const. Both take them since 2026-10-19.

Later, where wanted

  • Geometry: rays, planes, boxes, spheres and frustums, and the tests between them.
  • Rectangular matrices, as 3×4 for affine transforms, and matrices of any size for numerical work. Decision 3's (b) would bring them.
  • Lanes for vec2 and vec3 of f32, which aren't 16 or 32 bytes. vec4's are in decision 11, now simd is built.
  • std140 and std430 layouts, as types padded for uniform and storage buffers.
  • Reversed and infinite depth in projections, for precision far away.
  • Dual quaternions, for skinning, and rotors, from geometric algebra.
  • Writing vectors as arrays in JSON, as glTF does, through a serial format option.
  • One lerp for numbers and vectors, through a trait like the README's scales<S>, which std doesn't name.

Decisions for you

  1. Where it lives:
    • (a) std::math, beside its functions, in std/math/ (recommended). One import gives a program drawing in 3D everything it uses.
    • (b) std::linear, of its own. A program wanting only sqrt doesn't see vec3, but most that want one want both. Neither saves checking, since every program is checked with all of std.
  2. The numbers inside:
    • (a) Generic, as vec3<T>, with aliases for f32, f64 and i32 (recommended). One body serves floats, doubles and grids. 2.0 * v needs 2.0f for an f32 vector, or the rule for a number on the left changes so a constant there takes the type of a method that fits.
    • (b) f32 alone, as many game libraries default to, with vec3d and vec3i written again where wanted. 2.0 * v still needs 2.0f.
    • (c) Generic, with no aliases.
  3. Lengths, open now that constant parameters and for const make the second possible:
    • (a) A type for each, vec2, vec3 and vec4, with fields (recommended). Literals name the fields, vec3f{ x = 1, y = 2, z = 3 }, reflection and @serial see them, and cross and the swizzles are only where they mean something.
    • (b) One of any length, vec<T, const N: u64> holding a T[N], with the same aliases. One body serves every length, and matrices of any shape would come with it. But x to w are properties, a literal is vec3f{ c = [1, 2, 3] }, and cross, z and w refuse the wrong lengths by if const N != 3 { compile_error(...) }, which the rebuild reports from a property only as it runs, without the message.
  4. Layout:
    • (a) Packed, as C's arrays (recommended). Vertex buffers and C libraries read them as they are, and a vec4f is laid out as an f32x4 is.
    • (b) vec3 and vec4 aligned to 16, as std140 likes them. A vec3 would take 16 bytes, and wouldn't match a vertex format of three floats. simd doesn't need it: an f32x4 is aligned to 4.
  5. Matrices:
    • (a) Column by column, with vectors as columns, m * v (recommended). As GLSL, SPIR-V, Vulkan, OpenGL and glm have it, so a matrix goes to a shader as it is.
    • (b) Row by row, with vectors as rows, v * m, as Direct3D's older math libraries have it.
  6. Clip space:
    • (a) A parameter naming the API, Vulkan by default (recommended).
    • (b) Vulkan alone. Simpler, but OpenGL and WebGPU programs would fix every projection by hand.
    • (c) A function for each, as perspective_vulkan and perspective_gl.
  7. Angles:
    • (a) Radians, as plain numbers, with radians and degrees (recommended). As math::sin takes them, and every library has it.
    • (b) An angle type, made by degrees(90) or radians(x), as duration is made of a unit. Degrees can't then be passed for radians, at the cost of converting at every sin.
  8. Euler angles:
    • (a) One order, yaw about Y, pitch about X and roll about Z, for +Y up (recommended). That's what cameras and characters want.
    • (b) Every order, chosen by an enum, for tools reading other programs' conventions.
    • (c) None: axes and angles, and directions, alone.
  9. Swizzles:
    • (a) The common ones as properties (recommended): xy, xz and yz of a vec3 or vec4, and xyz of a vec4.
    • (b) Every one, written by a tool: 336 for a vec4, of two to four components. It's about 1,000 more lines of std, which every program's check pays about 3% for, by the measure in "Phases".
    • (c) A method, as v.swizzle(2, 0, 1).
  10. What's in it:
    • (a) Vectors, square matrices, quaternions, transforms and the helpers, with geometry later (recommended).
    • (b) Geometry now too: rays, planes, boxes, spheres and frustums.
    • (c) Vectors and matrices alone.
  11. Speed, where inlining is settled and f64 vectors are as fast as written out:
    • (a) Both, as part of this plan (recommended): in the rebuild's code generator, f32 in single precision and 4-byte fields held in registers; in std, vec4's and mat4's operations of 4-byte numbers through simd where lanes_held(). f32 vector code is otherwise 2.5 times slower than the same written out.
    • (b) Lanes alone, in std. vec4 is fast now, and mat4's products would be too, but vec2 and vec3 of f32 stay 2.5 times slower until the code generator's own plan.
    • (c) Left to the code generator's own plan, with f32 vectors slow until then.
    • (d) Accepted.