Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-10-30 13:26:21 -05:00
commit 80f851a1f6
34 files changed
+4606

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
+1
View File
@@ -0,0 +1 @@
.blossom
+171
View File
@@ -0,0 +1,171 @@
# 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 |
|---|---|
| `linear` | Vectors of two, three, and four `f32`s, rotations as quaternions, and matrices of three by three and four by four |
| `geometry` | The shapes of space made of them, rays, planes, boxes, spheres, and a camera's frustum, and the tests between them |
| `photometry` | Light in the units it's measured in, lumens, candela, lux, and nits, converted between them; exposure values; and the colors of temperatures |
| `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](https://git.malunal.studio/sakura/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.
```sakura
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();
```
```sakura
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
```
```sakura
import linear;
import 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
```
```sakura
import linear;
import 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`; each brings `linear`, which they read:
```yaml
requires:
- https://git.malunal.studio/malunal/physics@v1.0.0
targets:
- name: game
type: program
deps: [geometry, photometry, physics2d]
```
## Layout
| Path | Holds |
|---|---|
| `linear/linear.sakura` | The conventions, and reading a value of four `f32`s 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 * 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 `vec3`s, 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 `f32`s. 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.
- **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 `f32`s 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 `vec3`s | 9.66 ns | 2.00 ns | 4.8x |
| `dot` of `vec3`s | 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; 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 `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; 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.
`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.
`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 `vec3`s in three `f32x8`s, 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 `vec2`s 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.
+124
View File
@@ -0,0 +1,124 @@
name: physics
gpid: malunal
semv: 1.0.0
options:
level: 2
requires:
- https://git.malunal.studio/sakura/std@v1.0.0
targets:
- name: linear
type: library
root: ./linear
deps:
- std.math
- std.serial
# The shapes of space, made of `linear`'s vectors, and the tests between them.
- name: geometry
type: library
root: ./geometry
deps:
- linear
- std.math
- std.serial
# Light in the units it's measured in, lumens, candela, lux, and nits, and
# converted between them; exposure values; and the colors of temperatures.
- name: photometry
type: library
root: ./photometry
deps:
- linear
- std.math
# What collides in a plane: shapes, where and how deep two meet, rays, a tree
# of boxes, and a grid of solid cells, as a tilemap's walls are.
- name: physics2d
type: library
root: ./physics2d
deps:
- linear
- std.containers
- std.math
- std.serial
# Times what `linear` does against the same written a number at a time; see
# its header.
- name: linear.bench
type: program
level: ${level}
deps:
- linear
- std.containers
- std.io
- std.math
- std.time
srcs:
- tools/bench.sakura
# Times what `geometry` does against the same written a number at a time; see
# its header.
- name: geometry.bench
type: program
level: ${level}
deps:
- geometry
- linear
- std.containers
- std.io
- std.math
- std.time
srcs:
- tools/geometry_bench.sakura
tests:
# On the machine, which works each number at a time.
- name: linear.tests
type: program
deps: [linear, std.json, std.math, std.serial, std.testing]
srcs: [tests/main.sakura, tests/linear.sakura]
# The same tests built with `-O2`, which works vectors as lanes, and gives the
# same bits.
- name: linear.lanes.tests
type: program
runs: native
level: 2
deps: [linear, std.json, std.math, std.serial, std.testing]
srcs: [tests/main.sakura, tests/linear.sakura]
# `geometry`'s, the same two ways.
- name: geometry.tests
type: program
deps: [geometry, linear, std.json, std.math, std.serial, std.testing]
srcs: [tests/main.sakura, tests/geometry.sakura]
- name: geometry.lanes.tests
type: program
runs: native
level: 2
deps: [geometry, linear, std.json, std.math, std.serial, std.testing]
srcs: [tests/main.sakura, tests/geometry.sakura]
- name: photometry.tests
type: program
deps: [linear, photometry, std.math, std.testing]
srcs: [tests/main.sakura, tests/photometry.sakura]
- name: physics2d.tests
type: program
deps: [linear, physics2d, std.containers, std.math, std.testing]
srcs: [tests/main.sakura, tests/physics2d.sakura]
exports:
- linear
- geometry
- photometry
- physics2d
package:
desc: The numbers of physical space and what's in it. Vectors, quaternions, and matrices of f32, and the shapes of space made of them, worked as SIMD lanes where an executable holds them; light in the units it's measured in; and what collides in a plane.
auth: John Christman <sorakatadzuma@gmail.com>
+121
View File
@@ -0,0 +1,121 @@
#! Contains `bounds`, a box along the axes: the least corner and the greatest of
#! what it holds, as of a mesh, a body, or a part of a scene, so whether two
#! meet, or a ray or a camera reaches one, is a few comparisons.
import std::math;
import std::serial;
import linear;
module geometry;
#! A box along the axes, from its least corner to its greatest.
@serial
pub struct bounds {
@serial pub var min: vec3;
@serial pub var max: vec3;
}
#! The box holding nothing, from infinity to minus infinity, which takes the
#! place or box it's first grown by.
pub val bounds::empty := bounds{
vec3{ math::infinity::<f32>(), math::infinity::<f32>(), math::infinity::<f32>() },
vec3{ -math::infinity::<f32>(), -math::infinity::<f32>(), -math::infinity::<f32>() },
};
#! The box of a center, reaching so far from it along each axis.
pub def bounds::around(center: vec3, half_size: vec3): bounds {
return bounds{ center - half_size, center + half_size };
}
#! The least box holding places, or `empty` of none.
pub def bounds::of(points: span<vec3>): bounds {
var made := bounds::empty;
for p in points {
made = made.including(p);
}
return made;
}
#! The least box holding a sphere.
pub def bounds::of(s: sphere): bounds {
return bounds::around(s.center, vec3{ s.radius, s.radius, s.radius });
}
pub val bounds::center: vec3 {
get => (this.min + this.max) * 0.5;
}
pub val bounds::size: vec3 {
get => this.max - this.min;
}
#! How far it reaches from its center along each axis.
pub val bounds::half_size: vec3 {
get => (this.max - this.min) * 0.5;
}
#! Whether it holds nothing, as `empty` does: a least corner past its greatest.
pub val bounds::is_empty: bool {
get => this.min.x > this.max.x || this.min.y > this.max.y || this.min.z > this.max.z;
}
pub def bounds::equals(&this, other: &bounds): bool {
return this.min == other.min && this.max == other.max;
}
#! Whether a place is within it.
pub def bounds::contains(&this, p: vec3): bool {
return p.x >= this.min.x && p.y >= this.min.y && p.z >= this.min.z
&& p.x <= this.max.x && p.y <= this.max.y && p.z <= this.max.z;
}
#! Whether another box is within it whole.
pub def bounds::contains(&this, other: bounds): bool {
return this.contains(other.min) && this.contains(other.max);
}
#! Whether it and another box meet.
pub def bounds::overlaps(&this, other: bounds): bool {
return this.min.x <= other.max.x && this.min.y <= other.max.y && this.min.z <= other.max.z
&& this.max.x >= other.min.x && this.max.y >= other.min.y && this.max.z >= other.min.z;
}
#! Whether it and a sphere meet.
pub def bounds::overlaps(&this, s: sphere): bool {
return s.overlaps(this);
}
#! Its place nearest another: the place itself where it's within.
pub def bounds::closest(&this, p: vec3): vec3 {
return p.max(this.min).min(this.max);
}
#! The box grown to hold a place too.
pub def bounds::including(&this, p: vec3): bounds {
return bounds{ this.min.min(p), this.max.max(p) };
}
#! The least box holding it and another.
pub def bounds::merged(&this, other: bounds): bounds {
return bounds{ this.min.min(other.min), this.max.max(other.max) };
}
#! The least box along the axes holding this one moved, turned, and scaled by a
#! matrix that doesn't project: its center moved, and its reach along each of
#! its own axes turned, each number made positive, and added.
pub def bounds::transformed(&this, by: mat4): bounds {
return bounds::empty if this.is_empty;
val half := this.half_size;
val m := &by.m;
if lanes_held() {
# Each column as lanes, read where it lies, as `mat4`'s products read them.
val reach := lanes_at(&m[0]).abs() * f32x4::splat(half.x) + lanes_at(&m[4]).abs() * f32x4::splat(half.y)
+ lanes_at(&m[8]).abs() * f32x4::splat(half.z);
return bounds::around(by.transform_point(this.center), vec3::of_lanes(reach));
}
val reach := vec3{
math::abs(m[0]) * half.x + math::abs(m[4]) * half.y + math::abs(m[8]) * half.z,
math::abs(m[1]) * half.x + math::abs(m[5]) * half.y + math::abs(m[9]) * half.z,
math::abs(m[2]) * half.x + math::abs(m[6]) * half.y + math::abs(m[10]) * half.z,
};
return bounds::around(by.transform_point(this.center), reach);
}
+137
View File
@@ -0,0 +1,137 @@
#! Contains `frustum`, the part of space a camera sees: the six planes bounding
#! what a projection draws, each facing in, and whether a place, a box, or a
#! sphere is within them, so a renderer draws only what might be seen. The
#! planes' numbers are lanes, so an executable holding vectors in registers
#! tests four planes at once, then the other two: as two vectors of four, which
#! it holds in registers as it works them, where one of eight went through
#! memory a half at a time, twice as slow.
import linear;
module geometry;
#! The part of space a camera sees, within six planes facing in: left, right,
#! bottom, top, near, and far. It holds their normals' `x`s, `y`s, and `z`s, and
#! how far the origin is in front of each, eight of each, read as two `f32x4`s;
#! the last two are of planes of zeros, which nothing is behind.
pub struct frustum {
var _x: f32[8];
var _y: f32[8];
var _z: f32[8];
var _d: f32[8];
}
#! The frustum of what a matrix projects into its clip space, its planes in the
#! space it projects from: of `projection * view`, the world's, and of a
#! projection alone, the camera's. Clip space bounds x and y between -w and w,
#! and depth between 0 and w, so each plane is the matrix's row of w with
#! another row added or taken away, and the near plane its row of depth alone.
pub def frustum::of(clip: mat4): frustum {
val m := &clip.m;
val x := vec4{ m[0], m[4], m[8], m[12] };
val y := vec4{ m[1], m[5], m[9], m[13] };
val z := vec4{ m[2], m[6], m[10], m[14] };
val w := vec4{ m[3], m[7], m[11], m[15] };
return frustum::of_planes([plane_of(w + x), plane_of(w - x), plane_of(w + y), plane_of(w - y), plane_of(z), plane_of(w - z)]);
}
# The plane of a matrix's row: the places that, with a 1 after them, it makes
# 0 of, in front where it makes more, made of length 1.
def plane_of(row: vec4): plane {
val l := row.xyz.length;
return plane{ row.xyz / l, -row.w / l };
}
#! The frustum of six planes facing in: left, right, bottom, top, near, and far.
pub def frustum::of_planes(planes: plane[6]): frustum {
var made := frustum{};
for i in 0..6u {
made._x[i] = planes[i].normal.x;
made._y[i] = planes[i].normal.y;
made._z[i] = planes[i].normal.z;
made._d[i] = -planes[i].distance;
}
return made;
}
#! Its planes: left, right, bottom, top, near, and far.
pub val frustum::planes: plane[6] {
get {
var made: plane[6];
for i in 0..6u {
made[i] = plane{ vec3{ this._x[i], this._y[i], this._z[i] }, -this._d[i] };
}
return made;
}
}
#! Whether a place is within it.
pub def frustum::contains(&this, p: vec3): bool {
if lanes_held() {
val x := f32x4::splat(p.x);
val y := f32x4::splat(p.y);
val z := f32x4::splat(p.z);
return in_front(this.ahead(0, x, y, z), this.ahead(4, x, y, z));
}
for i in 0..6u {
return false if this._x[i] * p.x + this._y[i] * p.y + this._z[i] * p.z + this._d[i] < 0;
}
return true;
}
#! Whether a box might be seen: whether, of each plane, the box's corner
#! furthest in front of it is in front. A box beside a corner of the frustum,
#! outside it but in front of every plane, counts as seen, which a renderer
#! draws for nothing; one it reaches always counts.
pub def frustum::overlaps(&this, b: bounds): bool {
if lanes_held() {
return in_front(this.ahead_of(0, &b), this.ahead_of(4, &b));
}
for i in 0..6u {
val x := this._x[i] < 0 ? b.min.x : b.max.x;
val y := this._y[i] < 0 ? b.min.y : b.max.y;
val z := this._z[i] < 0 ? b.min.z : b.max.z;
return false if this._x[i] * x + this._y[i] * y + this._z[i] * z + this._d[i] < 0;
}
return true;
}
#! Whether a sphere might be seen: whether its center is no further behind any
#! plane than its radius. As of a box, one beside a corner counts too.
pub def frustum::overlaps(&this, s: sphere): bool {
val c := s.center;
if lanes_held() {
val x := f32x4::splat(c.x);
val y := f32x4::splat(c.y);
val z := f32x4::splat(c.z);
val r := f32x4::splat(s.radius);
return in_front(this.ahead(0, x, y, z) + r, this.ahead(4, x, y, z) + r);
}
for i in 0..6u {
return false if this._x[i] * c.x + this._y[i] * c.y + this._z[i] * c.z + this._d[i] + s.radius < 0;
}
return true;
}
# How far places, a lane each, are in front of four planes from one, as lanes.
def frustum::ahead(&this, first: u64, x: f32x4, y: f32x4, z: f32x4): f32x4 {
return lanes_at(&this._x[first]) * x + lanes_at(&this._y[first]) * y + lanes_at(&this._z[first]) * z + lanes_at(&this._d[first]);
}
# How far a box's corner furthest in front of each of four planes from one is
# in front of it, as lanes.
def frustum::ahead_of(&this, first: u64, b: &bounds): f32x4 {
val zero := f32x4::splat(0);
val x := lanes_at(&this._x[first]);
val y := lanes_at(&this._y[first]);
val z := lanes_at(&this._z[first]);
return x * select(x.less(&zero), f32x4::splat(b.min.x), f32x4::splat(b.max.x))
+ y * select(y.less(&zero), f32x4::splat(b.min.y), f32x4::splat(b.max.y))
+ z * select(z.less(&zero), f32x4::splat(b.min.z), f32x4::splat(b.max.z)) + lanes_at(&this._d[first]);
}
# Whether something is in front of each of eight planes, by how far it's in
# front of each, as lanes.
def in_front(first: f32x4, last: f32x4): bool {
val zero := f32x4::splat(0);
return (first.less(&zero) | last.less(&zero)).none();
}
+51
View File
@@ -0,0 +1,51 @@
#! Contains `geometry`: the shapes of space, made of `linear`'s vectors, and
#! what games, their renderers, and their physics ask of them: where a ray first
#! meets a plane, a sphere, or a box, which side of a plane something lies on,
#! whether boxes and spheres meet or hold a place, and whether a camera's
#! frustum reaches something, so only what it might see is drawn.
#!
#! Space is `linear`'s: right-handed, y up, and a camera looking down its -z. A
#! frustum is of a matrix's clip space as `linear`'s projections make it, depth
#! from 0 at the near plane to 1 at the far one.
#!
#! Each shape is of `linear`'s vectors and plain `f32`s, worked as lanes where
#! `linear` works them, and a frustum holds its six planes' numbers a lane
#! each, so an executable optimized with `-O2` tests a place, a box, or a sphere
#! against four planes at once, then the other two. What gives a number of a
#! few, as a dot product does, is a number at a time, as `linear`'s `cross` is:
#! lanes taken apart to be added, then worked as numbers, ran two to three times
#! as slow. The virtual machine works everything a number at a time, in the order
#! the lanes do, so either way gives the same answers and the same bits.
#!
#! A place exactly on a shape's surface is within it: a box holds its corners,
#! a sphere the places at its radius, and two boxes touching meet.
import linear;
module geometry;
# The dot product of two vectors, a number at a time, in the order `vec3::dot`
# adds them.
def dot_of(a: &vec3, b: &vec3): f32 {
return a.x * b.x + a.y * b.y + a.z * b.z;
}
# The square of the distance between two places, a number at a time, as the
# dot product of `a - b` with itself gives it.
def distance_squared(a: &vec3, b: &vec3): f32 {
val x := a.x - b.x;
val y := a.y - b.y;
val z := a.z - b.z;
return x * x + y * y + z * z;
}
# The lesser of two numbers, and the greater: of a NaN, either may be given,
# where `math::min` and `math::max` work three times as long to give it.
def least(a: f32, b: f32): f32 { return b < a ? b : a; }
def most(a: f32, b: f32): f32 { return a < b ? b : a; }
# Four numbers as lanes, read from where the first lies, which needs no
# alignment.
def lanes_at(first: &f32): f32x4 {
return ((first as *f32) as *f32x4)[0];
}
+72
View File
@@ -0,0 +1,72 @@
#! Contains `plane`, a flat surface without end, and which side of one something
#! lies on: what bounds a frustum, a floor or a wall a ray meets, and what splits
#! a space in two.
import std::serial;
import linear;
module geometry;
#! A plane: the places as far along its normal, a direction of length 1, as
#! `distance`. Its front is the side the normal points to.
@serial
pub struct plane {
@serial pub var normal: vec3;
@serial pub var distance: f32;
}
#! Which side of a plane something lies on.
pub enum side: u8 {
front, #! Wholly where the normal points.
back, #! Wholly behind.
across, #! On both sides, or touching it.
}
#! The plane through a place, facing a direction, made of length 1.
pub def plane::through(point: vec3, normal: vec3): plane {
val n := normal.normalized();
return plane{ n, n.dot(point) };
}
#! The plane through three places, facing where they turn counterclockwise, as
#! a triangle's front does.
pub def plane::of_points(a: vec3, b: vec3, c: vec3): plane {
return plane::through(a, (b - a).cross(c - a));
}
pub def plane::equals(&this, other: &plane): bool {
return this.normal == other.normal && this.distance == other.distance;
}
#! How far a place is in front of the plane, negative behind it.
pub def plane::distance_to(&this, p: vec3): f32 {
return dot_of(&this.normal, &p) - this.distance;
}
#! The plane's place nearest another.
pub def plane::closest(&this, p: vec3): vec3 {
return p - this.normal * this.distance_to(p);
}
#! The same plane facing the other way.
pub def plane::flipped(&this): plane {
return plane{ -this.normal, -this.distance };
}
#! Which side of the plane a box lies on: how far its center is in front,
#! against how far the box reaches along the normal.
pub def plane::side_of(&this, b: bounds): side {
val half := b.half_size;
return side_at(this.distance_to(b.center), dot_of(&half, &this.normal.abs()));
}
#! Which side of the plane a sphere lies on.
pub def plane::side_of(&this, s: sphere): side {
return side_at(this.distance_to(s.center), s.radius);
}
# The side of what is centered so far in front of a plane, and reaches so far.
def side_at(at: f32, reach: f32): side {
return side::front if at > reach;
return side::back if at < -reach;
return side::across;
}
+88
View File
@@ -0,0 +1,88 @@
#! Contains `ray`, a half line from a place in a direction, and where it first
#! meets a plane, a sphere, or a box, as picking what's under a pointer, a line
#! of sight, or a shot asks.
import std::math;
import std::serial;
import linear;
module geometry;
#! A half line from a place in a direction. How far along it something lies is
#! counted in lengths of its direction, so it's a distance where the direction
#! is of length 1, as `toward` makes it.
@serial
pub struct ray {
@serial pub var origin: vec3;
@serial pub var direction: vec3;
}
#! The ray from a place toward another, its direction of length 1.
pub def ray::toward(origin: vec3, target: vec3): ray {
return ray{ origin, (target - origin).normalized() };
}
pub def ray::equals(&this, other: &ray): bool {
return this.origin == other.origin && this.direction == other.direction;
}
#! The place so far along it.
pub def ray::at(&this, t: f32): vec3 {
return this.origin + this.direction * t;
}
#! Its place nearest another, from its origin on.
pub def ray::closest(&this, p: vec3): vec3 {
val d := &this.direction;
val toward := (p.x - this.origin.x) * d.x + (p.y - this.origin.y) * d.y + (p.z - this.origin.z) * d.z;
val along := toward / dot_of(d, d);
return this.at(along > 0 ? along : 0);
}
#! How far along it it meets a plane, from either side, or none where it runs
#! beside the plane or away from it.
pub def ray::hit(&this, p: plane): maybe<f32> {
val toward := dot_of(&p.normal, &this.direction);
return nothing {} if toward == 0;
val t := p.distance_to(this.origin) / -toward;
return nothing {} if !(t >= 0);
return t;
}
#! How far along it it first meets a sphere, 0 where it begins within, or none
#! where it passes by or away.
pub def ray::hit(&this, s: sphere): maybe<f32> {
val d := &this.direction;
val mx := this.origin.x - s.center.x;
val my := this.origin.y - s.center.y;
val mz := this.origin.z - s.center.z;
val c := mx * mx + my * my + mz * mz - s.radius * s.radius;
return 0f if c <= 0;
# Outside, and moving away from the center or across it, it never comes nearer.
val b := mx * d.x + my * d.y + mz * d.z;
return nothing {} if b >= 0;
val a := dot_of(d, d);
val e := b * b - a * c;
return nothing {} if e < 0;
return (-b - math::sqrt(e)) / a;
}
#! How far along it it first meets a box, 0 where it begins within, or none
#! where it passes by or away: where it is between the box's faces along every
#! axis at once. One along a face, in its plane, may meet the box or pass by.
pub def ray::hit(&this, b: bounds): maybe<f32> {
# Along an axis it doesn't move along, it's between the faces everywhere, or
# nowhere, as dividing by zero gives infinities.
val ix := 1 / this.direction.x;
val iy := 1 / this.direction.y;
val iz := 1 / this.direction.z;
val x0 := (b.min.x - this.origin.x) * ix;
val x1 := (b.max.x - this.origin.x) * ix;
val y0 := (b.min.y - this.origin.y) * iy;
val y1 := (b.max.y - this.origin.y) * iy;
val z0 := (b.min.z - this.origin.z) * iz;
val z1 := (b.max.z - this.origin.z) * iz;
val enter := most(most(least(x0, x1), least(y0, y1)), most(least(z0, z1), 0));
val leave := least(least(most(x0, x1), most(y0, y1)), most(z0, z1));
return nothing {} if !(enter <= leave);
return enter;
}
+40
View File
@@ -0,0 +1,40 @@
#! Contains `sphere`, the places within a distance of a center: what holds a
#! body for the quickest test of whether two might meet, their distance against
#! the sum of their radii.
import std::serial;
import linear;
module geometry;
#! The places within `radius` of `center`.
@serial
pub struct sphere {
@serial pub var center: vec3;
@serial pub var radius: f32;
}
#! The least sphere holding a box: of its center, reaching its corners.
pub def sphere::of(b: bounds): sphere {
return sphere{ b.center, b.half_size.length };
}
pub def sphere::equals(&this, other: &sphere): bool {
return this.center == other.center && this.radius == other.radius;
}
#! Whether a place is within it.
pub def sphere::contains(&this, p: vec3): bool {
return distance_squared(&p, &this.center) <= this.radius * this.radius;
}
#! Whether it and another sphere meet.
pub def sphere::overlaps(&this, other: sphere): bool {
val reach := this.radius + other.radius;
return distance_squared(&other.center, &this.center) <= reach * reach;
}
#! Whether it and a box meet: whether the box's place nearest its center is
#! within it.
pub def sphere::overlaps(&this, b: bounds): bool {
return this.contains(b.closest(this.center));
}
+43
View File
@@ -0,0 +1,43 @@
#! Contains `linear`: vectors of two, three, and four `f32`s, 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.
#!
#! Space is right-handed: x to the right, y up, and z toward the viewer, so a
#! camera looks down its own -z. A matrix is column-major, as GLSL reads one,
#! and multiplies a vector on its right: `m * v`. 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
#! is with its y flipped. Angles are radians.
#!
#! Each type is of plain `f32` fields, so it's laid out as C and the GPU lay
#! out its numbers, and the virtual machine reads a field as quickly as any.
#! `vec3`, `vec4`, and `quat` are 16 bytes, `vec3` holding a fourth number no one
#! names, so an executable optimized with `-O2`, which holds `simd` vectors in
#! registers, reads each as one `f32x4` from where it is, and works it as lanes
#! at once: adding, scaling, dots, lengths, 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. What gathers one vector's numbers into
#! other lanes, as a cross product and a quaternions' product would, it works a
#! number at a time, as `simd::shuffle` gathers them a lane at a time. The
#! virtual machine, which works lanes one at a time, works everything a number
#! at a time, in the order the lanes do, so both ways give the same bits.
#!
#! A product is rounded before it's added, not fused with the sum as `fma` does:
#! a column waiting on the fused sum before it is slower than one adding
#! products worked at once, and the virtual machine would work each fused sum
#! as `std::math` does without FMA3, many instructions for one.
module linear;
# The lanes of a value of four `f32`s, as `vec3`, `vec4`, and `quat` are, read
# from where it is, which needs no alignment.
def lanes_of<T>(v: &T): f32x4 {
return ((v as *T) as *f32x4)[0];
}
# The value of four `f32`s whose numbers are lanes.
def of_lanes<T>(lanes: f32x4): T where T: zeroable {
var made: T;
((&mut made) as *mut f32x4)[0] = lanes;
return made;
}
+104
View File
@@ -0,0 +1,104 @@
#! Contains `mat3`, a matrix of three by three: a rotation, a scale, or what
#! turns and stretches a direction without moving it, as an inertia tensor
#! does. Its columns are `vec3`s, each 16 bytes, so it's laid out as std140
#! lays out a GLSL `mat3`, and its columns are added and scaled as lanes.
import std::serial;
module linear;
#! A matrix of three by three, column after column: where it takes x, y, and z.
@serial
pub struct mat3 {
@serial pub var x_axis: vec3;
@serial pub var y_axis: vec3;
@serial pub var z_axis: vec3;
}
#! The matrix that changes nothing.
pub val mat3::identity := mat3{ vec3::right, vec3::up, vec3::back };
#! Turning by a rotation.
pub def mat3::rotation(by: quat): mat3 {
val q := by;
val xx := q.x * q.x;
val yy := q.y * q.y;
val zz := q.z * q.z;
val xy := q.x * q.y;
val xz := q.x * q.z;
val yz := q.y * q.z;
val wx := q.w * q.x;
val wy := q.w * q.y;
val wz := q.w * q.z;
return mat3{
vec3{ 1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy) },
vec3{ 2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx) },
vec3{ 2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy) },
};
}
#! Scaling along each axis.
pub def mat3::scaling(by: vec3): mat3 {
return mat3{ vec3{ by.x, 0, 0 }, vec3{ 0, by.y, 0 }, vec3{ 0, 0, by.z } };
}
#! The matrix doing another, then this: each of the other's columns, as this
#! turns and scales it.
pub def mat3::mul(&this, other: &mat3): mat3 {
return mat3{ this * other.x_axis, this * other.y_axis, this * other.z_axis };
}
#! A direction the matrix turns and scales: each column, scaled by one of its
#! numbers, added.
pub def mat3::mul(&this, v: &vec3): vec3 {
if lanes_held() {
return of_lanes::<vec3>(lanes_of(&this.x_axis) * f32x4::splat(v.x) + lanes_of(&this.y_axis) * f32x4::splat(v.y)
+ lanes_of(&this.z_axis) * f32x4::splat(v.z));
}
return vec3{
this.x_axis.x * v.x + this.y_axis.x * v.y + this.z_axis.x * v.z,
this.x_axis.y * v.x + this.y_axis.y * v.y + this.z_axis.y * v.z,
this.x_axis.z * v.x + this.y_axis.z * v.y + this.z_axis.z * v.z,
};
}
pub def mat3::mul(&this, by: &f32): mat3 {
return mat3{ this.x_axis * by, this.y_axis * by, this.z_axis * by };
}
pub def mat3::add(&this, other: &mat3): mat3 {
return mat3{ this.x_axis + other.x_axis, this.y_axis + other.y_axis, this.z_axis + other.z_axis };
}
pub def mat3::sub(&this, other: &mat3): mat3 {
return mat3{ this.x_axis - other.x_axis, this.y_axis - other.y_axis, this.z_axis - other.z_axis };
}
pub def mat3::equals(&this, other: &mat3): bool {
return this.x_axis == other.x_axis && this.y_axis == other.y_axis && this.z_axis == other.z_axis;
}
#! Its rows as its columns, which for a rotation is the rotation back.
pub def mat3::transposed(&this): mat3 {
return mat3{
vec3{ this.x_axis.x, this.y_axis.x, this.z_axis.x },
vec3{ this.x_axis.y, this.y_axis.y, this.z_axis.y },
vec3{ this.x_axis.z, this.y_axis.z, this.z_axis.z },
};
}
#! How much it scales a volume, negative where it mirrors one.
pub val mat3::determinant: f32 {
get => this.x_axis.dot(this.y_axis.cross(this.z_axis));
}
#! The matrix undoing this, or none where nothing can, as a scale of zero: each
#! row the cross product of the other two columns, over the determinant.
pub def mat3::inverse(&this): mat3 {
val a := this.y_axis.cross(this.z_axis);
val b := this.z_axis.cross(this.x_axis);
val c := this.x_axis.cross(this.y_axis);
val det := this.x_axis.dot(a);
# Scaled by 0 where nothing undoes it, so it returns once.
val k := det != 0 ? 1 / det : 0;
return mat3{ a * k, b * k, c * k }.transposed();
}
+258
View File
@@ -0,0 +1,258 @@
#! Contains `mat4`, a matrix of four by four: what moves, turns, and scales a
#! place, or projects it, as a camera does. Its numbers are column after
#! column, so a column is 16 bytes, read as one `f32x4`, and its products are
#! each column scaled and added at once.
import std::math;
import std::serial;
module linear;
#! A matrix of four by four, column after column. `std::serial` writes it as a
#! sequence of its 16 numbers, in the same order.
pub struct mat4 {
pub var m: f32[16];
}
pub def mat4::encode(&this, out: &mut serial::encoder): void {
out.begin_array(16);
for i in 0..16u {
serial::encode(&this.m[i], out);
}
out.end_array();
}
pub def mat4::decode(from: &serial::decoder, at: u32, given: serial::options): result<mat4, serial::error> {
if from.kind_of(at) != serial::kind::array || from.count(at) != 16 {
return serial::error::at(serial::error_kind::wrong_kind, from.place(at));
}
var made := mat4{};
var item: u32 = 0;
for i in 0..16u {
item = i == 0 ? from.element(at, 0) : from.next_element(at, item);
val read := serial::decode::<f32>(from, item, given) else (e) { return e; };
made.m[i] = read;
}
return made;
}
#! The matrix that changes nothing.
pub val mat4::identity := mat4{ m = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] };
#! Moving by a vector.
pub def mat4::translation(by: vec3): mat4 {
var made := mat4::identity;
made.m[12] = by.x;
made.m[13] = by.y;
made.m[14] = by.z;
return made;
}
#! Scaling along each axis.
pub def mat4::scaling(by: vec3): mat4 {
var made := mat4::identity;
made.m[0] = by.x;
made.m[5] = by.y;
made.m[10] = by.z;
return made;
}
#! Turning by a rotation.
pub def mat4::rotation(by: quat): mat4 {
return mat4::compose(vec3::zero, by, vec3::one);
}
#! Scaling, then turning, then moving: what a transform does.
pub def mat4::compose(translation: vec3, rotation: quat, scale: vec3): mat4 {
val q := rotation;
val xx := q.x * q.x;
val yy := q.y * q.y;
val zz := q.z * q.z;
val xy := q.x * q.y;
val xz := q.x * q.z;
val yz := q.y * q.z;
val wx := q.w * q.x;
val wy := q.w * q.y;
val wz := q.w * q.z;
return mat4{ m = [
(1 - 2 * (yy + zz)) * scale.x, 2 * (xy + wz) * scale.x, 2 * (xz - wy) * scale.x, 0,
2 * (xy - wz) * scale.y, (1 - 2 * (xx + zz)) * scale.y, 2 * (yz + wx) * scale.y, 0,
2 * (xz + wy) * scale.z, 2 * (yz - wx) * scale.z, (1 - 2 * (xx + yy)) * scale.z, 0,
translation.x, translation.y, translation.z, 1,
] };
}
#! A perspective projection, as a camera's: its field of view up and down, the
#! width over the height it's drawn at, and the nearest and furthest it draws.
pub def mat4::perspective(fov_y: f32, aspect: f32, near: f32, far: f32): mat4 {
val f := 1 / math::tan(fov_y / 2);
var made := mat4{};
made.m[0] = f / aspect;
made.m[5] = f;
made.m[10] = far / (near - far);
made.m[11] = -1;
made.m[14] = near * far / (near - far);
return made;
}
#! An orthographic projection of a box: its edges, and how near and far it
#! reaches down -z.
pub def mat4::orthographic(left: f32, right: f32, bottom: f32, top: f32, near: f32, far: f32): mat4 {
var made := mat4::identity;
made.m[0] = 2 / (right - left);
made.m[5] = 2 / (top - bottom);
made.m[10] = 1 / (near - far);
made.m[12] = -(right + left) / (right - left);
made.m[13] = -(top + bottom) / (top - bottom);
made.m[14] = near / (near - far);
return made;
}
#! The view of a camera at a place looking at another, y as near to `up` as it
#! can be: what moves the world into the camera's space.
pub def mat4::look_at(eye: vec3, target: vec3, up: vec3 = vec3::up): mat4 {
return mat4::compose(eye, quat::looking(target - eye, up), vec3::one).inverse();
}
#! The matrix doing another, then this: each of the other's columns, each of
#! this one's columns scaled by one of its numbers, added.
pub def mat4::mul(&this, other: &mat4): mat4 {
var made := mat4{};
if lanes_held() {
val c0 := lanes_of(&this.m[0]);
val c1 := lanes_of(&this.m[4]);
val c2 := lanes_of(&this.m[8]);
val c3 := lanes_of(&this.m[12]);
val out := (&mut made) as *mut f32x4;
for c in 0..4u {
out[c] = c0 * f32x4::splat(other.m[c * 4]) + c1 * f32x4::splat(other.m[c * 4 + 1])
+ c2 * f32x4::splat(other.m[c * 4 + 2]) + c3 * f32x4::splat(other.m[c * 4 + 3]);
}
return made;
}
for c in 0..4u {
for r in 0..4u {
made.m[c * 4 + r] = this.m[r] * other.m[c * 4] + this.m[4 + r] * other.m[c * 4 + 1]
+ this.m[8 + r] * other.m[c * 4 + 2] + this.m[12 + r] * other.m[c * 4 + 3];
}
}
return made;
}
#! What the matrix makes of a vector, as a projection makes a place of clip
#! space: each column, scaled by one of its numbers, added.
pub def mat4::mul(&this, v: &vec4): vec4 {
if lanes_held() {
return of_lanes::<vec4>(lanes_of(&this.m[0]) * f32x4::splat(v.x) + lanes_of(&this.m[4]) * f32x4::splat(v.y)
+ lanes_of(&this.m[8]) * f32x4::splat(v.z) + lanes_of(&this.m[12]) * f32x4::splat(v.w));
}
return vec4{
this.m[0] * v.x + this.m[4] * v.y + this.m[8] * v.z + this.m[12] * v.w,
this.m[1] * v.x + this.m[5] * v.y + this.m[9] * v.z + this.m[13] * v.w,
this.m[2] * v.x + this.m[6] * v.y + this.m[10] * v.z + this.m[14] * v.w,
this.m[3] * v.x + this.m[7] * v.y + this.m[11] * v.z + this.m[15] * v.w,
};
}
pub def mat4::equals(&this, other: &mat4): bool {
for i in 0..16u {
return false if this.m[i] != other.m[i];
}
return true;
}
#! A place moved by the matrix, which moves, turns, and scales but doesn't
#! project.
pub def mat4::transform_point(&this, p: vec3): vec3 {
if lanes_held() {
return of_lanes::<vec3>(lanes_of(&this.m[0]) * f32x4::splat(p.x) + lanes_of(&this.m[4]) * f32x4::splat(p.y)
+ lanes_of(&this.m[8]) * f32x4::splat(p.z) + lanes_of(&this.m[12]));
}
return vec3{
this.m[0] * p.x + this.m[4] * p.y + this.m[8] * p.z + this.m[12],
this.m[1] * p.x + this.m[5] * p.y + this.m[9] * p.z + this.m[13],
this.m[2] * p.x + this.m[6] * p.y + this.m[10] * p.z + this.m[14],
};
}
#! A direction turned and scaled by the matrix, which a move doesn't change.
pub def mat4::transform_vector(&this, v: vec3): vec3 {
if lanes_held() {
return of_lanes::<vec3>(lanes_of(&this.m[0]) * f32x4::splat(v.x) + lanes_of(&this.m[4]) * f32x4::splat(v.y)
+ lanes_of(&this.m[8]) * f32x4::splat(v.z));
}
return vec3{
this.m[0] * v.x + this.m[4] * v.y + this.m[8] * v.z,
this.m[1] * v.x + this.m[5] * v.y + this.m[9] * v.z,
this.m[2] * v.x + this.m[6] * v.y + this.m[10] * v.z,
};
}
#! Where the matrix moves the origin to.
pub val mat4::translation_of: vec3 {
get => vec3{ this.m[12], this.m[13], this.m[14] };
}
#! A column, from 0.
pub def mat4::column(&this, which: u64): vec4 {
return vec4{ this.m[which * 4], this.m[which * 4 + 1], this.m[which * 4 + 2], this.m[which * 4 + 3] };
}
#! What it does to directions: its first three columns' first three numbers.
pub def mat4::linear_part(&this): mat3 {
return mat3{
vec3{ this.m[0], this.m[1], this.m[2] },
vec3{ this.m[4], this.m[5], this.m[6] },
vec3{ this.m[8], this.m[9], this.m[10] },
};
}
pub def mat4::transposed(&this): mat4 {
var made := mat4{};
for c in 0..4u {
for r in 0..4u {
made.m[c * 4 + r] = this.m[r * 4 + c];
}
}
return made;
}
#! The matrix undoing this, or none where nothing can, as a scale of zero: of
#! the determinants of two by two its first two columns make, and its last
#! two, each cofactor of three of them, which is half the work of the
#! cofactors written out, a number at a time.
pub def mat4::inverse(&this): mat4 {
val a := &this.m;
val s0 := a[0] * a[5] - a[4] * a[1];
val s1 := a[0] * a[6] - a[4] * a[2];
val s2 := a[0] * a[7] - a[4] * a[3];
val s3 := a[1] * a[6] - a[5] * a[2];
val s4 := a[1] * a[7] - a[5] * a[3];
val s5 := a[2] * a[7] - a[6] * a[3];
val c5 := a[10] * a[15] - a[14] * a[11];
val c4 := a[9] * a[15] - a[13] * a[11];
val c3 := a[9] * a[14] - a[13] * a[10];
val c2 := a[8] * a[15] - a[12] * a[11];
val c1 := a[8] * a[14] - a[12] * a[10];
val c0 := a[8] * a[13] - a[12] * a[9];
val det := s0 * c5 - s1 * c4 + s2 * c3 + s3 * c2 - s4 * c1 + s5 * c0;
# Scaled by 0 where nothing undoes it, so it returns once.
val k := det != 0 ? 1 / det : 0;
return mat4{ m = [
(a[5] * c5 - a[6] * c4 + a[7] * c3) * k,
(a[2] * c4 - a[1] * c5 - a[3] * c3) * k,
(a[13] * s5 - a[14] * s4 + a[15] * s3) * k,
(a[10] * s4 - a[9] * s5 - a[11] * s3) * k,
(a[6] * c2 - a[4] * c5 - a[7] * c1) * k,
(a[0] * c5 - a[2] * c2 + a[3] * c1) * k,
(a[14] * s2 - a[12] * s5 - a[15] * s1) * k,
(a[8] * s5 - a[10] * s2 + a[11] * s1) * k,
(a[4] * c4 - a[5] * c2 + a[7] * c0) * k,
(a[1] * c2 - a[0] * c4 - a[3] * c0) * k,
(a[12] * s4 - a[13] * s2 + a[15] * s0) * k,
(a[9] * s2 - a[8] * s4 - a[11] * s0) * k,
(a[5] * c1 - a[4] * c3 - a[6] * c0) * k,
(a[0] * c3 - a[1] * c1 + a[2] * c0) * k,
(a[13] * s1 - a[12] * s3 - a[14] * s0) * k,
(a[8] * s3 - a[9] * s1 + a[10] * s0) * k,
] };
}
+143
View File
@@ -0,0 +1,143 @@
#! Contains `quat`, a rotation as a quaternion of length 1: made of an axis and
#! an angle, of angles about each axis, or of a direction to look in; turning
#! vectors, following one another, undone, and turned between at an even rate.
import std::math;
import std::serial;
module linear;
#! A rotation, as a quaternion of length 1.
@serial
pub struct quat {
@serial pub var x: f32;
@serial pub var y: f32;
@serial pub var z: f32;
@serial pub var w: f32 = 1;
}
#! No rotation.
pub val quat::identity := quat{ 0, 0, 0, 1 };
#! Its numbers as lanes, for code of its own to work several at once.
pub def quat::lanes(&this): f32x4 { return lanes_of(this); }
#! The quaternion of lanes.
pub def quat::of_lanes(lanes: f32x4): quat { return of_lanes::<quat>(lanes); }
#! A rotation about an axis, by an angle, counterclockwise as the axis points
#! at the viewer.
pub def quat::axis_angle(axis: vec3, angle: f32): quat {
val a := axis.normalized();
val s := math::sin(angle / 2);
return quat{ a.x * s, a.y * s, a.z * s, math::cos(angle / 2) };
}
#! A rotation by angles about each axis, as a camera's is: about z, its roll,
#! then about x, its pitch, then about y, its yaw.
pub def quat::euler(x: f32, y: f32, z: f32): quat {
return quat::axis_angle(vec3::up, y) * quat::axis_angle(vec3::right, x) * quat::axis_angle(vec3::back, z);
}
#! The rotation turning -z, where a camera looks, to a direction, and y as near
#! to `up` as it can be.
pub def quat::looking(direction: vec3, up: vec3 = vec3::up): quat {
val f := direction.normalized();
var r := f.cross(up).normalized();
if r.length == 0 {
# Looking along `up`, any right will do.
r = f.cross(math::abs(f.x) < 0.9 ? vec3::right : vec3::up).normalized();
}
val u := r.cross(f);
return quat::of_basis(r, u, -f);
}
#! The rotation whose matrix's columns are three axes, at right angles, each of
#! length 1, as `mat3::rotation` gives them.
pub def quat::of_basis(x: vec3, y: vec3, z: vec3): quat {
val trace := x.x + y.y + z.z;
if trace > 0 {
val s := math::sqrt(trace + 1) * 2;
return quat{ (y.z - z.y) / s, (z.x - x.z) / s, (x.y - y.x) / s, s / 4 };
}
if x.x > y.y && x.x > z.z {
val s := math::sqrt(1 + x.x - y.y - z.z) * 2;
return quat{ s / 4, (y.x + x.y) / s, (z.x + x.z) / s, (y.z - z.y) / s };
}
if y.y > z.z {
val s := math::sqrt(1 + y.y - x.x - z.z) * 2;
return quat{ (y.x + x.y) / s, s / 4, (z.y + y.z) / s, (z.x - x.z) / s };
}
val s := math::sqrt(1 + z.z - x.x - y.y) * 2;
return quat{ (z.x + x.z) / s, (z.y + y.z) / s, s / 4, (x.y - y.x) / s };
}
#! The rotation of this after another: `a * b` turns by `b`, then by `a`. A
#! number at a time, which an executable outruns gathering the other's numbers
#! into lanes with.
pub def quat::mul(&this, o: &quat): quat {
return quat{
o.x * this.w + o.w * this.x + o.z * this.y - o.y * this.z,
o.y * this.w - o.z * this.x + o.w * this.y + o.x * this.z,
o.z * this.w + o.y * this.x - o.x * this.y + o.w * this.z,
o.w * this.w - o.x * this.x - o.y * this.y - o.z * this.z,
};
}
#! A vector turned by the rotation, by its matrix, whose columns are scaled by
#! the vector's numbers and added as lanes, which an executable works three
#! times as fast as the crosses of the rotation's axis.
pub def quat::mul(&this, v: &vec3): vec3 {
return mat3::rotation(this) * v;
}
pub def quat::equals(&this, other: &quat): bool {
return this.x == other.x && this.y == other.y && this.z == other.z && this.w == other.w;
}
pub def quat::dot(&this, other: quat): f32 {
if lanes_held() {
val p := lanes_of(this) * lanes_of(&other);
return p[0] + p[1] + p[2] + p[3];
}
return this.x * other.x + this.y * other.y + this.z * other.z + this.w * other.w;
}
pub val quat::length: f32 {
get => math::sqrt(this.dot(this));
}
#! The rotation back.
pub def quat::inverse(&this): quat {
return quat{ -this.x, -this.y, -this.z, this.w };
}
#! The quaternion at a length of 1, as rounding keeps a rotation turned many
#! times.
pub def quat::normalized(&this): quat {
val l := this.length;
if lanes_held() {
return l > 0 ? of_lanes::<quat>(lanes_of(this) / f32x4::splat(l)) : quat::identity;
}
return l > 0 ? quat{ this.x / l, this.y / l, this.z / l, this.w / l } : quat::identity;
}
#! The rotation a fraction of the way to another, turning at an even rate by
#! the shorter way.
pub def quat::slerp(&this, to: quat, t: f32): quat {
var cos := this.dot(to);
var end := to;
if cos < 0 {
cos = -cos;
end = quat{ -to.x, -to.y, -to.z, -to.w };
}
var a := 1 - t;
var b := t;
if cos < 0.9995 {
val angle := math::acos(cos);
val s := math::sin(angle);
a = math::sin((1 - t) * angle) / s;
b = math::sin(t * angle) / s;
}
val made := quat{ this.x * a + end.x * b, this.y * a + end.y * b, this.z * a + end.z * b, this.w * a + end.w * b };
return made.normalized();
}
+66
View File
@@ -0,0 +1,66 @@
#! Contains `vec2`, a vector of two: a place or a direction in a plane, as of
#! a window's pixels, a glyph's outline, or a texture. It's 8 bytes, half the
#! lanes of an `f32x4`, so it's worked a number at a time.
import std::math;
import std::serial;
module linear;
#! A vector of two: a place or a direction in a plane.
@serial
pub struct vec2 {
@serial pub var x: f32;
@serial pub var y: f32;
}
pub val vec2::zero := vec2{ 0, 0 };
pub val vec2::one := vec2{ 1, 1 };
pub def vec2::add(&this, other: &vec2): vec2 { return vec2{ this.x + other.x, this.y + other.y }; }
pub def vec2::sub(&this, other: &vec2): vec2 { return vec2{ this.x - other.x, this.y - other.y }; }
pub def vec2::mul(&this, by: &f32): vec2 { return vec2{ this.x * by, this.y * by }; }
pub def vec2::mul(&this, other: &vec2): vec2 { return vec2{ this.x * other.x, this.y * other.y }; }
pub def vec2::div(&this, by: &f32): vec2 { return vec2{ this.x / by, this.y / by }; }
pub def vec2::div(&this, other: &vec2): vec2 { return vec2{ this.x / other.x, this.y / other.y }; }
pub def vec2::negate(&this): vec2 { return vec2{ -this.x, -this.y }; }
pub def vec2::equals(&this, other: &vec2): bool { return this.x == other.x && this.y == other.y; }
pub def vec2::dot(&this, other: vec2): f32 { return this.x * other.x + this.y * other.y; }
#! The z of the cross product of the two as vectors of three in the plane z is
#! 0: positive where `other` is counterclockwise of this.
pub def vec2::cross(&this, other: vec2): f32 { return this.x * other.y - this.y * other.x; }
#! The vector turned a quarter counterclockwise.
pub def vec2::perpendicular(&this): vec2 { return vec2{ -this.y, this.x }; }
pub val vec2::length: f32 {
get => math::sqrt(this.x * this.x + this.y * this.y);
}
#! The length squared, which needs no square root, to compare lengths by.
pub val vec2::length_squared: f32 {
get => this.x * this.x + this.y * this.y;
}
pub def vec2::distance(&this, other: vec2): f32 { return (other - this).length; }
#! The vector at a length of 1, or none where it has no length.
pub def vec2::normalized(&this): vec2 {
val l := math::sqrt(this.x * this.x + this.y * this.y);
return l > 0 ? vec2{ this.x / l, this.y / l } : vec2{};
}
#! The vector a fraction of the way to another.
pub def vec2::lerp(&this, to: vec2, t: f32): vec2 {
return vec2{ this.x + (to.x - this.x) * t, this.y + (to.y - this.y) * t };
}
#! The lesser of each pair of numbers, as `math::min` gives it.
pub def vec2::min(&this, other: vec2): vec2 { return vec2{ math::min(this.x, other.x), math::min(this.y, other.y) }; }
#! The greater of each pair of numbers, as `math::max` gives it.
pub def vec2::max(&this, other: vec2): vec2 { return vec2{ math::max(this.x, other.x), math::max(this.y, other.y) }; }
#! Each number's distance from zero.
pub def vec2::abs(&this): vec2 { return vec2{ math::abs(this.x), math::abs(this.y) }; }
+138
View File
@@ -0,0 +1,138 @@
#! Contains `vec3`, a vector of three: a place or a direction in space. It holds
#! a fourth number no one names, so it's 16 bytes, an `f32x4`'s, which an
#! executable holding vectors in registers works at once.
import std::math;
import std::serial;
module linear;
#! A vector of three: a place or a direction in space.
@serial
pub struct vec3 {
@serial pub var x: f32;
@serial pub var y: f32;
@serial pub var z: f32;
# Unnamed, so the vector is four lanes; what its lane holds means nothing.
var _w: f32;
}
pub val vec3::zero := vec3{ 0, 0, 0 };
pub val vec3::one := vec3{ 1, 1, 1 };
pub val vec3::right := vec3{ 1, 0, 0 };
pub val vec3::left := vec3{ -1, 0, 0 };
pub val vec3::up := vec3{ 0, 1, 0 };
pub val vec3::down := vec3{ 0, -1, 0 };
#! Toward the viewer: a camera looks the other way.
pub val vec3::back := vec3{ 0, 0, 1 };
#! Away from the viewer, where a camera looks.
pub val vec3::forward := vec3{ 0, 0, -1 };
#! Its numbers as lanes, the fourth meaning nothing, for code of its own to
#! work several at once.
pub def vec3::lanes(&this): f32x4 { return lanes_of(this); }
#! The vector of the first three of lanes.
pub def vec3::of_lanes(lanes: f32x4): vec3 { return of_lanes::<vec3>(lanes); }
pub def vec3::add(&this, other: &vec3): vec3 {
return of_lanes::<vec3>(lanes_of(this) + lanes_of(other)) if lanes_held();
return vec3{ this.x + other.x, this.y + other.y, this.z + other.z };
}
pub def vec3::sub(&this, other: &vec3): vec3 {
return of_lanes::<vec3>(lanes_of(this) - lanes_of(other)) if lanes_held();
return vec3{ this.x - other.x, this.y - other.y, this.z - other.z };
}
pub def vec3::mul(&this, by: &f32): vec3 {
return of_lanes::<vec3>(lanes_of(this) * f32x4::splat(by)) if lanes_held();
return vec3{ this.x * by, this.y * by, this.z * by };
}
pub def vec3::mul(&this, other: &vec3): vec3 {
return of_lanes::<vec3>(lanes_of(this) * lanes_of(other)) if lanes_held();
return vec3{ this.x * other.x, this.y * other.y, this.z * other.z };
}
pub def vec3::div(&this, by: &f32): vec3 {
return of_lanes::<vec3>(lanes_of(this) / f32x4::splat(by)) if lanes_held();
return vec3{ this.x / by, this.y / by, this.z / by };
}
pub def vec3::div(&this, other: &vec3): vec3 {
if lanes_held() {
# The unnamed lanes divide 0 by 0, which is kept from the vector.
var made := of_lanes::<vec3>(lanes_of(this) / lanes_of(other));
made._w = 0;
return made;
}
return vec3{ this.x / other.x, this.y / other.y, this.z / other.z };
}
pub def vec3::negate(&this): vec3 {
return of_lanes::<vec3>(-lanes_of(this)) if lanes_held();
return vec3{ -this.x, -this.y, -this.z };
}
pub def vec3::equals(&this, other: &vec3): bool {
return this.x == other.x && this.y == other.y && this.z == other.z;
}
pub def vec3::dot(&this, other: vec3): f32 {
if lanes_held() {
val p := lanes_of(this) * lanes_of(&other);
return p[0] + p[1] + p[2];
}
return this.x * other.x + this.y * other.y + this.z * other.z;
}
#! The vector at right angles to both, by the right hand: x cross y is z. Its
#! lanes would be shuffled, which no instruction does, so it's a number at a
#! time.
pub def vec3::cross(&this, other: vec3): vec3 {
return vec3{
this.y * other.z - this.z * other.y,
this.z * other.x - this.x * other.z,
this.x * other.y - this.y * other.x,
};
}
pub val vec3::length: f32 {
get => math::sqrt(this.dot(this));
}
#! The length squared, which needs no square root, to compare lengths by.
pub val vec3::length_squared: f32 {
get => this.dot(this);
}
pub def vec3::distance(&this, other: vec3): f32 { return (other - this).length; }
#! The vector at a length of 1, or none where it has no length.
pub def vec3::normalized(&this): vec3 {
val l := this.length;
return l > 0 ? this / l : vec3{};
}
#! The vector a fraction of the way to another.
pub def vec3::lerp(&this, to: vec3, t: f32): vec3 {
return this + (to - this) * t;
}
#! The lesser of each pair of numbers, as `math::min` gives it.
pub def vec3::min(&this, other: vec3): vec3 {
return of_lanes::<vec3>(lanes_of(this).min(&lanes_of(&other))) if lanes_held();
return vec3{ math::min(this.x, other.x), math::min(this.y, other.y), math::min(this.z, other.z) };
}
#! The greater of each pair of numbers, as `math::max` gives it.
pub def vec3::max(&this, other: vec3): vec3 {
return of_lanes::<vec3>(lanes_of(this).max(&lanes_of(&other))) if lanes_held();
return vec3{ math::max(this.x, other.x), math::max(this.y, other.y), math::max(this.z, other.z) };
}
#! Each number's distance from zero.
pub def vec3::abs(&this): vec3 {
return of_lanes::<vec3>(lanes_of(this).abs()) if lanes_held();
return vec3{ math::abs(this.x), math::abs(this.y), math::abs(this.z) };
}
+116
View File
@@ -0,0 +1,116 @@
#! Contains `vec4`, a vector of four: a place of space with its `w`, as a
#! matrix projects one, or four numbers worked alike, as a color's. It's an
#! `f32x4`'s 16 bytes, which an executable holding vectors in registers works at
#! once.
import std::math;
import std::serial;
module linear;
#! A vector of four, as a point of space with its `w`.
@serial
pub struct vec4 {
@serial pub var x: f32;
@serial pub var y: f32;
@serial pub var z: f32;
@serial pub var w: f32;
}
pub val vec4::zero := vec4{ 0, 0, 0, 0 };
pub val vec4::one := vec4{ 1, 1, 1, 1 };
#! Its numbers as lanes, for code of its own to work several at once.
pub def vec4::lanes(&this): f32x4 { return lanes_of(this); }
#! The vector of lanes.
pub def vec4::of_lanes(lanes: f32x4): vec4 { return of_lanes::<vec4>(lanes); }
pub def vec4::add(&this, other: &vec4): vec4 {
return of_lanes::<vec4>(lanes_of(this) + lanes_of(other)) if lanes_held();
return vec4{ this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w };
}
pub def vec4::sub(&this, other: &vec4): vec4 {
return of_lanes::<vec4>(lanes_of(this) - lanes_of(other)) if lanes_held();
return vec4{ this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w };
}
pub def vec4::mul(&this, by: &f32): vec4 {
return of_lanes::<vec4>(lanes_of(this) * f32x4::splat(by)) if lanes_held();
return vec4{ this.x * by, this.y * by, this.z * by, this.w * by };
}
pub def vec4::mul(&this, other: &vec4): vec4 {
return of_lanes::<vec4>(lanes_of(this) * lanes_of(other)) if lanes_held();
return vec4{ this.x * other.x, this.y * other.y, this.z * other.z, this.w * other.w };
}
pub def vec4::div(&this, by: &f32): vec4 {
return of_lanes::<vec4>(lanes_of(this) / f32x4::splat(by)) if lanes_held();
return vec4{ this.x / by, this.y / by, this.z / by, this.w / by };
}
pub def vec4::div(&this, other: &vec4): vec4 {
return of_lanes::<vec4>(lanes_of(this) / lanes_of(other)) if lanes_held();
return vec4{ this.x / other.x, this.y / other.y, this.z / other.z, this.w / other.w };
}
pub def vec4::negate(&this): vec4 {
return of_lanes::<vec4>(-lanes_of(this)) if lanes_held();
return vec4{ -this.x, -this.y, -this.z, -this.w };
}
pub def vec4::equals(&this, other: &vec4): bool {
return this.x == other.x && this.y == other.y && this.z == other.z && this.w == other.w;
}
pub def vec4::dot(&this, other: vec4): f32 {
if lanes_held() {
val p := lanes_of(this) * lanes_of(&other);
return p[0] + p[1] + p[2] + p[3];
}
return this.x * other.x + this.y * other.y + this.z * other.z + this.w * other.w;
}
pub val vec4::length: f32 {
get => math::sqrt(this.dot(this));
}
#! The length squared, which needs no square root, to compare lengths by.
pub val vec4::length_squared: f32 {
get => this.dot(this);
}
#! The vector at a length of 1, or none where it has no length.
pub def vec4::normalized(&this): vec4 {
val l := this.length;
return l > 0 ? this / l : vec4{};
}
#! The vector a fraction of the way to another.
pub def vec4::lerp(&this, to: vec4, t: f32): vec4 {
return this + (to - this) * t;
}
#! The lesser of each pair of numbers, as `math::min` gives it.
pub def vec4::min(&this, other: vec4): vec4 {
return of_lanes::<vec4>(lanes_of(this).min(&lanes_of(&other))) if lanes_held();
return vec4{ math::min(this.x, other.x), math::min(this.y, other.y), math::min(this.z, other.z), math::min(this.w, other.w) };
}
#! The greater of each pair of numbers, as `math::max` gives it.
pub def vec4::max(&this, other: vec4): vec4 {
return of_lanes::<vec4>(lanes_of(this).max(&lanes_of(&other))) if lanes_held();
return vec4{ math::max(this.x, other.x), math::max(this.y, other.y), math::max(this.z, other.z), math::max(this.w, other.w) };
}
#! Each number's distance from zero.
pub def vec4::abs(&this): vec4 {
return of_lanes::<vec4>(lanes_of(this).abs()) if lanes_held();
return vec4{ math::abs(this.x), math::abs(this.y), math::abs(this.z), math::abs(this.w) };
}
#! Its first three.
pub val vec4::xyz: vec3 {
get => vec3{ this.x, this.y, this.z };
}
+46
View File
@@ -0,0 +1,46 @@
#! Contains exposure: how a camera is set for a scene's light, as an exposure
#! value at ISO 100, of its settings or of what its meter reads; and what light
#! is multiplied by, so exposed, as a renderer records it.
#!
#! Exposed by a meter, a matte white surface lit as the meter read records as
#! about two thirds of the most, and an 18% grey card about an eighth, which an
#! sRGB display shows as middle grey.
import std::math;
module photometry;
#! The exposure value at ISO 100 of a camera's settings: its aperture's
#! f-number, its shutter's time open, in seconds, and its sensitivity, as ISO.
#! It's log₂(N²/t), a step less each time the ISO doubles past 100, so f/16 at a
#! hundredth of a second is about 15, a sunny day's, as the sunny 16 rule has
#! it.
pub def ev100_of_camera(aperture: f32, shutter: f32, iso: f32 = 100): f32 {
return math::log2(aperture * aperture / shutter) - math::log2(iso / 100);
}
#! The exposure value at ISO 100 a camera's own meter sets for a scene of an
#! average luminance, in nits, calibrated as such meters are, by 12.5:
#! log₂(nits × 100 / 12.5).
pub def ev100_of_nits(luminance: f32): f32 {
return math::log2(luminance * 8);
}
#! The exposure value at ISO 100 a meter held where a scene is lit sets for it,
#! of the lux it reads, calibrated as such meters are, by 250:
#! log₂(lux × 100 / 250). Direct sunlight's is about 15.3, an office's 7.3.
pub def ev100_of_lux(illuminance: f32): f32 {
return math::log2(illuminance * 0.4);
}
#! What light, in nits, is multiplied by, recorded by a camera at an exposure
#! value at ISO 100: the most it records, 1, over the luminance that fills its
#! sensor, 1.2 × 2^EV100 nits.
pub def exposure_of_ev100(ev100: f32): f32 {
return 1 / (1.2 * math::exp2(ev100));
}
#! The exposure value at ISO 100 at which light is multiplied by so much, as
#! `exposure_of_ev100` gives it.
pub def ev100_of_exposure(exposure: f32): f32 {
return -math::log2(1.2 * exposure);
}
+157
View File
@@ -0,0 +1,157 @@
#! Contains `photometry`: light as an eye sees it, in the units lights are named
#! by, and converted between them, so a game's lights are given as real ones
#! are: a bulb by its lumens, the sun by the lux it lights the ground with, the
#! sky by its luminance, and a camera by its exposure value.
#!
#! ```
#! lumens lm luminous flux: all the light a source gives, every way at once, as a bulb is sold by
#! candela cd, lm/sr luminous intensity: the light a source gives one way, in each steradian of it
#! lux lx, lm/m² illuminance: the light falling on a surface, as a meter on it reads
#! nits cd/m² luminance: the light a surface gives back toward an eye, or a sky gives
#! EV100 exposure value at ISO 100: how a camera is set for a scene's light, each step twice the light
#! ```
#!
#! Angles are radians, and a cone's angle is its half, from its axis to its
#! edge, as glTF's spot lights give theirs.
import std::math;
module photometry;
# π, as the `f32` nearest it.
const pi: f32 = 3.14159265;
#! The solid angle of a cone, in steradians: 2π(1 - cos angle), of its angle
#! from its axis to its edge. Of π, it's a sphere's, 4π.
pub def solid_angle_of(angle: f32): f32 {
return 2 * pi * (1 - math::cos(angle));
}
#! The candela of a light giving so many lumens within a cone, alike every way
#! within it: its lumens over the cone's solid angle. Of the angle left out, π,
#! it shines every way, as a bare bulb does, so it's its lumens over 4π; of a
#! narrower cone, its light is gathered into it, as a torch's reflector gathers
#! its bulb's, and it's brighter each way.
pub def candela_of_lumens(flux: f32, angle: f32 = pi): f32 {
return flux / solid_angle_of(angle);
}
#! The lumens of a light of so many candela within a cone, alike every way
#! within it, or every way, of the angle left out.
pub def lumens_of_candela(intensity: f32, angle: f32 = pi): f32 {
return intensity * solid_angle_of(angle);
}
#! The lumens of a lamp drawing so many watts, of how many lumens each watt of
#! its kind gives, as `efficacy` names them.
pub def lumens_of_watts(power: f32, lumens_per_watt: f32): f32 {
return power * lumens_per_watt;
}
#! The watts a lamp of so many lumens draws, of how many lumens each watt of
#! its kind gives.
pub def watts_of_lumens(flux: f32, lumens_per_watt: f32): f32 {
return flux / lumens_per_watt;
}
#! The lux a light of so many candela gives a surface so far from it, facing
#! it: its candela over the square of the distance. A surface turned from it is
#! given the cosine of the angle as much.
pub def lux_of_candela(intensity: f32, distance: f32): f32 {
return intensity / (distance * distance);
}
#! How far from a light of so many candela a surface facing it is given so many
#! lux: the square root of its candela over them, as far as it lights as much
#! as is seen.
pub def distance_of_lux(intensity: f32, illuminance: f32): f32 {
return math::sqrt(intensity / illuminance);
}
#! The nits a matte surface lit by so many lux gives back, every way alike, of
#! the fraction of what falls on it it gives back: what falls on it, by that
#! fraction, over π. White gives back all of it, and an 18% grey card, a
#! photograph's middle grey, 0.18.
pub def nits_of_lux(illuminance: f32, reflectance: f32 = 1): f32 {
return illuminance * reflectance / pi;
}
#! The lux lighting a matte surface that gives back so many nits, of the
#! fraction of what falls on it it gives back: π times its nits, over that
#! fraction. Of the fraction left out, it's the lux a sky of so many nits, alike
#! every way, lights the ground with.
pub def lux_of_nits(luminance: f32, reflectance: f32 = 1): f32 {
return luminance * pi / reflectance;
}
#! Illuminances, in lux, of the ground or a floor, about as each is lit.
pub struct lux {}
#! A moonless, overcast night, lit by starlight.
pub const lux::starlight: f32 = 0.0001;
#! A moonless clear night, lit by the sky's own glow.
pub const lux::moonless_night: f32 = 0.002;
#! A full moon on a clear night.
pub const lux::full_moon: f32 = 0.2;
#! The end of civil twilight, under a clear sky.
pub const lux::twilight: f32 = 3.4;
#! A family's living room.
pub const lux::living_room: f32 = 50;
#! An office building's hallway.
pub const lux::hallway: f32 = 80;
#! A very dark overcast day.
pub const lux::dark_overcast: f32 = 100;
#! An office's desks.
pub const lux::office: f32 = 400;
#! Sunrise or sunset on a clear day.
pub const lux::sunrise: f32 = 400;
#! An overcast day.
pub const lux::overcast: f32 = 1000;
#! Full daylight, out of the sun.
pub const lux::daylight: f32 = 20000;
#! Direct sunlight, at noon.
pub const lux::direct_sunlight: f32 = 100000;
#! Luminances, in nits, about as each is seen.
pub struct nits {}
#! The sky of a clear day, out of the sun, which lights the ground with about
#! 22,000 lux.
pub const nits::clear_sky: f32 = 7000;
#! Luminous fluxes, in lumens, about as each is sold or burns.
pub struct lumens {}
#! A candle, of a candela every way.
pub const lumens::candle: f32 = 12.566371;
#! A bulb as bright as a 40-watt incandescent bulb, as LED bulbs are sold.
pub const lumens::bulb_40w: f32 = 450;
#! As bright as a 60-watt incandescent bulb.
pub const lumens::bulb_60w: f32 = 800;
#! As bright as a 75-watt incandescent bulb.
pub const lumens::bulb_75w: f32 = 1100;
#! As bright as a 100-watt incandescent bulb.
pub const lumens::bulb_100w: f32 = 1600;
#! Luminous intensities, in candela.
pub struct candela {}
#! A candle's, every way, which the candela was first named for.
pub const candela::candle: f32 = 1;
#! How many lumens each watt a lamp draws gives, by its kind, about, as
#! `lumens_of_watts` takes them.
pub struct efficacy {}
#! The most a watt gives, as green light of 555 nm, by which the lumen is
#! defined.
pub const efficacy::most: f32 = 683;
#! An incandescent bulb's.
pub const efficacy::incandescent: f32 = 14;
#! A halogen bulb's.
pub const efficacy::halogen: f32 = 20;
#! A compact fluorescent bulb's.
pub const efficacy::fluorescent: f32 = 60;
#! A white LED's.
pub const efficacy::led: f32 = 100;
#! Sunlight's, of each watt of it falling on the ground.
pub const efficacy::sunlight: f32 = 93;
+34
View File
@@ -0,0 +1,34 @@
#! Contains color temperature: the color of a black body's light at a
#! temperature, as lamps' colors are named.
import std::math;
import linear;
module photometry;
#! The color of a black body's light at a temperature, in kelvin, as a lamp's
#! is named: a candle's about 1,900 K, a warm bulb's 2,700, daylight's 6,500,
#! and a blue sky's 10,000 and more. It's linear sRGB, its greatest channel 1,
#! as a light's color is, by its intensity. A temperature below 1,000 K, or past
#! 40,000, is taken as either.
#!
#! The color is of Krystek's fit of the Planckian locus, within a thousandth of
#! it from 1,000 K to 15,000, made sRGB of CIE 1931's XYZ, a channel past sRGB's
#! colors taken as none.
pub def color_of_temperature(kelvin: f32): vec3 {
val t := math::clamp(kelvin, 1000f, 40000f);
val tt := t * t;
# Where it lies in CIE 1960's u and v, then in 1931's x and y.
val u := (0.860117757 + 1.54118254e-4 * t + 1.28641212e-7 * tt) / (1 + 8.42420235e-4 * t + 7.08145163e-7 * tt);
val v := (0.317398726 + 4.22806245e-5 * t + 4.20481691e-8 * tt) / (1 - 2.89741816e-5 * t + 1.61456053e-7 * tt);
val d := 2 * u - 8 * v + 4;
val x := 3 * u / d;
val y := 2 * v / d;
# Of a brightness of 1.
val big_x := x / y;
val big_z := (1 - x - y) / y;
val r := math::max(3.2404542 * big_x - 1.5371385 - 0.4985314 * big_z, 0f);
val g := math::max(-0.9692660 * big_x + 1.8760108 + 0.0415560 * big_z, 0f);
val b := math::max(0.0556434 * big_x - 0.2040259 + 1.0572252 * big_z, 0f);
val most := math::max(r, math::max(g, b));
return vec3{ r / most, g / most, b / most };
}
+94
View File
@@ -0,0 +1,94 @@
#! Contains `aabb`, a box along the plane's axes, as what holds a shape, and
#! what an `aabb_tree` sorts.
import std::math;
import std::serial;
import linear;
module physics2d;
#! A box along the plane's axes, from its least corner to its greatest.
@serial
pub struct aabb {
@serial pub var min: vec2;
@serial pub var max: vec2;
}
#! The box of a middle, reaching so far each way.
pub def aabb::around(center: vec2, half: vec2): aabb {
return aabb{ center - half, center + half };
}
pub def aabb::equals(&this, other: &aabb): bool {
return this.min == other.min && this.max == other.max;
}
pub val aabb::center: vec2 {
get => (this.min + this.max) * 0.5;
}
#! How far it reaches each way from its middle.
pub val aabb::half_size: vec2 {
get => (this.max - this.min) * 0.5;
}
pub val aabb::size: vec2 {
get => this.max - this.min;
}
#! How far around it is, which an `aabb_tree` weighs where to put a box by.
pub val aabb::perimeter: f32 {
get => 2 * ((this.max.x - this.min.x) + (this.max.y - this.min.y));
}
#! Whether a place is within it, its edges among it.
pub def aabb::contains(&this, p: vec2): bool {
return p.x >= this.min.x && p.x <= this.max.x && p.y >= this.min.y && p.y <= this.max.y;
}
#! Whether it holds another box whole.
pub def aabb::encloses(&this, other: aabb): bool {
return other.min.x >= this.min.x && other.min.y >= this.min.y && other.max.x <= this.max.x && other.max.y <= this.max.y;
}
#! Whether it and another box meet, touching among it.
pub def aabb::overlaps(&this, other: aabb): bool {
return other.min.x <= this.max.x && other.max.x >= this.min.x && other.min.y <= this.max.y && other.max.y >= this.min.y;
}
#! The least box holding it and another.
pub def aabb::merged(&this, other: aabb): aabb {
return aabb{ this.min.min(other.min), this.max.max(other.max) };
}
#! It grown so far each way.
pub def aabb::grown(&this, by: f32): aabb {
return aabb{ this.min - vec2{ by, by }, this.max + vec2{ by, by } };
}
#! How far along a ray it's first met, from a place, along a direction, as far
#! as `reach` lengths of the direction: 0 where the place is within it.
pub def aabb::ray_hit(&this, origin: vec2, direction: vec2, reach: f32): maybe<f32> {
var low: f32 = 0;
var high := reach;
val origins: f32[2] = [origin.x, origin.y];
val ways: f32[2] = [direction.x, direction.y];
val lows: f32[2] = [this.min.x, this.min.y];
val highs: f32[2] = [this.max.x, this.max.y];
for i in 0..2u {
if math::abs(ways[i]) < tiny {
return nothing{} if origins[i] < lows[i] || origins[i] > highs[i];
continue;
}
var near := (lows[i] - origins[i]) / ways[i];
var far := (highs[i] - origins[i]) / ways[i];
if near > far {
val swapped := near;
near = far;
far = swapped;
}
low = math::max(low, near);
high = math::min(high, far);
return nothing{} if low > high;
}
return low;
}
+262
View File
@@ -0,0 +1,262 @@
#! Contains collision between shapes: whether two meet, where they're placed,
#! and the `manifold` of where and how deep, which way to push them apart.
#!
#! Each shape is taken as a hull, its points where its pose places them, with
#! its radius around them: a circle of one point, a capsule of two, a polygon
#! of its corners. 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 that holds 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 that face,
#! as Box2D clips one, so a box resting flat on another meets it at two
#! points; where only their round sides meet, they meet at one, along the line
#! between the hulls' nearest points.
import std::math;
import linear;
module physics2d;
#! A point where two shapes meet: midway between their surfaces, and how deep
#! the one is within the other there, 0 where they touch.
pub struct contact {
pub var point: vec2;
pub var depth: f32;
}
#! Where and how deep two shapes meet: the normal from the first toward the
#! second, along which the second is pushed out of the first, and one or two
#! points, as a box resting flat on another rests on two.
pub struct manifold {
pub var normal: vec2;
pub var points: contact[2];
pub var count: u32;
}
#! The deepest of its points.
pub val manifold::depth: f32 {
get => this.count == 0 ? 0f : this.count == 1 ? this.points[0].depth : math::max(this.points[0].depth, this.points[1].depth);
}
#! The manifold turned around, of the second shape against the first.
pub def manifold::flipped(&this): manifold {
return manifold{ normal = this.normal * -1f, points = this.points, count = this.count };
}
# A shape's points where its pose places it, and its edges' normals.
struct hull {
var points: vec2[8];
var normals: vec2[8];
var count: u32;
var radius: f32;
}
def hull_of(s: &shape, at: pose): hull {
var made := hull{ count = s.count, radius = s.radius };
for i in 0..s.count {
made.points[i] = at.apply(s.point(i));
made.normals[i] = at.turn.apply(s.normal(i));
}
return made;
}
#! Where two shapes meet, each where its pose places it, or nothing where they
#! don't: the manifold's normal from the first toward the second.
pub def collide(a: &shape, at_a: pose, b: &shape, at_b: pose): maybe<manifold> {
val ha := hull_of(a, at_a);
val hb := hull_of(b, at_b);
if ha.count == 1 && hb.count == 1 {
return circles(ha.points[0], ha.radius, hb.points[0], hb.radius);
}
if hb.count == 1 {
return hull_and_circle(&ha, hb.points[0], hb.radius);
}
if ha.count == 1 {
if hull_and_circle(&hb, ha.points[0], ha.radius) is some(m) {
return m.flipped();
}
return nothing{};
}
return hulls(&ha, &hb);
}
#! Whether two shapes meet, each where its pose places it, touching among it.
pub def overlaps(a: &shape, at_a: pose, b: &shape, at_b: pose): bool {
return collide(a, at_a, b, at_b) is some(_);
}
# A manifold of one point, between the surfaces of the first, at `on_a`
# within `radius_a` of it along the normal, and the second's, at `on_b` less
# `radius_b`.
def one_point(normal: vec2, on_a: vec2, radius_a: f32, on_b: vec2, radius_b: f32, depth: f32): manifold {
var made := manifold{ normal = normal, count = 1 };
made.points[0] = contact{ point = ((on_a + normal * radius_a) + (on_b - normal * radius_b)) * 0.5, depth = depth };
return made;
}
def circles(a: vec2, ra: f32, b: vec2, rb: f32): maybe<manifold> {
val between := b - a;
val distance := between.length;
return nothing{} if distance > ra + rb;
val normal := distance > tiny ? between * (1 / distance) : vec2{ 0, 1 };
return one_point(normal, a, ra, b, rb, ra + rb - distance);
}
# A hull and a circle: within a polygon, pushed out by the face it's nearest;
# else by the hull's point nearest the circle's middle.
def hull_and_circle(h: &hull, c: vec2, radius: f32): maybe<manifold> {
val reach := h.radius + radius;
# The face the middle is furthest in front of.
var face: u32 = 0;
var separation := -1e30f;
for i in 0..h.count {
val s := h.normals[i].dot(c - h.points[i]);
if s > separation {
separation = s;
face = i;
}
}
return nothing{} if separation > reach;
if h.count >= 3 && separation <= 0 {
val n := h.normals[face];
return one_point(n, c - n * separation, h.radius, c, radius, reach - separation);
}
var nearest := h.points[0];
var best := 1e30f;
for i in 0..h.count {
val p := nearest_on_segment(c, h.points[i], h.points[(i + 1) % h.count]);
val d := (c - p).length_squared;
if d < best {
best = d;
nearest = p;
}
}
val distance := math::sqrt(best);
return nothing{} if distance > reach;
val normal := distance > tiny ? (c - nearest) * (1 / distance) : h.normals[face];
return one_point(normal, nearest, h.radius, c, radius, reach - distance);
}
# How far in front of a hull's edge another hull lies, of the edge that holds
# it furthest: the edge, and the distance, below 0 where they overlap.
struct apart {
var edge: u32;
var separation: f32;
}
def furthest_apart(from: &hull, other: &hull): apart {
var found := apart{ separation = -1e30f };
for i in 0..from.count {
val n := from.normals[i];
var least := 1e30f;
for j in 0..other.count {
least = math::min(least, n.dot(other.points[j] - from.points[i]));
}
if least > found.separation {
found = apart{ edge = i, separation = least };
}
}
return found;
}
# Two hulls of two or more points each.
def hulls(a: &hull, b: &hull): maybe<manifold> {
val reach := a.radius + b.radius;
val of_a := furthest_apart(a, b);
return nothing{} if of_a.separation > reach;
val of_b := furthest_apart(b, a);
return nothing{} if of_b.separation > reach;
# The face of the first is taken where it's as good, so the same pair gives
# the same face from one frame to the next.
val flip := of_b.separation > of_a.separation + 1e-4;
val reference := flip ? b : a;
val incident := flip ? a : b;
val face := flip ? of_b.edge : of_a.edge;
val separation := flip ? of_b.separation : of_a.separation;
if separation > 1e-4 && reach > 0 {
# Apart but for their round sides: they meet along the line between the
# hulls' nearest points, or along a face nearly that way.
var best := 1e30f;
var on_a := a.points[0];
var on_b := b.points[0];
for i in 0..edges_of(a) {
for j in 0..edges_of(b) {
val pair := nearest_of_segments(a.points[i], a.points[(i + 1) % a.count], b.points[j], b.points[(j + 1) % b.count]);
val d := (pair[1] - pair[0]).length_squared;
if d < best {
best = d;
on_a = pair[0];
on_b = pair[1];
}
}
}
val distance := math::sqrt(best);
return nothing{} if distance > reach;
val normal := (on_b - on_a) * (1 / distance);
val along_face := flip ? normal * -1f : normal;
if along_face.dot(reference.normals[face]) < 0.995 {
return one_point(normal, on_a, a.radius, on_b, b.radius, reach - distance);
}
}
return clipped(reference, incident, face, flip);
}
# How many distinct edges a hull has: a capsule's two are one segment.
def edges_of(h: &hull): u32 {
return h.count == 2 ? 1 : h.count;
}
# The incident hull's edge facing most against the reference face, clipped to
# the face's width: each point of it within reach of the face a contact.
def clipped(reference: &hull, incident: &hull, face: u32, flip: bool): maybe<manifold> {
val n := reference.normals[face];
val v1 := reference.points[face];
val v2 := reference.points[(face + 1) % reference.count];
var edge: u32 = 0;
var least := 1e30f;
for i in 0..incident.count {
val d := n.dot(incident.normals[i]);
if d < least {
least = d;
edge = i;
}
}
var points: vec2[2] = [incident.points[edge], incident.points[(edge + 1) % incident.count]];
val tangent := (v2 - v1).normalized();
var kept: u32 = 2;
kept = clip(&mut points, kept, tangent * -1f, -tangent.dot(v1));
return nothing{} if kept < 2;
kept = clip(&mut points, kept, tangent, tangent.dot(v2));
return nothing{} if kept < 2;
val reach := reference.radius + incident.radius;
var made := manifold{ normal = flip ? n * -1f : n };
for i in 0..2u {
val s := n.dot(points[i] - v1);
continue if s > reach;
# Midway between the reference's surface and the incident's.
val on_reference := points[i] - n * (s - reference.radius);
val on_incident := points[i] - n * incident.radius;
made.points[made.count] = contact{ point = (on_reference + on_incident) * 0.5, depth = reach - s };
made.count++;
}
return nothing{} if made.count == 0;
return made;
}
# Clips a segment to the side of a line where `normal.dot(p) <= offset`, as
# Sutherland and Hodgman clip, keeping two points where any of it is there.
def clip(points: &mut vec2[2], kept: u32, normal: vec2, offset: f32): u32 {
val d0 := normal.dot(points[0]) - offset;
val d1 := normal.dot(points[1]) - offset;
return 2 if d0 <= 0 && d1 <= 0;
return 0 if d0 > 0 && d1 > 0;
val t := d0 / (d0 - d1);
val crossing := points[0] + (points[1] - points[0]) * t;
if d0 > 0 {
points[0] = crossing;
} else {
points[1] = crossing;
}
return 2;
}
+194
View File
@@ -0,0 +1,194 @@
#! Contains `grid`: solid cells of a grid, as a tilemap's walls are, each a box
#! of the grid's cell size, from the grid's origin at the bottom left of its
#! first cell, x to the right and y up.
#!
#! A shape meets each solid cell as a box, but for the faces two solid cells
#! share: a manifold pushing the shape into a solid neighbor, along the axis
#! it pushes most, is passed over, so a body sliding along a floor of many
#! cells slides as along one, never caught on the seams between them.
import std::containers;
import std::math;
import linear;
module physics2d;
#! Solid cells of a grid, so many across and up.
pub struct grid {
#! How wide and high each cell is.
pub var cell := vec2{ 1, 1 };
var _width: u32;
var _height: u32;
var _solid: vector<u8>; # Each cell, a row at a time, from the bottom left.
}
#! A grid so many cells across and up, each so wide and high, none solid.
pub def grid::new(width: u32, height: u32, cell: vec2 = vec2{ 1, 1 }): grid {
var made := grid{ cell = cell, _width = width, _height = height, _solid = vector::<u8>::new() };
made._solid.resize(width as u64 * height as u64, 0);
return made;
}
pub val grid::width: u32 {
get => this._width;
}
pub val grid::height: u32 {
get => this._height;
}
#! Whether a cell is solid: none outside the grid is.
pub def grid::is_solid(&this, x: i64, y: i64): bool {
return false if x < 0 || y < 0 || x >= this._width as i64 || y >= this._height as i64;
return this._solid[(y as u64) * this._width as u64 + x as u64] != 0;
}
#! Makes a cell solid, or not.
pub def grid::set(&mut this, x: u32, y: u32, solid: bool): void {
return if x >= this._width || y >= this._height;
this._solid[y as u64 * this._width as u64 + x as u64] = solid ? 1 : 0;
}
#! A cell's box, of the grid's own places.
pub def grid::box_of(&this, x: u32, y: u32): aabb {
val low := vec2{ x as f32 * this.cell.x, y as f32 * this.cell.y };
return aabb{ low, low + this.cell };
}
#! The box of all its cells, of its own places.
pub val grid::bounds: aabb {
get => aabb{ vec2::zero, vec2{ this._width as f32 * this.cell.x, this._height as f32 * this.cell.y } };
}
#! Visits each solid cell a box of the grid's own places meets, as
#! `visit(x, y)`, until it gives false.
pub def grid::cells_in<F>(&this, box: aabb, visit: F): void where F: invokable<def(u32, u32): bool> {
return if this._width == 0 || this._height == 0;
val x0 := math::max(math::floor(box.min.x / this.cell.x) as i64, 0);
val y0 := math::max(math::floor(box.min.y / this.cell.y) as i64, 0);
val x1 := math::min(math::floor(box.max.x / this.cell.x) as i64, this._width as i64 - 1);
val y1 := math::min(math::floor(box.max.y / this.cell.y) as i64, this._height as i64 - 1);
var y := y0;
while y <= y1 {
var x := x0;
while x <= x1 {
if this.is_solid(x, y) {
return if !visit(x as u32, y as u32);
}
x++;
}
y++;
}
}
#! Visits the manifold of a shape against each solid cell it meets, as
#! `visit(x, y, m)`, until it gives false: `at` places the grid, and `at_s`
#! the shape, and each manifold's normal is from the cell toward the shape,
#! of the plane's places. Those pushing the shape into a solid neighbor are
#! passed over.
pub def grid::collide<F>(&this, at: pose, s: &shape, at_s: pose, visit: F): void where F: invokable<def(u32, u32, manifold): bool> {
val local := at.unapply_pose(at_s);
val half := this.cell * 0.5;
this.cells_in(s.bounds(local), def(x: u32, y: u32): bool {
val box := shape::box(half, vec2{ (x as f32 + 0.5) * this.cell.x, (y as f32 + 0.5) * this.cell.y });
val found := collide(&box, pose::identity, s, local) else { return true; };
# Along the axis it pushes most, toward a solid neighbor, it's a face the
# two share.
val n := found.normal;
var nx: i64 = 0;
var ny: i64 = 0;
if math::abs(n.x) > math::abs(n.y) {
nx = n.x > 0 ? 1 : -1;
} else {
ny = n.y > 0 ? 1 : -1;
}
return true if this.is_solid(x as i64 + nx, y as i64 + ny);
var placed := manifold{ normal = at.turn.apply(n), count = found.count };
for i in 0..found.count {
placed.points[i] = contact{ point = at.apply(found.points[i].point), depth = found.points[i].depth };
}
return visit(x, y, placed);
});
}
#! Whether a shape meets any solid cell, `at` placing the grid and `at_s` the
#! shape, but where it only meets the faces solid cells share.
pub def grid::overlaps(&this, at: pose, s: &shape, at_s: pose): bool {
var met := false;
this.collide(at, s, at_s, def(x: u32, y: u32, m: manifold): bool {
met = true;
return false;
});
return met;
}
#! Where a ray met a grid: the hit, and the solid cell it met.
pub struct grid_hit {
pub var hit: ray_hit;
pub var x: u32;
pub var y: u32;
}
#! Where a ray first meets a solid cell, `at` placing the grid: from a place,
#! along a direction of length 1, as far as `reach`, passing from cell to cell
#! as Amanatides and Woo pass, the face it enters by its normal. A ray
#! beginning in a solid cell meets it at 0, facing back along the ray.
pub def grid::ray_cast(&this, at: pose, origin: vec2, direction: vec2, reach: f32): maybe<grid_hit> {
val o := at.unapply(origin);
val d := at.turn.unapply(direction);
val whole := this.bounds;
val start := whole.ray_hit(o, d, reach) else { return nothing{}; };
val p := o + d * start;
var x := math::clamp(math::floor(p.x / this.cell.x) as i64, 0, this._width as i64 - 1);
var y := math::clamp(math::floor(p.y / this.cell.y) as i64, 0, this._height as i64 - 1);
# The face of the grid it entered by, or none where it began within it.
var normal := d * -1f;
if start > 0 {
val gaps: f32[4] = [math::abs(p.x - whole.min.x), math::abs(p.x - whole.max.x), math::abs(p.y - whole.min.y), math::abs(p.y - whole.max.y)];
val faces: vec2[4] = [vec2{ -1, 0 }, vec2{ 1, 0 }, vec2{ 0, -1 }, vec2{ 0, 1 }];
var nearest: u64 = 0;
for i in 1..4u {
if gaps[i] < gaps[nearest] {
nearest = i;
}
}
normal = faces[nearest];
}
val step_x: i64 = d.x > 0 ? 1 : d.x < 0 ? -1 : 0;
val step_y: i64 = d.y > 0 ? 1 : d.y < 0 ? -1 : 0;
val across_x := step_x != 0 ? this.cell.x / math::abs(d.x) : 1e30f;
val across_y := step_y != 0 ? this.cell.y / math::abs(d.y) : 1e30f;
# How far along the ray, from its beginning, each next line of cells is.
var next_x := 1e30f;
var next_y := 1e30f;
if step_x > 0 {
next_x = ((x + 1) as f32 * this.cell.x - o.x) / d.x;
} else if step_x < 0 {
next_x = (x as f32 * this.cell.x - o.x) / d.x;
}
if step_y > 0 {
next_y = ((y + 1) as f32 * this.cell.y - o.y) / d.y;
} else if step_y < 0 {
next_y = (y as f32 * this.cell.y - o.y) / d.y;
}
var t := start;
while true {
if this.is_solid(x, y) {
return grid_hit{
hit = ray_hit{ distance = t, point = at.apply(o + d * t), normal = at.turn.apply(normal) }, x = x as u32, y = y as u32,
};
}
if next_x < next_y {
t = next_x;
next_x += across_x;
x += step_x;
normal = vec2{ -step_x as f32, 0 };
} else {
t = next_y;
next_y += across_y;
y += step_y;
normal = vec2{ 0, -step_y as f32 };
}
return nothing{} if t > reach || x < 0 || y < 0 || x >= this._width as i64 || y >= this._height as i64;
}
return nothing{};
}
+69
View File
@@ -0,0 +1,69 @@
#! Contains `physics2d`: what collides in a plane, as a game of two dimensions
#! asks it. Shapes, circles, capsules, and convex polygons, each about the
#! origin of its body and placed by a `pose`; whether two meet, and the
#! `manifold` of where and how deep, which way to push them apart; where a ray
#! first meets one; an `aabb_tree` of many, which finds those near a box or
#! along a ray without passing over the rest; and a `grid` of solid cells, as a
#! tilemap's walls are, met as boxes, each but the faces it shares with a solid
#! neighbor, so a body slides along a floor of many cells as along one.
#!
#! The plane is `linear`'s x and y: x to the right, y up, and angles
#! counterclockwise, in radians. A polygon's corners are counterclockwise, and
#! each edge's normal faces out. A shape's surface is within it, so two shapes
#! touching meet, at a depth of 0.
#!
#! What this holds is collision alone: bodies that move by forces and push one
#! another apart come after, as `physics2d`'s solver.
import std::math;
import linear;
module physics2d;
# How near two numbers are taken as one, as lengths in a game's units are.
const tiny: f32 = 1e-6;
# The point of a segment nearest a place.
def nearest_on_segment(p: vec2, a: vec2, b: vec2): vec2 {
val e := b - a;
val length_squared := e.dot(e);
return a if length_squared <= tiny * tiny;
val t := math::clamp((p - a).dot(e) / length_squared, 0f, 1f);
return a + e * t;
}
# The points of two segments nearest one another: on `a1`-`a2` first, then on
# `b1`-`b2`, as Ericson's Real-Time Collision Detection finds them.
def nearest_of_segments(a1: vec2, a2: vec2, b1: vec2, b2: vec2): vec2[2] {
val d1 := a2 - a1;
val d2 := b2 - b1;
val r := a1 - b1;
val a := d1.dot(d1);
val e := d2.dot(d2);
val f := d2.dot(r);
var s: f32 = 0;
var t: f32 = 0;
if a <= tiny && e <= tiny {
return [a1, b1];
}
if a <= tiny {
t = math::clamp(f / e, 0f, 1f);
} else {
val c := d1.dot(r);
if e <= tiny {
s = math::clamp(-c / a, 0f, 1f);
} else {
val b := d1.dot(d2);
val denominator := a * e - b * b;
s = denominator > tiny ? math::clamp((b * f - c * e) / denominator, 0f, 1f) : 0;
t = (b * s + f) / e;
if t < 0 {
t = 0;
s = math::clamp(-c / a, 0f, 1f);
} else if t > 1 {
t = 1;
s = math::clamp((b - c) / a, 0f, 1f);
}
}
}
return [a1 + d1 * s, b1 + d2 * t];
}
+91
View File
@@ -0,0 +1,91 @@
#! Contains `rot`, a rotation in the plane, and `pose`, where a body is and
#! which way it's turned, which places its shapes.
import std::math;
import std::serial;
import linear;
module physics2d;
#! A rotation in the plane, counterclockwise, as its angle's cosine and sine,
#! so turning a vector takes no trigonometry.
@serial
pub struct rot {
@serial pub var c: f32 = 1;
@serial pub var s: f32;
}
#! No rotation.
pub val rot::identity := rot{ 1, 0 };
#! A rotation by an angle, in radians, counterclockwise.
pub def rot::of(angle: f32): rot {
return rot{ math::cos(angle), math::sin(angle) };
}
#! Its angle, in radians, from -π to π.
pub val rot::angle: f32 {
get => math::atan2(this.s, this.c);
}
pub def rot::equals(&this, other: &rot): bool {
return this.c == other.c && this.s == other.s;
}
#! A vector turned by it.
pub def rot::apply(&this, v: vec2): vec2 {
return vec2{ this.c * v.x - this.s * v.y, this.s * v.x + this.c * v.y };
}
#! A vector turned back by it, as its inverse turns it.
pub def rot::unapply(&this, v: vec2): vec2 {
return vec2{ this.c * v.x + this.s * v.y, this.c * v.y - this.s * v.x };
}
#! It after another: turning by the product turns by `other`, then by this.
pub def rot::mul(&this, other: &rot): rot {
return rot{ this.c * other.c - this.s * other.s, this.s * other.c + this.c * other.s };
}
#! Where a body is in the plane, and which way it's turned: what a place of its
#! own, as its shapes' corners are, is in the plane.
@serial
pub struct pose {
@serial pub var at: vec2;
@serial pub var turn := rot::identity;
}
#! At the origin, unturned.
pub val pose::identity := pose{};
#! A pose at a place, turned by an angle, in radians, counterclockwise.
pub def pose::of(at: vec2, angle: f32 = 0): pose {
return pose{ at = at, turn = rot::of(angle) };
}
pub def pose::equals(&this, other: &pose): bool {
return this.at == other.at && this.turn == other.turn;
}
#! Where a place of the body's own is in the plane.
pub def pose::apply(&this, local: vec2): vec2 {
return this.at + this.turn.apply(local);
}
#! Where a place of the plane is in the body's own.
pub def pose::unapply(&this, place: vec2): vec2 {
return this.turn.unapply(place - this.at);
}
#! It after another: the pose of what's placed by `other` within what this
#! places.
pub def pose::mul(&this, other: &pose): pose {
return pose{ at = this.apply(other.at), turn = this.turn * other.turn };
}
#! Another pose of the plane, as one within what this places, of its own
#! places: what `this * found` is `other` of.
pub def pose::unapply_pose(&this, other: pose): pose {
val c := this.turn.c * other.turn.c + this.turn.s * other.turn.s;
val s := this.turn.c * other.turn.s - this.turn.s * other.turn.c;
return pose{ at = this.unapply(other.at), turn = rot{ c, s } };
}
+310
View File
@@ -0,0 +1,310 @@
#! Contains `shape`: a circle, a capsule, or a convex polygon, about the origin
#! of its body; the box holding it where a pose places it; whether it holds a
#! place; and where a ray first meets it.
import std::containers;
import std::math;
import linear;
module physics2d;
#! The most corners a polygon has.
pub const max_corners: u32 = 8;
#! What a shape is.
pub enum shape_kind: u8 {
#! The places within its radius of its middle.
circle,
#! The places within its radius of a segment, between its two ends, as a
#! pill; of a radius of 0, the segment itself, as a thin wall.
capsule,
#! A convex polygon of three to eight corners.
polygon,
}
#! A shape of a body, about the body's origin, as a pose places it: a circle,
#! a capsule, or a convex polygon, each its points and a radius around them. A
#! circle is its middle, a capsule its two ends, and a polygon its corners,
#! counterclockwise, each edge's normal facing out.
pub struct shape {
var _kind: shape_kind;
var _radius: f32;
var _count: u32;
var _points: vec2[8];
var _normals: vec2[8]; # Of edge `i`, from point `i` to the next.
}
#! Where a ray met a shape: how far along it, where, and which way the shape
#! faces there.
pub struct ray_hit {
pub var distance: f32;
pub var point: vec2;
pub var normal: vec2;
}
#! A circle of a radius, about a middle, the body's origin at first.
pub def shape::circle(radius: f32, center: vec2 = vec2::zero): shape {
var made := shape{ _kind = shape_kind::circle, _radius = radius, _count = 1 };
made._points[0] = center;
return made;
}
#! A capsule of a radius about the segment between two places: a circle of
#! the radius, where they're one place.
pub def shape::capsule(a: vec2, b: vec2, radius: f32): shape {
return shape::circle(radius, a) if (b - a).length_squared <= tiny * tiny;
var made := shape{ _kind = shape_kind::capsule, _radius = radius, _count = 2 };
made._points[0] = a;
made._points[1] = b;
made.find_normals();
return made;
}
#! A capsule standing up, as a character's body: so wide and so high in all,
#! its ends round, about a middle. Narrower than it's high, or a circle.
pub def shape::pill(width: f32, height: f32, center: vec2 = vec2::zero): shape {
val radius := width / 2;
val reach := math::max(height / 2 - radius, 0f);
return shape::capsule(center - vec2{ 0, reach }, center + vec2{ 0, reach }, radius);
}
#! A segment between two places, of no thickness, as a capsule of no radius.
pub def shape::segment(a: vec2, b: vec2): shape {
return shape::capsule(a, b, 0);
}
#! A box reaching so far each way from its middle, turned by an angle, in
#! radians.
pub def shape::box(half: vec2, center: vec2 = vec2::zero, angle: f32 = 0): shape {
val turn := rot::of(angle);
var made := shape{ _kind = shape_kind::polygon, _count = 4 };
val corners: vec2[4] = [vec2{ -half.x, -half.y }, vec2{ half.x, -half.y }, vec2{ half.x, half.y }, vec2{ -half.x, half.y }];
for i in 0..4u {
made._points[i] = center + turn.apply(corners[i]);
}
made.find_normals();
return made;
}
#! The convex polygon around places, three to eight of its corners among
#! them: what's inside it and on its edges left out. Nothing where the places
#! hold no area, or their hull has more than eight corners.
pub def shape::polygon(places: span<vec2>): maybe<shape> {
var sorted := vector::<vec2>::new();
for i in 0..places.length {
sorted.append(places[i]);
}
sorted.sort_by(before_in_x);
# Andrew's monotone chain: the hull's lower half, left to right, then its
# upper, right to left, each corner turning left of the last two.
var hull := vector::<vec2>::new();
for i in 0..sorted.length {
while hull.length >= 2 && turning(hull[hull.length - 2], hull[hull.length - 1], sorted[i]) <= tiny {
hull.truncate();
}
hull.append(sorted[i]);
}
val lower := hull.length + 1;
var i := sorted.length;
while i > 1 {
i--;
val p := sorted[i - 1];
while hull.length >= lower && turning(hull[hull.length - 2], hull[hull.length - 1], p) <= tiny {
hull.truncate();
}
hull.append(p);
}
# Its last corner is its first again.
if hull.length > 0 {
hull.truncate();
}
return nothing{} if hull.length < 3 || hull.length > max_corners as u64;
var made := shape{ _kind = shape_kind::polygon, _count = hull.length as u32 };
for k in 0..hull.length {
made._points[k] = hull[k];
}
made.find_normals();
return made;
}
# Whether a place comes before another, left to right, then bottom to top.
def before_in_x(a: &vec2, b: &vec2): bool {
return a.x < b.x if a.x != b.x;
return a.y < b.y;
}
# Twice the area of the triangle of three places, positive where they turn
# counterclockwise.
def turning(a: vec2, b: vec2, c: vec2): f32 {
return (b - a).cross(c - a);
}
# Finds the normal of each edge: its direction turned a quarter clockwise,
# which faces out of corners counterclockwise.
def shape::find_normals(&mut this): void {
for i in 0..this._count {
val edge := this._points[(i + 1) % this._count] - this._points[i];
this._normals[i] = vec2{ edge.y, -edge.x }.normalized();
}
}
pub val shape::kind: shape_kind {
get => this._kind;
}
#! How far around its points it reaches: a circle's or a capsule's radius,
#! and none of a polygon.
pub val shape::radius: f32 {
get => this._radius;
}
#! How many points it's of: a circle 1, a capsule 2, and a polygon its
#! corners.
pub val shape::count: u32 {
get => this._count;
}
#! A point of it: a circle's middle, a capsule's end, or a polygon's corner.
pub def shape::point(&this, i: u32): vec2 {
return this._points[i];
}
#! The normal of an edge of a capsule or a polygon, from point `i` to the
#! next, facing out.
pub def shape::normal(&this, i: u32): vec2 {
return this._normals[i];
}
#! The box holding it, where a pose places it.
pub def shape::bounds(&this, at: pose): aabb {
var low := at.apply(this._points[0]);
var high := low;
for i in 1..this._count {
val p := at.apply(this._points[i]);
low = low.min(p);
high = high.max(p);
}
val r := vec2{ this._radius, this._radius };
return aabb{ low - r, high + r };
}
#! Whether it holds a place of the plane, where a pose places it, its surface
#! among it.
pub def shape::contains(&this, at: pose, p: vec2): bool {
val local := at.unapply(p);
if this._kind == shape_kind::circle {
return (local - this._points[0]).length_squared <= this._radius * this._radius;
}
if this._kind == shape_kind::capsule {
val nearest := nearest_on_segment(local, this._points[0], this._points[1]);
return (local - nearest).length_squared <= this._radius * this._radius;
}
for i in 0..this._count {
return false if this._normals[i].dot(local - this._points[i]) > 0;
}
return true;
}
#! Where a ray first meets it, where a pose places it: from a place, along a
#! direction of length 1, as far as `reach`. A ray beginning within it meets
#! it at 0, facing back along the ray.
pub def shape::ray_cast(&this, at: pose, origin: vec2, direction: vec2, reach: f32): maybe<ray_hit> {
val o := at.unapply(origin);
val d := at.turn.unapply(direction);
var found: maybe<ray_hit> = nothing{};
match this._kind {
circle => found = ray_circle(o, d, reach, this._points[0], this._radius);
capsule => found = ray_capsule(o, d, reach, this._points[0], this._points[1], this._radius);
polygon => found = this.ray_polygon(o, d, reach);
}
if found is some(hit) {
return ray_hit{ distance = hit.distance, point = at.apply(hit.point), normal = at.turn.apply(hit.normal) };
}
return nothing{};
}
# A ray, of the shape's own places, meeting a circle.
def ray_circle(o: vec2, d: vec2, reach: f32, center: vec2, radius: f32): maybe<ray_hit> {
val s := o - center;
val c := s.dot(s) - radius * radius;
return ray_hit{ distance = 0, point = o, normal = d * -1f } if c <= 0;
val b := s.dot(d);
return nothing{} if b > 0;
val disc := b * b - c;
return nothing{} if disc < 0;
val t := -b - math::sqrt(disc);
return nothing{} if t > reach;
val p := o + d * t;
return ray_hit{ distance = t, point = p, normal = (p - center) * (1 / radius) };
}
# A ray meeting a capsule: its flat sides, where it meets them between its
# ends, else its round ends; or a segment, of no radius, from either side.
def ray_capsule(o: vec2, d: vec2, reach: f32, a: vec2, b: vec2, radius: f32): maybe<ray_hit> {
val nearest := nearest_on_segment(o, a, b);
if (o - nearest).length_squared <= radius * radius {
return ray_hit{ distance = 0, point = o, normal = d * -1f };
}
val along := (b - a).normalized();
val length := (b - a).length;
# The side facing the ray's beginning.
var side := along.perpendicular();
if side.dot(o - a) < 0 {
side = side * -1f;
}
val toward := d.dot(side);
var best: maybe<ray_hit> = nothing{};
if toward < 0 {
val t := (side.dot(o - a) - radius) / -toward;
if t >= 0 && t <= reach {
val p := o + d * t;
val s := (p - a).dot(along);
if s >= 0 && s <= length {
return ray_hit{ distance = t, point = p, normal = side };
}
}
}
return nothing{} if radius <= 0;
val first := ray_circle(o, d, reach, a, radius);
val second := ray_circle(o, d, reach, b, radius);
if first is some(hit) {
best = hit;
}
if second is some(hit) {
if best is some(held) {
if hit.distance < held.distance {
best = hit;
}
} else {
best = hit;
}
}
return best;
}
# A ray meeting a polygon, clipped by each edge's side in turn, as Cyrus and
# Beck clip a line: where it enters the last side it crosses into is where it
# meets the polygon.
def shape::ray_polygon(&this, o: vec2, d: vec2, reach: f32): maybe<ray_hit> {
var lower: f32 = 0;
var upper := reach;
var entered: i64 = -1;
for i in 0..this._count {
val n := this._normals[i];
val numerator := n.dot(this._points[i] - o);
val denominator := n.dot(d);
if denominator == 0 {
return nothing{} if numerator < 0;
continue;
}
val t := numerator / denominator;
if denominator < 0 && t > lower {
lower = t;
entered = i as i64;
} else if denominator > 0 && t < upper {
upper = t;
}
return nothing{} if upper < lower;
}
return ray_hit{ distance = 0, point = o, normal = d * -1f } if entered < 0;
return ray_hit{ distance = lower, point = o + d * lower, normal = this._normals[entered as u32] };
}
+340
View File
@@ -0,0 +1,340 @@
#! Contains `aabb_tree`, a tree of boxes: each leaf a box holding a number of
#! its user's, as an entity's bits, and each branch the least box holding its
#! two children, so what's near a box, or along a ray, is found by passing down
#! only the branches that reach it, as Box2D's dynamic tree finds it.
#!
#! A leaf's box is grown past what it holds 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,
#! so the tree stays shallow whatever order its leaves come in.
import std::math;
import linear;
module physics2d;
# No node.
const none_node: u32 = 0xFFFFFFFF;
# The deepest a tree of shallow branches can be, with room to spare: past 2^40
# leaves.
const most_depth: u64 = 64;
struct tree_node {
var box: aabb;
var data: u64;
var parent: u32 = 0xFFFFFFFF; # Or the next free node, where it's free.
var left: u32 = 0xFFFFFFFF; # None of a leaf.
var right: u32 = 0xFFFFFFFF;
var height: i32; # 0 of a leaf, and -1 where it's free.
}
#! A tree of boxes, each leaf holding a number of its user's, named by the leaf
#! `insert` gives, which stays its name until it's removed.
pub struct aabb_tree {
var nodes: vector<tree_node>;
var root: u32 = 0xFFFFFFFF;
var free: u32 = 0xFFFFFFFF;
var leaves: u64;
#! How far each leaf's box is grown past what it holds.
pub var margin: f32 = 0.1;
}
#! A tree of no leaves, its boxes grown by a margin.
pub def aabb_tree::new(margin: f32 = 0.1): aabb_tree {
return aabb_tree{ nodes = vector::<tree_node>::new(), margin = margin };
}
#! How many leaves it holds.
pub val aabb_tree::length: u64 {
get => this.leaves;
}
#! How deep it is: 0 of no leaves or one, and 1 more for each branch down to
#! its deepest leaf.
pub val aabb_tree::height: i32 {
get => this.root == none_node ? 0 : this.nodes[this.root as u64].height;
}
#! Adds a box, and a number of the user's, as a leaf.
#! @returns The leaf, which names it until it's removed.
pub def aabb_tree::insert(&mut this, box: aabb, data: u64): u32 {
val leaf := this.allocate();
this.nodes[leaf as u64].box = box.grown(this.margin);
this.nodes[leaf as u64].data = data;
this.nodes[leaf as u64].height = 0;
this.insert_leaf(leaf);
this.leaves++;
return leaf;
}
#! Removes a leaf.
pub def aabb_tree::remove(&mut this, leaf: u32): void {
this.remove_leaf(leaf);
this.release(leaf);
this.leaves--;
}
#! Moves a leaf to hold a box, where its grown box doesn't hold it already.
#! @returns Whether it was moved.
pub def aabb_tree::move(&mut this, leaf: u32, box: aabb): bool {
return false if this.nodes[leaf as u64].box.encloses(box);
this.remove_leaf(leaf);
this.nodes[leaf as u64].box = box.grown(this.margin);
this.insert_leaf(leaf);
return true;
}
#! The number a leaf holds.
pub def aabb_tree::data(&this, leaf: u32): u64 {
return this.nodes[leaf as u64].data;
}
#! A leaf's box, grown by the margin.
pub def aabb_tree::box_of(&this, leaf: u32): aabb {
return this.nodes[leaf as u64].box;
}
#! Visits each leaf whose box meets a box, as `visit(leaf, data)`, until it
#! gives false.
pub def aabb_tree::query<F>(&this, box: aabb, visit: F): void where F: invokable<def(u32, u64): bool> {
return if this.root == none_node;
var stack: u32[64];
var top: u64 = 1;
stack[0] = this.root;
while top > 0 {
top--;
val index := stack[top] as u64;
continue if !this.nodes[index].box.overlaps(box);
if this.nodes[index].left == none_node {
return if !visit(index as u32, this.nodes[index].data);
} else if top + 2 <= most_depth {
stack[top] = this.nodes[index].left;
stack[top + 1] = this.nodes[index].right;
top += 2;
}
}
}
#! Visits each leaf whose box a ray meets, from a place, along a direction of
#! length 1, as far as `reach`, as `visit(leaf, data, reach)`, which gives how
#! far to go on: the distance of what it found there, so only what's nearer is
#! visited after; `reach` as it was, to go on as far; or 0, to stop.
pub def aabb_tree::ray_cast<F>(&this, origin: vec2, direction: vec2, reach: f32, visit: F): void
where F: invokable<def(u32, u64, f32): f32> {
return if this.root == none_node;
var far := reach;
var stack: u32[64];
var top: u64 = 1;
stack[0] = this.root;
while top > 0 {
top--;
val index := stack[top] as u64;
continue if this.nodes[index].box.ray_hit(origin, direction, far) is none;
if this.nodes[index].left == none_node {
val next := visit(index as u32, this.nodes[index].data, far);
return if next <= 0;
far = math::min(far, next);
} else if top + 2 <= most_depth {
stack[top] = this.nodes[index].left;
stack[top + 1] = this.nodes[index].right;
top += 2;
}
}
}
#! Whether the tree is as it should be: each node's parent its parent, each
#! branch's box the least holding its children's, and its height one more than
#! its deeper child's, each branch's children no more than one apart in height.
#! For tests.
pub def aabb_tree::is_sound(&this): bool {
return true if this.root == none_node;
return false if this.nodes[this.root as u64].parent != none_node;
var stack: u32[64];
var top: u64 = 1;
var seen: u64 = 0;
stack[0] = this.root;
while top > 0 {
top--;
val index := stack[top] as u64;
val left := this.nodes[index].left;
val right := this.nodes[index].right;
if left == none_node {
return false if right != none_node || this.nodes[index].height != 0;
seen++;
continue;
}
val l := &this.nodes[left as u64];
val r := &this.nodes[right as u64];
return false if l.parent != index as u32 || r.parent != index as u32;
return false if this.nodes[index].height != 1 + math::max(l.height, r.height) || math::abs(l.height - r.height) > 1;
return false if !(l.box.merged(r.box) == this.nodes[index].box);
return false if top + 2 > most_depth;
stack[top] = left;
stack[top + 1] = right;
top += 2;
}
return seen == this.leaves;
}
# A node to use: a free one, or a new one.
def aabb_tree::allocate(&mut this): u32 {
if this.free == none_node {
this.nodes.append(tree_node{});
return (this.nodes.length - 1) as u32;
}
val made := this.free;
this.free = this.nodes[made as u64].parent;
this.nodes[made as u64] = tree_node{};
return made;
}
# Frees a node, for another to use.
def aabb_tree::release(&mut this, index: u32): void {
this.nodes[index as u64] = tree_node{ parent = this.free, height = -1 };
this.free = index;
}
# What putting a box beneath a child costs: what the child's box grows by, or
# all of it, of a leaf, which a new branch takes the place of.
def aabb_tree::descent_cost(&this, child: u32, box: aabb): f32 {
val node := &this.nodes[child as u64];
val merged := box.merged(node.box).perimeter;
return merged if node.left == none_node;
return merged - node.box.perimeter;
}
# Puts a leaf where it grows the boxes above it least: beside a node, beneath a
# new branch holding both.
def aabb_tree::insert_leaf(&mut this, leaf: u32): void {
if this.root == none_node {
this.root = leaf;
this.nodes[leaf as u64].parent = none_node;
return;
}
val box := this.nodes[leaf as u64].box;
var index := this.root;
while this.nodes[index as u64].left != none_node {
val node_box := this.nodes[index as u64].box;
val left := this.nodes[index as u64].left;
val right := this.nodes[index as u64].right;
val combined := node_box.merged(box).perimeter;
# Beside this node, a new branch holding both; beneath it, every box
# above grows as this one does.
val here := 2 * combined;
val inherited := 2 * (combined - node_box.perimeter);
val to_left := this.descent_cost(left, box) + inherited;
val to_right := this.descent_cost(right, box) + inherited;
break if here < to_left && here < to_right;
index = to_left < to_right ? left : right;
}
val sibling := index;
val old_parent := this.nodes[sibling as u64].parent;
val branch := this.allocate();
this.nodes[branch as u64].parent = old_parent;
this.nodes[branch as u64].box = box.merged(this.nodes[sibling as u64].box);
this.nodes[branch as u64].height = this.nodes[sibling as u64].height + 1;
this.nodes[branch as u64].left = sibling;
this.nodes[branch as u64].right = leaf;
this.nodes[sibling as u64].parent = branch;
this.nodes[leaf as u64].parent = branch;
if old_parent == none_node {
this.root = branch;
} else if this.nodes[old_parent as u64].left == sibling {
this.nodes[old_parent as u64].left = branch;
} else {
this.nodes[old_parent as u64].right = branch;
}
this.refit(this.nodes[leaf as u64].parent);
}
# Takes a leaf out, its sibling taking its parent's place.
def aabb_tree::remove_leaf(&mut this, leaf: u32): void {
if leaf == this.root {
this.root = none_node;
return;
}
val parent := this.nodes[leaf as u64].parent;
val grandparent := this.nodes[parent as u64].parent;
val sibling := this.nodes[parent as u64].left == leaf ? this.nodes[parent as u64].right : this.nodes[parent as u64].left;
this.nodes[sibling as u64].parent = grandparent;
this.release(parent);
if grandparent == none_node {
this.root = sibling;
return;
}
if this.nodes[grandparent as u64].left == parent {
this.nodes[grandparent as u64].left = sibling;
} else {
this.nodes[grandparent as u64].right = sibling;
}
this.refit(grandparent);
}
# Walks up from a branch to the root, turning each that's out of balance, and
# making its box and height those of its children again.
def aabb_tree::refit(&mut this, from: u32): void {
var index := from;
while index != none_node {
index = this.balance(index);
val left := this.nodes[index as u64].left;
val right := this.nodes[index as u64].right;
this.nodes[index as u64].height = 1 + math::max(this.nodes[left as u64].height, this.nodes[right as u64].height);
this.nodes[index as u64].box = this.nodes[left as u64].box.merged(this.nodes[right as u64].box);
index = this.nodes[index as u64].parent;
}
}
# Turns a branch whose children are two or more apart in height: the deeper
# child takes its place, and it takes the deeper child's shallower child.
# @returns The node in its place now.
def aabb_tree::balance(&mut this, a: u32): u32 {
return a if this.nodes[a as u64].left == none_node || this.nodes[a as u64].height < 2;
val b := this.nodes[a as u64].left;
val c := this.nodes[a as u64].right;
val leaning := this.nodes[c as u64].height - this.nodes[b as u64].height;
if leaning > 1 {
this.raise(a, c, b, true);
return c;
}
if leaning < -1 {
this.raise(a, b, c, false);
return b;
}
return a;
}
# Raises `up`, a child of `a`, into its place: `a` becomes `up`'s first child,
# beside `up`'s deeper child, and takes `up`'s shallower child where `up` was,
# `other` its child still. `on_right` says `up` was `a`'s right child.
def aabb_tree::raise(&mut this, a: u32, up: u32, other: u32, on_right: bool): void {
val f := this.nodes[up as u64].left;
val g := this.nodes[up as u64].right;
# `up` takes `a`'s place beneath its parent.
val above := this.nodes[a as u64].parent;
this.nodes[up as u64].left = a;
this.nodes[up as u64].parent = above;
this.nodes[a as u64].parent = up;
if above == none_node {
this.root = up;
} else if this.nodes[above as u64].left == a {
this.nodes[above as u64].left = up;
} else {
this.nodes[above as u64].right = up;
}
# `up` keeps its deeper child; `a` takes the shallower where `up` was.
val deeper := this.nodes[f as u64].height > this.nodes[g as u64].height ? f : g;
val shallower := deeper == f ? g : f;
this.nodes[up as u64].right = deeper;
if on_right {
this.nodes[a as u64].right = shallower;
} else {
this.nodes[a as u64].left = shallower;
}
this.nodes[shallower as u64].parent = a;
this.nodes[a as u64].box = this.nodes[other as u64].box.merged(this.nodes[shallower as u64].box);
this.nodes[a as u64].height = 1 + math::max(this.nodes[other as u64].height, this.nodes[shallower as u64].height);
this.nodes[up as u64].box = this.nodes[a as u64].box.merged(this.nodes[deeper as u64].box);
this.nodes[up as u64].height = 1 + math::max(this.nodes[a as u64].height, this.nodes[deeper as u64].height);
}
+178
View File
@@ -0,0 +1,178 @@
#! Contains the tests of `geometry`: planes, and which side of one something
#! lies on; boxes and spheres holding places and meeting; rays meeting each
#! shape; a camera's frustum reaching what it sees; and the same bits whether
#! numbers are worked as lanes or one at a time, which `geometry.tests` and
#! `geometry.lanes.tests` each check.
import std::testing;
import std::json;
import std::math;
import linear;
import geometry;
# Whether two numbers are within a millionth or so of one another.
def near(a: f32, b: f32): bool {
return math::abs(a - b) < 1e-5;
}
def near(a: vec3, b: vec3): bool {
return near(a.x, b.x) && near(a.y, b.y) && near(a.z, b.z);
}
# How far along a ray it meets a shape, or -1 where it doesn't.
def hit_at(found: maybe<f32>): f32 {
return found is some(t) ? t : -1;
}
@test def lays_out_its_shapes(t: &mut tester): void {
t.expects(size_of::<ray>() == 32 && size_of::<plane>() == 20 && size_of::<bounds>() == 32 && size_of::<sphere>() == 20);
t.expects(size_of::<frustum>() == 128 && align_of::<frustum>() == 4 && align_of::<bounds>() == 4);
}
@test def writes_and_reads_its_shapes(t: &mut tester): void {
# Each is written by its fields' names, its vectors as `linear` writes them.
val box := bounds::around(vec3{ 1, 2, 3 }, vec3{ 0.5, 0.5, 0.5 });
val text := json::to_text(&box) else (_) {
t.expects(false);
return;
};
t.expects(text.view() == "{\"min\":{\"x\":0.5,\"y\":1.5,\"z\":2.5},\"max\":{\"x\":1.5,\"y\":2.5,\"z\":3.5}}");
t.expects(json::from_text::<bounds>(text.view()).value == box);
val ball := sphere{ vec3{ 0, 1, 0 }, 0.75 };
t.expects(json::from_text::<sphere>(json::to_text(&ball).value.view()).value == ball);
val floor := plane::through(vec3{ 0, 2, 0 }, vec3::up);
t.expects(json::from_text::<plane>(json::to_text(&floor).value.view()).value == floor);
val look := ray::toward(vec3::zero, vec3{ 0, 0, -4 });
t.expects(json::from_text::<ray>(json::to_text(&look).value.view()).value == look);
}
@test def measures_planes(t: &mut tester): void {
val floor := plane::through(vec3{ 0, 2, 0 }, vec3{ 0, 5, 0 });
t.expects(floor.normal == vec3::up && floor.distance == 2);
t.expects(floor.distance_to(vec3{ 3, 5, -1 }) == 3 && floor.distance_to(vec3::zero) == -2);
t.expects(floor.closest(vec3{ 3, 5, -1 }) == vec3{ 3, 2, -1 } && floor.flipped().distance_to(vec3::zero) == 2);
# Turning counterclockwise as seen from +z, it faces +z.
val wall := plane::of_points(vec3{ 0, 0, 1 }, vec3{ 1, 0, 1 }, vec3{ 0, 1, 1 });
t.expects(wall.normal == vec3::back && wall.distance == 1);
t.expects(floor.side_of(bounds::around(vec3{ 0, 4, 0 }, vec3::one)) == side::front);
t.expects(floor.side_of(bounds::around(vec3{ 0, 2.5, 0 }, vec3::one)) == side::across);
t.expects(floor.side_of(bounds::around(vec3{ 5, -1, 5 }, vec3::one)) == side::back);
# A sphere touching it is on both sides.
t.expects(floor.side_of(sphere{ vec3::zero, 2 }) == side::across && floor.side_of(sphere{ vec3{ 0, -1, 0 }, 2 }) == side::back);
}
@test def holds_and_meets_boxes_and_spheres(t: &mut tester): void {
val b := bounds{ vec3{ -1, 0, -1 }, vec3{ 1, 2, 1 } };
t.expects(b.center == vec3{ 0, 1, 0 } && b.size == vec3{ 2, 2, 2 } && b.half_size == vec3::one);
t.expects(b.contains(vec3{ 1, 2, 1 }) && !b.contains(vec3{ 1, 2.5, 1 }));
t.expects(b.contains(bounds::around(b.center, vec3{ 0.5, 0.5, 0.5 })) && !b.contains(bounds::around(b.center, vec3{ 2, 0.5, 0.5 })));
# Touching at a corner, they meet.
t.expects(b.overlaps(bounds{ vec3{ 1, 2, 1 }, vec3{ 3, 3, 3 } }) && !b.overlaps(bounds{ vec3{ 1.5, 0, 0 }, vec3{ 3, 1, 1 } }));
t.expects(b.closest(vec3{ 5, 1, -3 }) == vec3{ 1, 1, -1 } && b.closest(vec3{ 0, 1, 0 }) == vec3{ 0, 1, 0 });
val points: vec3[3] = [vec3{ 1, 5, -2 }, vec3{ -3, 0, 4 }, vec3{ 2, 1, 0 }];
t.expects(bounds::of(points[:]) == bounds{ vec3{ -3, 0, -2 }, vec3{ 2, 5, 4 } } && bounds::of(points[0:0]) == bounds::empty);
t.expects(bounds::empty.is_empty && !b.is_empty && bounds::empty.including(vec3::one) == bounds{ vec3::one, vec3::one });
t.expects(b.merged(bounds::around(vec3{ 4, 0, 0 }, vec3::one)) == bounds{ vec3{ -1, -1, -1 }, vec3{ 5, 2, 1 } });
# A quarter turn about z takes the box's reach along y to x, and along x to y.
val quarter := quat::axis_angle(vec3::back, math::pi as f32 / 2);
val turned := bounds::around(vec3::zero, vec3{ 1, 2, 3 }).transformed(mat4::compose(vec3{ 10, 0, 0 }, quarter, vec3::one));
t.expects(near(turned.min, vec3{ 8, -1, -3 }) && near(turned.max, vec3{ 12, 1, 3 }));
t.expects(bounds::empty.transformed(mat4::identity).is_empty);
val s := sphere{ vec3::zero, 2 };
t.expects(s.contains(vec3{ 0, 2, 0 }) && !s.contains(vec3{ 1.5, 1.5, 0 }));
# Touching, they meet.
t.expects(s.overlaps(sphere{ vec3{ 3, 0, 0 }, 1 }) && !s.overlaps(sphere{ vec3{ 3, 0, 0.5 }, 0.9 }));
t.expects(s.overlaps(b) && b.overlaps(s) && !s.overlaps(bounds::around(vec3{ 3, 3, 0 }, vec3::one)));
t.expects(bounds::of(s) == bounds::around(vec3::zero, vec3{ 2, 2, 2 }));
t.expects(sphere::of(b).center == b.center && near(sphere::of(b).radius, math::sqrt(3f)));
}
@test def casts_rays(t: &mut tester): void {
val r := ray::toward(vec3{ 0, 0, 10 }, vec3::zero);
t.expects(r.direction == vec3::forward && r.at(4) == vec3{ 0, 0, 6 });
t.expects(r.closest(vec3{ 3, 0, 5 }) == vec3{ 0, 0, 5 } && r.closest(vec3{ 0, 0, 20 }) == r.origin);
# A wall ahead is met from in front, and one behind, and a floor it runs beside, aren't.
t.expects(hit_at(r.hit(plane::through(vec3{ 0, 0, 1 }, vec3::back))) == 9);
t.expects(hit_at(r.hit(plane::through(vec3{ 0, 0, 1 }, vec3::forward))) == 9);
t.expects(hit_at(r.hit(plane::through(vec3{ 0, 0, 11 }, vec3::back))) == -1 && hit_at(r.hit(plane::through(vec3::zero, vec3::up))) == -1);
# A sphere ahead is met at its surface, one begun within at 0, and one beside or behind not at all.
t.expects(hit_at(r.hit(sphere{ vec3::zero, 2 })) == 8 && hit_at(ray{ vec3::zero, vec3::up }.hit(sphere{ vec3::zero, 2 })) == 0);
t.expects(hit_at(r.hit(sphere{ vec3{ 3, 0, 0 }, 2 })) == -1 && hit_at(r.hit(sphere{ vec3{ 0, 0, 12 }, 1 })) == -1);
# A box ahead is met at its face, one begun within at 0, and one beside or behind not at all.
val b := bounds::around(vec3::zero, vec3::one);
t.expects(hit_at(r.hit(b)) == 9 && hit_at(ray{ vec3::zero, vec3{ 1, 2, 3 } }.hit(b)) == 0);
t.expects(hit_at(r.hit(bounds::around(vec3{ 3, 0, 0 }, vec3::one))) == -1 && hit_at(r.hit(bounds::around(vec3{ 0, 0, 12 }, vec3::one))) == -1);
# Slanting in, it meets the box where it crosses x = -1.
t.expects(near(hit_at(ray::toward(vec3{ -5, -5, 0 }, vec3::zero).hit(b)), 4 * math::sqrt(2f)));
}
@test def culls_by_a_cameras_frustum(t: &mut tester): void {
# Looking from z = 10 at the origin, a quarter turn wide, from 1 to 100 away.
val f := frustum::of(mat4::perspective(math::pi as f32 / 2, 1, 1, 100) * mat4::look_at(vec3{ 0, 0, 10 }, vec3::zero));
# Its planes face in, so the place it looks at is in front of each.
for p in f.planes {
t.expects(p.distance_to(vec3::zero) > 0 && near(p.normal.length, 1));
}
# The far plane is the difference of two rows nearly alike, so as near as an `f32` of 90 gets.
t.expects(near(f.planes[4].distance_to(vec3{ 0, 0, 9 }), 0) && math::abs(f.planes[5].distance_to(vec3{ 0, 0, -90 })) < 1e-3);
t.expects(f.contains(vec3::zero) && f.contains(vec3{ 9, 0, 0 }));
t.expects(!f.contains(vec3{ 0, 0, 9.5 }) && !f.contains(vec3{ 0, 0, -95 }) && !f.contains(vec3{ 11, 0, 0 }) && !f.contains(vec3{ 0, -11, 0 }));
# A box or sphere reaching in from beside is seen, and one wholly beside or behind isn't.
t.expects(f.overlaps(bounds::around(vec3{ 11, 0, 0 }, vec3{ 2, 1, 1 })) && !f.overlaps(bounds::around(vec3{ 14, 0, 0 }, vec3{ 2, 1, 1 })));
t.expects(f.overlaps(bounds::around(vec3{ 0, 0, 9.5 }, vec3::one)) && !f.overlaps(bounds::around(vec3{ 0, 0, 12 }, vec3::one)));
t.expects(f.overlaps(sphere{ vec3{ 0, 0, 9.5 }, 1 }) && !f.overlaps(sphere{ vec3{ 0, 0, 11 }, 1 }));
t.expects(f.overlaps(sphere{ vec3{ 0, 11, 0 }, 1.5 }) && !f.overlaps(sphere{ vec3{ 0, 13, 0 }, 1.5 }));
# Made of its own planes, it's the same.
val again := frustum::of_planes(f.planes);
for i in 0..6u {
t.expects(again.planes[i] == f.planes[i]);
}
# A projection alone gives the frustum in the camera's space, an orthographic one a box.
val o := frustum::of(mat4::orthographic(-10, 10, -10, 10, 0, 50));
t.expects(o.contains(vec3{ 9.5, -9.5, -49 }) && !o.contains(vec3{ 10.5, 0, -1 }) && !o.contains(vec3{ 0, 0, 1 }) && !o.contains(vec3{ 0, 0, -51 }));
}
# The bits of each number, folded together, as FNV-1a folds bytes, wrapping
# as it does.
def fold(hash: u64, x: f32): u64 {
var held := x;
val bits := ((&mut held) as *mut u32)[0] as u64;
return math::wrapping_mul(hash ^ bits, 0x100000001B3);
}
def fold(hash: u64, v: vec3): u64 {
return fold(fold(fold(hash, v.x), v.y), v.z);
}
def fold(hash: u64, yes: bool): u64 {
return math::wrapping_mul(hash ^ (yes ? 1u : 2u), 0x100000001B3);
}
@test def gives_the_same_bits_as_lanes_or_not(t: &mut tester): void {
var h: u64 = 0xCBF29CE484222325;
val f := frustum::of(mat4::perspective(1.1, 1.5, 0.5, 60) * mat4::look_at(vec3{ 3, 4, 12 }, vec3{ 0, 1, 0 }));
val turn := quat::axis_angle(vec3{ 0.2, 1, -0.4 }, 0.37);
var p := vec3{ 0.3, -1.7, 2.9 };
for i in 0..64u {
p = turn * (p * 1.07 + vec3{ 0.11, -0.05, 0.2 });
val b := bounds::around(p, (turn * vec3{ 0.5, 1.25, 0.75 }).abs());
val s := sphere{ p * 0.5, 1.5 };
val r := ray::toward(vec3{ 20, -3, 7 }, p);
val wall := plane::of_points(p, p + vec3::right, p + turn * vec3::up);
val moved := b.transformed(mat4::compose(p, turn, vec3{ 1, 2, 0.5 }));
h = fold(fold(fold(h, moved.min), moved.max), b.closest(s.center));
h = fold(fold(fold(h, hit_at(r.hit(b))), hit_at(r.hit(s))), hit_at(r.hit(wall)));
h = fold(fold(fold(h, r.closest(s.center)), wall.distance_to(s.center)), wall.closest(vec3::zero));
h = fold(fold(fold(h, f.contains(p)), f.overlaps(b)), f.overlaps(s));
h = fold(fold(fold(h, b.overlaps(s)), s.overlaps(moved)), b.overlaps(moved));
h = fold(fold(h, wall.side_of(b) == side::across), wall.side_of(s) == side::front);
}
val corners: vec3[3] = [p, p * 2, -p];
h = fold(fold(h, sphere::of(bounds::of(corners[:])).radius), f.planes[3].normal);
t.expects(h == expected_bits);
}
# What `gives_the_same_bits_as_lanes_or_not` folds, as the machine works it a
# number at a time.
const expected_bits: u64 = 16338969092856802616;
+226
View File
@@ -0,0 +1,226 @@
#! Contains the tests of `linear`: vectors of two, three, and four; rotations;
#! matrices of three and four; projections; values read as lanes where they lie
#! unaligned; and the same bits whether numbers are worked as lanes or one at a
#! time, which `linear.tests` and `linear.lanes.tests` each check.
import std::testing;
import std::json;
import std::math;
import std::serial;
import linear;
# Whether two numbers are within a millionth or so of one another.
def near(a: f32, b: f32): bool {
return math::abs(a - b) < 1e-5;
}
def near(a: vec3, b: vec3): bool {
return near(a.x, b.x) && near(a.y, b.y) && near(a.z, b.z);
}
def near(a: &mat4, b: &mat4): bool {
for i in 0..16u {
return false if !near(a.m[i], b.m[i]);
}
return true;
}
def near(a: &mat3, b: &mat3): bool {
return near(a.x_axis, b.x_axis) && near(a.y_axis, b.y_axis) && near(a.z_axis, b.z_axis);
}
@test def lays_out_its_numbers_as_lanes(t: &mut tester): void {
t.expects(size_of::<vec2>() == 8 && size_of::<vec3>() == 16 && size_of::<vec4>() == 16 && size_of::<quat>() == 16);
t.expects(size_of::<mat3>() == 48 && size_of::<mat4>() == 64);
# Each is of `f32`s, so a field of one is wherever the struct holding it puts it.
t.expects(align_of::<vec3>() == 4 && align_of::<mat4>() == 4);
val v := vec3{ 1, 2, 3 };
t.expects(v.x == 1 && v.y == 2 && v.z == 3 && vec3{ y = 5 } == vec3{ 0, 5, 0 });
}
@test def adds_scales_and_measures_vectors(t: &mut tester): void {
val a := vec3{ 1, 2, 3 };
val b := vec3{ 4, -5, 6 };
t.expects(a + b == vec3{ 5, -3, 9 } && a - b == vec3{ -3, 7, -3 } && -a == vec3{ -1, -2, -3 });
t.expects(a * 2 == vec3{ 2, 4, 6 } && a * b == vec3{ 4, -10, 18 } && b / 2 == vec3{ 2, -2.5, 3 });
t.expects(b / a == vec3{ 4, -2.5, 2 });
t.expects(a.dot(b) == 12 && a.length_squared == 14 && near(a.length, math::sqrt(14f)));
t.expects(near(a.normalized().length, 1) && vec3::zero.normalized() == vec3::zero);
t.expects(near(vec3{ 0, 3, 4 }.distance(vec3::zero), 5));
t.expects(a.lerp(b, 0.5) == vec3{ 2.5, -1.5, 4.5 });
t.expects(a.min(b) == vec3{ 1, -5, 3 } && a.max(b) == vec3{ 4, 2, 6 } && b.abs() == vec3{ 4, 5, 6 });
t.expects(vec3::right.cross(vec3::up) == vec3::back && vec3::up.cross(vec3::right) == vec3::forward);
val c := vec2{ 3, 4 };
t.expects(c + vec2::one == vec2{ 4, 5 } && c * 2 == vec2{ 6, 8 } && c.length == 5 && c.dot(vec2{ 1, 1 }) == 7);
t.expects(vec2{ 1, 0 }.cross(vec2{ 0, 1 }) == 1 && vec2{ 1, 0 }.perpendicular() == vec2{ 0, 1 });
t.expects(near(c.normalized().length, 1) && c.lerp(vec2::zero, 0.5) == vec2{ 1.5, 2 });
val d := vec4{ 1, 2, 3, 4 };
t.expects(d + vec4::one == vec4{ 2, 3, 4, 5 } && d * 0.5 == vec4{ 0.5, 1, 1.5, 2 } && d.dot(d) == 30);
t.expects(d.xyz == a && -d == vec4{ -1, -2, -3, -4 } && near(d.normalized().length, 1));
t.expects(d.min(vec4{ 2, 2, 2, 2 }) == vec4{ 1, 2, 2, 2 } && (d - vec4{ 5, 5, 5, 5 }).abs() == vec4{ 4, 3, 2, 1 });
}
@test def turns_and_moves_vectors(t: &mut tester): void {
val quarter: f32 = math::pi as f32 / 2;
# A quarter turn about y takes x to -z, and about z takes x to y.
t.expects(near(quat::axis_angle(vec3::up, quarter) * vec3::right, vec3{ 0, 0, -1 }));
t.expects(near(quat::axis_angle(vec3::back, quarter) * vec3::right, vec3::up));
# Turning by a rotation and then back changes nothing.
val q := quat::euler(0.3, -1.1, 0.7);
t.expects(near(q.length, 1) && near(q.inverse() * (q * vec3{ 1, 2, 3 }), vec3{ 1, 2, 3 }));
# Turning by one rotation after another is turning by their product.
val r := quat::axis_angle(vec3{ 1, 1, 0 }, 0.4);
t.expects(near((q * r) * vec3{ 1, 2, 3 }, q * (r * vec3{ 1, 2, 3 })));
# A matrix composed of a transform does what the transform does.
val m := mat4::compose(vec3{ 5, 0, -2 }, q, vec3{ 2, 2, 2 });
t.expects(near(m.transform_point(vec3{ 1, 0, 0 }), vec3{ 5, 0, -2 } + q * vec3{ 2, 0, 0 }));
t.expects(near(m.transform_vector(vec3{ 1, 0, 0 }), q * vec3{ 2, 0, 0 }));
t.expects(near(&(m * m.inverse()), &mat4::identity));
val p := m * vec4{ 1, 0, 0, 1 };
t.expects(near(p.xyz, m.transform_point(vec3{ 1, 0, 0 })) && near(p.w, 1));
# Halfway between no turn and a third of one is a sixth.
val half := quat::identity.slerp(quat::axis_angle(vec3::up, 4 * quarter / 3), 0.5);
t.expects(near(half * vec3::right, vec3{ 0.5, 0, -math::sqrt(3f) / 2 }));
# Looking at a place turns -z toward it.
t.expects(near(quat::looking(vec3{ 1, 0, 0 }) * vec3::forward, vec3::right));
}
@test def projects_into_clip_space(t: &mut tester): void {
# The near plane is depth 0, the far one 1, and y points up.
val p := mat4::perspective(math::pi as f32 / 2, 2, 1, 100);
val near_point := p * vec4{ 0, 1, -1, 1 };
t.expects(near(near_point.z / near_point.w, 0) && near(near_point.y / near_point.w, 1));
val far_point := p * vec4{ 0, 0, -100, 1 };
t.expects(near(far_point.z / far_point.w, 1));
val o := mat4::orthographic(0, 200, 100, 0, -1, 1);
val corner := o * vec4{ 200, 100, 0, 1 };
t.expects(near(corner.x, 1) && near(corner.y, -1) && near(corner.z, 0.5));
# A camera looking at the origin from +z sees it straight ahead.
val view := mat4::look_at(vec3{ 0, 0, 10 }, vec3::zero);
t.expects(near(view.transform_point(vec3::zero), vec3{ 0, 0, -10 }));
# A projection is undone, and a scale of zero can't be.
val clip := p * view;
t.expects(near(&(clip * clip.inverse()), &mat4::identity) && near(&(clip.inverse() * clip), &mat4::identity));
t.expects(mat4::scaling(vec3::zero).inverse() == mat4{});
}
@test def works_matrices_of_three(t: &mut tester): void {
val q := quat::euler(0.3, -1.1, 0.7);
val r := mat3::rotation(q);
# A rotation's matrix turns as the rotation does, and its transpose back.
t.expects(near(r * vec3{ 1, 2, 3 }, q * vec3{ 1, 2, 3 }) && near(&(r * r.transposed()), &mat3::identity));
t.expects(near(r.determinant, 1) && near(&r.inverse(), &r.transposed()));
# The rotation of a rotation's matrix is the rotation.
val back := quat::of_basis(r.x_axis, r.y_axis, r.z_axis);
t.expects(near(back * vec3{ 1, 2, 3 }, q * vec3{ 1, 2, 3 }));
val s := mat3::scaling(vec3{ 2, 4, 8 });
t.expects(s.determinant == 64 && near(&(s * s.inverse()), &mat3::identity) && mat3::scaling(vec3::zero).inverse() == mat3{});
t.expects(near(&(r * s), &mat4::compose(vec3::zero, q, vec3{ 2, 4, 8 }).linear_part()));
t.expects(s + s == s * 2 && (s - s) == mat3{});
}
# A value lying where a struct puts it, four bytes past a 16-byte boundary.
struct placed {
var tag: u32;
var at: vec3;
var turn: quat;
var by: mat4;
}
@test def reads_values_where_they_lie(t: &mut tester): void {
var p := placed{ tag = 7, at = vec3{ 1, 2, 3 }, turn = quat::axis_angle(vec3::back, math::pi as f32 / 2), by = mat4::translation(vec3{ 1, 1, 1 }) };
p.at = p.at * 2 + vec3::one;
t.expects(p.tag == 7 && p.at == vec3{ 3, 5, 7 });
t.expects(near(p.turn * vec3::right, vec3::up) && near(p.by.transform_point(p.at), vec3{ 4, 6, 8 }));
t.expects(near(&(p.by * p.by), &mat4::translation(vec3{ 2, 2, 2 })));
# Its lanes, and a vector of lanes.
val l := p.at.lanes();
t.expects(l[0] == 3 && l[1] == 5 && l[2] == 7 && vec3::of_lanes(l) == p.at);
t.expects(vec4::of_lanes(f32x4::of([1.0, 2.0, 3.0, 4.0])) == vec4{ 1, 2, 3, 4 });
}
@serial
struct posed {
@serial var at: vec3;
@serial var turn: quat;
@serial var by: mat3;
@serial var size: vec2;
@serial var tint: vec4;
}
@test def writes_and_reads_its_types(t: &mut tester): void {
# Each is written by its numbers' names, as the shortest text reading back as
# each `f32`, but a `mat4`, as its 16 numbers; `vec3`'s fourth isn't written.
val written := posed{
at = vec3{ 1, 0.1, -2.5 }, turn = quat::axis_angle(vec3::up, 1), by = mat3::scaling(vec3{ 2, 3, 4 }),
size = vec2{ 0.5, 8 }, tint = vec4{ 1, 0.25, 0, 1 },
};
val text := json::to_text(&written) else (_) {
t.expects(false);
return;
};
t.expects(text.view().find("\"at\":{\"x\":1,\"y\":0.1,\"z\":-2.5}") is some(_));
t.expects(text.view().find("\"size\":{\"x\":0.5,\"y\":8}") is some(_) && text.view().find("_w") is none);
val back := json::from_text::<posed>(text.view()) else (_) {
t.expects(false);
return;
};
t.expects(back.at == written.at && back.turn == written.turn && back.by == written.by);
t.expects(back.size == written.size && back.tint == written.tint);
val moved := mat4::compose(vec3{ 1, 2, 3 }, written.turn, vec3{ 2, 2, 2 });
val matrix := json::to_text(&moved) else (_) {
t.expects(false);
return;
};
t.expects(matrix.view().starts_with("[") && json::from_text::<mat4>(matrix.view()).value == moved);
t.expects(json::from_text::<mat4>("[1, 0, 0, 1]").error.kind == json::error_kind::wrong_kind);
# What's left out reads as each number's default, where asked: a rotation's
# `w` of 1, and 0 for the rest.
val lenient := serial::options{ defaults = true };
t.expects(json::from_text::<quat>("{}", lenient).value == quat::identity);
t.expects(json::from_text::<vec3>("{\"y\": 2}", lenient).value == vec3{ 0, 2, 0 });
}
# The bits of each number, folded together, as FNV-1a folds bytes, wrapping
# as it does.
def fold(hash: u64, x: f32): u64 {
var held := x;
val bits := ((&mut held) as *mut u32)[0] as u64;
return math::wrapping_mul(hash ^ bits, 0x100000001B3);
}
def fold(hash: u64, v: vec3): u64 {
return fold(fold(fold(hash, v.x), v.y), v.z);
}
def fold(hash: u64, q: quat): u64 {
return fold(fold(fold(fold(hash, q.x), q.y), q.z), q.w);
}
@test def gives_the_same_bits_as_lanes_or_not(t: &mut tester): void {
var h: u64 = 0xCBF29CE484222325;
var v := vec3{ 0.1, -2.3, 4.5 };
var q := quat::euler(0.2, 0.9, -0.4);
var m := mat4::compose(vec3{ 1, 2, 3 }, q, vec3{ 1.5, 0.5, 2 });
val turn := quat::axis_angle(vec3{ 0.3, 1, -0.2 }, 0.05);
for i in 0..64u {
v = (v + vec3{ 0.25, 0.5, -0.125 }) * 0.9;
v = q * v;
v = m.transform_point(v) - m.transform_vector(v).normalized();
q = (q * turn).normalized();
m = m * mat4::rotation(turn);
h = fold(fold(fold(h, v), q), v.dot(vec3{ 1, 2, 3 }));
h = fold(h, (m * vec4{ v.x, v.y, v.z, 1 }).w);
h = fold(h, (mat3::rotation(q) * v).lerp(v.min(vec3::one).abs(), 0.25));
}
h = fold(fold(h, q.slerp(quat::identity, 0.3)), m.inverse().m[7]);
t.expects(h == expected_bits);
}
# What `gives_the_same_bits_as_lanes_or_not` folds, as the machine works it a
# number at a time.
const expected_bits: u64 = 2409136494821621507;
+11
View File
@@ -0,0 +1,11 @@
#! Contains the `main` that runs the tests of `linear`, `geometry`,
#! `photometry`, and `physics2d`, each in a copy of the program of its own.
#! `blossom test` runs them, and `-- --only TEXT` those whose name holds the
#! text.
import system;
import std::testing;
def main(args: span<strview>): void {
exit(tester::run(args));
}
+71
View File
@@ -0,0 +1,71 @@
#! Contains the tests of `photometry`: lumens and candela of lights every way and
#! within cones, lux and nits of surfaces, exposure values and what they
#! multiply light by, and the colors of temperatures.
import std::testing;
import std::math;
import linear;
import photometry;
# Whether two numbers are within so much of one another, as a fraction of the
# greater: a hundred-thousandth, at first.
def close(a: f32, b: f32, within: f32 = 1e-5): bool {
return math::abs(a - b) <= within * math::max(math::abs(a), math::abs(b));
}
@test def converts_lumens_and_candela(t: &mut tester): void {
val pi := math::pi as f32;
# A sphere's solid angle, a hemisphere's, and a cone of 60 degrees each way.
t.expects(close(solid_angle_of(pi), 4 * pi) && close(solid_angle_of(pi / 2), 2 * pi) && close(solid_angle_of(pi / 3), pi));
# A bare bulb's 800 lumens are about 63.7 candela every way; gathered into
# the cone of 60 degrees, about 255.
t.expects(close(candela_of_lumens(lumens::bulb_60w), 63.66198) && close(candela_of_lumens(800, pi / 3), 254.6479));
t.expects(close(lumens_of_candela(candela::candle), lumens::candle) && close(lumens_of_candela(candela_of_lumens(300, 0.2), 0.2), 300));
# An LED of 8 watts gives what a 60-watt incandescent bulb did.
t.expects(close(lumens_of_watts(8, efficacy::led), lumens::bulb_60w) && close(watts_of_lumens(lumens::bulb_60w, efficacy::incandescent), 57.14286));
}
@test def converts_lux_and_nits(t: &mut tester): void {
# A light of 100 candela gives a surface 2 meters away 25 lux, and gives 4
# lux 5 meters away.
t.expects(close(lux_of_candela(100, 2), 25) && close(distance_of_lux(100, 4), 5));
# A white surface lit by π lux gives back a nit; a grey one half as much.
t.expects(close(nits_of_lux(math::pi as f32), 1) && close(nits_of_lux(100, 0.5), 15.915494));
t.expects(close(lux_of_nits(nits_of_lux(lux::office, 0.18), 0.18), lux::office));
# A clear sky of 7,000 nits lights the ground with about 22,000 lux.
t.expects(close(lux_of_nits(nits::clear_sky), 21991.15));
}
@test def exposes_by_exposure_values(t: &mut tester): void {
# f/16 at a hundredth of a second, as the sunny 16 rule has it, at ISO 100,
# and a step less at ISO 200.
t.expects(close(ev100_of_camera(16, 0.01), 14.643856) && close(ev100_of_camera(16, 0.01, 200), 13.643856));
t.expects(close(ev100_of_lux(lux::direct_sunlight), 15.287712) && close(ev100_of_nits(12.5), 6.643856));
t.expects(close(exposure_of_ev100(0), 1.0 / 1.2) && close(exposure_of_ev100(1), 1.0 / 2.4));
t.expects(close(ev100_of_exposure(exposure_of_ev100(9.7)), 9.7) && close(ev100_of_exposure(1), -0.2630344));
# Exposed as a meter where it's lit reads, a white surface records as two
# thirds of the most, and an 18% grey card about an eighth: middle grey.
for light in [lux::full_moon, lux::office, lux::direct_sunlight] {
val exposure := exposure_of_ev100(ev100_of_lux(light));
t.expects(close(nits_of_lux(light) * exposure, 0.6631456, 1e-4) && close(nits_of_lux(light, 0.18) * exposure, 0.1193662, 1e-4));
}
}
@test def colors_temperatures(t: &mut tester): void {
# A warm bulb's is orange, daylight's about white, and a blue sky's blue.
val warm := color_of_temperature(2700);
t.expects(warm.x == 1 && close(warm.y, 0.4159, 1e-3) && close(warm.z, 0.0984, 1e-2));
val day := color_of_temperature(6500);
t.expects(day.x == 1 && day.y > 0.93 && day.z > 0.98);
val sky := color_of_temperature(10000);
t.expects(sky.z == 1 && sky.y > sky.x && close(sky.x, 0.6095, 1e-3));
# Hotter is bluer all the way.
var last := color_of_temperature(1000);
for k in 1..40u {
val next := color_of_temperature(1000 * (k + 1) as f32);
t.expects(next.z / next.x >= last.z / last.x);
last = next;
}
# Past either end, as either.
t.expects(color_of_temperature(500) == color_of_temperature(1000) && color_of_temperature(90000) == color_of_temperature(40000));
}
+301
View File
@@ -0,0 +1,301 @@
#! Contains the tests of `physics2d`: rotations and poses; shapes, their boxes,
#! and what they hold; manifolds between circles, capsules, and polygons, a
#! box resting on another at two points, a corner at one; rays meeting each
#! shape; a tree of boxes, sound as it's changed, finding what a brute search
#! finds; and a grid of solid cells, met but for the faces they share, and
#! rays passing through it.
import std::testing;
import std::containers;
import std::math;
import linear;
import physics2d;
# Whether two numbers are within a hundred-thousandth or so of one another.
def near(a: f32, b: f32): bool {
return math::abs(a - b) < 1e-4;
}
def near(a: vec2, b: vec2): bool {
return near(a.x, b.x) && near(a.y, b.y);
}
@test def turns_and_places_by_poses(t: &mut tester): void {
val quarter := rot::of(math::pi as f32 / 2);
t.expects(near(quarter.apply(vec2{ 1, 0 }), vec2{ 0, 1 }) && near(quarter.unapply(vec2{ 0, 1 }), vec2{ 1, 0 }));
t.expects(near(quarter.angle, math::pi as f32 / 2) && near((quarter * quarter).apply(vec2{ 1, 0 }), vec2{ -1, 0 }));
val at := pose::of(vec2{ 3, 1 }, math::pi as f32 / 2);
t.expects(near(at.apply(vec2{ 1, 0 }), vec2{ 3, 2 }) && near(at.unapply(vec2{ 3, 2 }), vec2{ 1, 0 }));
# A pose within another, and found again within it.
val inner := pose::of(vec2{ -2, 0.5 }, 0.7);
val both := at * inner;
t.expects(near(both.apply(vec2{ 1, 1 }), at.apply(inner.apply(vec2{ 1, 1 }))));
val found := at.unapply_pose(both);
t.expects(near(found.at, inner.at) && near(found.turn.angle, 0.7));
}
@test def makes_shapes(t: &mut tester): void {
# A box's corners counterclockwise from its bottom left, each edge's normal
# facing out.
val box := shape::box(vec2{ 2, 1 });
t.expects(box.kind == shape_kind::polygon && box.count == 4 && near(box.point(0), vec2{ -2, -1 }) && near(box.point(2), vec2{ 2, 1 }));
t.expects(near(box.normal(0), vec2{ 0, -1 }) && near(box.normal(1), vec2{ 1, 0 }) && near(box.normal(2), vec2{ 0, 1 }) && near(box.normal(3), vec2{ -1, 0 }));
# A polygon around places leaves out what's within and along its edges.
val places: vec2[7] = [vec2{ 0, 0 }, vec2{ 2, 0 }, vec2{ 1, 0 }, vec2{ 2, 2 }, vec2{ 1, 1 }, vec2{ 0, 2 }, vec2{ 0, 2 }];
val square := shape::polygon(places[:]).expect("A square is made.");
t.expects(square.count == 4 && square.contains(pose::identity, vec2{ 1, 1 }) && !square.contains(pose::identity, vec2{ 2.1, 1 }));
# A line holds no area, and nine corners are too many.
val line: vec2[3] = [vec2{ 0, 0 }, vec2{ 1, 1 }, vec2{ 2, 2 }];
t.expects(shape::polygon(line[:]) is none);
var round := vector::<vec2>::new();
for i in 0..9u {
round.append(rot::of(i as f32 * 2 * math::pi as f32 / 9).apply(vec2{ 1, 0 }));
}
t.expects(shape::polygon(round.view()) is none);
# A capsule of one place is a circle; a pill stands up.
t.expects(shape::capsule(vec2{ 1, 1 }, vec2{ 1, 1 }, 0.5).kind == shape_kind::circle);
val pill := shape::pill(1, 3);
t.expects(pill.kind == shape_kind::capsule && near(pill.point(0), vec2{ 0, -1 }) && near(pill.point(1), vec2{ 0, 1 }) && near(pill.radius, 0.5));
# The box holding a shape where a pose places it.
val turned := box.bounds(pose::of(vec2{ 10, 0 }, math::pi as f32 / 2));
t.expects(near(turned.min, vec2{ 9, -2 }) && near(turned.max, vec2{ 11, 2 }));
val held := pill.bounds(pose::of(vec2{ 0, 5 }));
t.expects(near(held.min, vec2{ -0.5, 3.5 }) && near(held.max, vec2{ 0.5, 6.5 }));
t.expects(pill.contains(pose::identity, vec2{ 0.4, 1.2 }) && !pill.contains(pose::identity, vec2{ 0.45, 1.4 }));
}
@test def collides_circles_and_hulls(t: &mut tester): void {
val ball := shape::circle(0.5);
val other := shape::circle(1);
val met := collide(&ball, pose::identity, &other, pose::of(vec2{ 1.2, 0 })).expect("They meet.");
t.expects(met.count == 1 && near(met.normal, vec2{ 1, 0 }) && near(met.points[0].depth, 0.3) && near(met.points[0].point, vec2{ 0.35, 0 }));
t.expects(collide(&ball, pose::identity, &other, pose::of(vec2{ 1.6, 0 })) is none);
# Touching, they meet, at a depth of 0.
t.expects(collide(&ball, pose::identity, &other, pose::of(vec2{ 1.5, 0 })) is some(m) && near(m.depth, 0));
# A ball over a box's face, by its corner, and within it.
val slab := shape::box(vec2{ 1, 0.5 });
val above := collide(&slab, pose::identity, &ball, pose::of(vec2{ 0, 0.9 })).expect("It rests on the box.");
t.expects(near(above.normal, vec2{ 0, 1 }) && near(above.depth, 0.1) && near(above.points[0].point, vec2{ 0, 0.45 }));
val corner := collide(&slab, pose::identity, &ball, pose::of(vec2{ 1.3, 0.8 })).expect("It meets the corner.");
val diagonal := math::sqrt(0.5f);
t.expects(near(corner.normal, vec2{ diagonal, diagonal }) && near(corner.depth, 0.5 - math::sqrt(0.18f)));
val small := shape::circle(0.1);
val within := collide(&slab, pose::identity, &small, pose::of(vec2{ 0.8, 0 })).expect("It's within the box.");
t.expects(near(within.normal, vec2{ 1, 0 }) && near(within.depth, 0.3));
# The other way around, the normal is turned around.
val back := collide(&small, pose::of(vec2{ 0.8, 0 }), &slab, pose::identity).expect("It's within the box.");
t.expects(near(back.normal, vec2{ -1, 0 }) && near(back.depth, 0.3));
# A capsule and a ball meet as the ball nears its segment.
val pill := shape::capsule(vec2{ -1, 0 }, vec2{ 1, 0 }, 0.25);
val side := collide(&pill, pose::identity, &ball, pose::of(vec2{ 0.3, 0.7 })).expect("It meets the capsule's side.");
t.expects(near(side.normal, vec2{ 0, 1 }) && near(side.depth, 0.05));
}
@test def collides_hulls_at_one_point_or_two(t: &mut tester): void {
# A box resting flat on another meets it at two points, midway between their
# surfaces.
val slab := shape::box(vec2{ 1, 0.5 });
val crate := shape::box(vec2{ 0.5, 0.5 });
val resting := collide(&slab, pose::identity, &crate, pose::of(vec2{ 0, 0.9 })).expect("The crate rests on the slab.");
t.expects(resting.count == 2 && near(resting.normal, vec2{ 0, 1 }));
t.expects(near(resting.points[0].depth, 0.1) && near(resting.points[1].depth, 0.1));
t.expects(near(resting.points[0].point.y, 0.45) && near(math::abs(resting.points[0].point.x), 0.5) && near(resting.points[0].point.x, -resting.points[1].point.x));
t.expects(collide(&slab, pose::identity, &crate, pose::of(vec2{ 0, 1.1 })) is none);
val flipped := collide(&crate, pose::of(vec2{ 0, 0.9 }), &slab, pose::identity).expect("The slab is under the crate.");
t.expects(flipped.count == 2 && near(flipped.normal, vec2{ 0, -1 }));
# A crate turned onto its corner meets the slab at the corner alone.
val tipped := collide(&slab, pose::identity, &crate, pose::of(vec2{ 0, 1.2 }, math::pi as f32 / 4)).expect("Its corner meets the slab.");
t.expects(tipped.count == 1 && near(tipped.normal, vec2{ 0, 1 }) && near(tipped.depth, 0.5 * math::sqrt(2f) - 0.7));
# A capsule lying on the slab meets it at two points; one standing by its
# corner, at one, along the line from the corner to its end.
val lying := shape::capsule(vec2{ -0.5, 0 }, vec2{ 0.5, 0 }, 0.5);
val flat := collide(&slab, pose::identity, &lying, pose::of(vec2{ 0, 0.9 })).expect("The capsule lies on the slab.");
t.expects(flat.count == 2 && near(flat.normal, vec2{ 0, 1 }) && near(flat.points[0].depth, 0.1) && near(flat.points[0].point.y, 0.45));
val standing := shape::capsule(vec2{ 0, 0 }, vec2{ 0, 1 }, 0.5);
val by := collide(&slab, pose::identity, &standing, pose::of(vec2{ 1.3, 0.8 })).expect("The capsule's end meets the corner.");
val diagonal := math::sqrt(0.5f);
t.expects(by.count == 1 && near(by.normal, vec2{ diagonal, diagonal }) && near(by.depth, 0.5 - math::sqrt(0.18f)));
t.expects(!overlaps(&slab, pose::identity, &standing, pose::of(vec2{ 1.4, 0.9 })));
# Two capsules side by side, and crossing.
val beside := collide(&lying, pose::identity, &lying, pose::of(vec2{ 0, 0.8 })).expect("They lie together.");
t.expects(near(beside.normal, vec2{ 0, 1 }) && near(beside.depth, 0.2));
t.expects(overlaps(&lying, pose::identity, &lying, pose::of(vec2{ 0, 0 }, 1.2)));
# A segment, of no thickness, across a box.
val wire := shape::segment(vec2{ -2, 0 }, vec2{ 2, 0 });
t.expects(overlaps(&wire, pose::identity, &crate, pose::of(vec2{ 0, 0.3 })) && !overlaps(&wire, pose::identity, &crate, pose::of(vec2{ 0, 0.6 })));
}
@test def casts_rays_at_shapes(t: &mut tester): void {
val up := vec2{ 0, 1 };
val ball := shape::circle(1);
val struck := ball.ray_cast(pose::of(vec2{ 3, 0 }), vec2::zero, vec2{ 1, 0 }, 10).expect("It meets the ball.");
t.expects(near(struck.distance, 2) && near(struck.point, vec2{ 2, 0 }) && near(struck.normal, vec2{ -1, 0 }));
t.expects(ball.ray_cast(pose::of(vec2{ 3, 0 }), vec2::zero, up, 10) is none);
t.expects(ball.ray_cast(pose::of(vec2{ 3, 0 }), vec2::zero, vec2{ 1, 0 }, 1.5) is none);
val inside := ball.ray_cast(pose::of(vec2{ 3, 0 }), vec2{ 3, 0 }, up, 10).expect("It begins within the ball.");
t.expects(inside.distance == 0 && near(inside.normal, vec2{ 0, -1 }));
# A box, turned a quarter, its long side up and down.
val box := shape::box(vec2{ 1, 0.5 });
val roof := box.ray_cast(pose::of(vec2{ 0, 5 }, math::pi as f32 / 2), vec2::zero, up, 10).expect("It meets the box.");
t.expects(near(roof.distance, 4) && near(roof.normal, vec2{ 0, -1 }) && near(roof.point, vec2{ 0, 4 }));
t.expects(box.ray_cast(pose::of(vec2{ 0, 5 }), vec2::zero, up, 4) is none);
t.expects(box.ray_cast(pose::of(vec2{ 0, 5 }), vec2{ 2, 0 }, up, 10) is none);
# A capsule, by its side and its round end.
val pill := shape::capsule(vec2{ -1, 3 }, vec2{ 1, 3 }, 0.5);
val side := pill.ray_cast(pose::identity, vec2::zero, up, 10).expect("It meets the capsule's side.");
t.expects(near(side.distance, 2.5) && near(side.normal, vec2{ 0, -1 }));
val end := pill.ray_cast(pose::identity, vec2{ 3, 3 }, vec2{ -1, 0 }, 10).expect("It meets the capsule's end.");
t.expects(near(end.distance, 1.5) && near(end.normal, vec2{ 1, 0 }));
# A segment, from either side.
val wire := shape::segment(vec2{ -1, 2 }, vec2{ 1, 2 });
val from_below := wire.ray_cast(pose::identity, vec2::zero, up, 10).expect("It meets the segment from below.");
val from_above := wire.ray_cast(pose::identity, vec2{ 0, 5 }, vec2{ 0, -1 }, 10).expect("It meets the segment from above.");
t.expects(near(from_below.distance, 2) && near(from_below.normal, vec2{ 0, -1 }) && near(from_above.distance, 3) && near(from_above.normal, up));
}
# Numbers from 0 to 1, each of the last, as an LCG makes them.
struct dice {
var state: u64;
}
def dice::next(&mut this): f32 {
this.state = math::wrapping_add(math::wrapping_mul(this.state, 6364136223846793005), 1442695040888963407);
return (this.state >> 40) as f32 / (1u << 24) as f32;
}
# A box somewhere within 100 of the origin, as large as 3.
def some_box(seed: &mut dice): aabb {
val at := vec2{ seed.next() * 200 - 100, seed.next() * 200 - 100 };
return aabb::around(at, vec2{ 0.1 + seed.next() * 1.4, 0.1 + seed.next() * 1.4 });
}
@test def sorts_boxes_in_a_tree(t: &mut tester): void {
var seed := dice{ state = 7 };
var tree := aabb_tree::new(0.25);
var boxes := vector::<aabb>::new();
var leaves := vector::<u32>::new();
for i in 0..500u {
val box := some_box(&mut seed);
boxes.append(box);
leaves.append(tree.insert(box, i));
}
t.expects(tree.length == 500 && tree.is_sound() && tree.height <= 18);
# Moved a little, a leaf stays; moved further, it's put again. Half are
# removed.
t.expects(!tree.move(leaves[0], aabb{ boxes[0].min + vec2{ 0.1, 0 }, boxes[0].max + vec2{ 0.1, 0 } }));
for i in 0..500u {
if i % 2 == 0 {
boxes[i] = some_box(&mut seed);
_ = tree.move(leaves[i], boxes[i]);
} else if i % 4 == 1 {
tree.remove(leaves[i]);
}
}
t.expects(tree.length == 375 && tree.is_sound());
# What a box meets is what a brute search finds, of the leaves' grown boxes.
for k in 0..20u {
val asked := aabb::around(vec2{ seed.next() * 200 - 100, seed.next() * 200 - 100 }, vec2{ 8, 8 });
var found := vector::<u64>::new();
tree.query(asked, def(leaf: u32, data: u64): bool {
found.append(data);
return true;
});
var expected: u64 = 0;
for i in 0..500u {
if i % 4 != 1 && tree.box_of(leaves[i]).overlaps(asked) {
expected++;
}
}
t.expects(found.length == expected);
}
# The nearest box along a ray, the search narrowing as each is met.
val from := vec2{ -120, 3 };
val way := vec2{ 1, 0.1 }.normalized();
var nearest: f32 = 1000;
tree.ray_cast(from, way, 1000, def(leaf: u32, data: u64, reach: f32): f32 {
if boxes[data].ray_hit(from, way, reach) is some(at) {
nearest = math::min(nearest, at);
return at;
}
return reach;
});
var expected: f32 = 1000;
for i in 0..500u {
if i % 4 != 1 && boxes[i].ray_hit(from, way, 1000) is some(at) {
expected = math::min(expected, at);
}
}
t.expects(near(nearest, expected) && expected < 1000);
for i in 0..500u {
if i % 4 != 1 {
tree.remove(leaves[i]);
}
}
t.expects(tree.length == 0 && tree.is_sound() && tree.height == 0);
}
# Six cells across and four up: a floor along the bottom, and a wall up the
# right side.
def walled(): grid {
var made := grid::new(6, 4);
for x in 0..6u {
made.set(x as u32, 0, true);
}
for y in 0..4u {
made.set(5, y as u32, true);
}
return made;
}
# The manifolds a shape meets a grid with.
def met(g: &grid, at: pose, s: &shape, at_s: pose): vector<manifold> {
var found := vector::<manifold>::new();
g.collide(at, s, at_s, def(x: u32, y: u32, m: manifold): bool {
found.append(m);
return true;
});
return found;
}
@test def meets_a_grid_of_solid_cells(t: &mut tester): void {
val g := walled();
t.expects(g.is_solid(2, 0) && !g.is_solid(2, 1) && g.is_solid(5, 3) && !g.is_solid(-1, 0) && !g.is_solid(6, 0));
val crate := shape::box(vec2{ 0.4, 0.4 });
# On the floor, across two cells, pushed up by both.
val resting := met(&g, pose::identity, &crate, pose::of(vec2{ 2, 1.35 }));
t.expects(resting.length == 2 && near(resting[0].normal, vec2{ 0, 1 }) && near(resting[1].normal, vec2{ 0, 1 }) && near(resting[0].depth, 0.05));
# Sunk into the floor and just over a seam: the cell past the seam would
# push it back across the floor, along the face two cells share, so it's
# passed over.
val sunk := met(&g, pose::identity, &crate, pose::of(vec2{ 1.61, 0.75 }));
t.expects(sunk.length == 1 && near(sunk[0].normal, vec2{ 0, 1 }) && near(sunk[0].depth, 0.65));
# Against the wall, pushed back from it.
val leaning := met(&g, pose::identity, &crate, pose::of(vec2{ 4.65, 2 }));
t.expects(leaning.length == 2 && near(leaning[0].normal, vec2{ -1, 0 }) && near(leaning[0].depth, 0.05));
t.expects(g.overlaps(pose::identity, &crate, pose::of(vec2{ 4.65, 2 })) && !g.overlaps(pose::identity, &crate, pose::of(vec2{ 2, 2 })));
# The grid placed elsewhere is met there.
val moved := pose::of(vec2{ 10, 0 });
t.expects(met(&g, moved, &crate, pose::of(vec2{ 12, 1.35 })).length == 2 && met(&g, moved, &crate, pose::of(vec2{ 2, 1.35 })).is_empty);
# A ray down to the floor, through the cells above it.
val down := vec2{ 1, -1 }.normalized();
val floor := g.ray_cast(pose::identity, vec2{ 0.3, 3.5 }, down, 10).expect("It meets the floor.");
t.expects(floor.x == 2 && floor.y == 0 && near(floor.hit.distance, 2.5 * math::sqrt(2f)) && near(floor.hit.normal, vec2{ 0, 1 }));
t.expects(near(floor.hit.point, vec2{ 2.8, 1 }));
# From outside the grid, into the wall.
val wall := g.ray_cast(pose::identity, vec2{ -2, 2.5 }, vec2{ 1, 0 }, 10).expect("It meets the wall.");
t.expects(wall.x == 5 && wall.y == 2 && near(wall.hit.distance, 7) && near(wall.hit.normal, vec2{ -1, 0 }));
t.expects(g.ray_cast(pose::identity, vec2{ -2, 2.5 }, vec2{ 1, 0 }, 6.5) is none);
t.expects(g.ray_cast(pose::identity, vec2{ 1, 2 }, vec2{ 0, 1 }, 10) is none);
val within := g.ray_cast(pose::identity, vec2{ 5.5, 2.5 }, vec2{ -1, 0 }, 10).expect("It begins in the wall.");
t.expects(within.hit.distance == 0 && within.x == 5 && within.y == 2);
val there := g.ray_cast(moved, vec2{ 8, 2.5 }, vec2{ 1, 0 }, 10).expect("It meets the moved wall.");
t.expects(near(there.hit.distance, 7) && near(there.hit.point, vec2{ 15, 2.5 }));
}
+304
View File
@@ -0,0 +1,304 @@
#! Times what `linear` does most, each over a thousand values two thousand
#! times, against the same worked a number at a time on a `vec3` of 12 bytes,
#! as hearth's scenes worked it before: adding and scaling vectors, their dots
#! and lengths, quaternions' products and turns, and matrices' products,
#! points, and inverses.
#!
#! Each pass is a function of its own, as a system is, and what it times is
#! called from elsewhere too, so nothing is inlined only for being called once:
#! the code an executable makes of a loop hangs on what is around it.
#!
#! `blossom build`, then run `linear.bench`, as an executable optimized with
#! `-O2`: the VM works numbers one at a time either way.
import std::io;
import std::math;
import std::time;
import std::containers;
import linear;
# A vector of three of 12 bytes, and the rest, as they were before.
struct old3 { var x: f32; var y: f32; var z: f32; }
struct oldq { var x: f32; var y: f32; var z: f32; var w: f32; }
struct oldm { var m: f32[16]; }
def old3::add(&this, o: &old3): old3 { return old3{ this.x + o.x, this.y + o.y, this.z + o.z }; }
def old3::mul(&this, by: &f32): old3 { return old3{ this.x * by, this.y * by, this.z * by }; }
def old3::dot(&this, o: old3): f32 { return this.x * o.x + this.y * o.y + this.z * o.z; }
def old3::cross(&this, o: old3): old3 { return old3{ this.y * o.z - this.z * o.y, this.z * o.x - this.x * o.z, this.x * o.y - this.y * o.x }; }
def old3::normalized(&this): old3 {
val l := math::sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
return l > 0 ? old3{ this.x / l, this.y / l, this.z / l } : old3{};
}
def oldq::mul(&this, o: &oldq): oldq {
return oldq{
this.w * o.x + this.x * o.w + this.y * o.z - this.z * o.y,
this.w * o.y - this.x * o.z + this.y * o.w + this.z * o.x,
this.w * o.z + this.x * o.y - this.y * o.x + this.z * o.w,
this.w * o.w - this.x * o.x - this.y * o.y - this.z * o.z,
};
}
def oldq::turn(&this, v: &old3): old3 {
val q := old3{ this.x, this.y, this.z };
val t := q.cross(v) * 2;
return v + t * this.w + q.cross(t);
}
def oldm::mul(&this, other: &oldm): oldm {
var made := oldm{};
for c in 0..4u {
for r in 0..4u {
made.m[c * 4 + r] = this.m[r] * other.m[c * 4] + this.m[4 + r] * other.m[c * 4 + 1]
+ this.m[8 + r] * other.m[c * 4 + 2] + this.m[12 + r] * other.m[c * 4 + 3];
}
}
return made;
}
# A matrix of three as one would be worked a number at a time.
struct old33 { var x: old3; var y: old3; var z: old3; }
def old33::turned(&this, v: &old3): old3 {
return old3{
this.x.x * v.x + this.y.x * v.y + this.z.x * v.z,
this.x.y * v.x + this.y.y * v.y + this.z.y * v.z,
this.x.z * v.x + this.y.z * v.y + this.z.z * v.z,
};
}
def old33::mul(&this, o: &old33): old33 {
return old33{ this.turned(&o.x), this.turned(&o.y), this.turned(&o.z) };
}
def oldm::point(&this, p: old3): old3 {
return old3{
this.m[0] * p.x + this.m[4] * p.y + this.m[8] * p.z + this.m[12],
this.m[1] * p.x + this.m[5] * p.y + this.m[9] * p.z + this.m[13],
this.m[2] * p.x + this.m[6] * p.y + this.m[10] * p.z + this.m[14],
};
}
const count: u64 = 1024;
const rounds: u64 = 2000;
const dt: f32 = 0.016;
# What each pass works over.
struct data {
var ps: vector<vec3>;
var vs: vector<vec3>;
var qs: vector<quat>;
var ms: vector<mat4>;
var rs: vector<mat3>;
var ws: vector<vec4>;
var out: vector<mat4>;
var ops: vector<old3>;
var ovs: vector<old3>;
var oqs: vector<oldq>;
var oms: vector<oldm>;
var oout: vector<oldm>;
var ors: vector<old33>;
var r_out: vector<mat3>;
var or_out: vector<old33>;
var sum: f32;
}
# How long a pass took, for each value, beside what it took before.
def report(what: strview, started: &instant, before: f64): f64 {
val ns := started.elapsed().in_nanoseconds as f64 / (count * rounds) as f64;
if before == 0 {
println($"{what}: {ns} ns");
} else {
println($"{what}: {ns} ns, before {before} ns, {before / ns}x");
}
return ns;
}
def step_before(d: &mut data): f64 {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.ops[i] = d.ops[i] + d.ovs[i] * dt; } }
return report("vec3 p + v * dt, before", &at, 0);
}
def step(d: &mut data, before: f64): void {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.ps[i] = d.ps[i] + d.vs[i] * dt; } }
_ = report("vec3 p + v * dt", &at, before);
}
def dots_before(d: &mut data): f64 {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.sum += d.ops[i].dot(d.ovs[i]); } }
return report("vec3 dot, before", &at, 0);
}
def dots(d: &mut data, before: f64): void {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.sum += d.ps[i].dot(d.vs[i]); } }
_ = report("vec3 dot", &at, before);
}
def normals_before(d: &mut data): f64 {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.ovs[i] = (d.ovs[i] + d.ops[i]).normalized(); } }
return report("vec3 normalized, before", &at, 0);
}
def normals(d: &mut data, before: f64): void {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.vs[i] = (d.vs[i] + d.ps[i]).normalized(); } }
_ = report("vec3 normalized", &at, before);
}
def crosses_before(d: &mut data): f64 {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.ovs[i] = d.ovs[i].cross(d.ops[i]); } }
return report("vec3 cross, before", &at, 0);
}
def crosses(d: &mut data, before: f64): void {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.vs[i] = d.vs[i].cross(d.ps[i]); } }
_ = report("vec3 cross", &at, before);
}
def turns_before(d: &mut data, by: &oldq): f64 {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.oqs[i] = d.oqs[i] * by; } }
return report("quat * quat, before", &at, 0);
}
def turns(d: &mut data, by: &quat, before: f64): void {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.qs[i] = d.qs[i] * by; } }
_ = report("quat * quat", &at, before);
}
def rotations_before(d: &mut data): f64 {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.ops[i] = d.oqs[i].turn(&d.ops[i]); } }
return report("quat * vec3, before", &at, 0);
}
def rotations(d: &mut data, before: f64): void {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.ps[i] = d.qs[i] * d.ps[i]; } }
_ = report("quat * vec3", &at, before);
}
def directions(d: &mut data): void {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.ps[i] = d.rs[i] * d.ps[i]; } }
_ = report("mat3 * vec3", &at, 0);
}
def tensors_before(d: &mut data): f64 {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.or_out[i] = d.ors[i] * d.ors[(i + 1) % count]; } }
return report("mat3 * mat3, a number at a time", &at, 0);
}
def tensors(d: &mut data, before: f64): void {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.r_out[i] = d.rs[i] * d.rs[(i + 1) % count]; } }
_ = report("mat3 * mat3", &at, before);
}
def products_before(d: &mut data): f64 {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.oout[i] = d.oms[i] * d.oms[(i + 1) % count]; } }
return report("mat4 * mat4, before", &at, 0);
}
def products(d: &mut data, before: f64): void {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.out[i] = d.ms[i] * d.ms[(i + 1) % count]; } }
_ = report("mat4 * mat4", &at, before);
}
def projections(d: &mut data): void {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.ws[i] = d.ms[i] * d.ws[i]; } }
_ = report("mat4 * vec4", &at, 0);
}
def points_before(d: &mut data): f64 {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.ops[i] = d.oms[i].point(d.ops[i]); } }
return report("mat4 transform_point, before", &at, 0);
}
def points(d: &mut data, before: f64): void {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.ps[i] = d.ms[i].transform_point(d.ps[i]); } }
_ = report("mat4 transform_point", &at, before);
}
def inverses(d: &mut data): void {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.out[i] = d.ms[i].inverse(); } }
_ = report("mat4 inverse", &at, 0);
}
# Each of what's timed, called once more, so none is called from one place.
def elsewhere(d: &mut data): void {
d.ps[0] = d.ps[1] + d.vs[1] * 2;
d.ops[0] = d.ops[1] + d.ovs[1] * 2;
d.sum += d.ps[1].dot(d.vs[1]) + d.ops[1].dot(d.ovs[1]);
d.vs[0] = d.vs[1].normalized().cross(d.ps[1]);
d.ovs[0] = d.ovs[1].normalized().cross(d.ops[1]);
d.qs[0] = d.qs[1] * d.qs[2];
d.oqs[0] = d.oqs[1] * d.oqs[2];
d.ps[0] = d.qs[1] * (d.rs[1] * d.ps[1]);
d.ops[0] = d.oqs[1].turn(&d.ops[1]);
d.out[0] = d.ms[1] * d.ms[2];
d.oout[0] = d.oms[1] * d.oms[2];
d.r_out[0] = d.rs[1] * d.rs[2];
d.or_out[0] = d.ors[1] * d.ors[2];
d.ws[0] = d.ms[1] * d.ws[1];
d.ps[0] = d.ms[1].transform_point(d.ps[1]);
d.ops[0] = d.oms[1].point(d.ops[1]);
d.out[0] = d.ms[1].inverse();
}
def main(): void {
println($"lanes held: {lanes_held()}");
var d := data{
ps = vector::<vec3>::new(), vs = vector::<vec3>::new(), qs = vector::<quat>::new(), ms = vector::<mat4>::new(),
rs = vector::<mat3>::new(), ws = vector::<vec4>::new(), out = vector::<mat4>::new(), ops = vector::<old3>::new(),
ovs = vector::<old3>::new(), oqs = vector::<oldq>::new(), oms = vector::<oldm>::new(), oout = vector::<oldm>::new(),
ors = vector::<old33>::new(), r_out = vector::<mat3>::new(), or_out = vector::<old33>::new(),
};
for i in 0..count {
d.ps.append(vec3{ i as f32 * 0.001, 1, 2 });
d.vs.append(vec3{ 0.5, 0.25, 0.125 });
d.ops.append(old3{ i as f32 * 0.001, 1, 2 });
d.ovs.append(old3{ 0.5, 0.25, 0.125 });
val q := quat::axis_angle(vec3{ 1, 2, i as f32 }, i as f32 * 0.01);
d.qs.append(q);
d.oqs.append(oldq{ q.x, q.y, q.z, q.w });
val r := mat3::rotation(q);
d.rs.append(r);
d.ors.append(old33{
old3{ r.x_axis.x, r.x_axis.y, r.x_axis.z }, old3{ r.y_axis.x, r.y_axis.y, r.y_axis.z }, old3{ r.z_axis.x, r.z_axis.y, r.z_axis.z },
});
val m := mat4::compose(vec3{ i as f32, 1, 2 }, q, vec3{ 1, 2, 1 });
d.ms.append(m);
d.oms.append(oldm{ m = m.m });
d.ws.append(vec4{ i as f32, 1, 2, 1 });
}
d.out.resize(count);
d.oout.resize(count);
d.r_out.resize(count);
d.or_out.resize(count);
elsewhere(&mut d);
step(&mut d, step_before(&mut d));
dots(&mut d, dots_before(&mut d));
normals(&mut d, normals_before(&mut d));
crosses(&mut d, crosses_before(&mut d));
val turn := quat::axis_angle(vec3::up, 0.001);
turns(&mut d, &turn, turns_before(&mut d, &oldq{ turn.x, turn.y, turn.z, turn.w }));
rotations(&mut d, rotations_before(&mut d));
directions(&mut d);
tensors(&mut d, tensors_before(&mut d));
products(&mut d, products_before(&mut d));
projections(&mut d);
points(&mut d, points_before(&mut d));
inverses(&mut d);
# What was worked, so none of it is left out.
println($"checks: {d.sum} {d.ps[3].y} {d.ops[3].y} {d.vs[5].x} {d.ovs[5].x} {d.qs[7].w} {d.oqs[7].w} {d.out[9].m[5]} {d.oout[9].m[5]} {d.ws[2].y}");
}
+236
View File
@@ -0,0 +1,236 @@
#! Times what `geometry` does most, each over a thousand values two thousand
#! times, against the same worked a number at a time on a `vec3` of 12 bytes:
#! a camera's frustum culling boxes and spheres, rays meeting boxes and
#! spheres, and boxes moved by matrices.
#!
#! Each pass is a function of its own, as a system is, and what it times is
#! called from elsewhere too, so nothing is inlined only for being called once:
#! the code an executable makes of a loop hangs on what is around it.
#!
#! `blossom build`, then run `geometry.bench`, as an executable optimized with
#! `-O2`: the VM works numbers one at a time either way.
import std::io;
import std::math;
import std::time;
import std::containers;
import linear;
import geometry;
# The shapes as they'd be written a number at a time, of vectors of 12 bytes.
struct old3 { var x: f32; var y: f32; var z: f32; }
struct oldp { var x: f32; var y: f32; var z: f32; var d: f32; }
struct oldb { var min: old3; var max: old3; }
struct olds { var center: old3; var radius: f32; }
struct oldr { var origin: old3; var direction: old3; }
struct oldm { var m: f32[16]; }
# Whether a box is in front of each of six planes, of the corner furthest in
# front of each, a plane at a time.
def oldb::seen(&this, planes: &oldp[6]): bool {
for i in 0..6u {
val p := planes[i];
val x := p.x < 0 ? this.min.x : this.max.x;
val y := p.y < 0 ? this.min.y : this.max.y;
val z := p.z < 0 ? this.min.z : this.max.z;
return false if p.x * x + p.y * y + p.z * z - p.d < 0;
}
return true;
}
def olds::seen(&this, planes: &oldp[6]): bool {
for i in 0..6u {
val p := planes[i];
return false if p.x * this.center.x + p.y * this.center.y + p.z * this.center.z - p.d + this.radius < 0;
}
return true;
}
# Where a ray meets a box, or -1, between the box's faces along each axis.
def oldr::hit(&this, b: &oldb): f32 {
val ix := 1 / this.direction.x;
val iy := 1 / this.direction.y;
val iz := 1 / this.direction.z;
val x0 := (b.min.x - this.origin.x) * ix;
val x1 := (b.max.x - this.origin.x) * ix;
val y0 := (b.min.y - this.origin.y) * iy;
val y1 := (b.max.y - this.origin.y) * iy;
val z0 := (b.min.z - this.origin.z) * iz;
val z1 := (b.max.z - this.origin.z) * iz;
val enter := math::max(math::max(math::min(x0, x1), math::min(y0, y1)), math::max(math::min(z0, z1), 0));
val leave := math::min(math::min(math::max(x0, x1), math::max(y0, y1)), math::max(z0, z1));
return enter <= leave ? enter : -1;
}
# Where a ray meets a sphere, or -1.
def oldr::hit(&this, s: &olds): f32 {
val mx := this.origin.x - s.center.x;
val my := this.origin.y - s.center.y;
val mz := this.origin.z - s.center.z;
val c := mx * mx + my * my + mz * mz - s.radius * s.radius;
return 0 if c <= 0;
val b := mx * this.direction.x + my * this.direction.y + mz * this.direction.z;
return -1 if b >= 0;
val a := this.direction.x * this.direction.x + this.direction.y * this.direction.y + this.direction.z * this.direction.z;
val d := b * b - a * c;
return d < 0 ? -1 : (-b - math::sqrt(d)) / a;
}
# The box holding a box a matrix moves.
def oldb::moved(&this, by: &oldm): oldb {
val m := &by.m;
val cx := (this.min.x + this.max.x) * 0.5;
val cy := (this.min.y + this.max.y) * 0.5;
val cz := (this.min.z + this.max.z) * 0.5;
val hx := (this.max.x - this.min.x) * 0.5;
val hy := (this.max.y - this.min.y) * 0.5;
val hz := (this.max.z - this.min.z) * 0.5;
val x := m[0] * cx + m[4] * cy + m[8] * cz + m[12];
val y := m[1] * cx + m[5] * cy + m[9] * cz + m[13];
val z := m[2] * cx + m[6] * cy + m[10] * cz + m[14];
val rx := math::abs(m[0]) * hx + math::abs(m[4]) * hy + math::abs(m[8]) * hz;
val ry := math::abs(m[1]) * hx + math::abs(m[5]) * hy + math::abs(m[9]) * hz;
val rz := math::abs(m[2]) * hx + math::abs(m[6]) * hy + math::abs(m[10]) * hz;
return oldb{ old3{ x - rx, y - ry, z - rz }, old3{ x + rx, y + ry, z + rz } };
}
const count: u64 = 1024;
const rounds: u64 = 2000;
# What each pass works over.
struct data {
var boxes: vector<bounds>;
var spheres: vector<sphere>;
var rays: vector<ray>;
var ms: vector<mat4>;
var moved: vector<bounds>;
var oboxes: vector<oldb>;
var ospheres: vector<olds>;
var orays: vector<oldr>;
var oms: vector<oldm>;
var omoved: vector<oldb>;
var seen: u64;
var sum: f32;
}
# How long a pass took, for each value, beside what it took before.
def report(what: strview, started: &instant, before: f64): f64 {
val ns := started.elapsed().in_nanoseconds as f64 / (count * rounds) as f64;
if before == 0 {
println($"{what}: {ns} ns");
} else {
println($"{what}: {ns} ns, before {before} ns, {before / ns}x");
}
return ns;
}
def culled_boxes_before(d: &mut data, planes: &oldp[6]): f64 {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.seen += d.oboxes[i].seen(planes) ? 1 : 0; } }
return report("frustum overlaps bounds, before", &at, 0);
}
def culled_boxes(d: &mut data, f: &frustum, before: f64): void {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.seen += f.overlaps(d.boxes[i]) ? 1 : 0; } }
_ = report("frustum overlaps bounds", &at, before);
}
def culled_spheres_before(d: &mut data, planes: &oldp[6]): f64 {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.seen += d.ospheres[i].seen(planes) ? 1 : 0; } }
return report("frustum overlaps sphere, before", &at, 0);
}
def culled_spheres(d: &mut data, f: &frustum, before: f64): void {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.seen += f.overlaps(d.spheres[i]) ? 1 : 0; } }
_ = report("frustum overlaps sphere", &at, before);
}
def boxes_hit_before(d: &mut data): f64 {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.sum += d.orays[i].hit(&d.oboxes[(i + 1) % count]); } }
return report("ray hit bounds, before", &at, 0);
}
def boxes_hit(d: &mut data, before: f64): void {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.sum += d.rays[i].hit(d.boxes[(i + 1) % count]) is some(t) ? t : -1; } }
_ = report("ray hit bounds", &at, before);
}
def spheres_hit_before(d: &mut data): f64 {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.sum += d.orays[i].hit(&d.ospheres[(i + 1) % count]); } }
return report("ray hit sphere, before", &at, 0);
}
def spheres_hit(d: &mut data, before: f64): void {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.sum += d.rays[i].hit(d.spheres[(i + 1) % count]) is some(t) ? t : -1; } }
_ = report("ray hit sphere", &at, before);
}
def moves_before(d: &mut data): f64 {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.omoved[i] = d.oboxes[i].moved(&d.oms[i]); } }
return report("bounds transformed, before", &at, 0);
}
def moves(d: &mut data, before: f64): void {
val at := instant::now();
for _ in 0..rounds { for i in 0..count { d.moved[i] = d.boxes[i].transformed(d.ms[i]); } }
_ = report("bounds transformed", &at, before);
}
# Each of what's timed, called once more, so none is called from one place.
def elsewhere(d: &mut data, f: &frustum, planes: &oldp[6]): void {
d.seen += (f.overlaps(d.boxes[1]) ? 1 : 0) + (d.oboxes[1].seen(planes) ? 1 : 0);
d.seen += (f.overlaps(d.spheres[1]) ? 1 : 0) + (d.ospheres[1].seen(planes) ? 1 : 0);
d.sum += d.orays[1].hit(&d.oboxes[2]) + d.orays[1].hit(&d.ospheres[2]);
d.sum += (d.rays[1].hit(d.boxes[2]) is some(t) ? t : -1) + (d.rays[1].hit(d.spheres[2]) is some(u) ? u : -1);
d.moved[0] = d.boxes[1].transformed(d.ms[1]);
d.omoved[0] = d.oboxes[1].moved(&d.oms[1]);
}
def old3_of(v: vec3): old3 {
return old3{ v.x, v.y, v.z };
}
def main(): void {
println($"lanes held: {lanes_held()}");
var d := data{
boxes = vector::<bounds>::new(), spheres = vector::<sphere>::new(), rays = vector::<ray>::new(), ms = vector::<mat4>::new(),
moved = vector::<bounds>::new(), oboxes = vector::<oldb>::new(), ospheres = vector::<olds>::new(),
orays = vector::<oldr>::new(), oms = vector::<oldm>::new(), omoved = vector::<oldb>::new(),
};
# A camera at the middle of a field of boxes, seeing about half of them.
val f := frustum::of(mat4::perspective(math::pi as f32 / 3, 16.0 / 9.0, 0.1, 400) * mat4::look_at(vec3{ 0, 5, 0 }, vec3{ 0, 0, -10 }));
var planes: oldp[6];
for i in 0..6u {
val p := f.planes[i];
planes[i] = oldp{ p.normal.x, p.normal.y, p.normal.z, p.distance };
}
for i in 0..count {
val at := vec3{ (i % 32) as f32 * 8 - 128, (i % 3) as f32, (i / 32) as f32 * 8 - 128 };
val b := bounds::around(at, vec3{ 1, 2, 1.5 });
d.boxes.append(b);
d.oboxes.append(oldb{ old3_of(b.min), old3_of(b.max) });
d.spheres.append(sphere{ at, 2 });
d.ospheres.append(olds{ old3_of(at), 2 });
val r := ray::toward(vec3{ 0, 5, 0 }, at);
d.rays.append(r);
d.orays.append(oldr{ old3_of(r.origin), old3_of(r.direction) });
val m := mat4::compose(at, quat::axis_angle(vec3{ 1, 2, i as f32 }, i as f32 * 0.01), vec3{ 1, 2, 1 });
d.ms.append(m);
d.oms.append(oldm{ m = m.m });
}
d.moved.resize(count);
d.omoved.resize(count);
elsewhere(&mut d, &f, &planes);
culled_boxes(&mut d, &f, culled_boxes_before(&mut d, &planes));
culled_spheres(&mut d, &f, culled_spheres_before(&mut d, &planes));
boxes_hit(&mut d, boxes_hit_before(&mut d));
spheres_hit(&mut d, spheres_hit_before(&mut d));
moves(&mut d, moves_before(&mut d));
# What was worked, so none of it is left out.
println($"checks: {d.seen} {d.sum} {d.moved[3].max.y} {d.omoved[3].max.y}");
}