physics
The numbers of physical space and what's in it, as games, their renderers, and their physics work them, in four libraries:
| Library | What it is |
|---|---|
malunal.linear |
Vectors of two, three, and four f32s, rotations as quaternions, and matrices of three by three and four by four |
malunal.geometry |
The shapes of space made of them, rays, planes, boxes, spheres, and a camera's frustum, and the tests between them |
malunal.photometry |
Light in the units it's measured in, lumens, candela, lux, and nits, converted between them; exposure values; and the colors of temperatures |
malunal.physics2d |
What collides in a plane: circles, capsules, and convex polygons, where and how deep two meet, rays, a tree of boxes, and a grid of solid cells, as a tilemap's walls are |
It's Sakura's, built with blossom, and reads only std's containers, math, and serial. An executable optimized with -O2 works what linear and geometry do to whole vectors as SIMD lanes, which the virtual machine works a number at a time, giving the same bits. It was the package linear, of linear and geometry, until photometry and physics2d joined them.
import std::math;
import malunal::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 malunal::linear;
import malunal::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
import malunal::linear;
import malunal::photometry;
val bulb := candela_of_lumens(lumens::bulb_60w); # about 63.7 candela, every way
val torch := candela_of_lumens(300, 0.2); # 300 lumens gathered into a cone of 0.2 radians each way
val lit := lux_of_candela(bulb, 2); # what it lights a surface 2 meters away with
val metered := ev100_of_lux(lux::office); # about 7.3, as a meter where it's lit reads
val scale := exposure_of_ev100(metered); # what light in nits is multiplied by, so exposed
val warm := color_of_temperature(2700); # a warm bulb's color, linear sRGB
import malunal::linear;
import malunal::physics2d;
val crate := shape::box(vec2{ 0.5, 0.5 });
val ball := shape::circle(0.25);
val met := collide(&crate, pose::of(vec2{ 0, 0 }), &ball, pose::of(vec2{ 0.6, 0.1 })); # the manifold: normal, points, depths
val ray := crate.ray_cast(pose::of(vec2{ 3, 0 }, 0.3), vec2::zero, vec2{ 1, 0 }, 10); # where a ray first meets the turned crate
var tree := aabb_tree::new();
val leaf := tree.insert(crate.bounds(pose::identity), 7); # a box and a number of the user's
tree.query(aabb::around(vec2::zero, vec2{ 2, 2 }), def(leaf: u32, data: u64): bool { ...; return true; });
var walls := grid::new(20, 10); # solid cells, as a tilemap's walls
walls.set(3, 0, true);
walls.collide(pose::identity, &ball, pose::of(vec2{ 3.5, 1.2 }), def(x: u32, y: u32, m: manifold): bool { ...; return true; });
tests/linear.sakura, tests/geometry.sakura, tests/photometry.sakura, and tests/physics2d.sakura drive all of it, and tools/bench.sakura and tools/geometry_bench.sakura time linear and geometry.
A project reads it by requiring this folder, or its remote, and naming the libraries it uses among a target's deps, as malunal.geometry, whose module is malunal::geometry; each brings malunal.linear, which they read:
requires:
- https://git.malunal.studio/malunal/physics@v1.0.0
targets:
- name: game
type: program
deps: [malunal.geometry, malunal.photometry, malunal.physics2d]
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 |
photometry/photometry.sakura |
The units, and lumens, candela, lux, and nits converted between them, of lights every way and within cones; lumens of watts; and what's commonly lit, as lux::office, nits::clear_sky, and lumens::bulb_60w |
photometry/exposure.sakura |
Exposure values at ISO 100, of a camera's settings or what its meter reads, and what light is multiplied by, so exposed |
photometry/temperature.sakura |
The color of a black body's light at a temperature, as lamps' colors are named |
physics2d/physics2d.sakura |
The conventions of physics2d, and the nearest points of segments |
physics2d/pose.sakura |
rot, a rotation in the plane, and pose, where a body is and which way it's turned |
physics2d/aabb.sakura |
aabb, a box along the plane's axes: what it holds and meets, grown, merged, and where a ray meets it |
physics2d/shape.sakura |
shape: circles, capsules, segments, boxes, and convex polygons, as the hull of places; the box holding one, what it holds, and where a ray first meets it |
physics2d/collide.sakura |
collide and overlaps: the manifold of where two shapes meet, its normal and one or two points, each with its depth |
physics2d/tree.sakura |
aabb_tree: boxes kept in a tree of boxes, inserted, moved, and removed, and found by a box or along a ray |
physics2d/grid.sakura |
grid: solid cells, the manifolds of a shape against them, but for the faces they share, and rays passed from cell to cell |
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 * bdoesb, thena, 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
f32fields, aligned as anf32, 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.vec3holds a fourthf32no one names, so it's 16 bytes, anf32x4's, asvec4andquatare. It's 0 as a literal leaves it, asvec3{ 1, 2, 3 }andvec3{ y = 1 }do, and printing avec3shows it as_w. Amat3's columns arevec3s, so it's laid out as std140 lays out a GLSLmat3; amat4is its 16 numbers, column after column. - Lanes: an executable optimized with
-O2holdssimdvectors in registers, so it reads avec3,vec4, orquatas onef32x4from 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, andnormalized, 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 aquatturns 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, assimd::shufflegathers them a lane at a time.lanes_held()says which way while compiling, so only that way's code is kept.lanes()andof_lanesgive avec3's,vec4's, orquat's numbers as anf32x4, 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.sakurafolds the bits of a long chain of operations, and the machine and an executable each check they're those. - Shapes:
geometry's shapes are oflinear's vectors and plainf32s. Afrustumis of a matrix's clip space aslinear's projections make it, sofrustum::of(projection * view)gives the world's planes, andfrustum::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, asray::towardmakes 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 ofvec3::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 callingmath::minandmath::max, which keep NaN and-0as 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. - Written and read: each type but
frustumis@serial, sostd::serial, and any format of it, asstd::yamlandstd::json, writes and reads it: a vector or rotation as a mapping of its numbers, as{x: 1, y: 0.1, z: -2.5}, each the shortest text reading back as the samef32, withvec3's fourth number left out; amat3as its axes; amat4as a sequence of its 16 numbers, column after column; andgeometry's shapes by their fields. Read withserial::options{ defaults = true }, a number left out is 0, and a rotation'sw1. Afrustumholds its planes as lanes, and is made again of its matrix. - Light's units:
photometrygives each of light's quantities in its own unit, as real lights are measured: a source's luminous flux in lumens, all the light it gives, as a bulb is sold by; its luminous intensity in candela, the light it gives one way, in each steradian; the illuminance of a surface in lux, the light falling on it; and a surface's or a sky's luminance in nits, candela a square meter, the light it gives back toward an eye. A light every way spreads its lumens over 4π steradians, and one within a cone over the cone's solid angle, 2π(1 - cos angle), of its angle from its axis to its edge, as glTF gives a spot light's; a surface so far from a light of so many candela is lit by candela over the distance squared; and a matte surface gives back what lights it over π, by the fraction it gives back. An exposure value at ISO 100 is of a camera's aperture, shutter, and ISO, or of what a meter reads, calibrated as reflected-light meters are, by 12.5, and incident-light meters, by 250, so a scene exposed as a meter where it's lit reads gives a white surface about two thirds of the most a camera records, 1.2 × 2^EV100 nits, and middle grey about an eighth. A temperature's color is of Krystek's fit of the Planckian locus, made linear sRGB of CIE 1931's XYZ. What's commonly lit and sold is named as constants of empty types, solux::officeandlumens::bulb_60wread as what they are. - Collision in a plane:
physics2dtakes each shape as a hull, its points where its pose places them, and its radius around them: a circle of one point, a capsule of two, of no radius a segment, and a polygon of three to eight corners, counterclockwise, each edge's normal facing out. Two circles meet as their middles near; a circle and a hull as the circle's middle nears the hull's edges, or lies within it; and two hulls by the edge of either holding them furthest apart, as the separating axis theorem finds it. Where their hulls overlap, or their round sides near along a face, the other's nearest edge is clipped to the face, as Box2D clips one, so a box resting flat on another, or a capsule lying on one, meets it at two points; where only their round sides meet, at one, along the line between the hulls' nearest points. A manifold's normal is from the first shape toward the second, and each point midway between their surfaces, with how deep the one is within the other; two shapes touching meet, at a depth of 0. A ray meets a circle by its quadratic, a polygon as Cyrus and Beck clip a line by each edge's side, and a capsule by its flat sides between its ends, else its round ends; one beginning within a shape meets it at 0, facing back along it. - The tree: an
aabb_treekeeps a box and a number of the user's at each leaf, each branch the least box holding its two children, so a query passes down only the branches that reach what it asks, and a ray's narrows as it meets what's nearer. A leaf's box is grown by the tree's margin, so what moves a little stays within it and the tree isn't changed; a leaf is put where it grows the boxes above it least, and each branch it passes is turned, as an AVL tree turns one, where one child is two or more deeper than the other: 500 boxes in any order make a tree 18 deep at most. - Grids: a
gridholds solid cells, from its origin at the bottom left of its first, each a box of its cell size. A shape meets each solid cell it reaches as a box, but a manifold pushing it into a solid neighbor, along the axis it pushes most, is passed over, as that's a face two cells share: so a body sliding along a floor of many cells slides as along one, never caught on the seams between them, the ghost collisions of tile maps. A ray passes from cell to cell as Amanatides and Woo pass one, entering by a face, which is its normal. - Nothing fused: a product is rounded before it's added, not fused with the sum as
fmadoes. 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 * mat4took 39 cycles fused, against 32, andtransform_point7 against 6. The same bits would also have the machine work each fused sum asstd::math::fmadoes without FMA3, many instructions for one.
Speed
blossom run malunal.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 malunal.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: malunal.linear.tests on the machine, a number at a time, with every read and write checked, and malunal.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; values written as JSON and read back; and the bits of a long chain of all of it.
It runs tests/geometry.sakura the same two ways, as malunal.geometry.tests and malunal.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; shapes written as JSON and read back; and the bits of a long chain of all of it. The bits are folded by math::wrapping_mul, as FNV-1a wraps, which a checked program's own arithmetic must name.
malunal.photometry.tests runs tests/photometry.sakura: lumens and candela of bulbs every way and gathered into cones, and of watts; lux at distances, and nits of surfaces lit by them, white and grey, and of a clear sky; exposure values of the sunny 16 rule, at another ISO, and of meters, what they multiply light by and back, and a white surface and a grey card exposed as a meter reads, from moonlight to sunlight; and the colors of a warm bulb, of daylight, and of a blue sky, bluer as hotter all the way, and past either end as either.
malunal.physics2d.tests runs tests/physics2d.sakura: rotations and poses, within one another and found again; boxes' corners and normals, polygons around places, leaving out what's within and along their edges, and none of a line or of nine corners, capsules, pills, the boxes holding turned shapes, and what they hold; circles meeting circles, touching, and apart, a ball on a box's face, by its corner, and within it, both ways around, and a ball by a capsule's side; a box resting on a slab at two points, apart, and the other way around, a crate on its corner at one, a capsule lying on the slab at two and standing by its corner at one, capsules side by side and crossing, and a segment across a box; rays meeting a ball, from within it, passing by, and short of it, a turned box, a capsule's side and end, and a segment from either side; 500 boxes in a tree, sound, moved and half removed, found as a brute search finds them, the nearest along a ray, and every one removed; and a grid's floor and wall met, a box resting across two cells, sunk over a seam, the face the cells share passed over, against the wall, the grid placed elsewhere, and rays into its floor and wall, from outside it, short of it, and from within a cell.
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. Of photometry: radiometric units and spectra, and luminance of what a camera sees, for exposure that adapts. Of physics2d: bodies that move by forces and push one another apart, with friction and restitution, and joints; shapes swept along a motion, as time of impact finds where they first meet; rounded polygons; chains of segments, one-way platforms, and terrain; mass and inertia of shapes; and physics3d, the same in space, each benchmarked against Box2D and Jolt.