sigil-geometry
3D maths for games and graphics: vectors, matrices, quaternions, cameras, rays
Report a bug or suggest a featuregit clone https://git.usesigil.org/sigil/sigil-geometry.git
sigil-geometry
3D maths for games and graphics in Sigil: vectors, matrices, quaternions, camera matrices and ray casts.
Every value is a float32 bytevector laid out the way a GPU uniform expects it, so a matrix goes to a shader with no conversion. Every operation that produces a vector or matrix has an allocation-free ! form that writes into a destination you reuse from frame to frame. The package is pure Sigil and runs the same on bytecode, native and wasm.
Install
(dependencies: (list
(from-git url: "codeberg:sigil/sigil-geometry" version: "^0.1")))(import (sigil geometry))Example: a camera matrix for a shader
The vertex shader:
uniform mat4 u_mvp;
in vec3 a_position;
void main() { gl_Position = u_mvp * vec4(a_position, 1.0); }The Sigil side. The matrices are made once; each frame rewrites them in place:
(import (sigil geometry))
(define proj (mat4-perspective (degrees->radians 70.0) (/ 480.0 270.0) 0.1 100.0))
(define view (make-mat4))
(define model (make-mat4))
(define mvp (make-mat4))
(define eye (vec3 0 1.7 5))
(define target (vec3 0 1.7 0))
(define up (vec3 0 1 0))
(define spin (make-quat))
(define (update-camera! seconds)
(quat-from-axis-angle! spin up seconds)
(mat4-from-quat! model spin)
(mat4-look-at! view eye target up)
(mat4-mul! mvp view model) ; view * model
(mat4-mul! mvp proj mvp) ; proj * view * model
mvp) ; 64 bytes, column-major float32Read the rest
mvp is the uniform's data as it stands: sigil-graphics' 3D path takes the bytevector directly. With sigil-graphics 0.11's set-shader-uniform, which takes a list of numbers and reaches the fragment stage only, pass (mat4->list mvp); the list is in the column-major order GLSL expects.
The layout contract
This is what GPU-facing code (sigil-graphics) relies on. It is pinned by test/test-layout.sgl.
| value | bytes | contents |
|---|---|---|
| vec2 | 8 | x y |
| vec3 | 12 | x y z |
| vec4 | 16 | x y z w |
| quat | 16 | x y z w (w is the scalar part; identity is 0 0 0 1) |
| mat3 | 36 | 9 floats, column-major |
| mat4 | 64 | 16 floats, column-major |
- float32, IEEE-754 single precision, in native byte order (little-endian on x86-64, aarch64 and wasm32). That is the order GL reads client memory in.
- Column-major, the OpenGL convention: element (column
c, rowr) of a mat4 is floatc*4 + r. A translation sits in floats 12, 13 and 14. Pass a mat4 to GL with no transpose. - Column vectors, multiplied on the left.
(mat4-mul a b)appliesbfirst, thena.(quat-mul a b)follows the same order. - OpenGL clip space. The camera looks down -Z in a right-handed view space with +Y up, and projections map depth to -1..1 after the divide by w. The results match
gluPerspective,glOrthoandgluLookAt. - A std140 uniform block pads each mat3 column to 4 floats, so it does not take the tight 36-byte mat3.
mat3->std140!writes the 48-byte padded form. A mat4 needs no padding. - Reads return flonums (double precision); writes round to float32, so
(vec3-x (vec3 0.1 0 0))is 0.10000000149011612.
sigil-geometry and sigil-graphics do not depend on each other: the contract is the bytes.
Conventions
- Two forms.
(vec3-add a b)returns a new vec3.(vec3-add! dst a b)writes intodst, returnsdst, and allocates nothing. The destination may be the same bytevector as any input:(mat4-mul! m m other)is fine. - Scalars never allocate.
vec3-dot,vec3-length,mat4-determinant,quat-angleand the ray casts return a number (or #f) directly. make-gives a useful starting value.make-vec3is zeros;make-mat3,make-mat4andmake-quatare the identity.- Failure is a value where it can happen in normal use.
mat4-inverse!returns #f for a singular matrix and leavesdstuntouched; a ray cast that misses returns #f; normalizing a zero vector gives zero. Arguments that describe nothing (a perspective withnear <= 0, a plane with a zero normal) raise an error. - Tolerant comparison.
vec3-approx=?,mat4-approx=?and friends take an optional epsilon (default 1e-5, relative above magnitude 1, must be positive). A NaN on either side is never approx=?.quat-same-rotation?compares components up to sign, soqand-qmatch and a non-unit quaternion does not match a unit one. Passing the epsilon explicitly allocates one list cell per call (it is a rest argument); the default allocates nothing.
API
Vectors: (sigil geometry vec)
For each of vec2, vec3 and vec4 (a ! marks a form that also has an allocating twin without the !):
| make | vec3, make-vec3, vec3-copy, vec3-copy!, vec3-set!, vec3? (size check) |
| access | vec3-x, vec3-y, vec3-z (vec4-w), vec3->list |
| arithmetic | vec3-add!, vec3-sub!, vec3-mul! (per component), vec3-scale!, vec3-negate!, vec3-lerp! |
| measure | vec3-dot, vec3-length, vec3-length-squared, vec3-normalize!, vec2-distance, vec3-distance |
| vec3 only | vec3-cross!, vec3-add-scaled! (a + b·s), vec3-min!, vec3-max!, vec3-distance-squared |
| compare | vec3-approx=?, float-approx=? |
| angles | degrees->radians, radians->degrees |
Matrices: (sigil geometry mat4), (sigil geometry mat3)
| mat4 | mat3 | |
|---|---|---|
| make | mat4 (16 values), make-mat4, mat4-identity!, list->mat4, mat4-copy!, mat4? | mat3, make-mat3, mat3-identity!, list->mat3, mat3-copy!, mat3? |
| access | mat4-ref m col row, mat4-set!, mat4->list | mat3-ref, mat3-set!, mat3->list |
| algebra | mat4-mul!, mat4-transpose!, mat4-inverse!, mat4-determinant | mat3-mul!, mat3-transpose!, mat3-inverse!, mat3-determinant |
| 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! |
| apply | mat4-transform-point! (w = 1, divides by w), mat4-transform-direction! (w = 0), mat4-transform-vec4!, mat4-get-translation! | mat3-transform-vec3! |
| upload | the bytevector itself | mat3->std140! |
| compare | mat4-approx=? | mat3-approx=? |
Quaternions: (sigil geometry quat)
quat, make-quat, quat?, quat-identity!, quat-from-axis-angle!, quat-from-mat3!, quat-from-mat4!, quat-mul!, quat-conjugate!, quat-inverse!, quat-normalize!, quat-dot, quat-length, quat-slerp!, quat-nlerp!, quat-rotate-vec3!, quat-angle, quat-x / -y / -z / -w, quat-set!, quat-copy!, quat->list, quat-approx=?, quat-same-rotation?.
quat-slerp! blends two orientations at constant angular speed along the shorter arc, which is what pose blending needs; quat-nlerp! is the cheaper approximation.
Cameras: (sigil geometry camera)
(mat4-perspective! dst fovy aspect near far) | fovy is the full vertical angle in radians; aspect is width / height |
(mat4-orthographic! dst left right bottom top near far) | the view-space box from (left, bottom, -near) to (right, top, -far) |
(mat4-look-at! dst eye target up) | a view matrix; looking straight along up still gives a valid rotation |
Rays: (sigil geometry ray)
A ray is an origin vec3 and a dir vec3. dir need not be unit length: casts return the parameter t of the hit point origin + dir·t. That makes a sight line a ray with dir = target - eye, where a hit with t < 1 is something in between:
(vec3-sub! dir player-eye guard-eye)
(let ((t (ray-aabb guard-eye dir crate-min crate-max)))
(and t (< t 1.0))) ; #t: the crate blocks the guard's view(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 |
(ray-aabb origin dir box-min box-max) | entry t (0.0 from inside) or #f |
(ray-triangle origin dir a b c) | t or #f, either face |
(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 |
(ray-point! dst origin dir t) | the point at t |
plane-from-point-normal!, plane-from-points!, plane-signed-distance | planes with unit normals; counterclockwise points face the viewer |
aabb-contains-point?, aabb-overlap? | box tests |
Allocation, measured
scripts/check-targets counts GC allocations over 1000 calls of each of 123 checks, against an empty-loop baseline and a positive control. The checks cover all 80 exported ! forms, the scalar, ray and comparison functions, and the other branches of the ops that have them (a projection's divide by w, a singular inverse, a degenerate look-at, each branch of the matrix-to-quaternion conversion, zero-length normalize, ray misses). The script refuses to run if an exported ! form has no check. Results with sigil 0.22.7:
| target | allocations per call |
|---|---|
| native wasm (the web) | 0 for all 123 |
| bytecode | 0 for all 123 |
| native ELF | 0 for 87; the other 36 allocate where the call crosses from native code into bytecode (see below) |
On a native ELF build, sigil 0.22.7 loads a dependency package's compiled bytecode rather than its native code, so an app's calls into sigil-geometry cross from native to bytecode. That crossing allocates one object per argument for calls with 4 or more arguments, and 2 for a call to a procedure with a rest argument (the approx=? family). It is a property of the toolchain's ELF bundles, not of this package, and the wasm build is not affected.
What the package avoids in its hot paths, and why (each measured to allocate on every call under native codegen):
syntax-rulesmacros whose template names a global: native codegen looks the global up at run time through%hygiene-ref, which conses. Helper procedures cost nothing.- Named-let loops (3 to 5 objects per call) and
case-lambda(2 to 4): loops are top-level recursive procedures instead. - Passing a rest argument (one list cell).
Sigil 0.22.7 also answers #t to (<= x y), (>= x y) and (= x y) when an operand is NaN, so the comparisons here are written with < and >, which answer correctly.
Development
sigil deps install
sigil test # the suite on the host (bytecode)
guix shell -m manifest.scm -- scripts/check-targets
# suite + allocation check on bytecode,
# native ELF and wasm (needs wasm-opt, node)scripts/check-targets turns each test file into a library, compiles it into the app in harness/ with the allocation check, runs it on each target (wasm under Node), and reports per target. A target passes when every test ran and passed and, where the geometry code is native or all bytecode, none of the 123 checks allocated.
License
BSD-3-Clause
v0.1.0 — latest by version, released 25 Sep 2026
All releases — 1 tag in this repository.
One page per file, and every line has a permalink.
d478406b
The last 20 commits keep a page here. Everything older lives in the clone.