Commit136b0c66Recorded25 Sep 2026Repositorysigil-geometry

Add README, CHANGELOG; non-commuting product test; harness exit status

Message

The aa product test could not tell ab from b*a (a sabotage of mat4-mul! was caught by one property test only). The harness now exits 1 on a FAIL verdict, and the Node driver turns WASI proc_exit back into the process status.

Changed
 CHANGELOG.md                          |  30 ++++++++++++++++++++
 README.md                             | 232 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 harness/run-wasm.mjs                  |  11 +++++++-
 harness/src/geometry-harness/main.sgl |   3 +-
 test/test-mat4.sgl                    |   9 ++++++
 5 files changed, 283 insertions(+), 2 deletions(-)
Diff
CHANGELOG.mdadded
@@ -0,0 +1,30 @@
+1
# Changelog
+2
+3
All notable changes to **sigil-geometry** are documented in this file.
+4
+5
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
+6
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+7
+8
## [0.1.0] - Unreleased
+9
+10
### Added
+11
+12
- **vec2, vec3, vec4** as float32 bytevectors: arithmetic, dot and cross
+13
products, length, normalize, lerp, min/max and tolerant comparison.
+14
- **mat3 and mat4**, column-major (the OpenGL convention): multiply,
+15
transpose, determinant, inverse (#f for a singular matrix),
+16
translation, scale, axis rotations, rotation about any axis, model
+17
matrices from translation, rotation and scale, point, direction and
+18
vec4 transforms, the normal matrix, and a std140-padded mat3 for
+19
uniform blocks.
+20
- **Quaternions**: axis-angle, conversion to and from rotation matrices,
+21
multiply, conjugate, inverse, slerp and nlerp, and vector rotation.
+22
- **Camera matrices** matching `gluPerspective`, `glOrtho` and
+23
`gluLookAt`.
+24
- **Ray casts** against planes, boxes and triangles (with barycentric
+25
weights for picking), plus plane and box helpers.
+26
- Every operation that produces a value has an allocation-free `!` form
+27
whose destination may alias its inputs. Measured at zero allocations
+28
per call for all 55 checked operations on wasm and on bytecode.
+29
- `scripts/check-targets`: the test suite and the allocation check on
+30
bytecode, native ELF and wasm.
README.mdadded
@@ -0,0 +1,232 @@
+1
# sigil-geometry
+2
+3
3D maths for games and graphics in [Sigil](https://codeberg.org/sigil/sigil):
+4
vectors, matrices, quaternions, camera matrices and ray casts.
+5
+6
Every value is a float32 bytevector laid out the way a GPU uniform
+7
expects it, so a matrix goes to a shader with no conversion. Every
+8
operation that produces a vector or matrix has an allocation-free `!`
+9
form that writes into a destination you reuse from frame to frame. The
+10
package is pure Sigil and runs the same on bytecode, native and wasm.
+11
+12
## Install
+13
+14
```scheme
+15
(dependencies: (list
+16
(from-git url: "codeberg:sigil/sigil-geometry" version: "^0.1")))
+17
```
+18
+19
```scheme
+20
(import (sigil geometry))
+21
```
+22
+23
## Example: a camera matrix for a shader
+24
+25
The vertex shader:
+26
+27
```glsl
+28
uniform mat4 u_mvp;
+29
in vec3 a_position;
+30
void main() { gl_Position = u_mvp * vec4(a_position, 1.0); }
+31
```
+32
+33
The Sigil side. The matrices are made once; each frame rewrites them in
+34
place:
+35
+36
```scheme
+37
(import (sigil geometry))
+38
+39
(define proj (mat4-perspective (degrees->radians 70.0) (/ 480.0 270.0) 0.1 100.0))
+40
(define view (make-mat4))
+41
(define model (make-mat4))
+42
(define mvp (make-mat4))
+43
+44
(define eye (vec3 0 1.7 5))
+45
(define target (vec3 0 1.7 0))
+46
(define up (vec3 0 1 0))
+47
(define spin (make-quat))
+48
+49
(define (update-camera! seconds)
+50
(quat-from-axis-angle! spin up seconds)
+51
(mat4-from-quat! model spin)
+52
(mat4-look-at! view eye target up)
+53
(mat4-mul! mvp view model) ; view * model
+54
(mat4-mul! mvp proj mvp) ; proj * view * model
+55
mvp) ; 64 bytes, column-major float32
+56
```
+57
+58
`mvp` is the uniform's data as it stands: sigil-graphics' 3D path takes
+59
the bytevector directly. With sigil-graphics 0.11's `set-shader-uniform`,
+60
which takes a list of numbers and reaches the fragment stage only, pass
+61
`(mat4->list mvp)`; the list is in the column-major order GLSL expects.
+62
+63
## The layout contract
+64
+65
This is what GPU-facing code (sigil-graphics) relies on. It is pinned by
+66
`test/test-layout.sgl`.
+67
+68
| value | bytes | contents |
+69
|---|---|---|
+70
| vec2 | 8 | x y |
+71
| vec3 | 12 | x y z |
+72
| vec4 | 16 | x y z w |
+73
| quat | 16 | x y z w (w is the scalar part; identity is 0 0 0 1) |
+74
| mat3 | 36 | 9 floats, column-major |
+75
| mat4 | 64 | 16 floats, column-major |
+76
+77
- **float32**, IEEE-754 single precision, in **native byte order**
+78
(little-endian on x86-64, aarch64 and wasm32). That is the order GL
+79
reads client memory in.
+80
- **Column-major**, the OpenGL convention: element (column `c`, row `r`)
+81
of a mat4 is float `c*4 + r`. A translation sits in floats 12, 13
+82
and 14. Pass a mat4 to GL with no transpose.
+83
- **Column vectors, multiplied on the left.** `(mat4-mul a b)` applies
+84
`b` first, then `a`. `(quat-mul a b)` follows the same order.
+85
- **OpenGL clip space.** The camera looks down -Z in a right-handed view
+86
space with +Y up, and projections map depth to -1..1 after the divide
+87
by w. The results match `gluPerspective`, `glOrtho` and `gluLookAt`.
+88
- A **std140 uniform block** pads each mat3 column to 4 floats, so it
+89
does not take the tight 36-byte mat3. `mat3->std140!` writes the
+90
48-byte padded form. A mat4 needs no padding.
+91
- Reads return flonums (double precision); writes round to float32, so
+92
`(vec3-x (vec3 0.1 0 0))` is 0.10000000149011612.
+93
+94
sigil-geometry and sigil-graphics do not depend on each other: the
+95
contract is the bytes.
+96
+97
## Conventions
+98
+99
- **Two forms.** `(vec3-add a b)` returns a new vec3. `(vec3-add! dst a b)`
+100
writes into `dst`, returns `dst`, and allocates nothing. The destination
+101
may be the same bytevector as any input: `(mat4-mul! m m other)` is fine.
+102
- **Scalars never allocate.** `vec3-dot`, `vec3-length`,
+103
`mat4-determinant`, `quat-angle` and the ray casts return a number (or
+104
#f) directly.
+105
- **`make-` gives a useful starting value.** `make-vec3` is zeros;
+106
`make-mat3`, `make-mat4` and `make-quat` are the identity.
+107
- **Failure is a value where it can happen in normal use.**
+108
`mat4-inverse!` returns #f for a singular matrix and leaves `dst`
+109
untouched; a ray cast that misses returns #f; normalizing a zero vector
+110
gives zero. Arguments that describe nothing (a perspective with
+111
`near <= 0`, a plane with a zero normal) raise an error.
+112
- **Tolerant comparison.** `vec3-approx=?`, `mat4-approx=?` and friends
+113
take an optional epsilon (default 1e-5, relative above magnitude 1).
+114
`quat-same-rotation?` treats `q` and `-q` as equal.
+115
+116
## API
+117
+118
### Vectors: `(sigil geometry vec)`
+119
+120
For each of vec2, vec3 and vec4 (a `!` marks a form that also has an
+121
allocating twin without the `!`):
+122
+123
| | |
+124
|---|---|
+125
| make | `vec3`, `make-vec3`, `vec3-copy`, `vec3-copy!`, `vec3-set!`, `vec3?` |
+126
| access | `vec3-x`, `vec3-y`, `vec3-z` (`vec4-w`), `vec3->list` |
+127
| arithmetic | `vec3-add!`, `vec3-sub!`, `vec3-mul!` (per component), `vec3-scale!`, `vec3-negate!`, `vec3-lerp!` |
+128
| measure | `vec3-dot`, `vec3-length`, `vec3-length-squared`, `vec3-normalize!`, `vec2-distance`, `vec3-distance` |
+129
| vec3 only | `vec3-cross!`, `vec3-add-scaled!` (a + b·s), `vec3-min!`, `vec3-max!`, `vec3-distance-squared` |
+130
| compare | `vec3-approx=?`, `float-approx=?` |
+131
| angles | `degrees->radians`, `radians->degrees` |
+132
+133
### Matrices: `(sigil geometry mat4)`, `(sigil geometry mat3)`
+134
+135
| | mat4 | mat3 |
+136
|---|---|---|
+137
| make | `mat4` (16 values), `make-mat4`, `mat4-identity!`, `list->mat4`, `mat4-copy!` | `mat3`, `make-mat3`, `mat3-identity!`, `list->mat3`, `mat3-copy!` |
+138
| access | `mat4-ref m col row`, `mat4-set!`, `mat4->list` | `mat3-ref`, `mat3-set!`, `mat3->list` |
+139
| algebra | `mat4-mul!`, `mat4-transpose!`, `mat4-inverse!`, `mat4-determinant` | `mat3-mul!`, `mat3-transpose!`, `mat3-inverse!`, `mat3-determinant` |
+140
| build | `mat4-translation!`, `mat4-scaling!`, `mat4-rotation-x!` / `-y!` / `-z!`, `mat4-rotation! axis angle`, `mat4-from-quat!`, `mat4-from-trs! t q s` | `mat3-from-mat4!`, `mat3-normal-matrix!`, `mat3-from-quat!` |
+141
| apply | `mat4-transform-point!` (w = 1, divides by w), `mat4-transform-direction!` (w = 0), `mat4-transform-vec4!`, `mat4-get-translation!` | `mat3-transform-vec3!` |
+142
| upload | the bytevector itself | `mat3->std140!` |
+143
| compare | `mat4-approx=?` | `mat3-approx=?` |
+144
+145
### Quaternions: `(sigil geometry quat)`
+146
+147
`quat`, `make-quat`, `quat-identity!`, `quat-from-axis-angle!`,
+148
`quat-from-mat3!`, `quat-from-mat4!`, `quat-mul!`, `quat-conjugate!`,
+149
`quat-inverse!`, `quat-normalize!`, `quat-dot`, `quat-length`,
+150
`quat-slerp!`, `quat-nlerp!`, `quat-rotate-vec3!`, `quat-angle`,
+151
`quat-x` / `-y` / `-z` / `-w`, `quat-set!`, `quat-copy!`, `quat->list`,
+152
`quat-approx=?`, `quat-same-rotation?`.
+153
+154
`quat-slerp!` blends two orientations at constant angular speed along
+155
the shorter arc, which is what pose blending needs; `quat-nlerp!` is the
+156
cheaper approximation.
+157
+158
### Cameras: `(sigil geometry camera)`
+159
+160
| | |
+161
|---|---|
+162
| `(mat4-perspective! dst fovy aspect near far)` | `fovy` is the full vertical angle in radians; `aspect` is width / height |
+163
| `(mat4-orthographic! dst left right bottom top near far)` | the view-space box from (left, bottom, -near) to (right, top, -far) |
+164
| `(mat4-look-at! dst eye target up)` | a view matrix; looking straight along `up` still gives a valid rotation |
+165
+166
### Rays: `(sigil geometry ray)`
+167
+168
A ray is an `origin` vec3 and a `dir` vec3. `dir` need not be unit
+169
length: casts return the parameter `t` of the hit point `origin + dir·t`.
+170
That makes a sight line a ray with `dir = target - eye`, where a hit with
+171
`t < 1` is something in between:
+172
+173
```scheme
+174
(vec3-sub! dir player-eye guard-eye)
+175
(let ((t (ray-aabb guard-eye dir crate-min crate-max)))
+176
(and t (< t 1.0))) ; #t: the crate blocks the guard's view
+177
```
+178
+179
| | |
+180
|---|---|
+181
| `(ray-plane origin dir plane)` | `t >= 0` or #f; a plane is a vec4 (a b c d) for a·x + b·y + c·z + d = 0 |
+182
| `(ray-aabb origin dir box-min box-max)` | entry `t` (0.0 from inside) or #f |
+183
| `(ray-triangle origin dir a b c)` | `t` or #f, either face |
+184
| `(ray-triangle-hit! dst origin dir a b c)` | also writes (t u v) into `dst`: u and v weight `b` and `c`, for texture coordinates at a picked point |
+185
| `(ray-point! dst origin dir t)` | the point at `t` |
+186
| `plane-from-point-normal!`, `plane-from-points!`, `plane-signed-distance` | planes with unit normals; counterclockwise points face the viewer |
+187
| `aabb-contains-point?`, `aabb-overlap?` | box tests |
+188
+189
## Allocation, measured
+190
+191
`scripts/check-targets` counts GC allocations over 1000 calls of each of
+192
55 operations (every `!` form plus the scalar and ray functions),
+193
against an empty-loop baseline and a positive control. Results with
+194
sigil 0.22.7:
+195
+196
| target | allocations per call |
+197
|---|---|
+198
| native wasm (the web) | 0 for all 55 |
+199
| bytecode | 0 for all 55 |
+200
| native ELF | 0 for 42; one per argument for the 13 that take 4 or more arguments (see below) |
+201
+202
On a native ELF build, sigil 0.22.7 loads a dependency package's
+203
compiled bytecode rather than its native code, so an app's calls into
+204
sigil-geometry cross from native to bytecode, and that crossing
+205
allocates for calls with 4 or more arguments. It is a property of the
+206
toolchain's ELF bundles, not of this package, and the wasm build is not
+207
affected.
+208
+209
The package uses no `syntax-rules` macros in its hot paths, on purpose:
+210
under native codegen, each global a macro template introduces is looked
+211
up at run time through `%hygiene-ref`, which allocates on every call.
+212
Helper procedures cost nothing.
+213
+214
## Development
+215
+216
```sh
+217
sigil deps install
+218
sigil test # the suite on the host (bytecode)
+219
guix shell -m manifest.scm -- scripts/check-targets
+220
# suite + allocation check on bytecode,
+221
# native ELF and wasm (needs wasm-opt, node)
+222
```
+223
+224
`scripts/check-targets` turns each test file into a library, compiles it
+225
into the app in `harness/` with the allocation check, runs it on each
+226
target (wasm under Node), and reports per target. A target passes when
+227
every test ran and passed and, where the geometry code is native or all
+228
bytecode, no `!` form allocated.
+229
+230
## License
+231
+232
BSD-3-Clause
harness/run-wasm.mjsmodified
@@ -50,6 +50,15 @@ if (typeof ex.sigil_wasm_native_start !== "function") {
50
process.exit(2);
51
}
52
if (ex.sigil_wasm_init() !== 0) { console.error("SETUP-FAILED: sigil_wasm_init"); process.exit(2); }
−53
const rc = ex.sigil_wasm_start();
+53
// A program that calls (exit n) reaches proc_exit, which throws above;
+54
// turn that back into the process exit status.
+55
let rc;
+56
try {
+57
rc = ex.sigil_wasm_start();
+58
} catch (e) {
+59
const m = /WASI proc_exit\((\d+)\)/.exec(String(e && e.message));
+60
if (!m) throw e;
+61
process.exit(Number(m[1]));
+62
}
63
process.stderr.write(`sigil_wasm_start -> ${rc}\n`);
64
process.exit(rc === 0 ? 0 : 1);
harness/src/geometry-harness/main.sglmodified
@@ -49,4 +49,5 @@
49
(if pass? "PASS" "FAIL") total failed alloc-checked alloc-bad
50
(if control-ok? "ok" "SETUP-FAILED")
51
(code-kind vec3-lerp!))
−52
(if pass? 0 1))))))
+52
(unless pass? (exit 1))
+53
0)))))
test/test-mat4.sglmodified
@@ -64,6 +64,15 @@
64
(assert-mat4 (mat4 90 202 314 426 100 228 356 484 110 254 398 542 120 280 440 600)
65
(mat4-mul a a))))
66
+67
(test "known product of two different matrices, both orders"
+68
;; a is rows (1 2 3 4) ... (13 14 15 16); numpy (float64) products with
+69
;; `general`, column by column. a*a above cannot tell a*b from b*a.
+70
(let ((a (mat4 1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16)))
+71
(assert-mat4 (mat4 8 24 40 56 11 27 43 59 12 28 44 60 14 42 70 98)
+72
(mat4-mul a general))
+73
(assert-mat4 (mat4 50 32 37 32 56 36 42 36 62 40 47 40 68 44 52 44)
+74
(mat4-mul general a))))
+75
76
(test "mul applies the right-hand matrix first"
77
(let ((tr (mat4-translation (vec3 10 0 0)))
78
(sc (mat4-scaling (vec3 2 2 2)))