ALICE-Physics
Deterministic 128-bit Fixed-Point Physics Engine - v1.0.0 stable
English | 日本語
Part of ALICE-Eco-System — 260+ crate Edge-to-Cloud data pipeline (SDF / Physics / LLM / Motion / Font / TTS)
A high-precision physics engine designed for deterministic simulation across different platforms and hardware. The rigid-body core uses 128-bit fixed-point arithmetic (Fix128); the surrounding engineering / field modules use IEEE f32 / f64 with every transcendental routed through the crate's own det_math. Either way the result is bit-exact regardless of CPU, compiler, or operating system — see Determinism scope.
Published on crates.io (1.0.0 semver-locked stable released 2026-09-14; 1.1.0 makes every module cross-platform bit-exact via det_math; 1.2.0 fixes the default-config physics found by the 2026-09-15 external review and adds analytic-solution oracles — see CHANGELOG.md).
Determinism scope
Every module in the crate is bit-exact across platforms, for two different reasons:
| Tier | Modules | Why the bits agree everywhere |
|---|---|---|
| Fix128 core | rigid-body solver, joints, distance / contact constraints, BVH broad-phase, GJK / EPA, CCD, sleeping, scene I/O, netcode snapshot / rollback, neural controller, and every module whose public API is expressed in Fix128 / Vec3Fix / QuatFix |
Pure i64 / u64 integer arithmetic. Pinned by tests/determinism_golden.rs |
f32 / f64 field modules (27: acoustic_wave, aeroelasticity, anomaly, convex_decompose, erosion, fracture, gpu_sdf, phase_change, piezoelectric, pressure, privacy, rolling_contact, sdf_adaptive, sdf_ccd, sdf_character, sdf_collider, sdf_destruction, sdf_fem_mesh, sdf_manifold, sdf_sph, sdf_wind_field, sim_field, sim_modifier, sketch, thermal, thin_wall, transient_thermal; list generated by scripts/f32_modules.py --check, which CI-gates this row — 8 more modules carry floats only across an I/O boundary: ffi, pipeline, analytics_bridge, db_bridge, replay, fluid_netcode, character_state, solver_tgs) |
IEEE 754 + - * / sqrt and fused multiply-add are specified to the bit on every target Rust supports (SSE2+, aarch64, wasm32). Every transcendental (sin, exp, ln, powf, cbrt, hypot, …) goes through det_math — integer range reduction + fixed-order polynomials — never the platform libm. clippy.toml disallowed-methods makes a stray libm call a CI error. Pinned by tests/determinism_golden_f32.rs (13 scenarios, 29 modules) |
Both golden suites run on macOS ARM / x86, Linux ARM / x86, Windows and wasm32-wasip1 in CI.
Boundary — code you pass in. ClosureSdf takes a user closure Fn(f32, f32, f32) -> f32. The solver stays deterministic, but the closure is your code: call alice_physics::det_math::{sin, exp, …} instead of f32::sin etc. inside it, or hand in an SDF whose evaluator has the same discipline. (ALICE-SDF's CPU evaluator is being aligned with det_math; until then treat it as same-binary deterministic.)
Out of scope. Targets that do not honour IEEE 754 for the basic operations: 32-bit x86 built for x87 (i586, no SSE2) and any build with fast-math style flags.
Correctness scope — what "deterministic" does and does not tell you
Bit-exactness says every peer computes the same numbers; it says nothing
about whether those numbers are right. The 2026-09-15 external review found
four physics bugs in the default configuration with 1456 tests and 44 golden
hashes green (see CHANGELOG.md 1.2.0), so the crate now separates the two
properties explicitly. Validation below means "compared against a
closed-form solution or an independent reference in tests/"; the golden
hashes only detect change.
| Layer | Modules | Validation |
|---|---|---|
| Core — what the determinism guarantee is for | math (Fix128, Vec3Fix, QuatFix, CORDIC), solver (XPBD rigid bodies, distance / contact constraints, sleeping), joint, bvh, collider (GJK / EPA), ccd, contact_cache, sdf_collider, netcode / snapshot |
tests/analytic_physics.rs — free fall, projectile, terminal velocity, mg/k extension, spring and pendulum periods, collision momentum + energy bound, kinematic targets, torque-free rotation, resting contact; sqrt / transcendental oracles in math::tests; det_math sweeps vs correctly-rounded references |
| Engineering / field modules — textbook formulas made deterministic | transient_thermal, fatigue |
tests/engineering_oracles.rs — cosine eigenmode decay (Carslaw & Jaeger) for explicit and Crank–Nicolson steps, Basquin / Miner closed forms |
solid / structural: beam_stress, buckling, thin_wall, fillet_stress, modal, vibration_wall, damping_rayleigh, hyperelastic, plastic, creep_longterm, structural_solver, laminate, laminate_failure (Tsai-Wu / Hashin / Puck), anisotropic, bimaterial, prestressed, bridging, thermal_stress, mass_properties, print_orientation, filament_db |
tests/engineering_oracles_solid.rs (34) — Roark beam deflection / stress and section properties, Euler–Johnson buckling (Shigley), Rayleigh damping (Chopra), CLT laminate ABD and ply transformation (Jones), Tsai-Wu / Hashin envelopes at the uniaxial strengths, Shigley bolt joint and Irvine cable, Kirsch / Inglis exact concentration and Peterson fit invariants, Norton creep, Findley / WLF, hyperelastic uniaxial stress as derivative of the strain energy, first modes (Blevins beam, Leissa plate, Rao SDOF), closed-form inertia tensors and Steiner parallel axis, rule of mixtures / thermal mismatch, thermal-stress magnitude and sign |
|
fluid / thermal / field: cfd_solver, eulerian_grid, sdf_sph, multiphase, interface_capture, surface_tension_csf, compressible, non_newtonian, turbulence, buoyancy_zone, wind_zone, sdf_wind_field, cloth_fluid, fsi_advanced, smoke_fire, wave_ship, aeroelasticity (Facchinetti 2004), acoustic_wave, electromagnetic, piezoelectric, thermal, phase_change, pressure, erosion |
tests/engineering_oracles_fluid.rs (39) — viscous shear-mode decay, pressure projection removes divergence and is identity on solenoidal fields, SPH kernel normalisation and lattice rest density, Young–Laplace through the CSF band, ISA density / speed of sound, normal-shock and isentropic tables (Anderson), Bingham / Herschel–Bulkley / power-law / Carreau flow curves (integer and fractional index), Smagorinsky simple shear, Archimedes, quadratic drag, d'Alembert at Courant 1, Coulomb / Lorentz / dipole, d33 piezo relations, Arrhenius / Boussinesq, deep-water dispersion / Froude–Krylov / JONSWAP, van der Pol amplitude and Strouhal frequency, Newton cooling and conduction eigenmode, enthalpy-method plateau and conservation, level-set curvature and fast-sweeping distance, erosion rate-law invariants |
|
cloth, rope, deformable, fluid (PBF), character, vehicle (WheelConfig / EngineConfig), sleeping, netcode, audio_physics, support (print supports), neural |
tests/default_configs.rs — every Config::default() on its most ordinary scenario: hanging curtain / rope geometry, free-fall closed form for a deformable cube and a fluid block's centre of mass, wheel compression mg/k, engine first-frame Δv = T·gear/(r·m)·dt, sleep at exactly frames_to_sleep, lockstep checksums + rollback bit-exact, support volumes to 1e-6 |
|
mechanisms / fields / netcode: rolling_contact, fracture, kinematic_loop, sdf_force, anisotropic_friction, physics2d, sdf_destruction, soft_body_cut, layer_adhesion, fluid_netcode |
tests/engineering_oracles_misc.rs (27) — Hertz sphere contact and Basquin life (Johnson §4.2), crack growth L = min(vt, L_max) and Quilez capsule subtraction, PBD loop closure (mass-weighted projection, geometric residual contraction, four-bar link lengths), F = −kφ∇φ and the contain / repel / vortex closed forms, orthotropic friction ellipse (Zmitrowicz) with the Coulomb isotropic limit, 2-D free fall / θ = ωt / momentum / Newton restitution v_sep = e·v_app / Coulomb sliding μ g / inertia tensors (Meriam & Kraige), hemisphere crater and capped-cylinder bore volumes, plane-cut partition invariants, bit-exact snapshot round trip and lossless τ = 0 delta |
|
warp_risk (empirical fit: two ALICE-Bamboo data points), sim_field, layer_adhesion (empirical FDM factors, invariants only) and the remaining utility / bridge modules |
none yet — the formulas are implemented as published and the code is bit-exact, but no test compares them with a reference solver, a textbook worked example or experimental data. Treat their numbers as implementations of the cited equation, not as validated predictions, until the module gains an oracle (the 1.2.0 batches above show the pattern: closed form at Config::default(), precision parameter varied) |
Where the crate fits. The core is built for use cases where bit-exact
replay is the requirement, not a nicety: rollback netcode (fighting / RTS /
.io games, tens to hundreds of bodies), server-side replay verification and
anti-cheat, and reproducible research or audit batches. Measured on the
1000-overlapping-sphere scene (cargo bench --bench physics_bench,
thousand_overlapping_spheres_1_step) it runs at a few ms per frame with the
default configuration. It is not a drop-in replacement for a float engine
in a general game: destruction, crowds of thousands, VFX-grade contact counts
at 60 fps are outside its design point, and a float engine pays none of the
fixed-point cost for a determinism it does not need.
v0.10-0.14 highlights — a five-wave completeness push adds
54 modules + 3 integrated solver loops + a Session 4 19-module tier-classified push
covering the full spectrum from 3D-printing safety (warp / thin-wall /
stress / bridging) through composite / plastic / fatigue mechanics, up
to turbulence, VOF / level-set multi-phase flow, a runnable CFD
time-step loop, humanoid ragdoll, SDF-boundary SPH, transient thermal,
composite failure, VIV / piezoelectric / acoustic / electromagnetic,
IK / anisotropic friction / netcode prediction / character FSM /
kinematic loop / buoyancy zone / wind zone / SDF FEM / SDF wind.
All bit-exact across platforms — Fix128 modules by integer arithmetic, f32 modules via det_math (Determinism scope); see
Session 1-3 Additions and
v0.13.0 Session 4 Additions.
v1.0.0 release highlights (2026-09-14)
- API surface freeze — 32 module × 512 pub items audit (Iterations 1-6 + Final), 133+ items
pub → pub(crate)downgraded, snapshot 20,201 → 19,406 (−795 items).solver_tgs*extension mechanism moved topub(crate)(Option C). 7 prelude-exported structs marked#[non_exhaustive]for forward-compat. - 6-platform bit-exact determinism — golden hash (9 tests) + semantic invariant (22 tests) suite verified on macOS ARM/x86 + Linux ARM/x86 + Windows + WASM (
wasm32-wasip1viawasmtime). - Hard-gated semver enforcement —
cargo semver-checksblocks breaking-API PRs. - Ecosystem contracts frozen — [
docs/ECOSYSTEM_CONTRACTS.md] catalogues API for ALICE-TRT (GpuSolverBridge), ALICE-SDF (SdfField), ALICE-Bamboo, ALICE-Anima, ALICE-Kinematics. - 8/8 fuzz targets —
fuzz_step/fuzz_collision/fuzz_deterministic_roundtrip/fuzz_joint/fuzz_cfd/fuzz_ccd/fuzz_trimesh/fuzz_structural. - 1695 lib tests + 44 determinism tests — all passing on all 6 platforms.
v0.12.0 addition — GpuSolverBridge gains a joint-solve pipeline
(send_joints / send_body_rotations / dispatch_joint_solve_iteration)
and PhysicsWorld auto-routes both contact AND joint solve through the
installed bridge, coordinated with ALICE-TRT v3.1.0's
FIX128_BALL_SOCKET_JOINT_SOLVE_WGSL kernel (byte-exact vs CPU
solve_ball_joint). See CHANGELOG.md.
v0.13.0 Session 4 Additions (19 modules across 3 tiers)
Extends the v0.10-0.12 engineering-solver foundation with a 19-module push covering game-physics polish (ragdoll / character state / netcode prediction / IK), soft-body simulation (SDF SPH / SDF character / SDF FEM / SDF wind), engineering research (composite failure / transient thermal / rolling contact fatigue / VIV / piezoelectric / acoustic / electromagnetic), and multi-material coupling (buoyancy zone / anisotropic friction / kinematic loop). All bit-exact across platforms (Determinism scope); formula sources cited in module docs.
Tier ★★★ — 5 modules (real-world critical, downstream-load-bearing)
| Module | Purpose |
|---|---|
ragdoll |
Humanoid ragdoll builder with pose targets, joint limits, breakable constraints (G1) |
buoyancy_zone |
Bounded 3-D fluid volume with buoyancy + drag, fluid-surface CSF coupling (G2) |
laminate_failure |
Tsai-Wu / Tsai-Hill / Hashin / Puck composite failure indices (R1) |
transient_thermal |
Temperature-dependent material properties + 1-D unsteady heat solver + phase-boundary tracking (R2) |
ALICE-SDF morphology |
Signed offset + tolerance fit check for print clearance (S1, ships in ALICE-SDF v1.7.7) |
Tier ★★ — 7 modules (broad utility, cross-domain glue)
| Module | Purpose |
|---|---|
wind_zone |
Bounded 3-D wind volume with drag + lift on rigid / soft bodies (G3) |
sdf_character |
SDF-terrain-aware character controller with slope / step / air-time state (S4) |
rolling_contact |
Rolling contact fatigue (Hertz + subsurface shear + Basquin S-N cycle counting) (R3) |
netcode_prediction |
Client-side prediction + reconciliation + input replay (G5) |
character_state |
Character FSM (idle / walk / run / jump / fall / crouch) with transition validation (G6) |
sdf_sph |
SDF-boundary SPH fluid with density / viscosity / surface tension (S3) |
kinematic_loop |
Kinematic body loop constraint solver for closed-chain mechanisms (R4) |
Tier ★ — 8 modules (specialized engineering / research)
| Module | Purpose |
|---|---|
ik_physics_bridge |
Physics-aware IK solver with joint-limit respecting FABRIK / CCD backend (G4) |
anisotropic_friction |
Direction-dependent friction coefficient (rolling vs sliding, wood grain, fabric) (G7) |
aeroelasticity |
Vortex-induced vibration (VIV) + flutter + galloping for slender structures (R5) |
piezoelectric |
Piezoelectric coupling for sensors / actuators (voltage ↔ strain) (R6) |
acoustic_wave |
1-D / 2-D / 3-D acoustic wave propagation with material impedance boundary (R7) |
electromagnetic |
Electromagnetic force field (Lorentz / induction / eddy current) for conductor bodies (R8) |
sdf_fem_mesh |
SDF-to-tetrahedral FEM mesh generator for large-deformation simulation (S2) |
sdf_wind_field |
SDF-boundary-aware wind field with turbulence intensity + gust modeling (S5) |
Features
| Feature | Description |
|---|---|
| 128-bit Fixed-Point | I64F64 format (64-bit integer + 64-bit fraction) for extreme precision |
| CORDIC Trigonometry | Deterministic sin/cos/atan without FPU instructions |
| XPBD Solver | Extended Position Based Dynamics for stable constraint solving |
| GJK/EPA Collision | Robust collision detection for convex shapes |
| Stackless BVH | Morton code-based spatial acceleration with escape pointers |
| Constraint Batching | Graph-colored parallel constraint solving |
| Rollback Support | Complete state serialization for netcode |
| Neural Controller | Deterministic AI via ALICE-ML ternary weights + Fix128 inference |
| 12 Joint Types | Ball, Hinge, Fixed, Slider, Spring, D6, Cone-Twist, Pulley, Gear, Weld (breakable), Rack-and-Pinion, Mouse |
| Raycasting | Ray and shape casting against spheres, AABBs, capsules, planes |
| Shape Cast / Overlap | Sphere cast, capsule cast, overlap sphere, overlap AABB queries |
| CCD | Continuous collision detection (TOI, conservative advancement) |
| Sleep/Islands | Automatic sleep with Union-Find island management |
| Triangle Mesh | BVH-accelerated triangle mesh collision (Moller-Trumbore) |
| Height Field | Grid terrain with bilinear interpolation |
| Articulated Bodies | Multi-joint chains, ragdolls, robotic arms with FK propagation |
| Force Fields | Wind, gravity wells, drag, buoyancy, vortex, explosion, magnetic dipole |
| PD Controllers | 1D/3D proportional-derivative joint motors |
| Collision Filtering | Layer/mask bitmask system with collision groups |
| Trigger/Sensor | Sensor bodies that detect overlap without physics response |
| Character Controller | Kinematic capsule-based move-and-slide with stair stepping and SDF terrain |
| Rope | XPBD distance chain rope and cable simulation |
| Cloth | XPBD triangle mesh cloth with self-collision (spatial hash grid) |
| Fluid | Position-Based Fluids (PBF) with spatial hash grid |
| Deformable | FEM-XPBD deformable body (tetrahedral mesh) |
| Vehicle | Wheel, suspension, engine, steering, gear shifting |
| Animation Blend | Ragdoll-to-animation blending with SLERP |
| Audio Physics | Physics-based audio parameter generation (impact, friction, rolling) |
| SDF Manifold | Multi-point contact manifold from SDF surfaces |
| SDF CCD | Sphere tracing continuous collision detection for SDF |
| SDF Force Fields | SDF-driven force fields (attract, repel, contain, flow) |
| SDF Destruction | Real-time CSG boolean destruction |
| SDF Adaptive | Adaptive SDF evaluation with distance-based LOD |
| Convex Decompose | Convex decomposition from SDF voxel grid |
| GPU SDF | GPU compute shader interface for batch SDF evaluation |
| Fluid Netcode | Deterministic fluid netcode with delta compression |
| Simulation Fields | 3D scalar/vector fields with trilinear interpolation and diffusion |
| Thermal | Heat diffusion, melt, thermal expansion, freeze |
| Pressure | Contact force accumulation, crush, bulge, dent deformation |
| Erosion | Wind, water, chemical corrosion, ablation |
| Fracture | Stress-driven crack propagation with CSG subtraction |
| Phase Change | Solid/liquid/gas transitions driven by temperature |
| Deterministic RNG | PCG-XSH-RR pseudo-random number generator |
| Contact Events | Begin/Persist/End contact and trigger event tracking |
| Box/OBB Collider | Oriented Bounding Box with GJK support and fast AABB |
| Compound Shape | Multi-shape compound collider with local transforms |
| Contact Cache | Persistent manifold cache with HashMap O(1) lookup and warm starting |
| Dynamic AABB Tree | Incremental BVH with O(log n) insert/remove/update, AVL balancing |
| D6 Joint | 6-DOF configurable joint with per-axis lock/free/limit |
| Cone-Twist Joint | Ball joint with cone swing limit and twist limit |
| Material Table | Per-pair friction/restitution with combine rules (Avg, Min, Max, Mul) |
| Scaled Shape | Uniform scale wrapper for any Support-implementing shape |
| Speculative CCD | Speculative contacts for fast-moving bodies without time rewinding |
| Featherstone | O(n) forward dynamics for articulated bodies |
| Debug Render | Wireframe visualization API (bodies, contacts, joints, BVH, forces) |
| Profiling | Per-stage timer and per-frame statistics API |
| Substep Interpolation | WorldSnapshot with NLERP quaternion blending for smooth rendering |
| Probabilistic Sketches | HyperLogLog, DDSketch, Count-Min Sketch, Heavy Hitters |
| Streaming Anomaly Detection | MAD, EWMA, Z-score composite detector |
| Local Differential Privacy | Laplace noise, RAPPOR, randomized response |
| Metric Pipeline | Lock-free ring buffer metric aggregation with registry |
| Cone Collider | Cone shape with GJK support (apex +Y, base -Y) |
| Ellipsoid Collider | Three independent semi-axes with anisotropic support |
| Torus Collider | Major/minor radii with Minkowski sum decomposition |
| Plane Collider | Infinite plane (Hessian normal form) with sphere/AABB intersection |
| Wedge Collider | Triangular prism with 6-vertex GJK support |
| Convex Hull Builder | Incremental convex hull from arbitrary point sets |
| 2D Physics | Complete 2D subsystem: SAT collision, XPBD solver, Circle/Polygon/Capsule/Edge shapes |
| Mass Properties | Inertia tensor computation for sphere, box, cylinder, capsule, convex hull |
| Collision Mesh Gen | Marching cubes SDF-to-mesh with edge-collapse simplification |
| Scene I/O | Binary (.aphys) and JSON scene serialization with bit-exact Fix128 roundtrip |
| Cloth-Fluid Coupling | Bidirectional cloth-fluid interaction (drag, buoyancy, boundary repulsion) |
| Rope Attachment | Rigid body rope attachment with compliance and break force |
| Soft Body Cutting | Plane-based cutting of deformable bodies and cloth |
| Stress Heatmap | Stress/temperature/pressure 2D slice visualization with viridis colormap |
| Flow Visualization | Fluid velocity field arrows and streamline generation |
| Contact Visualization | Contact force arrows and friction cone rendering |
| Multi-World | Multiple independent physics worlds with body transfer |
| Particle System | General-purpose emitters, lifetime, force field integration |
| no_std Compatible | Works on embedded systems and WebAssembly |
Session 1-3 Additions (v0.10-0.12)
Three completeness sessions added 35 modules + 3 integrated solver loops + 3 runnable examples to close the gap between "physics primitives" and "usable engineering solvers." Every addition is bit-exact across platforms (see Determinism scope) and cites the source formula (Roark / Timoshenko / Simo & Hughes / Jones / Tsai-Wu / Hill / Norton / Findley / WLF / Brackbill / Smagorinsky / Launder-Spalding / Wilcox / Hasselmann / Turns / Anderson / etc.).
Session 1 — 3D Print Safety + Structural Tier 1 (v0.10)
| Module | Purpose | Formula source |
|---|---|---|
filament_db |
10-material property DB (Young's / yield / tensile / density / Tg / anisotropy) | MatWeb / ASM Metals Handbook |
thin_wall |
SDF sphere-marching wall thickness detection | Bambu/Prusa min-wall guidance |
beam_stress |
Cross-section + load case + Euler buckling + FoS | Roark's Formulas for Stress and Strain |
support_volume |
Overhang → filament mm³ + print time estimate | Bambu Studio support manual |
anisotropic |
9-constant orthotropic + Hill + Tsai-Wu failure | Jones, Mechanics of Composite Materials |
plastic |
von Mises + isotropic/kinematic/combined hardening + Norton creep | Simo & Hughes; Norton (1929) |
buckling |
Johnson / Euler / plate / snap-through | Timoshenko & Gere; Bažant & Cedolin |
hyperelastic |
Neo-Hookean / Mooney-Rivlin / Yeoh | Ogden (1984); Yeoh (1990) |
bimaterial |
Timoshenko bimetal residual + Voigt/Reuss bounds | Timoshenko (1925) |
layer_adhesion |
XY vs Z 6-component effective strength envelope | Empirical FDM data |
print_orientation |
Load-direction optimization + Euler grid search | Anisotropy transformation |
bridging |
Material-specific max bridge distance check | Bambu/Prusa knowledge base |
warp_risk |
Cooling shrinkage × footprint → Low/Medium/High/Critical | ALICE-Bamboo docs incident-tuned |
Session 2 — Structural Tier 2 + Fluid Tier 1-2 (v0.11-0.12)
| Module | Purpose | Formula source |
|---|---|---|
fatigue |
Basquin S-N + Miner cumulative damage | Basquin (1910); Miner (1945) |
modal |
1-DOF / beam / Warburton plate / torsional natural frequency | Blevins; Warburton (1954) |
damping_rayleigh |
C = αM + βK + fit_two_modes | Clough & Penzien |
laminate |
Classical Laminate Theory ABD matrix | Jones eq. 2.84 |
prestressed |
Motosh bolt preload + parabolic cable pretension | Shigley; VDI 2230 |
fillet_stress |
Kirsch / Inglis / Peterson K_t | Peterson; Pilkey; Norton |
vibration_wall |
Thin-wall resonance vs 6 printer excitation presets | Blevins; Bambu X1C spec |
thermal_stress |
Constrained σ = c·E·α·ΔT + Tg proximity warning | Timoshenko & Goodier |
creep_longterm |
Findley 3-parameter + WLF time-temperature superposition | Findley (1989); Williams et al. (1955) |
non_newtonian |
Power-law / Carreau / Bingham / Herschel-Bulkley | Bird, Stewart, Lightfoot |
multiphase |
VOF advection + level set reinit + curvature | Hirt & Nichols (1981); Osher & Sethian (1988) |
compressible |
Ideal gas + Rankine-Hugoniot shock + Riemann invariants | Anderson, Modern Compressible Flow |
eulerian_grid |
Staggered MAC + Jacobi/red-black GS pressure projection | Harlow & Welch (1965) |
turbulence |
Smagorinsky LES + k-ε + k-ω + wall function | Pope; Wilcox; Launder & Spalding |
surface_tension_csf |
Continuum Surface Force | Brackbill, Kothe & Zemach (1992) |
fsi_advanced |
Solid ↔ fluid drag / buoyancy / reaction | Peskin immersed boundary |
smoke_fire |
Arrhenius reaction + soot + Boussinesq buoyancy | Turns; Kuo |
wave_ship |
JONSWAP spectrum + Froude-Krylov + 2-DOF | Hasselmann (1973); Faltinsen |
interface_capture |
Fast Sweeping FSM + PLIC (Rider-Kothe analytical) | Zhao (2005); Youngs (1982) |
Session 3 — Solver Loops + 12 Improvements + 3 Demos (v0.12)
Integrated solver loops — single step(dt) entry points that compose
the Session 1-2 modules into a driven simulation:
| Solver | Composes |
|---|---|
cfd_solver::CfdSolver |
MAC + turbulence + non-Newtonian + level_set + CSF + Boussinesq + gravity |
structural_solver::StructuralSolver |
beam + plastic + creep + fatigue + buckling with history tracking |
print_pipeline_solver |
10 print-safety checks (warp + layer + orientation + thermal + beam + bridging + support + fillet + bimaterial) in one shot |
12 improvements — accuracy / performance / robustness:
- I1
math_utilsharedexp_fix/cbrt_fix/pow_int/clamp_fix - I2
eulerian_gridtrilinear P2G / G2P (was nearest-cell) - I3
multiphasesemi-Lagrangian advection (was first-order upwind) - I4 PLIC Rider-Kothe analytical + cbrt (bisection collapse)
- I5 FSM Godunov 3-neighbour quadratic Eikonal (was min + dx)
- I6
safety::sdf_aabbNaN/degenerate/min-dim guards - I7
safety_validateintegratesthin_wall+layer_adhesion+thermal_stress - I8 turbulence log-law wall function +
ln_fix - I9 pressure projection red-black Gauss-Seidel (~2× convergence)
- I10 dynamic Smagorinsky Germano estimator
- I11
laminate::compute_abdrayon parallel (feature-gated) - I12
fatigue::stress_at_cyclesNewton early exit
3 runnable examples demonstrating the solvers end-to-end:
cfd_smoke_plume demonstrates bit-exact v_y = -g·t recovery, with the
pressure projection maintaining zero divergence at the grid centre throughout
the run. print_full_safety exercises all 10 safety checks and returns a
realistic UNSAFE verdict for a 300 × 300 × 5 mm PLA plate (Warp Critical /
Beam FoS 1.16 / Fillet K_t 3.30) — exactly matching the failure mode
documented in the ALICE-Bamboo warp incident.
Mutation score (cargo-mutants, quality-deep.yml)
"Tests pass" says nothing about whether they check values. The core modules
are measured with cargo-mutants (-- --lib, test
helpers excluded via .cargo/mutants.toml); a mutant is caught when some
test fails after the mutation. Score = caught / (caught + missed), unviable
mutants excluded. The campaign started at 32.0 % (2026-09-15, 16-shard
weekly run) and found six real defects on the way (remove_body constraint
remap, Fix128::atan CORDIC shift, cloth bending sign, LinearBvh::find_pairs
n², joint angular split / unsigned twist, EPA normal sign).
| module | score | measured |
|---|---|---|
ccd |
95.4 % (208 / 218) | local run after batch 8 |
collider |
93.5 % (145 / 155) | local run after batch 8 |
math |
92.2 % (295 / 320) | weekly run at b187144, partial shards; scoped run pending |
contact_cache |
88.0 % (66 / 75) | scoped run at 3c12ee6, before batch 7 tests |
solver_tgs |
81.7 % (89 / 109) | weekly run at b187144, before batch 7 tests |
bvh |
79.9 % (135 / 169) | weekly run at b187144, before batch 8 (9 tests added) |
solver |
76.2 % compiled code (433 / 568) | weekly run at b187144, before batch 8 (24 tests added); 163 further mutants sit in cfg(feature = "parallel" / "gpu-solver-bridge") code and are measured on that feature axis |
joint |
72.0 % (206 / 286) | weekly run at b187144, before batch 8 (15 tests + 8 re-derived after the angular-split fix) |
Rows marked "before batch N" are the last measured figure; the tests written
since target the listed misses (equivalent mutants documented in each test
module) and are re-measured by the scoped quality-deep dispatch. The next
measured numbers replace this table; estimates are not written here.
Test count
Session 1 baseline (v0.9): 719 → Session 1 end (v0.10): 904 → Session 2 end (v0.11): 1170 → Session 3 end (v0.12): 1175 alice-physics tests + 53 alice-bamboo integration tests, all passing.
Sub-stepping TGS Solver — v1.0 status: pub(crate) internal
The trait-abstracted temporal Gauss-Seidel solver primitives (TgsHooks, ImpulseCache, build_islands, 6-DOF hooks, per-island scoped solve, rayon parallelisation, quaternion orientation integration) exist in-crate as solver_tgs* modules but are pub(crate) since 1.0.0 — the extension mechanism had zero downstream adoption during the v1.0 API audit (Option C, see docs/PUB_AUDIT_FINAL.md). The primary PhysicsWorld::step API uses its own internal TGS solver in crate::solver and remains fully public. If your project needs a generic hooks-based TGS integrator, open an issue — re-exposing pub(crate) items via a semver-minor bump is non-breaking.
Advanced solver primitives (Turn D / Phase E / Phase F)
Additional building blocks stacked on top of the sub-stepping TGS core:
-
Adaptive sub-stepping —
AdaptiveSubStepConfig+HasVelocity+adaptive_substeps_forcompute a deterministic sub-step count from the fastest body's L∞ velocity (Fix128 pure, closed-form, division-free — safe under lockstep and rollback) -
CCD-optimised adaptive sub-stepping —
adaptive_substeps_for_ccdtightens the per-step translation cap tosmallest_collider_radius × safety_factor, guaranteeing fast bodies never tunnel through thin walls -
Adaptive sub-TOI —
adaptive_toi_substepsbridges Adaptive sub-stepping with the existingspeculative_contactTOI so a pair on a collision course overdtimmediately requestsmax_substeps(Phase F 11.1, body complete) -
ImpulseCacheobservability —hits/misses/stats/hit_rate/reset_statsexpose warm-starting effectiveness so callers can gauge whether contact IDs stay stable across frames (high hit rate) or the scene is churning (low hit rate) -
Per-island scoped oriented solve —
solver_tgs_hooks_6dof_oriented_scopedextracts an isolated body / contact subset per island for the full 6-DOF oriented hook, prevents gravity double-counting, and preserves bit-perfect parallel-vs-serial equality -
LinearBvh::refit_leaves(bottom-up) — retains the flat tree structure while requantising leaf AABBs and propagating unions to internal nodes in the i32 domain (no CORDIC / rounding dependency), enablingO(N)refit as an alternative to full rebuild -
BroadphaseHybrid— layers aSpatialGridhash grid over a staticLinearBvh(Turn D 5' plan), reducing per-frame broad-phase work fromO(N_total log N_total)toO(N_dynamic + log N_static). Recommended per-frame flow:clear_dynamic→insert_dynamic× N →build_dynamic→query_pairs -
FeatherstoneSolver::solve_with_mass_splitting— extends the O(n) forward-dynamics solver with a mass-ratio split threshold (heavy / light > threshold →dt / 2× 2 recursion), relieving stiffness-induced ill-conditioning for extreme mass-ratio stacks. Determinism preserved via lookup-free multiplicative comparison andFix128::half(Phase F 11.2, body + 3 tests complete) -
FFI byte-for-byte determinism —
AliceVec3Fix128Raw+alice_physics_body_get_position_fix128_rawexpose Fix128 hi/lo pairs across the C ABI.ffi_contract_gravity_fall_deterministicasserts a bracket bound plus a full second-world replay that must produce the exact same hi/lo pair, so Unity / UE5 hosts can assert bit-pattern equality (Phase F 11.3, runtime determinism gate complete) -
GpuSolverBridgetrait (--features gpu-solver-bridge) — opt-in extension surface for external GPU offload backends (e.g. ALICE-TRTTrtSolverAdapter). Ships withDiffFixture/GpuDivergencetypes so implementations must certify byte-for-byte equivalence with the CPU-side solver before the runtime accepts them. Default builds keep the CPU-native TGS pipeline as the only code path
Companion crate — ALICE-TRT (GPU solver offload)
Pair with ALICE-TRT v1.0.0+ --features physics-solver for the reference GpuSolverBridge implementation (TrtSolverAdapter). Enabling physics-solver on ALICE-TRT automatically activates gpu-solver-bridge on this crate, so a single feature line covers both sides. ALICE-TRT v1.x is semver-stable — public adapter surface (send_island / dispatch_iterations / set_gravity / set_floor / push_distance_constraint / recv_island / assert_bit_exact_vs_cpu) is byte-stable across the v1.x line.
[]
= { = "1", = ["gpu-solver-bridge"] }
= { = "3.1", = ["physics-solver"] }
use ;
use Fix128;
use ;
// Live PGS dispatch (integrate + gravity + floor + multi-distance constraints)
let device = new?;
let mut adapter = new;
adapter.send_island;
adapter.set_gravity;
adapter.set_floor;
adapter.push_distance_constraint; // Gauss-Seidel ordered
adapter.push_distance_constraint;
adapter.dispatch_iterations; // real GPU dispatch, not a stub
adapter.recv_island;
// Production gate: certify byte-for-byte equivalence with the CPU solver.
adapter.assert_bit_exact_vs_cpu?;
Companion releases: ALICE-TRT v3.1.0 (coordinated with alice-physics v0.12.0 for joint-solve GPU offload). Every ALICE-TRT release is validated on macOS (Metal) / Ubuntu (Vulkan lavapipe) / Windows (DX12 WARP) with 37 Fix128 unit tests + 170 physics-solver tests, all byte-exact against the CPU golden.
Determinism guardrails for every primitive above are documented in the deterministic-physics-lockstep-discipline skill (private reference).
Optimizations ("黒焦げ" Edition) — 100/100
ALICE-Physics achieves a perfect 100/100 optimization score across 6 layers:
Optimization Scorecard
| Layer | Score | Key Techniques |
|---|---|---|
| L1: Memory Layout | 15/15 | #[repr(C, align(64))] on RigidBody/Cloth/Fluid, hot/cold field reorder |
| L2: Execution | 20/20 | #[inline(always)] on GJK/BVH/constraints, branchless select, precomputed grid_half |
| L3: Compute | 20/20 | Warm-start cached_lambda, reciprocal precomputation (inv_rest_length, inv_rest_density) |
| L4: GPU & Throughput | 15/15 | SIMD_WIDTH const + simd_width(), GpuSdfInstancedBatch/GpuSdfMultiDispatch, batch_size() |
| L5: Build Profile | 10/10 | opt-level=3, lto="fat", codegen-units=1, panic="abort", strip=true |
| L6: Code Quality | 20/20 | 1695 lib tests + 13 analytic-solution oracles + 105 engineering oracles (5 thermal/fatigue + 34 solid + 39 fluid + 27 misc) + 13 default-config oracles + 53 alice-bamboo integration tests + 8 fuzz targets + 44 determinism tests (6-platform bit-exact, Fix128 + f32 golden), clippy -D warnings (default + full native feature set, all targets), MSRV 1.85 CI job (default / no_std / native), #![deny(missing_docs)], cargo-semver-checks hard-gated |
| Total | 100/100 |
L1: Memory Layout (15/15)
All hot data structures use 64-byte cache-line alignment with hot/cold field separation:
- RigidBody (
solver.rs):#[repr(C, align(64))]+ hot/cold field reorder - Cloth (
cloth.rs):#[repr(C, align(64))]+ precomputedinv_rest_lengthper edge constraint - Fluid (
fluid.rs):#[repr(C, align(64))]+ precomputedinv_rest_densityandgrid_half
L2: Execution Model (20/20)
Aggressive inlining and branchless execution across all hot paths:
- GJK/BVH: All support functions and traversal marked
#[inline(always)](35 annotations total) - Constraint solving:
#[inline(always)]on distance/contact constraint kernels - Fluid spatial grid:
grid_halfprecomputed at construction, eliminates repeated division inhash()hot path - Branchless primitives (
math.rs):select_fix128(),select_vec3()— CMOV-equivalent using bitwise masks, zero pipeline flushes
L3: Compute Strategy (20/20)
Division elimination and warm-starting for faster convergence:
- Distance constraint warm-start:
cached_lambdafield stores the Lagrange multiplier from the previous substep, biasing the initial guess for dramatically faster convergence - Cloth reciprocal precomputation:
inv_rest_lengthcomputed once at construction, constraint solving uses multiplication instead of division - Fluid reciprocal precomputation:
inv_rest_densityeliminates 2+ divisions per particle per iteration in incompressibility constraint - Contact manifold warm-start: Per-contact
lambda_n,lambda_t1,lambda_t2accumulated across frames viaapply_warm_start() - Contact modifier parallel pre-pass:
pre_process_contacts()runs sequentially before Rayon parallel dispatch, applying pre-solve hooks and contact modifiers safely without data races
L4: GPU & Throughput (15/15)
SIMD-width-aware batching for optimal GPU and CPU utilization:
// Compile-time CPU feature detection
pub const SIMD_WIDTH: usize = simd_width;
// AVX2=8, SSE=4, NEON=4, scalar=1
SIMD_WIDTHconstant (math.rs): Compile-time CPU feature detection (AVX2=8, SSE=4, NEON=4, scalar=1)GpuSdfInstancedBatch(gpu_sdf.rs): Groups SDF queries by ID to minimize GPU kernel launchesGpuSdfMultiDispatch(gpu_sdf.rs): Manages multiple GPU batches withtotal_queries()andtotal_dispatches()statisticsbatch_size()(gpu_sdf.rs): ReturnsSIMD_WIDTHfor register-width-aligned data streams
L5: Build Profile (10/10)
[]
= 3 # Maximum optimization
= "fat" # Link-time optimization (all crates unified)
= 1 # Single code generation unit (maximum optimization)
= "abort" # No unwinding tables
= true # Strip symbols
L6: Code Quality (20/20)
- 1695 lib tests + 44 determinism tests across the alice-physics crate (Iter 2-6 audit + v1.0 stable release additions + v1.0.1 coloring / island / Fix128 tests + 1.2.0 mutation-score batches 1-8 and analytic oracles)
- 53 alice-bamboo integration tests (end-to-end 3D-print safety scenarios)
- 9 fuzz targets (
fuzz_step,fuzz_collision,fuzz_deterministic_roundtrip,fuzz_joint,fuzz_cfd,fuzz_ccd,fuzz_trimesh,fuzz_structural,fuzz_step_parity) - Total: 2001 passing tests in
cargo test(default features: 1695 lib + 44 determinism (9 Fix128 golden + 13 f32 golden + 22 semantic) + 220 integration / oracle (72 + 13 analytic + 105 engineering + 13 default-config + 3 parallel + 14 other) + 21 doctests + 3 ignored; 1728 lib tests with the full native feature set), clippy: 0 warnings under-D warnings(default +std,simd,parallel,ffi,gpu-solver-bridge,neural,replay,analytics,--all-targets),#
Additional Optimizations
Stackless BVH Traversal
Traditional BVH traversal uses a stack to track nodes to visit. Our implementation uses escape pointers embedded in each node:
┌──────────────────────────────────────────────────────┐
│ BvhNode Layout (32 bytes, cache-aligned) │
├──────────────────────────────────────────────────────┤
│ aabb_min[3] (12 bytes) - Bounding box min │
│ first_child/prim (4 bytes) - Child or prim idx │
│ aabb_max[3] (12 bytes) - Bounding box max │
│ prim_count_escape (4 bytes) - [count:8|escape:24]│
└──────────────────────────────────────────────────────┘
Traversal: single index variable, no stack allocation
if (hit) → descend to first_child
if (miss) → jump to escape_idx (skip entire subtree)
Benefits:
- Zero heap allocation during queries
- Single register for traversal state
- Better branch prediction
- i32 AABB comparison (no Fix128 reconstruction)
SIMD Acceleration (optional)
Enable with --features simd:
// x86_64 with SSE2
Constraint Batching (optional)
Enable with --features parallel:
Constraints are grouped by graph coloring - constraints with no shared bodies are placed in the same "color" and can be solved independently:
// Rebuild constraint batches (greedy graph coloring)
world.rebuild_batches;
// Step with batched constraint solving
world.step_parallel;
// Check number of color batches
println!;
Benefits:
- Zero heap allocation in constraint loop (index-based iteration)
- Rayon-ready parallel solving
- Reduced lock contention
- Better cache utilization
HashMap Contact Cache
Contact manifold lookup via BodyPairKey → usize HashMap for O(1) access:
// O(1) manifold lookup (was O(n) linear scan)
Falls back to linear scan for no_std environments.
Rayon Parallel Integration
Enable with --features parallel:
Position integration and velocity updates run in parallel via par_iter_mut():
// Parallel position integration (gravity + damping + Euler)
bodies.par_iter_mut.for_each;
Python Batch APIs
Zero-copy NumPy batch operations with GIL release:
# Batch body creation from (N,4) array [x, y, z, mass]
# Batch velocity update with GIL release
# (N,3)
# Combined state output as (N,10) array [px,py,pz,vx,vy,vz,qx,qy,qz,qw]
=
Why Deterministic Physics?
Traditional physics engines using IEEE 754 floating-point can produce different results across:
- Different CPU architectures (x86 vs ARM)
- Different compilers (GCC vs Clang vs MSVC)
- Different optimization levels (-O0 vs -O3)
- Different instruction sets (SSE vs AVX)
ALICE-Physics guarantees bit-exact results across platforms for every module (see Determinism scope), enabling:
- Lockstep Multiplayer: All clients compute identical simulation
- Rollback Netcode: Replay inputs deterministically
- Replay Systems: Perfect reproduction of game sessions
- Distributed Simulation: Parallel computation with consistent results
Architecture
┌─────────────────────────────────────────────────────────────────────────────┐
│ ALICE-Physics v1.0.0 stable │
│ 1695 lib tests + 44 determinism tests (9 golden + 22 semantic), 6 CI │
├─────────────────────────────────────────────────────────────────────────────┤
│ Core Layer │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ math │ │ collider │ │ solver │ │ bvh │ │sdf_colldr│ │
│ │ Fix128 │ │ AABB │ │ RigidBody│ │ Morton │ │ SdfField │ │
│ │ Vec3Fix │ │ Sphere │ │ XPBD │ │ Stackless│ │ Gradient │ │
│ │ QuatFix │ │ Capsule │ │ Sensor │ │ Zero- │ │ Early-out│ │
│ │ CORDIC │ │ GJK/EPA │ │ Rollback │ │ alloc │ │ │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ │
│ AAA Engine Layer │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │box_colldr│ │ compound │ │cont_cache│ │dynamic_bv│ │ material │ │
│ │ OBB │ │ Multi- │ │ HashMap │ │ Incr BVH │ │ Pair Tbl │ │
│ │ GJK Supp │ │ Shape │ │ O(1) Get │ │ AVL Bal │ │ Combine │ │
│ │ Inertia │ │ Local Tx │ │ Warm Str │ │ O(log n) │ │ Friction │ │
│ │ Corners │ │ AABB Mrg │ │ 4-point │ │ Fat AABB │ │ Restit │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │dbg_rendr │ │profiling │ │ interp │ │
│ │ Wireframe│ │ Timers │ │ Snapshot │ │
│ │ Contacts │ │ Per-Stage│ │ NLERP │ │
│ │ Joints │ │ Stats │ │ Blend │ │
│ │ BVH/AABB │ │ History │ │ Alpha │ │
│ └──────────┘ └──────────┘ └──────────┘ │
│ │
│ Collision Shapes (v0.5.0) │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ cone │ │ellipsoid │ │ torus │ │plane_col │ │ wedge │ │
│ │ Apex/Base│ │ 3-Axis │ │ Maj/Min │ │ Hessian │ │ TriPrism │ │
│ │ GJK Supp│ │ Aniso │ │ Minkowsk │ │ Sph/AABB │ │ 6-Vertex │ │
│ │ Inertia │ │ Support │ │ Support │ │ Intersct │ │ GJK Supp│ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ ┌──────────┐ │
│ │cvx_mesh │ │
│ │ Incr Hull│ │
│ │ Tetra │ │
│ │ Horizon │ │
│ └──────────┘ │
│ │
│ Constraint & Dynamics Layer │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ joint │ │joint_extr│ │ motor │ │articulatn│ │ force │ │
│ │ Ball │ │ Pulley │ │ PD 1D/3D │ │ Ragdoll │ │ Wind │ │
│ │ Hinge │ │ Gear │ │ Position │ │ FK Chain │ │ Gravity │ │
│ │ Fixed │ │ Weld │ │ Velocity │ │ Robotic │ │ Buoyancy │ │
│ │ Slider │ │ Rack&Pin │ │ Max Torq │ │ Feather- │ │ Drag │ │
│ │ Spring │ │ Mouse │ │ │ │ stone │ │ Vortex │ │
│ │ D6 │ │ Breakabl │ │ │ │ 12-body │ │ Explosion│ │
│ │ ConeTwst │ │ │ │ │ │ │ │ Magnetic │ │
│ │ Breakable│ │ │ │ │ │ │ │ │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ ┌──────────┐ │
│ │ sleeping │ │
│ │ Islands │ │
│ │ Union- │ │
│ │ Find │ │
│ └──────────┘ │
│ │
│ Query & Collision Layer │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ raycast │ │ ccd │ │ trimesh │ │heightfld │ │ filter │ │
│ │ Sphere │ │ TOI │ │ Triangle │ │ Bilinear │ │ Layer │ │
│ │ AABB │ │ Conserv. │ │ BVH-accel│ │ Normal │ │ Mask │ │
│ │ Capsule │ │ Advance │ │ Moller- │ │ Sphere │ │ Group │ │
│ │ Plane │ │ Swept │ │ Trumbore │ │ Collide │ │ Bidirect │ │
│ │ Sweep │ │ Specultv │ │ Closest │ │ Signed │ │ │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ ┌──────────┐ ┌──────────┐ │
│ │ query │ │character │ │
│ │ SphCast │ │ Move&Sld │ │
│ │ CapCast │ │ Stair │ │
│ │ Overlap │ │ Ground │ │
│ │ AABB Ovr │ │ SDF Terr │ │
│ └──────────┘ └──────────┘ │
│ │
│ Soft Body & Simulation Layer │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ rope │ │ cloth │ │ fluid │ │deformable│ │ vehicle │ │
│ │ XPBD │ │ XPBD │ │ PBF │ │ FEM-XPBD │ │ Wheel │ │
│ │ Distance │ │ Triangle │ │ SPH Hash │ │ Tetrahedr│ │ Suspensn │ │
│ │ Chain │ │ Self-Col │ │ Density │ │ Volume │ │ Engine │ │
│ │ Cable │ │ SpatHash │ │ Viscosty │ │ Neo-Hook │ │ Steering │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │clth_flud │ │rope_atth │ │soft_cut │ │ particle │ │
│ │ Drag │ │ RigidBdy │ │ Plane │ │ Emitters │ │
│ │ Buoyancy │ │ Complnce │ │ Deform │ │ Lifetime │ │
│ │ Boundary │ │ Break │ │ Cloth │ │ ForceInt │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ │
│ SDF Advanced Layer │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │sdf_mnfld │ │ sdf_ccd │ │sdf_force │ │sdf_destr │ │sdf_adapt │ │
│ │ Manifold │ │ SphTrace │ │ Attract │ │ CSG Bool │ │ LOD │ │
│ │ N-point │ │ March │ │ Repel │ │ Subtract │ │ Distance │ │
│ │ Contact │ │ TOI │ │ Contain │ │ Real-time│ │ Adaptive │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ ┌──────────┐ ┌──────────┐ │
│ │cvx_decomp│ │ gpu_sdf │ │
│ │ Voxel │ │ Compute │ │
│ │ Flood │ │ Batch │ │
│ │ Convex │ │ Shader │ │
│ └──────────┘ └──────────┘ │
│ │
│ SDF Simulation Modifiers Layer │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │sim_field │ │sim_modif │ │ thermal │ │ pressure │ │ erosion │ │
│ │ Scalar3D │ │ Modifier │ │ Heat Eq │ │ Crush │ │ Wind │ │
│ │ Vector3D │ │ Chain │ │ Melt │ │ Bulge │ │ Water │ │
│ │ Trilin │ │ Modified │ │ Freeze │ │ Dent │ │ Chemical │ │
│ │ Diffuse │ │ SDF │ │ Expand │ │ Yield │ │ Ablation │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ ┌──────────┐ ┌──────────┐ │
│ │ fracture │ │phase_chg │ │
│ │ Stress │ │ Solid │ │
│ │ Crack │ │ Liquid │ │
│ │ CSG Sub │ │ Gas │ │
│ │ Voronoi │ │ Latent H │ │
│ └──────────┘ └──────────┘ │
│ │
│ 2D Physics Subsystem (v0.5.0) │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ physics2d │ │
│ │ Vec2Fix, Shape2D (Circle/Polygon/Capsule/Edge), RigidBody2D │ │
│ │ SAT + Voronoi collision, XPBD 2D solver, Joint2D (Rev/Dist/Weld/M) │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │
│ Mesh & I/O Utilities (v0.5.0) │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │mass_prop │ │col_mesh │ │ scene_io │ │multi_wrld│ │
│ │ Sphere │ │ Marching │ │ Binary │ │ N worlds │ │
│ │ Box │ │ Cubes │ │ APHYS │ │ Transfer │ │
│ │ Cylinder │ │ EdgeClps │ │ JSON │ │ Isolate │ │
│ │ PAxis │ │ Simplify │ │ Fix128 │ │ Step All │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ │
│ Visualization (v0.5.0) │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ heatmap │ │ flow_viz │ │contct_viz│ │
│ │ Stress │ │ Arrows │ │ Force │ │
│ │ Temp │ │ Streamln │ │ Friction │ │
│ │ Viridis │ │ Velocity │ │ Cone │ │
│ └──────────┘ └──────────┘ └──────────┘ │
│ │
│ Game Systems Layer │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │anim_blnd │ │audio_phys│ │ netcode │ │
│ │ SLERP │ │ Impact │ │ FrameInp │ │
│ │ Ragdoll │ │ Friction │ │ Checksum │ │
│ │ Blend │ │ Rolling │ │ Snapshot │ │
│ │ IK Mix │ │ Material │ │ Rollback │ │
│ └──────────┘ └──────────┘ └──────────┘ │
│ │
│ Analytics & Privacy Layer │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │
│ │ sketch │ │ anomaly │ │ privacy │ │ pipeline │ │
│ │ HyperLog │ │ MAD │ │ Laplace │ │ MetricPi │ │
│ │ DDSketch │ │ EWMA │ │ RAPPOR │ │ RingBuf │ │
│ │ CountMin │ │ Z-score │ │ RandResp │ │ Registry │ │
│ │ HeavyHit │ │ Composit │ │ XorShift │ │ Snapshot │ │
│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │
│ │
│ Utility Layer │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌─────────────────────────────────┐│
│ │ rng │ │ event │ │fluid_net │ │ neural (ALICE-ML × Phys) ││
│ │ PCG-XSH │ │ Begin │ │ Delta │ │ Ternary {-1,0,+1} → Fix128 ││
│ │ Fix128 │ │ Persist │ │ Compress │ │ Deterministic AI ││
│ │ Direction│ │ End │ │ Snapshot │ │ Ragdoll Controller ││
│ └──────────┘ └──────────┘ └──────────┘ └─────────────────────────────────┘│
└─────────────────────────────────────────────────────────────────────────────┘
Usage
Choose Your Path
Pick the entry point that matches your role. All paths share the same deterministic PhysicsWorld, so you can start simple and layer in advanced features (rollback / GPU offload / joints) later without rewriting.
| You are… | Path | Best for | Section |
|---|---|---|---|
| First time here | Hello, first physics ↓ | Sanity-check the install with a falling sphere | ↓ |
| Simulation dev, want the basics | Basic Simulation | Rigid bodies, gravity, ground, per-frame stepping | ↓ |
| Netcode / lockstep game dev | Rollback Netcode | Snapshot save/load, deterministic replay, Fix128 bit-exact | ↓ |
| Rope / cloth / constraint dev | Distance Constraint + joint module |
Chains, ropes, ragdolls, breakable constraints | ↓ |
| Perf-sensitive (many bodies) | BVH Broad-Phase | Spatial acceleration, zero-alloc queries, Morton codes | ↓ |
| GPU offload (advanced) | GPU Solver Bridge | PGS iteration on GPU via ALICE-TRT, byte-exact vs CPU | ↑ |
| Unity / UE5 / Godot integrator | C-ABI FFI | Fix128 hi/lo pairs across the C ABI, bit-pattern equality | see alice_physics_ffi::* |
| CCD / raycast / trimesh user | Module-specific | ccd / raycast / trimesh modules with dedicated APIs |
see Modules |
Hello, First Physics (30 seconds)
The smallest working sample — one falling sphere onto static ground, step it, print the y-coord:
use *;
let mut world = new;
let sphere = new_dynamic;
let _sphere_id = world.add_body;
world.add_body; // ground plane at y=0
let dt = from_ratio;
for frame in 0..60
Once this runs, jump to the path that matches your role.
Basic Simulation
use *;
Distance Constraint (Rope/Chain)
use *;
Rollback Netcode
use *;
BVH Broad-Phase Collision
use ;
// Build BVH from primitives
let primitives: = bodies.iter.enumerate
.map
.collect;
let bvh = build;
// Query with zero heap allocation (callback version)
bvh.query_callback;
// Or collect results
let hits = bvh.query;
// Get BVH statistics
let stats = bvh.stats;
println!;
Common Recipes
Additional patterns that come up frequently — copy-paste starting points.
1. Raycast against the world
use *;
let ray = Ray ;
if let Some = world.raycast
2. Put idle bodies to sleep (perf win)
// PhysicsConfig has sleeping enabled by default; tune the thresholds when needed.
let mut config = default;
config.sleeping.linear_threshold = from_ratio; // 0.01 m/s
config.sleeping.angular_threshold = from_ratio;
config.sleeping.time_to_sleep = from_ratio; // 0.5 s
let mut world = new;
3. Breakable constraint (rope snap under load)
let constraint = DistanceConstraint ;
let id = world.add_distance_constraint;
world.set_constraint_break_force; // snaps > 500 N
4. Static-ground quick setup
let ground = new_static;
let ground_id = world.add_body;
world.set_collider;
5. Save + reload a snapshot (rollback primitive)
let snapshot: = world.serialize_state; // byte-exact across arch
// ... later, or on another machine:
world.deserialize_state; // resumes at frame boundary
6. Continuous collision (fast-moving projectile)
use ccd;
let bullet = new_dynamic;
let bullet_id = world.add_body;
world.enable_ccd; // subswept collision, avoids tunneling
Session 3 Solver Loops (v0.12)
CFD gravity settling — solve incompressible Navier-Stokes for one time step with pressure projection:
use CfdSolver;
use Fix128;
let mut solver = new;
solver.jacobi_iterations = 100;
// Water in gravity, closed box → settles, divergence ≈ 0
for _ in 0..30
// solver.grid.v[…] centre column will read −0.294 m/s at t = 0.03 s
// matching −g·t exactly (bit-exact recovery of the free-fall analytical solution)
Structural creep + fatigue history — advance a PLA shelf through 20 h of sustained load at 55 °C and print the diagnostic table:
use ;
use MaterialProperties;
use Fix128;
use StructuralSolver;
let section = Rectangular ;
let load = SimplySupportedCenter ;
let mut solver = new;
solver.operating_temp_c = from_int;
solver.dt_s = from_int; // 1-hour steps
let history = solver.run;
println!;
Print pipeline safety — run 10 print-safety checks in one call:
use ;
use Fix128;
use LoadDirection;
use ;
use OverhangRegion;
use Footprint;
let footprint = Footprint ;
let inputs = PrintPipelineInputs ;
let report = analyze_print_pipeline;
report.print;
// Prints warp / strength envelope / thermal / beam FoS / bridging /
// support volume / K_t / bimaterial and an overall SAFE / UNSAFE verdict.
Where to go next
| I want to… | See |
|---|---|
| Understand the full type surface | Modules section below |
| Deep dive into determinism guarantees | Why Deterministic Physics? |
| Offload PGS iterations to the GPU | Companion crate — ALICE-TRT |
| Wire into Unity / UE5 native plugin | alice_physics_ffi::* (module in this crate) |
| See the joint catalog (12 base + 5 advanced) | joint / joint_extra sections |
| Prove byte-exact CI on 3 platforms | See ALICE-TRT's Fix128 + physics-solver test matrix (companion release) |
| Compare to Rapier / PhysX / Box2D | Why Deterministic Physics? benchmark table |
Companion crates that plug directly into PhysicsWorld:
- ALICE-TRT (
gpu-solver-bridgefeature) — GPU PGS solver offload with byte-exact CPU parity - ALICE-Cloth — XPBD cloth on top of the same Fix128 primitives
- ALICE-Vehicle — Deterministic vehicle rig
- ALICE-Netcode — Rollback netcode plumbing built for
serialize_state/deserialize_state
Modules
math - Fixed-Point Primitives
| Type | Description |
|---|---|
Fix128 |
128-bit fixed-point number (I64F64) |
Vec3Fix |
3D vector with Fix128 components |
QuatFix |
Quaternion for rotations |
Mat3Fix |
3x3 matrix for inertia tensors |
Constants:
Fix128::ZERO,Fix128::ONE,Fix128::NEG_ONEFix128::PI,Fix128::HALF_PI,Fix128::TWO_PI
CORDIC functions (deterministic, no FPU):
Fix128::sin(),Fix128::cos(),Fix128::sin_cos()Fix128::atan(),Fix128::atan2()Fix128::sqrt()(Newton-Raphson, 64 iterations)
Utility:
Fix128::from_ratio(num, denom)- Create from fractionFix128::half(),Fix128::double()- Exact bit shiftsFix128::abs(),Fix128::floor(),Fix128::ceil()
collider - Collision Detection
| Shape | Description |
|---|---|
AABB |
Axis-Aligned Bounding Box |
Sphere |
Sphere collider |
Capsule |
Capsule (cylinder + hemispheres) |
ConvexHull |
Arbitrary convex polyhedron |
CollisionResult |
Contact information |
Algorithms:
- GJK: Gilbert-Johnson-Keerthi for intersection test (64 iterations max)
- EPA: Expanding Polytope Algorithm for penetration depth (64 iterations max)
solver - XPBD Physics
RigidBody fields:
| Field | Type | Description |
|---|---|---|
position |
Vec3Fix |
Center of mass position |
rotation |
QuatFix |
Orientation quaternion |
velocity |
Vec3Fix |
Linear velocity |
angular_velocity |
Vec3Fix |
Angular velocity |
inv_mass |
Fix128 |
Inverse mass (0 = static) |
inv_inertia |
Vec3Fix |
Inverse inertia tensor (diagonal) |
restitution |
Fix128 |
Bounciness (0-1) |
friction |
Fix128 |
Friction coefficient |
is_sensor |
bool |
Sensor mode: detects overlap but no physics response |
Constraints:
DistanceConstraint: Fixed distance between anchor pointsContactConstraint: Collision response with friction/restitution
Methods:
RigidBody::new(position, mass)- Create dynamic bodyRigidBody::new_dynamic(position, mass)- Alias for newRigidBody::new_static(position)- Create immovable bodyRigidBody::new_sensor(position)- Create sensor/trigger body (no physics response)
bvh - Spatial Acceleration
| Type | Description |
|---|---|
LinearBvh |
Flat array BVH with stackless traversal |
BvhNode |
32-byte cache-aligned node with escape pointer |
BvhPrimitive |
Primitive entry for construction |
BvhStats |
Tree statistics |
Features:
- Morton Codes: Z-order curve for spatial locality
- Escape Pointers: Stackless traversal (zero allocation)
- i32 AABB: Fast integer comparison without Fix128 reconstruction
joint - 12 Joint Types + Breakable Constraints
| Type | Description |
|---|---|
BallJoint |
Spherical joint (3 rotational DOF) |
HingeJoint |
Revolute joint (1 rotational DOF) with angle limits |
FixedJoint |
Weld joint (0 DOF) |
SliderJoint |
Prismatic joint (1 translational DOF) with limits |
SpringJoint |
Damped spring constraint |
D6Joint |
6-DOF configurable joint with per-axis lock/free/limit |
ConeTwistJoint |
Ball joint with cone swing limit and twist limit |
joint_extra - 5 Advanced Joints (v0.5.0)
| Type | Description |
|---|---|
PulleyJoint |
Pulley with 2 anchors and rope ratio (total distance constraint) |
GearJoint |
Gear coupling (angular velocity ratio between two bodies) |
WeldJoint |
Rigid weld with break_force / break_torque threshold |
RackAndPinionJoint |
Rotation-to-translation conversion with pitch radius |
MouseJoint |
Target-following joint for mouse/touch drag interaction |
All joint types support breakable constraints via with_break_force(max_force). When the constraint force exceeds the threshold, the joint breaks and is removed from simulation.
use *;
// Hinge with angle limits
let hinge = new
.with_limits;
// D6 joint (lock X translation, free Y rotation, limit Z rotation)
let d6 = new
.with_axis
.with_axis
.with_axis;
// Cone-twist joint (shoulder-like with cone + twist limits)
let cone = new
.with_cone_limit // 45° cone
.with_twist_limit; // 30° twist
// Breakable ball joint (breaks at force > 100)
let ball = new
.with_break_force;
// Solve with breakable support — returns indices of broken joints
let broken = solve_joints_breakable;
raycast - Ray & Shape Casting
| Function | Description |
|---|---|
ray_sphere |
Ray vs sphere intersection |
ray_aabb |
Ray vs AABB (slab method) |
ray_capsule |
Ray vs capsule |
ray_plane |
Ray vs infinite plane |
sweep_sphere |
Moving sphere vs sphere (Minkowski expansion) |
ccd - Continuous Collision Detection
| Function | Description |
|---|---|
sphere_sphere_toi |
Sphere-sphere TOI via quadratic |
sphere_plane_toi |
Sphere-plane TOI |
conservative_advancement |
TOI via iterative safe stepping |
swept_aabb |
Swept AABB bounding volume |
speculative_contact |
Speculative contact for CCD integration with solver |
needs_ccd |
Velocity threshold check for CCD activation |
sleeping - Sleep & Island System
| Type | Description |
|---|---|
IslandManager |
Union-Find island management |
SleepData |
Per-body sleep tracking |
SleepConfig |
Velocity thresholds, idle frame count |
trimesh - Triangle Mesh Collision
| Type | Description |
|---|---|
Triangle |
Single triangle with Moller-Trumbore intersection |
TriMesh |
BVH-accelerated triangle mesh |
Features:
- Ray-triangle intersection (Moller-Trumbore)
- Closest point on triangle
- Sphere-mesh collision detection
heightfield - Height Field Terrain
| Type | Description |
|---|---|
HeightField |
Grid-based terrain with bilinear interpolation |
Features:
sample_height(world_x, world_z)with bilinear interpolationsample_normal(world_x, world_z)from central differencescollide_sphere()for sphere-terrain collisionsigned_distance(point)for point-terrain distance
filter - Collision Filtering
| Type | Description |
|---|---|
CollisionFilter |
Layer/mask bitmask with collision groups |
layers module |
Predefined layers (DEFAULT, STATIC, PLAYER, ENEMY, etc.) |
force - 7 Force Fields
| Variant | Description |
|---|---|
Directional |
Uniform wind/gravity (direction + strength) |
Point |
Radial gravity well with inverse-square falloff |
Drag |
Velocity-proportional drag |
Buoyancy |
Plane-based buoyancy with density |
Vortex |
Spinning vortex field (center + axis + strength) |
Explosion |
Radial impulse with configurable falloff_power attenuation |
Magnetic |
Simplified dipole model with 1/r^3 inverse cube law |
motor - PD Controllers
| Type | Description |
|---|---|
PdController |
1D proportional-derivative controller |
PdController3D |
3D PD controller |
JointMotor |
Joint motor with position/velocity/torque modes |
articulation - Articulated Bodies
| Type | Description |
|---|---|
ArticulatedBody |
Multi-joint chain with FK propagation |
Link |
Joint + body pair in a chain |
Presets:
build_ragdoll()— 12-body humanoid (head, torso, arms, legs)
rng - Deterministic Random
| Type | Description |
|---|---|
DeterministicRng |
PCG-XSH-RR 32-bit generator |
Methods:
next_fix128()— Random Fix128 in [0, 1)range_fix128(min, max)— Random in [min, max)next_direction()— Random unit Vec3Fix
event - Contact Events
| Type | Description |
|---|---|
EventCollector |
Tracks contact begin/persist/end per pair |
ContactEvent |
Body pair + event type + contact point |
ContactEventType |
Begin, Persist, End |
query - Shape Cast & Overlap Queries
| Function | Description |
|---|---|
sphere_cast |
Sweep a sphere along a direction (Minkowski sum approach) |
capsule_cast |
Sweep a capsule along a direction (3-point sphere cast) |
overlap_sphere |
Find all bodies overlapping a sphere |
overlap_aabb |
Find all bodies within an AABB (point test) |
overlap_aabb_expanded |
Find all bodies within an AABB expanded by body radius |
character - Character Controller
| Type | Description |
|---|---|
CharacterController |
Kinematic capsule-based character with move-and-slide |
CharacterConfig |
Radius, height, max slope, step height, skin width |
MoveResult |
Movement result with ground state |
Features:
- Collide-and-slide algorithm with configurable max slides
- Ground detection via downward raycast + SDF
- Stair stepping (automatic step-up for small obstacles)
- SDF terrain integration (push out of SDF surfaces)
rope - XPBD Rope & Cable
| Type | Description |
|---|---|
Rope |
XPBD distance-chain rope simulation |
RopeConfig |
Segment count, length, stiffness, damping |
cloth - XPBD Cloth Simulation
| Type | Description |
|---|---|
Cloth |
XPBD triangle mesh cloth with stretch/shear/bend constraints |
ClothConfig |
Stiffness, damping, self-collision, gravity |
Features:
- Distance constraints (stretch resistance)
- Bending constraints
- Self-collision via spatial hash grid
fluid - Position-Based Fluids
| Type | Description |
|---|---|
Fluid |
Position-Based Fluids (PBF) simulation |
FluidConfig |
Particle count, rest density, viscosity, kernel radius |
Features:
- SPH density estimation with spatial hash grid
- Incompressibility constraint solving
- Viscosity (XSPH)
- Surface tension
deformable - FEM-XPBD Deformable Bodies
| Type | Description |
|---|---|
DeformableBody |
FEM tetrahedral mesh deformable body |
DeformableConfig |
Young's modulus, Poisson's ratio, damping |
vehicle - Vehicle Physics
| Type | Description |
|---|---|
Vehicle |
Complete vehicle simulation |
VehicleConfig |
Wheel count, suspension, engine, steering parameters |
Features:
- Wheel contact with ground/terrain
- Spring-damper suspension
- Engine torque with gear shifting
- Ackermann steering geometry
cone - Cone Collider (v0.5.0)
| Type | Description |
|---|---|
Cone |
Cone collider with apex at +Y and base at -Y |
Features:
- GJK
Supporttrait implementation (apex/base center switching) - AABB computation, volume, surface area, inertia diagonal
- Configurable radius and half-height with rotation
ellipsoid - Ellipsoid Collider (v0.5.0)
| Type | Description |
|---|---|
Ellipsoid |
Ellipsoid with three independent semi-axes (rx, ry, rz) |
Features:
- Anisotropic GJK support (scale direction by radii, normalize, scale back)
- Volume, AABB, and inertia diagonal computation
torus - Torus Collider (v0.5.0)
| Type | Description |
|---|---|
Torus |
Torus with major radius (ring) and minor radius (tube) |
Features:
- GJK support via Minkowski sum decomposition
- Volume and AABB computation
plane_collider - Infinite Plane Collider (v0.5.0)
| Type | Description |
|---|---|
PlaneCollider |
Infinite plane in Hessian normal form (normal + offset) |
Features:
intersect_sphere()— sphere-plane intersection with contact pointintersect_aabb()— AABB-plane overlap testsigned_distance()— point-plane signed distance
wedge - Wedge Collider (v0.5.0)
| Type | Description |
|---|---|
Wedge |
Triangular prism (wedge) with 6 vertices |
Features:
- GJK support (iterates 6 vertices for max dot product)
- Volume, AABB, and centroid computation
convex_mesh_builder - Convex Hull Builder (v0.5.0)
| Function | Description |
|---|---|
build_convex_hull(points) |
Build convex hull from arbitrary point set |
compute_centroid(faces, vertices) |
Compute centroid of convex hull |
Algorithm: Incremental convex hull — find initial tetrahedron, incrementally insert points, remove visible faces, patch with horizon edges.
physics2d - 2D Physics Engine (v0.5.0)
| Type | Description |
|---|---|
Vec2Fix |
2D vector with Fix128 components |
Shape2D |
Circle, Polygon (max 16 vertices), Capsule, Edge |
RigidBody2D |
2D rigid body with position, angle, velocity, angular velocity |
PhysicsWorld2D |
Complete 2D physics world with XPBD solver |
PhysicsConfig2D |
Gravity, substeps, iterations, sleep threshold |
Contact2D |
Contact point with normal, depth, body indices |
Joint2D |
Revolute, Distance, Weld, Mouse joint variants |
BodyType2D |
Dynamic, Static, Kinematic |
Algorithms:
- SAT (Separating Axis Theorem) with Voronoi region classification
- XPBD position-based solver with configurable substeps
- Broad-phase AABB overlap, narrow-phase polygon projection
mass_properties - Mass & Inertia (v0.5.0)
| Function | Description |
|---|---|
sphere_mass_properties(radius, density) |
Sphere mass + inertia tensor |
box_mass_properties(half_extents, density) |
Box mass + inertia tensor |
cylinder_mass_properties(radius, half_h, density) |
Cylinder mass + inertia |
capsule_mass_properties(radius, half_h, density) |
Capsule mass + inertia |
convex_hull_mass_properties(vertices, faces, density) |
Convex hull mass + inertia |
translate_inertia(inertia, mass, offset) |
Parallel axis theorem |
collision_mesh_gen - SDF to Mesh (v0.5.0)
| Type / Function | Description |
|---|---|
CollisionMeshConfig |
Grid resolution, bounding box, simplification target |
CollisionMesh |
Vertices + triangle indices output |
generate_collision_mesh(sdf, config) |
Marching cubes mesh generation |
simplify_mesh(mesh, target) |
Edge-collapse mesh simplification |
scene_io - Scene Serialization (v0.5.0, std)
| Function | Description |
|---|---|
save_binary(path, scene) |
Save to .aphys binary format (bit-exact Fix128) |
load_binary(path) |
Load from .aphys binary format |
save_json(path, scene) |
Save to .aphys.json human-readable format |
load_json(path) |
Load from .aphys.json format |
Binary format: Magic APHYS\0, little-endian, raw Fix128 {hi: i64, lo: u64} for bit-exact deterministic roundtrip.
cloth_fluid - Cloth-Fluid Coupling (v0.5.0)
| Type | Description |
|---|---|
ClothFluidCoupling |
Bidirectional cloth-fluid interaction |
Effects: Fluid drag force on cloth vertices, buoyancy based on submersion, boundary repulsion to prevent penetration.
rope_attach - Rope Attachment (v0.5.0)
| Type | Description |
|---|---|
RopeAttachment |
Attach rope endpoints to rigid bodies |
Features: Configurable compliance, break force threshold, automatic detachment.
soft_body_cut - Soft Body Cutting (v0.5.0)
| Function | Description |
|---|---|
cut_deformable(body, plane) |
Cut deformable body along a plane |
cut_cloth(cloth, plane) |
Cut cloth mesh along a plane |
Algorithm: Plane-based topology splitting — classifies vertices, creates new vertices at intersection points, rebuilds connectivity.
heatmap - Stress/Temperature Heatmap (v0.5.0)
| Type | Description |
|---|---|
Heatmap |
2D scalar field visualization with colormap |
HeatmapConfig |
Resolution, value range, colormap selection |
Features: Viridis colormap, RGBA pixel output, configurable min/max range.
flow_viz - Flow Visualization (v0.5.0)
| Type | Description |
|---|---|
FlowArrow |
Velocity arrow with position, direction, magnitude |
Streamline |
Ordered list of points tracing a flow path |
Functions: generate_flow_arrows(), generate_streamlines() from velocity fields.
contact_viz - Contact Visualization (v0.5.0)
| Type | Description |
|---|---|
ContactArrow |
Force arrow at contact point |
FrictionCone |
Cone geometry representing friction limit |
Functions: visualize_contacts(), visualize_friction_cones() from contact manifolds.
multi_world - Multiple Physics Worlds (v0.5.0)
| Type | Description |
|---|---|
MultiWorld |
Container for N independent physics worlds |
Features:
add_world()/remove_world()— manage independent worldsstep_all(dt)— advance all worlds simultaneouslytransfer_body(from, to, body_id)— move body between worlds
particle - Particle System (v0.5.0)
| Type | Description |
|---|---|
ParticleSystem |
General-purpose particle simulation |
ParticleEmitter |
Directional emitter with cone spread |
Particle |
Position, velocity, age, lifetime, mass |
Features:
- Configurable emission rate, spread angle, speed range
- Lifetime management with automatic recycling
- Full
ForceFieldintegration (including Explosion and Magnetic) - Deterministic via
DeterministicRng
animation_blend - Animation Blending
| Type | Description |
|---|---|
AnimationBlender |
Ragdoll-to-animation pose blending |
BlendMode |
Lerp, Slerp, Additive |
SkeletonPose |
Joint transforms for a skeleton |
AnimationClip |
Keyframed animation data |
audio_physics - Physics-Based Audio
| Type | Description |
|---|---|
AudioGenerator |
Generates audio parameters from physics contacts |
AudioConfig |
Material properties for audio synthesis |
AudioEvent |
Impact, friction, rolling audio events |
AudioMaterial |
Surface material with audio properties |
sdf_manifold - SDF Contact Manifold
Multi-point contact generation from SDF surfaces for more stable collision response.
sdf_ccd - SDF Continuous Collision Detection
Sphere tracing-based CCD for bodies moving against SDF surfaces.
sdf_force - SDF Force Fields
| Variant | Description |
|---|---|
Attract |
Pull bodies toward SDF surface |
Repel |
Push bodies away from SDF surface |
Contain |
Keep bodies inside SDF boundary |
Flow |
Flow field following SDF gradient |
sdf_destruction - SDF Boolean Destruction
Real-time CSG boolean operations for destructible environments.
| Type | Description |
|---|---|
DestructibleSdf |
SDF that accumulates destruction shapes |
DestructionShape |
Sphere, box, or custom SDF subtraction |
sdf_adaptive - Adaptive SDF Evaluation
Distance-based LOD for SDF evaluation — faraway queries use coarser sampling.
convex_decompose - Convex Decomposition
Generate convex hull decomposition from an SDF voxel grid for use with GJK/EPA.
gpu_sdf - GPU Compute Shader
Batch SDF evaluation on GPU via compute shaders. Requires --features std.
fluid_netcode - Fluid Netcode
Deterministic fluid simulation with delta-compressed snapshots for network sync. Requires --features std.
sim_field - 3D Simulation Fields
| Type | Description |
|---|---|
ScalarField3D |
Uniform grid scalar field with trilinear interpolation |
VectorField3D |
Uniform grid vector field with trilinear interpolation |
Features:
- Trilinear interpolation for smooth sampling
- Diffusion (heat equation solver)
- Decay over time
- Point splatting for localized effects
sim_modifier - SDF Simulation Modifiers
| Type | Description |
|---|---|
PhysicsModifier |
Trait for physics-driven SDF modification |
ModifiedSdf |
Chain of modifiers that alter SDF distance |
SingleModifiedSdf |
Single-modifier convenience wrapper |
thermal - Thermal Simulation
| Type | Description |
|---|---|
ThermalModifier |
Heat diffusion SDF modifier |
ThermalConfig |
Conductivity, melt/freeze thresholds |
HeatSource |
Point/area heat source |
Effects: Melt (surface recedes), thermal expansion, freeze (crystalline growth)
pressure - Pressure Simulation
| Type | Description |
|---|---|
PressureModifier |
Contact-force-driven deformation |
PressureConfig |
Yield threshold, elastic spring-back |
Effects: Crush (high pressure), bulge (internal pressure), permanent dents
erosion - Erosion Simulation
| Type | Description |
|---|---|
ErosionModifier |
Surface material removal from forces |
ErosionConfig |
Hardness, erosion rate |
ErosionType |
Wind, Water, Chemical, Ablation |
fracture - Fracture Simulation
| Type | Description |
|---|---|
FractureModifier |
Stress-driven crack propagation |
FractureConfig |
Fracture toughness, crack speed |
Crack |
Individual crack with position and direction |
Effects: Stress accumulation, crack seeds, Voronoi-like fragmentation via CSG subtraction
phase_change - Phase Change Simulation
| Type | Description |
|---|---|
PhaseChangeModifier |
Temperature-driven state transitions |
PhaseChangeConfig |
Melt/boil temperatures, latent heat |
Phase |
Solid, Liquid, Gas |
Effects: Melting (solid→liquid, flows downward), vaporization (liquid→gas, expands), solidification, condensation
box_collider - Oriented Bounding Box
| Type | Description |
|---|---|
OrientedBox |
OBB with center, half-extents, and rotation quaternion |
Features:
- GJK
Supporttrait implementation for collision detection - Fast world-space AABB computation from OBB
- Corner vertices, volume, surface area, inertia tensor
compound - Compound Shape
| Type | Description |
|---|---|
CompoundShape |
Multi-shape collider with local transforms |
ChildShape |
Individual shape + local offset/rotation |
Features:
- Merges child AABBs for broadphase
- Per-child GJK support (transforms direction to child local space)
- Mass properties from children
contact_cache - Persistent Contact Cache
| Type | Description |
|---|---|
ContactCache |
Frame-persistent contact manifold storage |
ContactManifold |
Up to 4 contact points with warm-started lambdas |
Features:
- HashMap O(1) manifold lookup by body pair
- Warm starting (carry lambda across frames for stable stacking)
- Automatic manifold pruning at end of frame
dynamic_bvh - Dynamic AABB Tree
| Type | Description |
|---|---|
DynamicBvh |
Incremental BVH with insert/remove/update |
Features:
- O(log n) insert, remove, and update operations
- AVL-style tree balancing (rotation on height imbalance)
- Fat AABBs with margin to reduce update frequency
- AABB query and ray query
material - Material Pair Table
| Type | Description |
|---|---|
MaterialTable |
Per-pair friction/restitution override table |
MaterialProperties |
Friction, restitution, combine rule |
CombineRule |
Average, Min, Max, Multiply |
debug_render - Debug Visualization
| Type | Description |
|---|---|
DebugRenderer |
Wireframe rendering of physics state |
DebugLine |
Line segment with color |
DebugDrawFlags |
Bitmask for bodies, contacts, joints, BVH, forces |
profiling - Performance Profiling
| Type | Description |
|---|---|
PhysicsProfiler |
Per-stage timing and statistics |
StageTimer |
Individual stage measurement |
FrameStats |
Broadphase/narrowphase/solver/total times |
interpolation - Substep Interpolation
| Type | Description |
|---|---|
WorldSnapshot |
Captured physics state for interpolation |
interpolate_snapshots |
NLERP blending between two snapshots |
Features:
- Capture position + rotation snapshots
- NLERP quaternion interpolation (faster than SLERP, visually smooth)
- Alpha-based blending for fixed-timestep rendering
pipeline - Metric Aggregation Pipeline
| Type | Description |
|---|---|
MetricPipeline |
Lock-free ring buffer metric aggregation engine |
MetricRegistry |
Named metric registration and lookup |
MetricSnapshot |
Point-in-time metric state capture |
MetricEvent |
Timestamped metric event with type and value |
MetricType |
Counter, Gauge, Histogram metric kinds |
RingBuffer |
Fixed-capacity circular buffer for time-series data |
Features:
- Lock-free ring buffer for high-throughput metric collection
- Named metric registry with typed metric support
- Snapshot capture for periodic reporting
- Integrates with
sketchmodule for probabilistic aggregation
sketch - Probabilistic Sketches
| Type | Description |
|---|---|
HyperLogLog |
Cardinality estimation with configurable precision |
DDSketch |
Distribution-aware quantile sketch (P50/P99/P99.9) |
CountMinSketch |
Frequency estimation with configurable width/depth |
HeavyHitters |
Top-k frequent item tracking via Count-Min Sketch |
FnvHasher |
FNV-1a hash for deterministic, allocation-free hashing |
Mergeable |
Trait for sketch merging across distributed workers |
Size variants:
HyperLogLog10(1 KB),HyperLogLog12(4 KB),HyperLogLog14(16 KB),HyperLogLog16(64 KB)DDSketch128,DDSketch256,DDSketch512CountMinSketch256x4,CountMinSketch512x4,CountMinSketch1024x8
anomaly - Streaming Anomaly Detection
| Type | Description |
|---|---|
MadDetector |
Median Absolute Deviation detector |
EwmaDetector |
Exponentially Weighted Moving Average detector |
ZScoreDetector |
Standard Z-score detector with running statistics |
CompositeDetector |
Combines multiple detectors with voting |
StreamingMedian |
O(log n) streaming median via sorted-insert buffer |
AnomalyEvent |
Timestamped anomaly report with severity |
AnomalyCallback |
Callback trait for anomaly notifications |
Features:
- Streaming operation with constant memory per detector
- Composite detector with configurable voting threshold
- Callback-driven anomaly notification
privacy - Local Differential Privacy
| Type | Description |
|---|---|
LaplaceNoise |
Calibrated Laplace mechanism for numeric queries |
Rappor |
RAPPOR protocol for categorical data collection |
RandomizedResponse |
Binary randomized response with tunable epsilon |
PrivacyBudget |
Epsilon budget tracker with composition accounting |
PrivateAggregator |
Privacy-preserving aggregation over multiple queries |
XorShift64 |
Deterministic PRNG for reproducible noise generation |
Features:
- Laplace noise calibrated to sensitivity/epsilon
- RAPPOR with Bloom filter encoding for categorical data
- Composable privacy budget tracking
SDF Collider (ALICE-SDF Integration)
ALICE-Physics can use ALICE-SDF distance fields as collision shapes. Instead of approximating complex shapes with convex hulls (GJK/EPA), the solver samples the SDF directly — giving mathematically exact surfaces at O(1) cost per query.
How It Works
Body (sphere) SdfCollider
┌───┐ ┌──────────────────────┐
│ ● │──world_to_local(pos)──▶│ SdfField::distance() │─── >0 → no hit (early-out)
└───┘ │ SdfField::normal() │─── ≤0 → contact + resolve
│ cached inv_rotation │
│ cached scale_f32 │
└──────────────────────┘
Key Optimizations
| Optimization | Description | Benefit |
|---|---|---|
| Early-out | Call distance() (1 eval) first, only compute normal() (4 evals) on collision |
80% fewer evals for non-colliding bodies |
| Cached invariants | Pre-computed inv_rotation, scale_f32, inv_scale_f32 |
No per-query recomputation |
| Rayon parallel | par_iter_mut over bodies with --features parallel |
Linear speedup with cores |
| 4-eval combined | Tetrahedral gradient gives distance + normal from 4 evals | 1 eval saved vs naive 1+4 |
Usage
use *;
use SdfCollider;
use CompiledSdfField;
use *;
// 1. Create SDF shape in ALICE-SDF
let terrain = plane // ground plane
.union; // hill
let field = new;
// 2. Create physics world
let mut world = new;
// 3. Register SDF as static collider
let collider = new_static;
world.add_sdf_collider;
// 4. Add dynamic bodies — they will collide with the SDF surface
let ball = new_dynamic;
world.add_body;
// 5. Simulate — SDF collisions resolved automatically in step()
let dt = from_ratio;
for _ in 0..300
SdfCollider API
| Method | Description |
|---|---|
SdfCollider::new_static(field, position, rotation) |
Static SDF collider |
SdfCollider::new_dynamic(field, position, rotation, body_index) |
Attached to a body |
.with_scale(scale) |
Set uniform scale (updates cached invariants) |
.update_cache() |
Recompute cached inv_rotation, scale_f32 after manual changes |
collide_point_sdf(point, sdf) |
Point vs SDF contact test |
collide_sphere_sdf(center, radius, sdf) |
Sphere vs SDF contact test |
Requirements
Enable the physics feature in ALICE-SDF:
[]
= { = "../ALICE-SDF", = ["physics"] }
See the ALICE-SDF README for CompiledSdfField details.
Rendering Pipeline Integration (ALICE-SDF v1.4.0+)
ALICE-Physics provides physics state data that drives ALICE-SDF's rendering pipeline destruction uniforms. The physics engine simulates thermal, fracture, erosion, and pressure fields — the application layer samples these fields and uploads them as shader uniforms for real-time visual feedback.
Architecture
ALICE-Physics (CPU) ALICE-SDF Shader (GPU)
┌─────────────────────┐ ┌──────────────────────┐
│ ThermalModifier │──→ sample ──→│ uniform float uShatter│
│ FractureModifier │──→ sample ──→│ uniform float uEntropy│
│ PressureModifier │──→ sample ──→│ uniform float uImpact │
│ ErosionModifier │──→ sample ──→│ uniform vec2 uShake │
│ ForceField::Explosion│──→ sample ──→│ uniform float uMeteorY│
└─────────────────────┘ └──────────────────────┘
↓ Application layer bridges the gap (each frame)
Uniform Mapping
| Physics Source | Field / Method | Rendering Uniform | Description |
|---|---|---|---|
ThermalModifier |
temperature.sample(pos) |
uShatter |
Temperature above melt threshold → destruction intensity |
ThermalModifier |
melt_accumulator.sample(pos) |
uEntropy |
Cumulative material loss (0-1) |
FractureModifier |
stress_field.sample(pos) |
uShatter |
Stress-driven crack propagation |
PressureModifier |
pressure_field.sample(pos) |
uImpact |
Contact force deformation depth |
ForceField::Explosion |
center, radius |
uMeteorImpact, uImpactRing |
Explosion center and blast radius |
| Impact event | collision velocity | uShake |
Camera shake from impact force |
| Projectile body | body.position.y |
uMeteorY |
Falling object altitude |
Example: Physics-Driven Destruction
use ;
use RenderConfig;
// Physics side: thermal simulation
let mut thermal = new;
thermal.add_heat_source;
// Each frame:
thermal.step;
// Application bridge: sample physics → upload to shader
let shatter = thermal.melt_accumulator.sample.min;
let entropy = thermal.temperature.sample / 1000.0;
gl.uniform1f;
gl.uniform1f;
Relevant Modules
| Module | Description | Drives Uniform |
|---|---|---|
thermal.rs |
Heat diffusion, melt, thermal expansion, freeze | uShatter, uEntropy |
fracture.rs |
Stress-driven crack propagation (CSG subtraction) | uShatter |
pressure.rs |
Contact force → crush/bulge/dent deformation | uImpact |
erosion.rs |
Wind, water, chemical, ablation erosion | uEntropy |
sdf_destruction.rs |
Real-time CSG boolean destruction | uImpactRing |
force.rs |
Explosion force field (center, radius, falloff) | uMeteorImpact, uImpactRing |
sim_field.rs |
3D scalar/vector field with trilinear interpolation | All (infrastructure) |
RenderConfig Compatibility
Enable destruction: true in ALICE-SDF's RenderConfig to activate the shader-side destruction features:
let config = RenderConfig ;
Deterministic Neural Controller (ALICE-ML Integration)
ALICE-Physics integrates with ALICE-ML to provide bit-exact deterministic AI for game characters. By combining 1.58-bit ternary weights {-1, 0, +1} with 128-bit fixed-point arithmetic, neural inference reduces to pure addition/subtraction — the inference path is integer-only (Fix128 mat-vec, no IEEE 754 rounding, no platform-dependent behavior).
This is the "holy grail" for networked fighting games and action games: all clients compute identical AI behavior without synchronization.
How It Works
Ternary Weight {-1, 0, +1}:
+1 → Fix128 addition
-1 → Fix128 subtraction
0 → skip (free sparsity)
Result: Zero floating-point multiplication in the entire inference pipeline.
Ragdoll Controller Example
use *;
use ;
// 1. Quantize pre-trained weights to ternary
let = quantize_to_ternary;
let = quantize_to_ternary;
// 2. Convert to fixed-point (one-time)
let ftw1 = from_ternary_weight;
let ftw2 = from_ternary_weight;
// 3. Build deterministic network
let network = new;
// 4. Create ragdoll controller
let config = ControllerConfig ;
let mut controller = new;
// 5. In physics loop — deterministic across ALL clients
for frame in 0..3600
Neural Controller API
| Type | Description |
|---|---|
FixedTernaryWeight |
TernaryWeight wrapper with Fix128 scale |
DeterministicNetwork |
Multi-layer network (zero-allocation forward pass) |
RagdollController |
Body states → joint torques |
ControllerConfig |
max_torque, num_joints, num_bodies |
ControllerOutput |
Vec3Fix torque per joint |
Activation |
ReLU, HardTanh, TanhApprox, None |
| Function | Description |
|---|---|
fix128_ternary_matvec() |
Core kernel — pure add/sub, zero multiplication |
fix128_relu() |
max(0, x) via sign-bit comparison |
fix128_hard_tanh() |
clamp(x, -1, 1) for bounded output |
fix128_tanh_approx() |
Padé rational x(27+x²)/(27+9x²) |
fix128_leaky_relu() |
Leaky ReLU with Fix128 alpha |
Requirements
[]
= { = "../ALICE-Physics", = ["neural"] }
Configuration
// SolverConfig / PhysicsConfig
let config = PhysicsConfig ;
// Or use defaults
let config = default;
Performance Characteristics
Measured, not estimated: cargo bench --bench physics_bench (criterion, release
profile) on Apple M-series, 2026-09-15, alice-physics 1.2.0. Absolute numbers are
machine-dependent; the algorithmic column is what the implementation actually does.
| Operation | Algorithm | Measured |
|---|---|---|
| Fix128 add/sub | 128-bit add with carry | < 1 ns |
| Fix128 mul | 3 × 64×64→128 partial products | 1.1 ns |
| Fix128 div | u128 integer quotient + 64-step long division for the fraction | 141 ns |
| Fix128 sqrt | 96-step restoring digit recurrence (exact floor) | 193–354 ns across runs (1.1.0: 9,676 ns, Newton × 64 divisions) |
| Vec3Fix normalize | length via sqrt + 3 div | 618 ns (1.1.0: 10,390 ns) |
| CORDIC sin/cos / atan | 48 fixed iterations | ~1 µs |
| GJK intersection | max 64 iterations | — |
| EPA penetration | max 64 iterations | — |
| BVH build | Morton code sort, O(n log n) | — |
| BVH query / find_pairs | stackless traversal per leaf AABB, O(n log n) expected | 1.1.0 queried the root AABB → O(n²) |
| World step, 10 bodies × 60 steps (default config) | 398 µs (1.1.0: 5.11 ms) | |
| World step, 1000 overlapping spheres (10³ grid, default config: detection in each of 8 substeps) | thousand_overlapping_spheres_1_step |
first frame 65 ms (2 700 contacts, 57 k broad-phase candidates × 8); frames 2–10 as the bodies separate: 7.7 ms/frame |
External review of 1.1.0 (Linux x86_64) measured 1000 overlapping bodies at 432 ms/frame with frame-level detection; 1.2.0 detects in every substep (a correctness requirement, see CHANGELOG), so the dense first frame costs more and the steady state less. Re-run the bench on your target before quoting numbers.
MSRV Policy
Minimum Supported Rust Version: 1.85
ALICE-Physics follows a Serde-style MSRV policy:
- MSRV bumps within the 0.x line are treated as minor version bumps (
0.13.x → 0.14.0), never patch bumps - MSRV bumps within a stable 1.x line will also be treated as minor version bumps (
1.x → 1.(x+1)), never patch - The MSRV commitment covers the latest 3 stable Rust channels (N-2 policy) — at the time of a release, we support the current stable + previous 2
alice-physicsdoes not require a nightly toolchain- CI enforces the declared MSRV via a dedicated
msrvjob:cargo +1.85 checkon the default feature set, theno_stdbuild (rlib) and the core native feature set, resolved byresolver = "3"(MSRV-aware). 1.0.x–1.1.0 declared 1.70.0; that toolchain could not even parse the lockfile and theno_stdbuild neededcore::f32::abs(1.85), so the claim was corrected in 1.2.0 (minor bump per the policy above)
Scope of the MSRV guarantee — the library with the default feature set, no_std (--no-default-features, as rlib) and the core native features (std, simd, parallel, ffi, gpu-solver-bridge) builds on 1.85. Outside that scope:
| Component | Effective MSRV | Why |
|---|---|---|
neural / replay / analytics bridge features |
follows the sibling crate (alice-ml / alice-db / alice-analytics); 1.87 as of alice-db 0.2.0-beta.2 → alice-zip 0.3.0 |
sibling crates set their own MSRV |
| Tests / benches (dev-dependencies) | 1.85+ | criterion, serde_derive |
wasm feature |
stable channel recommended | wasm-bindgen moves fast |
Downstream crates can rely on alice-physics not raising its MSRV within a patch release, preserving their own MSRV window.
Building
Note on --all-features: alice-physics uses wasm and ffi as mutually exclusive features (they link wasm-bindgen and C ABI FFI respectively, which cannot coexist in a single binary). cargo build --all-features will fail with a compile_error! by design. Build with one or the other.
Recommended feature combinations:
| Target | Command |
|---|---|
| Native app / game engine host (Unity, UE5, Godot) | cargo build --features "std,simd,parallel,ffi,gpu-solver-bridge" |
| Browser (WebGL / WebGPU via wasm-bindgen) | cargo build --features "std,simd,parallel,wasm,gpu-solver-bridge" |
| Embedded / no_std | as a dependency: default-features = false; standalone: cargo rustc --lib --no-default-features --crate-type rlib (the package also declares cdylib/staticlib for the C ABI, which need std) |
| Python bindings | cargo build --features "std,simd,parallel,python" |
docs.rs builds with the native feature set (see [package.metadata.docs.rs] in Cargo.toml).
# Standard build
# no_std library build (for embedded/WASM); downstream crates just set default-features = false
# C ABI artifacts for Unity / UE5 (target/release/libalice_physics.{so,dylib,a}, alice_physics.dll)
# Run tests
# Run all feature combinations
# Run benchmarks (requires nightly or criterion)
Cargo Features
| Feature | Default | Description |
|---|---|---|
std |
Yes | Standard library support |
simd |
No | *_simd / dot_batch_4 API surface + SIMD_WIDTH. Scalar-equivalent as of 1.2.0: SSE2/AVX2 have no 128-bit multiply and cannot carry lo→hi, so no intrinsic path is faster than the scalar ADC chain; kept for a future AVX-512 / NEON batch path |
parallel |
No | Constraint batching with Rayon (graph-colored parallel solving) |
neural |
No | Deterministic neural controller via ALICE-ML ternary inference |
python |
No | Python bindings (PyO3 + NumPy zero-copy) |
replay |
No | Replay recording/playback via ALICE-DB |
ffi |
No | C FFI for Unity, Unreal Engine, and other game engines |
wasm |
No | WebAssembly bindings via wasm-bindgen |
analytics |
No | Simulation profiling via ALICE-Analytics |
Note:
wasmandffiare mutually exclusive — enabling both causes a compile error.
# Enable SIMD optimizations
# Enable parallel constraint solving
# Enable both
# Enable neural controller (requires ALICE-ML)
# Build C shared library for game engines
Tested Feature Combinations
All feature combinations are tested in CI across macOS, Ubuntu, and Windows:
| Combination | Status | Tests |
|---|---|---|
--no-default-features (no_std) |
✅ | 9 |
--features std (default) |
✅ | 1695 unit + 72 integration + 13 analytic + 105 engineering + 13 default-config oracles + 44 determinism + 21 doc |
--features simd |
✅ | 20 |
--features parallel |
✅ | 20 |
--features "simd,parallel" |
✅ | 20 |
--features ffi |
✅ | build + cdylib/staticlib artifact check |
--features python |
✅ | 1 |
--features replay |
✅ | build only |
--features analytics |
✅ | build only |
--features neural |
✅ | build only |
--features wasm |
✅ | build only |
Feature compatibility matrix:
| std | simd | parallel | neural | python | ffi | wasm | replay | analytics | |
|---|---|---|---|---|---|---|---|---|---|
| std | - | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| simd | ✅ | - | ✅ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ |
| parallel | ✅ | ✅ | - | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ |
| wasm | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | - | ❌ | ❌ |
Game Engine Integration (C FFI / Unity / UE5)
ALICE-Physics provides a C FFI layer for integration with Unity, Unreal Engine, and any language that can call C functions.
Building the Shared Library
# macOS (.dylib)
# Linux (.so)
# Windows (.dll)
The output library is in target/release/ (libalice_physics.dylib, libalice_physics.so, or alice_physics.dll).
C API
The C header is at include/alice_physics.h. All types use f64 at the FFI boundary and convert to Fix128 internally.
// Create world
AlicePhysicsWorld* world = ;
// Add bodies
AliceVec3 pos = ;
uint32_t body = ;
// Step simulation
;
// Read back position
AliceVec3 out_pos;
;
// State serialization (rollback netcode)
uint32_t len;
uint8_t* state = ;
;
;
// Cleanup
;
Unity C# Bindings
Copy bindings/AlicePhysics.cs and the native library to your Unity project:
Assets/
Plugins/
macOS/ libalice_physics.dylib
Win64/ alice_physics.dll
Linux/ libalice_physics.so
Scripts/
AlicePhysics.cs
using AlicePhysics;
var world = new AlicePhysicsWorld();
uint body = world.AddDynamicBody(new Vector3(0, 10, 0), 1.0);
world.Step(1.0 / 60.0);
Vector3 pos = world.GetBodyPosition(body);
// Rollback netcode
byte[] state = world.SerializeState();
world.DeserializeState(state);
world.Dispose();
Unreal Engine 5 Plugin
Copy the unreal-plugin/ contents to Plugins/AlicePhysics/ in your UE5 project and place the native library in ThirdParty/AlicePhysics/lib/<Platform>/.
The plugin provides UAlicePhysicsWorldComponent with full Blueprint support:
AddDynamicBody,AddStaticBody— body creationGetBodyPosition,GetBodyRotation,GetBodyVelocity— state queriesApplyImpulse,ApplyImpulseAt— force applicationSerializeState,DeserializeState— rollback netcode- Automatic coordinate system conversion (UE5 Z-up cm → ALICE Y-up m)
Release Workflow
Tag a version to trigger automatic cross-platform builds:
GitHub Actions builds for macOS (ARM + Intel), Windows, and Linux, then packages:
- UE5 Plugin ZIP — includes native library + plugin source + header
- Unity Package ZIP — includes native library + C# bindings + header
Comparison with Floating-Point Engines
| Aspect | ALICE-Physics | Float Engines |
|---|---|---|
| Determinism | Guaranteed | Platform-dependent |
| Precision | 64-bit fraction | 23-bit (f32) / 52-bit (f64) |
| Speed | Slower (2-5x) | Faster |
| Rollback | Trivial | Requires care |
| Embedded | no_std | Requires FPU |
| Range | ±9.2×10^18 | ±3.4×10^38 (f32) |
Deterministic Netcode
ALICE-Physics includes a frame-based deterministic netcode foundation. Because the engine guarantees bit-exact results, only player inputs need to be synchronized — state sync is unnecessary.
Bandwidth Savings
| Approach | Per-Frame (10 bodies, 2 players) |
|---|---|
| State sync (traditional) | ~1,600 bytes |
| Input sync (ALICE) | ~40 bytes |
| Savings | 97.5% |
Core Types
| Type | Description |
|---|---|
FrameInput |
20-byte serializable player input (movement, actions, aim) |
SimulationChecksum |
XOR rolling hash of physics state (WyHash-style avalanche) |
SimulationSnapshot |
Full state capture for rollback |
DeterministicSimulation |
PhysicsWorld wrapper with frame counter, checksum history, snapshot ring buffer |
InputApplicator |
Trait for game-specific input → physics force mapping |
Usage
use *;
// Both clients create identical simulation
let mut sim = new;
// Add bodies and assign to players
let body0 = sim.add_body;
sim.assign_player_body;
// Each frame: collect inputs, advance, compare checksums
let inputs = vec!;
let checksum = sim.advance_frame;
// Save snapshot for rollback
sim.save_snapshot;
// Verify remote client's checksum
assert_eq!;
ALICE-Sync Integration (Game Engine Pipeline)
ALICE-Physics integrates with ALICE-Sync for complete multiplayer game networking. Enable physics feature in ALICE-Sync:
[]
= { = "../ALICE-Sync", = ["physics"] }
How It Works
Player Input ──► InputFrame (i16, 24B) ──► FrameInput (Fix128) ──► PhysicsWorld
ALICE-Sync bridge step()
│
PhysicsWorld ──► SimulationChecksum ──► WorldHash ──► Desync Verify
from_world() bridge ALICE-Sync
ALICE-Sync's PhysicsRollbackSession wraps both RollbackSession (input sync) and DeterministicSimulation (physics) into a single game loop driver:
- Submit local input → predict remote inputs
- Convert InputFrame (i16) → FrameInput (Fix128)
- Save snapshot → step physics → record checksum
- On mismatch: auto rollback + re-simulate
Bandwidth
| Approach | Per-Frame (4 players, 60fps) |
|---|---|
| State sync | ~960 KB/s |
| Input sync (ALICE) | 5.6 KB/s |
| Savings | 99.4% |
See ALICE-Sync README for full API.
Python Bindings (PyO3 + NumPy Zero-Copy)
Install with:
Optimization Layers
| Layer | Technique | Effect |
|---|---|---|
| L1 | GIL Release (py.allow_threads) |
Parallel physics stepping |
| L2 | Zero-Copy NumPy (into_pyarray_bound) |
No memcpy for bulk positions/velocities |
| L3 | Batch API (step_n, positions, states) |
FFI amortization |
| L4 | Batch Mutation (add_bodies_batch, set_velocities_batch, apply_impulses_batch) |
Bulk operations with GIL release |
| L5 | Rust backend (Fix128, XPBD, BVH) | Hardware-speed simulation |
Python API
# Basic physics world
=
=
=
# Step with GIL release (other Python threads can run)
# Batch step for training loops
# Get all positions as NumPy (N, 3) float64 array (zero-copy)
= # shape: (N, 3)
= # shape: (N, 3)
# Deterministic netcode simulation
=
=
# Advance with player inputs: (player_id, move_x, move_y, move_z, actions)
=
# Snapshot for rollback
=
# Serialization
= # NumPy uint8 array
# Frame input encoding (20 bytes, network-ready)
=
, , , , , , , =
# === Batch APIs (v0.4.0) ===
# Batch body creation from (N,4) array [x, y, z, mass]
=
# Batch velocity update (N,3) with GIL release
# Batch impulse (M,4) [body_id, ix, iy, iz] with GIL release
# Combined state output (N,10) [px,py,pz, vx,vy,vz, qx,qy,qz,qw]
= # shape: (N, 10), zero-copy NumPy
Replay Recording (ALICE-DB Integration)
ALICE-Physics can record and replay simulation trajectories via ALICE-DB. Enable with --features replay.
[]
= { = "../ALICE-Physics", = ["replay"] }
Recording
use ReplayRecorder;
// Create recorder (path, body_count)
let mut recorder = new?;
// In game loop: record every frame
for _ in 0..300
recorder.flush?;
recorder.close?;
Playback
use ReplayPlayer;
let player = open?;
// Random access: get position at any frame
let pos = player.get_position?;
// Returns Option<(f32, f32, f32)>
// Range query: scan positions over frame range
let trajectory = player.scan_positions?;
// Returns Vec<(u64, f32, f32, f32)>
player.close?;
Storage Format
Each body stores 6 channels (pos_x/y/z, vel_x/y/z) in ALICE-DB. ALICE-DB's model-based compression automatically fits trajectories:
- Constant velocity → linear model (2 coefficients)
- Projectile motion → quadratic model (3 coefficients)
- Complex motion → Fourier model
Test Results
v0.4.0 Test Summary:
- 358 unit tests across 63 modules
- 62 integration tests (end-to-end physics scenarios)
- 12 doc tests (runnable examples)
- Total: 432 passing tests (435 with --features parallel)
- Clippy: 0 warnings
- CI: Format + Clippy + Test (macOS/Ubuntu/Windows)
- All feature combinations pass (default, parallel, simd, no_std)
Cross-Crate Bridges
ALICE-Physics connects to other ALICE ecosystem crates via feature-gated bridge modules:
| Bridge | Feature | Target Crate | Description |
|---|---|---|---|
| Physics Visualization | view |
ALICE-View | Real-time physics debug overlay rendering |
| GPU Physics Controller | trt |
ALICE-TRT | GPU ternary inference for physics control policies |
| Physics State Streaming | asp |
ALICE-Streaming-Protocol | Physics body state delta encoding as ASP D-packets |
db_bridge |
replay |
ALICE-DB | Physics state snapshot persistence (energy, bodies, contacts) |
analytics_bridge |
analytics |
ALICE-Analytics | Simulation profiling (step time, collision pairs, energy drift) |
Recent Performance Improvements
| Module | Change | Impact |
|---|---|---|
fluid.rs |
Buffer reuse in neighbor queries | ~99% allocation reduction in SPH simulation |
animation_blend.rs |
clone_from() replaces clone() |
Eliminates 60 allocs/sec during blend |
Cargo Profile
Standardized [profile.bench] added for consistent benchmarking across ALICE crates.
Complete API Reference
Core Types
| Module | Type / Function | Description |
|---|---|---|
math |
Fix128 |
128-bit fixed-point number (I64F64) |
math |
Vec3Fix |
3D vector with Fix128 components |
math |
QuatFix |
Quaternion for rotations |
math |
Mat3Fix |
3x3 matrix for inertia tensors |
math |
SIMD_WIDTH |
Compile-time SIMD lane count (AVX2=8, NEON=4, scalar=1) |
math |
simd_width() |
Returns SIMD width at compile time |
math |
select_fix128() |
Branchless conditional select |
math |
select_vec3() |
Branchless Vec3 conditional select |
Collision Detection
| Module | Type / Function | Description |
|---|---|---|
collider |
AABB |
Axis-Aligned Bounding Box |
collider |
Sphere |
Sphere collider |
collider |
Capsule |
Capsule (cylinder + hemispheres) |
collider |
ConvexHull |
Arbitrary convex polyhedron |
collider |
ScaledShape |
Uniform scale wrapper for any Support shape |
collider |
CollisionResult |
Contact point, normal, depth |
collider |
Support trait |
GJK support function interface |
box_collider |
OrientedBox |
OBB with center, half-extents, rotation |
compound |
CompoundShape |
Multi-shape compound collider |
compound |
ShapeRef |
Shape reference within compound |
cylinder |
Cylinder |
Cylinder collider with GJK support |
filter |
CollisionFilter |
Layer/mask bitmask collision groups |
Solver & Dynamics
| Module | Type / Function | Description |
|---|---|---|
solver |
PhysicsWorld |
Main simulation world |
solver |
PhysicsConfig |
Substeps, iterations, gravity, damping |
solver |
RigidBody |
Dynamic/static/sensor rigid body |
solver |
BodyType |
Dynamic, Static, Kinematic |
solver |
DistanceConstraint |
Fixed distance between anchor points |
solver |
ContactConstraint |
Collision response with friction/restitution |
solver |
ContactModifier |
Trait for custom contact modification (std) |
joint |
BallJoint |
Spherical joint (3 rotational DOF) |
joint |
HingeJoint |
Revolute joint with angle limits |
joint |
FixedJoint |
Weld joint (0 DOF) |
joint |
SliderJoint |
Prismatic joint with limits |
joint |
SpringJoint |
Damped spring constraint |
joint |
D6Joint |
6-DOF configurable joint |
joint |
ConeTwistJoint |
Cone swing + twist limit joint |
joint |
solve_joints_breakable() |
Solve with break-force support |
motor |
PdController |
1D proportional-derivative controller |
motor |
JointMotor |
Joint motor (position/velocity/torque modes) |
force |
ForceField |
Wind, gravity well, drag, buoyancy, vortex |
force |
ForceFieldInstance |
Active force field in simulation |
material |
MaterialTable |
Per-pair friction/restitution override |
material |
PhysicsMaterial |
Material properties |
material |
CombineRule |
Average, Min, Max, Multiply |
Spatial Acceleration
| Module | Type / Function | Description |
|---|---|---|
bvh |
LinearBvh |
Flat array BVH with stackless traversal |
bvh |
BvhNode |
32-byte cache-aligned node |
bvh |
BvhPrimitive |
Primitive entry for BVH construction |
dynamic_bvh |
DynamicAabbTree |
Incremental BVH with O(log n) insert/remove |
spatial |
SpatialGrid |
Hash grid for neighbor queries |
Queries
| Module | Type / Function | Description |
|---|---|---|
raycast |
Ray |
Ray origin + direction |
raycast |
RayHit |
Hit result (t, normal, index) |
raycast |
ray_sphere(), ray_aabb(), ray_capsule(), ray_plane() |
Shape-specific ray tests |
raycast |
raycast_all_spheres(), raycast_all_aabbs() |
Batch raycasts |
query |
sphere_cast() |
Sweep sphere along direction |
query |
capsule_cast() |
Sweep capsule along direction |
query |
overlap_sphere() |
Find bodies in sphere |
query |
overlap_aabb() |
Find bodies in AABB |
query |
batch_raycast(), batch_sphere_cast() |
Batch queries |
ccd |
sphere_sphere_toi() |
Time of impact (sphere-sphere) |
ccd |
conservative_advancement() |
Iterative safe stepping TOI |
ccd |
speculative_contact() |
Speculative CCD contacts |
Soft Body & Simulation
| Module | Type / Function | Description |
|---|---|---|
rope |
Rope |
XPBD distance-chain rope |
rope |
RopeConfig |
Segment count, stiffness, damping |
cloth |
Cloth |
XPBD triangle mesh cloth |
cloth |
ClothConfig |
Stiffness, self-collision, gravity |
fluid |
Fluid |
Position-Based Fluids (PBF) |
fluid |
FluidConfig |
Rest density, viscosity, kernel radius |
deformable |
DeformableBody |
FEM tetrahedral mesh |
deformable |
DeformableConfig |
Young's modulus, Poisson's ratio |
vehicle |
Vehicle |
Vehicle simulation |
vehicle |
VehicleConfig |
Wheels, suspension, engine, steering |
character |
CharacterController |
Kinematic capsule move-and-slide |
character |
CharacterConfig |
Radius, height, max slope, step height |
SDF Integration
| Module | Type / Function | Description |
|---|---|---|
sdf_collider |
SdfCollider |
SDF as collision shape |
sdf_collider |
SdfField trait |
Distance + normal evaluation interface |
sdf_collider |
ClosureSdf |
Closure-based SDF implementation |
sdf_manifold |
SdfManifold |
Multi-point contact from SDF surface |
sdf_manifold |
ManifoldConfig |
Contact point count, spread |
sdf_ccd |
SdfCcdConfig |
Sphere tracing CCD for SDF |
sdf_force |
SdfForceField |
SDF-driven force field |
sdf_force |
SdfForceType |
Attract, Repel, Contain, Flow |
sdf_destruction |
DestructibleSdf |
CSG boolean destruction (std) |
sdf_destruction |
DestructionShape |
Sphere/box subtraction shape |
sdf_adaptive |
AdaptiveSdfEvaluator |
Distance-based LOD evaluation (std) |
convex_decompose |
DecomposeConfig |
Voxel grid decomposition settings (std) |
gpu_sdf |
GpuSdfBatch |
GPU compute SDF batch (std) |
gpu_sdf |
GpuSdfInstancedBatch |
Instanced GPU SDF batch |
gpu_sdf |
GpuSdfMultiDispatch |
Multi-batch GPU dispatch |
SDF Simulation Modifiers
| Module | Type / Function | Description |
|---|---|---|
sim_field |
ScalarField3D |
3D scalar field with trilinear interpolation (std) |
sim_field |
VectorField3D |
3D vector field with trilinear interpolation (std) |
sim_modifier |
PhysicsModifier trait |
SDF modifier interface (std) |
sim_modifier |
ModifiedSdf |
Modifier chain (std) |
thermal |
ThermalModifier |
Heat diffusion, melt, freeze (std) |
thermal |
ThermalConfig |
Conductivity, melt/freeze thresholds |
pressure |
PressureModifier |
Contact-force deformation (std) |
pressure |
PressureConfig |
Yield threshold, spring-back |
erosion |
ErosionModifier |
Wind/water/chemical erosion (std) |
erosion |
ErosionType |
Wind, Water, Chemical, Ablation |
fracture |
FractureModifier |
Stress-driven crack propagation (std) |
fracture |
FractureConfig |
Toughness, crack speed |
phase_change |
PhaseChangeModifier |
Solid/liquid/gas transitions (std) |
phase_change |
Phase |
Solid, Liquid, Gas |
Game Systems
| Module | Type / Function | Description |
|---|---|---|
animation_blend |
AnimationBlender |
Ragdoll-to-animation blending |
animation_blend |
BlendMode |
Lerp, Slerp, Additive |
animation_blend |
SkeletonPose |
Joint transforms for skeleton |
audio_physics |
AudioGenerator |
Physics-based audio parameters |
audio_physics |
AudioEvent |
Impact, friction, rolling events |
audio_physics |
AudioMaterial |
Surface material with audio properties |
netcode |
DeterministicSimulation |
PhysicsWorld + frame counter + checksum |
netcode |
FrameInput |
20-byte serializable player input |
netcode |
SimulationChecksum |
XOR rolling hash of physics state |
netcode |
SimulationSnapshot |
Full state capture for rollback |
netcode |
InputApplicator trait |
Game-specific input → force mapping |
fluid_netcode |
FluidSnapshot |
Deterministic fluid state (std) |
fluid_netcode |
FluidDelta |
Delta-compressed fluid update (std) |
Analytics & Privacy
| Module | Type / Function | Description |
|---|---|---|
sketch |
HyperLogLog |
Cardinality estimation (std) |
sketch |
DDSketch |
Quantile sketch (P50/P99/P99.9) (std) |
sketch |
CountMinSketch |
Frequency estimation (std) |
sketch |
HeavyHitters |
Top-k frequent items (std) |
sketch |
FnvHasher |
FNV-1a deterministic hasher (std) |
sketch |
Mergeable trait |
Distributed sketch merging (std) |
anomaly |
MadDetector |
Median Absolute Deviation (std) |
anomaly |
EwmaDetector |
Exponentially Weighted Moving Average (std) |
anomaly |
ZScoreDetector |
Standard Z-score detector (std) |
anomaly |
CompositeDetector |
Multi-detector voting (std) |
anomaly |
StreamingMedian |
O(log n) streaming median (std) |
privacy |
LaplaceNoise |
Calibrated Laplace mechanism (std) |
privacy |
Rappor |
RAPPOR protocol for categorical data (std) |
privacy |
RandomizedResponse |
Binary randomized response (std) |
privacy |
PrivacyBudget |
Epsilon budget tracker (std) |
privacy |
PrivateAggregator |
Privacy-preserving aggregation (std) |
privacy |
XorShift64 |
Deterministic PRNG (std) |
pipeline |
MetricPipeline |
Lock-free ring buffer aggregation (std) |
pipeline |
MetricRegistry |
Named metric registration (std) |
pipeline |
MetricEvent |
Timestamped metric event (std) |
pipeline |
MetricType |
Counter, Gauge, Histogram (std) |
pipeline |
RingBuffer |
Fixed-capacity circular buffer (std) |
Utility
| Module | Type / Function | Description |
|---|---|---|
rng |
DeterministicRng |
PCG-XSH-RR 32-bit generator |
event |
EventCollector |
Contact begin/persist/end tracking |
event |
ContactEvent |
Body pair + event type + contact point |
sleeping |
IslandManager |
Union-Find island management |
sleeping |
SleepConfig |
Velocity thresholds, idle frame count |
trimesh |
TriMesh |
BVH-accelerated triangle mesh |
trimesh |
Triangle |
Single triangle (Moller-Trumbore) |
heightfield |
HeightField |
Grid terrain with bilinear interpolation |
articulation |
ArticulatedBody |
Multi-joint chain with FK propagation |
articulation |
FeatherstoneSolver |
O(n) forward dynamics |
contact_cache |
ContactCache |
HashMap O(1) manifold lookup |
contact_cache |
ContactManifold |
Up to 4 contact points |
interpolation |
WorldSnapshot |
Physics state for interpolation |
debug_render |
DebugDrawData |
Wireframe visualization |
debug_render |
DebugDrawFlags |
Bitmask for what to draw |
profiling |
PhysicsProfiler |
Per-stage timing |
profiling |
StepStats |
Broadphase/narrowphase/solver times |
error |
PhysicsError |
Typed physics error enum |
Feature-Gated Modules
| Module | Feature | Description |
|---|---|---|
neural |
neural |
Deterministic ternary neural controller (ALICE-ML) |
python |
python |
PyO3 + NumPy zero-copy Python bindings |
ffi |
ffi |
C FFI for Unity/UE5 game engines |
wasm |
wasm |
WebAssembly bindings (wasm-bindgen) |
replay |
replay |
Replay recording/playback via ALICE-DB |
db_bridge |
replay |
Physics state persistence bridge |
analytics_bridge |
analytics |
Simulation profiling bridge (ALICE-Analytics) |
Python API (PyO3)
| Class / Function | Description |
|---|---|
PhysicsWorld |
Python wrapper for physics simulation |
PhysicsWorld.add_dynamic_body(x, y, z, mass) |
Add dynamic body |
PhysicsWorld.add_static_body(x, y, z) |
Add static body |
PhysicsWorld.step(dt) |
Step with GIL release |
PhysicsWorld.step_n(dt, steps) |
Batch step for training |
PhysicsWorld.positions() |
NumPy (N,3) zero-copy |
PhysicsWorld.velocities() |
NumPy (N,3) zero-copy |
PhysicsWorld.states() |
NumPy (N,10) combined state |
PhysicsWorld.add_bodies_batch(array) |
Batch body creation from (N,4) |
PhysicsWorld.set_velocities_batch(array) |
Batch velocity update (N,3) |
PhysicsWorld.apply_impulses_batch(array) |
Batch impulse (M,4) |
PhysicsWorld.serialize_state() |
State to NumPy uint8 |
PhysicsWorld.deserialize_state(data) |
Restore from bytes |
DeterministicSimulation |
Netcode simulation wrapper |
DeterministicSimulation.advance_frame(inputs) |
Advance with player inputs |
DeterministicSimulation.save_snapshot() |
Save for rollback |
DeterministicSimulation.load_snapshot(frame) |
Restore snapshot |
encode_frame_input(...) |
Encode 20-byte input |
decode_frame_input(data) |
Decode 20-byte input |
C FFI API
| Function | Description |
|---|---|
alice_physics_world_create() |
Create physics world |
alice_physics_world_destroy(world) |
Destroy physics world |
alice_physics_world_step(world, dt) |
Step simulation |
alice_physics_body_add_dynamic(world, pos, mass) |
Add dynamic body |
alice_physics_body_add_static(world, pos) |
Add static body |
alice_physics_body_get_position(world, id, out) |
Get body position |
alice_physics_body_apply_impulse(world, id, impulse) |
Apply impulse |
alice_physics_state_serialize(world, len) |
Serialize state |
alice_physics_state_deserialize(world, data, len) |
Deserialize state |
alice_physics_state_free(data, len) |
Free serialized buffer |
License
AGPL-3.0-or-later - See LICENSE for details.
AGPL is a strong copyleft: a game or application that links alice-physics
(including through the Unity / UE5 bindings) and is distributed or served to
users must be released under the AGPL as well. That is intentional for the open
ecosystem. For commercial use without the AGPL obligations, contact
sakamoro@alicelaw.net for a separate license.
Copyright (C) 2024-2026 Moroya Sakamoto
Acknowledgments
- XPBD: Müller et al., "XPBD: Position-Based Simulation of Compliant Constrained Dynamics"
- GJK/EPA: Ericson, "Real-Time Collision Detection"
- Morton Codes: Morton, "A Computer Oriented Geodetic Data Base"
- CORDIC: Volder, "The CORDIC Trigonometric Computing Technique"