Files
physics/README.md
T
2026-10-31 07:24:40 -05:00

45 KiB
Raw Blame History

physics

The numbers of physical space and what's in it, as games, their renderers, and their physics work them, in five 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 and moves 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; and a space of rigid bodies, pushed by forces and what they meet, held by joints, and sleeping at rest
malunal.physics3d What collides and moves in space: spheres, capsules, and convex hulls, boxes among them, where and how deep two meet, rays, a tree of boxes, and the triangles of a surface, as a level's ground and walls are; and a space of rigid bodies, as in a plane

It's Sakura's, built with blossom, and reads only std's containers, math, serial, and time, which times a space's steps. 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, physics2d, and physics3d 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; });
import malunal::linear;
import malunal::physics3d;

val crate := shape::box(vec3{ 0.5, 0.5, 0.5 });
val rock := shape::hull_of(places.view()).expect("...");                                  # the convex hull of places, as many as 32 its corners
val met := collide(&crate, pose::identity, &rock, pose::of(vec3{ 0.2, 0.9, 0 }, turn));     # the manifold: normal, one to four points, depths
val hit := crate.ray_cast(pose::of(vec3{ 3, 0, 0 }), vec3::zero, vec3{ 1, 0, 0 }, 10);      # where a ray first meets the crate

val ground := triangle_mesh::new(points.view(), indices.view());                           # a level's triangles, in a tree of their own
ground.collide(pose::identity, &crate, pose::of(vec3{ 0, 0.45, 0 }), 0, def(t: u32, m: manifold): bool { ...; return true; });
import malunal::linear;
import malunal::physics2d;

var s := space::new();                                                                   # gravity 10 down, lengths in meters
val ground := s.add(body{ kind = body_kind::static, at = pose::of(vec2{ 0, -1 }) });
_ = s.attach(ground, collider{ shape = shape::box(vec2{ 50, 1 }) });
val crate := s.add(body{ at = pose::of(vec2{ 0, 4 }) });                                 # dynamic, as bodies are at first
_ = s.attach(crate, collider{ shape = shape::box(vec2{ 0.5, 0.5 }), density = 2, friction = 0.8 });
val door := s.add(body{ at = pose::of(vec2{ 6, 2 }) });
_ = s.attach(door, collider{ shape = shape::box(vec2{ 1, 0.1 }) });
val hinge := s.pin(ground, door, vec2{ 5, 2 });                                          # a revolute joint, limits and a motor its own to set
s.apply_impulse(crate, vec2{ 2, 0 }, s.center_of(crate));
for i in 0..60u {
  s.step(1f / 60f);                                                                      # four substeps, as Box2D's soft step
}
val at := s.pose_of(crate);                                                              # resting on the ground, near y = 0.5
for e in s.events() { ... }                                                              # what began and stopped touching
val hit := s.ray_cast(vec2{ 0, 10 }, vec2{ 0, -1 }, 20);                                 # the collider, its body, and where
import malunal::linear;
import malunal::physics3d;

var s := space::new();
val level := s.add(body{ kind = body_kind::static });
_ = s.attach_mesh(level, triangle_mesh::new(points.view(), indices.view()), collider{ friction = 0.8 });   # a level's triangles
val ball := s.add(body{ at = pose::of(vec3{ 0, 5, 0 }), velocity = vec3{ 2, 0, 0 } });
_ = s.attach(ball, collider{ shape = shape::sphere(0.5), restitution = 0.5 });
val wheel := s.add(body{ at = pose::of(vec3{ 4, 2, 0 }) });
_ = s.attach(wheel, collider{ shape = shape::capsule(vec3{ 0, 0, -0.2 }, vec3{ 0, 0, 0.2 }, 0.5) });
val axle := s.hinge(level, wheel, vec3{ 4, 2, 0 }, vec3::back);                         # ball, hinge, fixed, and distance joints
s.step(1f / 60f);

tests/linear.sakura, tests/geometry.sakura, tests/photometry.sakura, tests/physics2d.sakura, tests/space2d.sakura, tests/physics3d.sakura, and tests/space3d.sakura drive all of it; tools/bench.sakura and tools/geometry_bench.sakura time linear and geometry, and tools/physics2d_bench.sakura and tools/physics3d_bench.sakura step Box2D's and Jolt's benchmark scenes.

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, malunal.physics3d]

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
physics2d/mass.sakura mass_data: a shape's mass of a density, its center, and its rotational inertia, and two summed
physics2d/body.sakura body_kind, body, and collider, what a space makes bodies and colliders of, and the ids naming them
physics2d/space.sakura space: bodies and colliders added, attached, and taken away, a grid among them; their poses, velocities, and masses; forces, torques, and impulses; rays; and the step, timed by its step_profile
physics2d/contacts.sakura Pairs of colliders found by the tree as they move, their contacts kept from step to step, a grid's one for each cell, and contact_events of what began and stopped touching
physics2d/solver.sakura The soft step: substeps of forces, pushes, moves, and relaxing, bouncing, and each contact's impulses kept
physics2d/wide.sakura Contacts sorted into colors, none of whose bodies any other of its color pushes, and solved as lanes of eight
physics2d/sleep.sakura Islands of bodies touching or joined, put to sleep together, and woken
physics2d/joints.sakura joint: revolute, distance, and weld joints, made and changed, and how they keep bodies from meeting
physics2d/joint_solver.sakura How each kind of joint is prepared, warmed, and solved, its limits, motor, and spring among it
physics3d/physics3d.sakura The conventions of physics3d, and the nearest points of segments
physics3d/pose.sakura pose, where a body is in space and which way it's turned, as a place and a quaternion
physics3d/hull.sakura hull: a convex polyhedron's corners, faces, and edges; made as a box, as a triangle, or around places, coplanar triangles made one face
physics3d/shape.sakura shape: spheres, capsules, boxes, and convex hulls; the box holding one, what it holds, and where a ray first meets it
physics3d/collide.sakura collide and overlaps: the manifold of where two shapes meet, its normal and one to four points, each with its depth and the features that met
physics3d/tree.sakura aabb_tree: boxes kept in a tree of boxes, inserted, moved, and removed, and found by a box or along a ray
physics3d/mesh.sakura triangle_mesh: the triangles of a surface, in a tree, their shared edges flat or hollow passed over, met by shapes and rays
physics3d/mass.sakura mass_data: a shape's mass of a density, its center, and its inertia tensor, and two summed
physics3d/body.sakura body_kind, body, and collider, what a space makes bodies and colliders of, and the ids naming them
physics3d/space.sakura space: bodies and colliders added, attached, and taken away, a triangle mesh among them; their poses, velocities, and masses; forces, torques, and impulses
physics3d/step.sakura The step, timed by its step_profile, and rays
physics3d/contacts.sakura Pairs of colliders found by the tree as they move, their contacts kept from step to step, a mesh's one for each face of triangles met, and contact_events
physics3d/solver.sakura The soft step, as in a plane, each contact of as many as four points, its friction along two tangents
physics3d/sleep.sakura Islands of bodies touching or joined, put to sleep together, and woken
physics3d/joints.sakura joint: ball, hinge, fixed, and distance joints, made and changed, and how they keep bodies from meeting
physics3d/joint_solver.sakura How each kind of joint is prepared, warmed, and solved, a hinge's limits, motor, and spring among it

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.
  • Written and read: each type but frustum is @serial, so std::serial, and any format of it, as std::yaml and std::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 same f32, with vec3's fourth number left out; a mat3 as its axes; a mat4 as a sequence of its 16 numbers, column after column; and geometry's shapes by their fields. Read with serial::options{ defaults = true }, a number left out is 0, and a rotation's w 1. A frustum holds its planes as lanes, and is made again of its matrix.
  • Light's units: photometry gives 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, so lux::office and lumens::bulb_60w read as what they are.
  • Collision in a plane: physics2d takes 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_tree keeps 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 grid holds 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.
  • Collision in space: physics3d takes each shape as a core with its radius around it: a sphere's a place, a capsule's a segment, and a hull itself, of no radius. A hull is plain data, as many as 32 corners, its faces convex polygons, counterclockwise from outside, and each edge between two faces; hull::of makes the least one around places by adding them one at a time, the furthest first, each replacing the faces it sees with faces from their horizon to it, then makes the triangles of one plane one face, so a box of eight places is six squares. Two spheres or capsules meet as their cores near, a capsule lying along another at two points. A sphere or capsule and a hull meet as the core nears the hull's surface, by its places nearest a face it's in front of and its edges', a capsule lying along a face at two; or, where the core passes within the hull, by the face, or the axis across an edge and the segment, holding them furthest apart. Two hulls meet by the face of either, or the pair of edges, one of each, holding them furthest apart, as the separating axis theorem finds it, testing only the pairs of edges whose arcs on the sphere of directions cross, as Gregorius tests them, so they're a face of the hulls' Minkowski difference; a flat hull's edges, a triangle's, are tested by how far the hulls reach along each axis. At a face, the other's face most against it is clipped to its sides, as Sutherland and Hodgman clip, at as many as four points, those holding most of what the rest hold; at two edges, at one, between them. A face of the second hull is taken over the first's only where it holds them apart by a millimeter and 2 percent more, and an edge over a face by a millimeter and 5 percent, so the same pair meets the same way from one step to the next, as deep as it is to within those. Each point has an id of the features that met there, for a solver to carry over what it found; within a margin, shapes apart are given points too, of depths below 0. A ray meets a sphere by its quadratic, a capsule's side as Ericson meets a cylinder, and its ends as spheres, and a hull as Cyrus and Beck clip a line by each face's side.
  • Meshes: a triangle_mesh keeps its triangles, those of no area left out, in a tree of their boxes, and a shape meets each triangle it reaches as a flat hull. An edge two triangles share is passed over where they're flat, turning less than 5 degrees, or hollow, as Jolt's active edges are: a shape meeting a triangle by such an edge, or a corner of such edges only, is pushed out as the triangle's face pushes it, as deep as it is below the face's plane, so a body sliding across a floor of many triangles slides as along one. A ray meets each triangle from either side, as Möller and Trumbore find it, its normal facing back along the ray.
  • Bodies: a space holds bodies, each static, standing where it's put; kinematic, moving by the velocity it's given and pushing what it meets but never pushed; or dynamic, moving by forces, gravity, and what it meets. A body is made of colliders, each a shape about the body's origin, or a grid or a triangle_mesh, which a static body is given as a level's walls are, and its mass is its colliders' areas or volumes by their densities, centered where they're centered, and its rotational inertia about that center, as the parallel axis theorem sums them. A body's data and a collider's are a number of the user's, as an entity's bits. Ids name bodies, colliders, and joints by their place and a generation, so one kept past its removal is never taken for the next of its place.
  • Pairs and contacts: each collider is a leaf of the space's tree, its box grown by a tenth of a meter, and each that leaves its grown box as its body moves finds what its box newly meets: a pair, where the two may meet, of bodies one of them dynamic, on layers each other's masks hold, and not held apart by a joint. Each step, a pair of a moving body is met again, within a speculative margin of 2 centimeters, and dropped where their grown boxes part. Its contact keeps the impulses that held its bodies apart at each point, matched to the next step's points by the features that met, so a stack begins each step pushing as it ended the last. A grid's pair has a contact for each solid cell met, and a mesh's for each face of triangles met, those facing one way taken as one, their points together and the four holding the most of them kept, as Jolt takes them, so a box resting across a seam is pushed as on one face rather than one triangle's after the other's. Sensors' pairs only note whether they overlap. What began and stopped touching is told as contact_events of the step.
  • The soft step: a step is solved as Box2D's soft step solves one, in four substeps, each of which moves each body's velocities by its forces and gravity, pushes the bodies' velocities apart where they meet, moves them, and pushes again without undoing overlaps, the relax, so what was pushed out doesn't fly. A contact pushes as a stiff, damped spring of 30 cycles a second, damped ten times over, twice as stiff against what doesn't move, so an overlap is undone over a few substeps, no faster than 3 meters a second, and a stack doesn't jitter; a point apart within the margin pushes only as much as closes the gap in the substep, so what falls stops at what's below it, not in it. Where it moved, each point's separation is worked out again from how far its body has moved and turned since the step began, not met again. Friction holds each point along its tangent, in space along two, no harder than the friction, mixed as the square root of the two colliders', times what pushes it apart; and what met faster than 1 meter a second bounces back, at its points that pushed, as much as the greater restitution keeps.
  • Eight at once: in a plane, each step sorts its contacts into 24 colors, each given the first color none of its dynamic bodies has yet, so no two contacts of a color push one body, and solves each color's as the lanes of f32x8s, eight contacts at once, each body's velocities gathered from where its state lies and scattered back, as Box2D's wide solver does; the rare contact fitting no color is solved one at a time after. The colors solve contacts in another order than one at a time would, which gives the same bits as solving them one at a time in that order.
  • Joints: a joint holds two bodies at anchors of their own, and its bodies don't meet but where it says they do. A revolute joint, or a hinge in space, holds them at a point, a hinge about an axis of each too, with limits to how far it turns, a motor turning it at a speed with as much torque as it's given, and a spring toward where it rests; a distance joint keeps two points as far apart as its length, as a rod, or between its limits, as a rope, or springily; a weld, or a fixed joint, holds them as one, rigidly or springily; and a ball joint holds them at a point they turn about every way. Joints are solved before contacts in each substep, softly, as stiff springs of 60 cycles a second, and a limit pushes as a contact does, only as much as closes it where it's apart. A pin's and a hinge's limits, motor, and spring push as hard as turning the body about the joint, its mass as far from it as its center is, takes, not about its center, so a door striking its stop stops there, rather than the point the joint holds it at turning it back.
  • Sleep: bodies touching or joined are an island, found anew each step, and an island sleeps when all its bodies have moved slower than 5 centimeters a second, at their farthest, for half a second. A sleeping body costs nothing: its pairs aren't met again, and the solver passes it over. It wakes, with its island, where a force, an impulse, or a velocity is given it, where what touches it is awake and moving, where a joint is made or taken from it, or where what it rested on is taken away. A kinematic body sleeps alone, when it's been still as long, and keeps what rests on it awake while it moves.
  • Units: lengths are a game's own, and a space's tolerances, its slop, margins, push speed, bounce threshold, and top speed of 400 meters a second, are made for a meter; space::new takes how many of a game's lengths a meter is, so a game of pixels keeps its tolerances as many meters.
  • 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 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.

malunal.physics2d.bench steps two of Box2D v3.2's benchmark scenes, built as its benchmark builds them, and malunal.physics3d.bench two of Jolt v5.6's performance test scenes, each built as it builds them; Box2D and Jolt were built with GCC 16.2 at -O2, each on one thread, Box2D with its SIMD both on, AVX2, and off, and every time is of a step at 60 steps a second, on a Ryzen 9 9950X3D:

Scene Box2D, AVX2 Box2D, no SIMD Jolt physics2d or physics3d
large_pyramid: 5050 boxes, 100 at the base, 500 steps 0.97 ms 2.45 ms 7.24 ms 3.0x Box2D's scalar
many_pyramids: 400 pyramids of 55 boxes, 200 steps 3.9 ms 9.4 ms 29.3 ms 3.1x
Pyramid: 1240 boxes in 15 tiers, 500 steps 6.17 ms 32.8 ms 5.3x Jolt's
ConvexVsMesh: 1764 shapes onto 20000 triangles, 500 steps, sleeping 2.09 ms 12.7 ms 6.1x

These are with the compiler of 2026-10-31; with that of 2026-10-30 they were 11.9, 47.4, 41.3, and 17.1 ms, with the same results to the bit.

Stacks stand about as Box2D's do. Box2D's large pyramid ends its 500 steps with its top box 0.74 meters lower, squeezed, and 0.27 meters to one side, after 0.77 at the hundredth step; physics2d's with its top 0.84 lower and 0.88 to one side, the colors' order of solving pushing it the way it goes, as one at a time in that order does to the bit. Of the many pyramids, the last one's top box ends within 8 millimeters of where it began; and in Jolt's pyramid, physics3d's top box settles within 6 millimeters of the height its tiers stack it to, 8 centimeters aside from where it fell, where Jolt's own wasn't measured.

The difference was the compiler's more than the solver's, and the compiler of 2026-10-31 closed some of it: it keeps small vectors, and the values a statement's temporaries hold, out of memory, so a contact solved with vec2s runs nearly as fast as one worked a number at a time; it works f32s, their comparisons, and the choices between them as f32s, with no branch to choose; and it keeps eight lanes in registers where the processor has AVX. What's left, as profiled: the solver of eight lanes spills, its vectors given 11 of the processor's 16 registers; math::min and math::max of reals test for NaN and signed zeros around each; in space, meeting two boxes still calls cross and makes a rotation's matrix, and zeroes six kilobytes of arrays each time; and contacts in space are solved one at a time, where Jolt's are four at once.

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.

malunal.physics3d.tests runs tests/physics3d.sakura: poses, within one another, found again, and undone; boxes' faces facing out, each edge between two at right angles, turned and moved; hulls around a cube's corners and places within it, on its faces, and along its edges, of six square faces, a tetrahedron, and an icosahedron of 20 triangles, and none of flat places or of 40 corners; triangles, flat; spheres and capsules meeting, touching, apart, and within a margin, capsules lying along one another at two points and crossing at one; a ball on a box's face, by its edge, by its corner, within it, both ways around, and over a turned box; a capsule lying on a box at two points, standing by its edge at one, and stood within it; a crate resting on a slab at four points, apart, within a margin, the other way around, and turned, on its edge at two, on its corner at one, and edge across edge at one; rays meeting a ball, a turned box, and a capsule's side, along and across it, and its end; 500 boxes in a tree, as in physics2d's; and a room of triangles, a floor of 128 and a wall: a crate resting across four squares, a ball sunk beside a seam pushed up by every triangle, against the wall, and in its corner, and rays into its floor, from below it, and into its wall. Then, against searches of their own: 400 pairs of boxes and of hulls of places, turned every way, met where no axis of every face and every pair of edges parts them, and as deep as the axis parting them least, to within the faces taken over others as good; and 200 spheres and capsules against turned boxes, met as their nearest places say, a capsule's found among a thousand along its segment.

malunal.physics2d.tests runs tests/space2d.sakura too: the masses of boxes, circles, capsules, and shapes moved off their bodies' origins, and two summed; a box dropped onto the ground, resting on it, still, and touching it once; a tower of ten boxes standing still; bodies sleeping, woken by a blow with what they rest on but not what's apart, and what rested on a body taken away waking and falling; a ball bouncing as high as it fell, and on a slope of 30 degrees a box of friction staying and one of none sliding; a body on a layer the ground's mask doesn't hold falling through, and a sensor noting a stone falling through it; a kinematic lift carrying a crate; a pendulum keeping its length, a wheel turned by its motor, a door stopped by its limit, a rod, and a weld; a box sliding across a grid's floor of 40 cells without catching at its seams, stopped by its wall; and rays.

malunal.physics3d.tests runs tests/space3d.sakura the same: boxes', balls', hulls', and capsules' masses and inertia tensors, and two summed; and in space, as in a plane, a box dropped, a tower, sleeping and waking, bouncing and sliding, layers and sensors, a kinematic lift, a ball joint's pendulum, a wheel turned by a hinge's motor, a door swung against its hinge's limit, stopped there, a rod and a fixed joint; a box sliding across a mesh's floor of 800 triangles without sinking, bouncing, slowing, or turning at its seams; and rays meeting shapes and a mesh's triangle.

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: shapes swept along a motion, as time of impact finds where they first meet, so what's fast never passes through what's thin, as Box2D's continuous collision keeps a fast body from passing what's static; prismatic, wheel, motor, and mouse joints; rounded polygons; chains of segments, one-way platforms, and terrain; queries of a space by shapes, and shapes cast through it; rolling resistance and moving surfaces, as a conveyor's; and steps solved on several threads, as the colors let. Of physics3d: its contacts solved as lanes, as a plane's are; shapes swept along a motion; slider, cone and twist, and six-way joints, as a ragdoll's limbs are held, and a ball joint's limits; a character's body that walks, steps up, and is pushed; cylinders, rounded hulls, and hulls of more than 32 corners, made fewer; heightfields; a mesh's triangles kept by a tree built once, from the top down, rather than one inserted at a time, and a triangle met without making a whole hull of it each time; queries by shapes, and shapes cast; turning bodies' gyroscopic torque; and steps on several threads. Of both: the speed Box2D and Jolt reach, which waits on what sakurac makes of small vectors, lanes of eight, and arrays it zeroes.