Files
physics/README.md
T
2026-10-28 04:25:49 -05:00

13 KiB

linear

Vectors of two, three, and four f32s, rotations as quaternions, and matrices of three by three and four by four: the numbers of space as games, their renderers, and their physics work it. Beside it, geometry makes the shapes of space of them, rays, planes, boxes, spheres, and a camera's frustum, and the tests between them. It's Sakura's, built with blossom, and reads only std's math. An executable optimized with -O2 works what it does to whole vectors as SIMD lanes, which the virtual machine works a number at a time, giving the same bits.

import std::math;
import linear;

val up := vec3::up;
var at := vec3{ 1, 2, 3 };
at = at + vec3{ x = 0.5 } * 2;                        # vec3{ 2, 2, 3 }
val ahead := at.cross(up).normalized();
val far := at.dot(ahead) + at.length;

val turn := quat::axis_angle(vec3::back, math::pi as f32 / 2);
val turned := turn * vec3::right;                     # vec3::up, as near as f32 gets
val both := quat::euler(0.3, -1.1, 0.7) * turn;       # turn, then the other

val place := mat4::compose(vec3{ 5, 0, -2 }, turn, vec3::one);
val moved := place.transform_point(vec3::zero);       # vec3{ 5, 0, -2 }
val clip := mat4::perspective(math::pi as f32 / 3, 16.0 / 9.0, 0.1, 100) * mat4::look_at(vec3{ 0, 2, 10 }, vec3::zero);

val inertia := mat3::rotation(turn) * mat3::scaling(vec3{ 2, 1, 1 }) * mat3::rotation(turn).transposed();
import linear;
import geometry;

val seen := frustum::of(clip);                        # the camera's six planes, facing in
val crate := bounds::around(vec3{ 4, 1, -6 }, vec3::one);
val drawn := seen.overlaps(crate);                    # true: it's in view
val under := ray::toward(vec3{ 0, 2, 10 }, crate.center);
val reach := under.hit(crate) is some(t) ? t : -1;    # how far along it meets the box
val ground := plane::through(vec3::zero, vec3::up);
val lying := ground.side_of(sphere{ vec3{ 0, 0.5, 0 }, 1 });   # side::across
val carried := crate.transformed(place);              # the box holding the crate moved

tests/linear.sakura and tests/geometry.sakura drive all of it, and tools/bench.sakura and tools/geometry_bench.sakura time it.

A project reads it by requiring this folder, or its remote, and naming linear, or geometry, which reads linear and brings it, among a target's deps:

requires:
- ../linear
targets:
- name: game
  type: program
  deps: [geometry]

Layout

Path Holds
linear/linear.sakura The conventions, and reading a value of four f32s as one f32x4 where it lies
linear/vec2.sakura vec2: a place or direction in a plane
linear/vec3.sakura vec3: a place or direction in space, and the axes' directions
linear/vec4.sakura vec4: a place of space with its w, as a matrix projects one
linear/quat.sakura quat: rotations by an axis and angle, by angles about each axis, by where they look, and of a basis; turning vectors, following, undoing, and slerp
linear/mat3.sakura mat3: rotations, scales, and what turns directions, as an inertia tensor; transposes, determinants, and inverses
linear/mat4.sakura mat4: moving, turning, scaling, and composing them; perspective and orthographic projections; look_at; points and directions moved; inverses
geometry/geometry.sakura The conventions of geometry, and the dot products and lanes its shapes are worked with
geometry/ray.sakura ray: a half line from a place, its places, and where it first meets a plane, a sphere, or a box
geometry/plane.sakura plane: through a place or three, how far a place is in front, and which side of it a box or sphere lies on
geometry/bounds.sakura bounds: a box along the axes, of places or a sphere; what it holds and meets; grown, merged, and moved by a matrix
geometry/sphere.sakura sphere: what it holds and meets, and the least one holding a box
geometry/frustum.sakura frustum: the six planes of what a projection sees, and whether a place, a box, or a sphere is within them

How it works

  • Space is right-handed: x to the right, y up, z toward the viewer, so a camera looks down its -z. Matrices are column-major, as GLSL reads them, and multiply a vector on their right, so a * b does b, then a, as quaternions' products do. Projections give a clip space of y up and depth from 0 at the near plane to 1 at the far one, as Vulkan's with its y flipped. Angles are radians.
  • Plain fields: each type is of f32 fields, aligned as an f32, so a struct holding one lays it out wherever it falls, as C and the GPU do, and the virtual machine reads a field as quickly as any. vec3 holds a fourth f32 no one names, so it's 16 bytes, an f32x4's, as vec4 and quat are. It's 0 as a literal leaves it, as vec3{ 1, 2, 3 } and vec3{ y = 1 } do, and printing a vec3 shows it as _w. A mat3's columns are vec3s, so it's laid out as std140 lays out a GLSL mat3; a mat4 is its 16 numbers, column after column.
  • Lanes: an executable optimized with -O2 holds simd vectors in registers, so it reads a vec3, vec4, or quat as one f32x4 from where it is, aligned or not, and works lanes at once: adding, subtracting, scaling, and dividing vectors, their least, greatest, and absolute numbers, lerp, dots, lengths, distance, and normalized, and what a matrix makes of a vector or another matrix, each of its columns scaled by a number splat into every lane, and added, as a quat turns a vector by its matrix. What gathers one vector's numbers into other lanes, as a cross product or a quaternions' product would, it works a number at a time, as simd::shuffle gathers them a lane at a time. lanes_held() says which way while compiling, so only that way's code is kept. lanes() and of_lanes give a vec3's, vec4's, or quat's numbers as an f32x4, for code of one's own to work.
  • The same bits: the virtual machine, which works lanes one at a time, and constants work everything a number at a time, in the order the lanes do, so either way gives the same bits; tests/linear.sakura folds the bits of a long chain of operations, and the machine and an executable each check they're those.
  • Shapes: geometry's shapes are of linear's vectors and plain f32s. A frustum is of a matrix's clip space as linear's projections make it, so frustum::of(projection * view) gives the world's planes, and frustum::of(projection) the camera's; it holds its planes' numbers a lane each, so an executable tests a place, a box, or a sphere against four planes at once, then the other two. A box against a frustum is tested by its corner furthest in front of each plane, so one beside a corner of the frustum, outside it but in front of every plane, counts as seen, which draws it for nothing, and one in view always counts. A place on a shape's surface is within it, and two shapes touching meet. A ray's distances are counted in lengths of its direction, so they're distances where it's of length 1, as ray::toward makes it, and a ray beginning within a sphere or box meets it at 0. What gives a number of a few, as a dot product does, is worked a number at a time: of the lanes of vec3::dot, then worked as numbers, a ray's tests ran two to three times as slow. A ray's test against a box compares its numbers rather than calling math::min and math::max, which keep NaN and -0 as IEEE 754 orders them at three times the cost, so a ray running along a face, in its plane, may meet the box or pass by.
  • Nothing fused: a product is rounded before it's added, not fused with the sum as fma does. FMA3 works a fused sum as one instruction, but a column waiting on the sum before it is slower than one adding products worked at once: mat4 * mat4 took 39 cycles fused, against 32, and transform_point 7 against 6. The same bits would also have the machine work each fused sum as std::math::fma does without FMA3, many instructions for one.

Speed

blossom run linear.bench works each operation over 1,024 values 2,000 times, each pass a function of its own, as a system is, its operations called from elsewhere too, built with -O2, here on an i5-13420H held at 2.1 GHz by its low-power profile, against the same worked a number at a time on a vec3 of 12 bytes, as hearth's scenes worked them before linear. They need the compiler of 2026-10-28 or later, which works f32s in single precision and splats a number into lanes with one instruction; before it, what a matrix made of a vector was faster a number at a time.

What Before linear
p + v * dt of vec3s 9.66 ns 2.00 ns 4.8x
dot of vec3s 3.83 ns 3.84 ns 1.0x
vec3::normalized 13.4 ns 2.85 ns 4.7x
quat * vec3 68.6 ns 24.9 ns 2.8x
mat4 * mat4 35.7 ns 13.5 ns 2.6x
mat4::transform_point 11.1 ns 2.67 ns 4.2x
mat3 * mat3 42.0 ns 5.26 ns 8.0x
quat * quat 16.8 ns 15.3 ns 1.1x
vec3::cross 11.2 ns 12.8 ns 0.88x
mat3 * vec3 2.64 ns
mat4 * vec4 2.95 ns
mat4::inverse 96.4 ns

What works whole vectors gains most, and what a matrix makes of a vector with it: integrating places by velocities, as physics does for every body, is nearly five times as fast, and mat3 * mat3 eight. What builds a vec3 a number at a time, as cross does, runs about as it did of 12 bytes, since the caller reads the 16 bytes back at once, which waits on the numbers written one at a time. How fast the same operation runs hangs on the code around it, by as much as three times either way, as code inlined into a large function slows; these are of small functions, as a game's systems are. hearth's scenes turning 2,000 entities' transforms, a rotation's product, normalized, and a mat4 composed for each, took 42.7 ns an entity on a Ryzen 9 9950X3D, as they did before linear, with the compiler before 2026-10-28.

blossom run geometry.bench times geometry's tests the same way, here on battery, in the low-power profile, the best of five runs, against the same written a number at a time on a vec3 of 12 bytes, a plane at a time, and with math::min and math::max:

What Before geometry
frustum::overlaps of bounds 20.3 ns 10.0 ns 2.0x
frustum::overlaps of a sphere 7.38 ns 4.50 ns 1.6x
ray::hit of bounds 61.2 ns 19.7 ns 3.1x
ray::hit of a sphere 10.9 ns 12.0 ns 0.91x
bounds::transformed 25.2 ns 22.1 ns 1.1x

Culling a scene's boxes by a camera's frustum, which a renderer does for everything it might draw, is twice as fast, of four planes at once: of eight, as one f32x8, it was no faster than a plane at a time, and in one build twice as slow, as the compiler moves vectors of 32 bytes through memory a half at a time where a function works several. A ray meeting a box is three times as fast for comparing its numbers. A ray meeting a sphere works as the plain code does, but gives a maybe<f32>, which the compiler returns through memory.

Testing

blossom test runs tests/linear.sakura twice: linear.tests on the machine, a number at a time, with every read and write checked, and linear.lanes.tests as an executable built with -O2, as lanes. Each checks the types' sizes; vectors' arithmetic, dots, crosses, lengths, and the rest; rotations turning, following one another, undone, and between; projections, and undoing them; matrices of three's rotations, scales, transposes, determinants, and inverses; values read where a struct puts them, unaligned; and the bits of a long chain of all of it.

It runs tests/geometry.sakura the same two ways, as geometry.tests and geometry.lanes.tests: the shapes' sizes; planes through places, distances to them, and which side a box or sphere lies on; boxes and spheres holding places and boxes, meeting, grown, merged, and moved; rays meeting planes, spheres, and boxes from outside, from within, and passing by; a camera's frustum of a perspective and of an orthographic projection, its planes facing in, and what it reaches; and the bits of a long chain of all of it.

Not yet

Vectors of several values at once, as eight vec3s in three f32x8s, which physics passes over its bodies with, and which the bench's own tries found ten to twenty times as fast as one at a time; f64 vectors; and vec2s worked as lanes, which hold half an f32x4. Of geometry: triangles, capsules, and boxes turned with what they hold, and rays and the tests between them; testing many boxes against a frustum at once, their numbers lanes of several; and the frustum of a projection whose depth runs the other way, or without end.