Overview
Rigid bodies with contacts and joints, XPBD cloth and soft bodies, SPH and stable fluids, linear finite elements and heat conduction, orbital mechanics, SoA particle steppers, and typed units with CODATA 2018 constants. Built on riptide_math (vectors, GJK/EPA, inertia, broadphase), riptide_numerics_calculus (part B: ODE and symplectic integrators) and riptide_numerics_sparse (PCG with IC(0) for FEM).
Units are SI (metres, kilograms, seconds, radians) except orbital mechanics, which uses kilometres and seconds like Vallado's examples (Bodies.earthMu = 398600.4418 \frac{km^{3}}{s^{2}}).
What's in it
| Area | Files | Contents |
|---|---|---|
| Rigid bodies | rigid/ | RigidBody (dynamic, static, kinematic; mass from density; inertia in world frame); colliders: sphere, box, capsule, convex hull (mass properties by the divergence theorem), plane, compound (re-centred, parallel-axis theorem); PhysicsWorld |
| Broadphase | rigid/broadphase.ray | DynamicAabbTree (fat AABBs, surface-area insertion cost, AVL rotations) and sweep-and-prune over riptide_math's Broadphase |
| Narrowphase | rigid/narrowphase.ray | sphere–sphere, sphere–capsule, sphere–box, capsule–capsule (two points when parallel), shape–plane (all vertices), box–box (15-axis SAT, Sutherland–Hodgman clipping of the incident face, edge–edge closest points), everything else GJK + EPA from riptide_math; manifolds reduced to 4 points |
| Solver | rigid/contact.ray, rigid/joint.ray | sequential impulses with warm starting (points matched across steps), Coulomb friction (pyramid), restitution with a threshold, non-linear Gauss–Seidel position correction (no energy added); persistent manifolds for single-point generators; ball, distance, hinge and fixed joints (Baumgarte) |
| Rotation | rigid/world.ray | implicit-midpoint gyroscopic term (preserves kinetic energy and \|L\| exactly), exact quaternion integration, optional sleeping |
| Soft bodies | soft/xpbd.ray | XpbdBody (small-step XPBD: distance, tetrahedral volume, collision with rigid shapes by signed distance, friction), SoftBodies.cloth, SoftBodies.softBox |
| Fluids | fluid/ | SphFluid (Müller 2003 kernels, mirror-particle walls, float32 SoA buffers laid out for the GPU), NeighborGrid (public counting-sort grid for any particle code), StableFluid2 (Stam's method on a MAC grid, CG pressure: divergence-free to the solver tolerance) |
| FEM | fem/fem.ray | PlaneStressFem (CST triangles), TetFem (linear tetrahedra, Kuhn box meshes), Heat (1-D FTCS, backward Euler, Crank–Nicolson), HeatFem2 (P1 triangles, lumped mass, backward Euler) |
| Orbital | orbital/ | Kepler's equation (elliptic Halley, hyperbolic Newton), anomaly conversions, universal-variable propagation (safeguarded), RV2COE / COE2RV, vis-viva, escape and circular speed, Hohmann, Lambert (Izzo 2015), Earth–Moon CR3BP (Jacobi constant, L1–L5, part B's RK45) |
| Particles | particles/ | ParticleState (SoA position, velocity, mass, charge), ParticleStepper interface, SymplecticStepper / VelocityVerlet and RungeKutta4 over part B's integrators, SemiImplicitEuler |
| Units | units/ (package:riptide_physics/units.ray) | typed quantities as extension types (Length, Time, Mass, Speed, Force, Energy, … with only dimensionally valid operators), run-time Quantity / Dimension, Constants (CODATA 2018, IAU/IERS astronomical values) |
Accuracy and conservation (tests)
raya test (51 tests): elastic collisions conserve momentum and energy to 1e-9 and match the 1-D formulas; a torque-free tumbling box keeps \|L\| and energy to 1e-9 with L's direction within 0.7% over 25 s at 240 Hz; a 6-box stack rests 10 s within 3 cm; restitution bounces to e^{2} \cdot h; friction sticks at \mu = 0.6 on 20^{\circ} and slides at g(\sin\theta - \mu\cos\theta) at \mu = 0.1; joints hold to 1 cm; tree and sweep-and-prune broadphases give identical simulations. Cloth stays within 4% stretch; a soft box keeps its volume within 2%; cloth drapes on a sphere without penetrating. SPH interior density is within 5% of \rho_{0} after settling; the MAC projection leaves divergence below 1e-8 of the input. FEM: bar tension and tetrahedral cube exact to 1e-9, cantilever within 3% of Timoshenko, 1-D heat within 2e-4 of the analytic decay (FTCS and Crank–Nicolson; backward Euler first order), 2-D FEM heat within 3%. Orbital: Kepler round trips to 1e-13, Vallado Examples 2-4 (KEPLER), 2-5 (RV2COE) and 7-5 (Lambert) to their printed digits, 200 random Lambert transfers re-propagated to 1e-6, ISS and Molniya periods and closure, Earth–Moon L1–L5 to 2e-4 against Koon, Lo, Marsden and Ross, Jacobi constant to 1e-9.
Stability limits
- Rigid bodies: 60 Hz with 10 velocity and 4 position iterations holds the tested 6-box stack; taller stacks need more iterations or substeps (no islands or block solver yet). Box–box edge contacts and GJK/EPA give one point per step (manifolds fill over a few steps). No continuous collision detection yet: thin, fast objects can tunnel.
- SPH (weakly compressible):
stableDtgives the CFL and viscous limits; Müller's scheme needs real viscosity to stay calm (the tests use \mu = 20 Pa \cdot s); low-viscosity water wants PCISPH/DFSPH (not here yet). - XPBD: stiffness depends on substeps (small steps converge better); one-way coupling with rigid bodies.
- Stable fluids are 2-D only.
Functions and constants
Functions
(Vec3d, Vec3d) lambert(Vec3d r1, Vec3d r2, double tof, {double mu = Bodies.earthMu, bool prograde = true})Lambert's problem: the conic from r1 to r2 in time tof (zero revolutions), by Izzo's method ("Revisiting Lambert's problem", Celest. Mech. Dyn. Astron. 121, 2015), written from the paper: the Lancaster–Blanchard variable x with \lambda, the non-dimensional time of flight T(x), Householder iterations (third order) from Izzo's initial guesses, Battin's hypergeometric series near the parabola. Returns the velocities at both ends.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
// From 7000 km to a point 90° on at 10000 km in 1 hour (Earth).
final r1 = const Vec3d(7000, 0, 0), r2 = const Vec3d(0, 10000, 0);
final (v1, v2) = lambert(r1, r2, 3600);
print('depart ${d3(v1)} km/s, arrive ${d3(v2)} km/s');
final pts = <List<double>>[];
for (var i = 0; i <= 40; i++) {
final (p, _) = Kepler.propagate(r1, v1, 3600 * i / 40);
pts.add([p.x, p.y]);
}
}depart (4.2977, 6.4576, 0.0000) km/s, arrive (-4.5203, -2.3604, 0.0000) km/s
List<(int, int)> sweepAndPrunePairs(List<Aabb> boxes)Candidate pairs from sweep and prune (riptide_math's Broadphase.sweepAndPrune) over double boxes.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final boxes = [for (final x in [0.0, 1.5, 4.0, 4.5]) Aabb(Vec3d(x, 0, 0), Vec3d(x + 2, 1, 1))];
print(sweepAndPrunePairs(boxes));
}[(0, 1), (2, 3)]
ContactSet? collide(Collider a, Vec3d pa, Quatd qa, Collider b, Vec3d pb, Quatd qb, {double margin = 0})Collides shape a at pose (pa, qa) with b at (pb, qb). Returns null when separated by more than margin. Fast analytic paths for sphere, capsule, box and plane pairs; everything else through GJK + EPA.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final s = const SphereCollider(1), b = const BoxCollider(Vec3d(1, 1, 1));
final c = collide(s, const Vec3d(0, 1.8, 0), Quatd.identity, b, Vec3d.zero, Quatd.identity)!;
print('normal ${d3(c.normal)}, ${c.points.length} point(s), depth ${f(c.points.first.depth)}');
print('apart: ${collide(s, const Vec3d(0, 3, 0), Quatd.identity, b, Vec3d.zero, Quatd.identity)}');
}normal (0.0000, -1.0000, 0.0000), 1 point(s), depth 0.2000 apart: null
(Vec3d, Vec3d) closestSegmentSegment(Vec3d p1, Vec3d q1, Vec3d p2, Vec3d q2)Closest points between segments p1–q1 and p2–q2 (Ericson, Real-Time Collision Detection 5.1.9).
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final (a, b) = closestSegmentSegment(const Vec3d(0, 0, 0), const Vec3d(4, 0, 0), const Vec3d(1, 2, 0), const Vec3d(3, 1, 0));
print('closest ${d3(a)} and ${d3(b)}');
}closest (3.0000, 0.0000, 0.0000) and (3.0000, 1.0000, 0.0000)
ContactSet? boxBox(BoxCollider ba, Vec3d pa, Quatd qa, BoxCollider bb, Vec3d pb, Quatd qb, {double margin = 0})Box–box contact manifold: separating-axis test over the 15 axes, then for a face axis the incident face is clipped against the reference face's side planes (Sutherland–Hodgman), as in Box2D Lite and Bullet's box-box. Edge–edge contacts give one point (closest points of the two edges) and set complete: false.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final b = const BoxCollider(Vec3d(1, 1, 1));
final q = Quatd.axisAngle(Vec3d.unitZ, math.pi / 4);
final c = boxBox(b, Vec3d.zero, Quatd.identity, b, const Vec3d(0, 2.2, 0), q)!;
print('normal ${d3(c.normal)}, ${c.points.length} contact(s), deepest ${f(c.points.map((p) => p.depth).reduce(math.max))}');
}normal (0.0000, 1.0000, 0.0000), 4 contact(s), deepest 0.2142
({double distance, Vec3d normal})? signedDistance(RigidBody body, Vec3d p)Signed distance from p to a body's shape, with the outward normal (null for shapes without an analytic SDF: hulls and compounds' hull children are skipped).
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final body = RigidBody.static(const BoxCollider(Vec3d(1, 1, 1)));
for (final p in [const Vec3d(3, 0, 0), const Vec3d(0.5, 0, 0)]) {
final d = signedDistance(body, p);
print('${d3(p)}: ${d == null ? 'n/a' : '${f(d.distance)} along ${d3(d.normal)}'}');
}
}(3.0000, 0.0000, 0.0000): 2.0000 along (1.0000, 0.0000, 0.0000) (0.5000, 0.0000, 0.0000): -0.5000 along (1.0000, 0.0000, 0.0000)
int solveSpd(CsrMatrix a, Float64List b, Float64List x, {double tolerance = 1e-12})Solves the symmetric positive-definite system a x = b by PCG with IC(0) (riptide_numerics_sparse), starting from and writing into x. Returns the iterations.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray' show CsrMatrix;
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final s = SparseBuilder(3);
for (var i = 0; i < 3; i++) {
s.add(i, i, 2);
if (i > 0) s.add(i, i - 1, -1);
if (i < 2) s.add(i, i + 1, -1);
}
final x = Float64List(3);
final it = solveSpd(s.build(), Float64List.fromList([1, 1, 1]), x);
print('x = $x in $it CG iterations');
}x = [1.4999999999999996, 2.0, 1.4999999999999998] in 1 CG iterations
Float64List solveTridiagonal(Float64List a, Float64List b, Float64List c, Float64List d)Solves a tridiagonal system (sub a, diagonal b, super c, right side d) by the Thomas algorithm.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final x = solveTridiagonal(Float64List.fromList([0, -1, -1]), Float64List.fromList([2, 2, 2]), Float64List.fromList([-1, -1, 0]), Float64List.fromList([1, 0, 1]));
print(x);
}[0.9999999999999999, 0.9999999999999998, 0.9999999999999999]
Typedefs
typedef FemSolution = ({Float64List displacement, int iterations})Result of a static solve: nodal displacements (interleaved per dimension) and PCG iterations.
typedef ForceField = void Function(ParticleState state, double t, Float64List forceOut)Writes the force on every particle (N, interleaved xyz) for the current positions and velocities at time t.
typedef MassProperties = ({double mass, Vec3d center, Mat3d inertia})Mass, centre of mass (body frame) and inertia about the centre of mass (body frame).
typedef CompoundChild = ({Collider shape, Vec3d offset, Quatd rotation})One child of a CompoundCollider: a shape at a local offset and rotation.
typedef ContactPoint = ({Vec3d point, double depth})One contact point: point is the midpoint between the two surfaces, depth the penetration (> 0 overlapping).
typedef ContactSet = ({Vec3d normal, List<ContactPoint> points, bool complete})The contacts between two shapes: normal points from shape A to shape B (moving B along it separates them). complete is false when the generator returns one point of a face contact (the GJK/EPA path, edge–edge box contacts); the world then keeps points from previous steps to build a stable manifold.
Classes
ElasticMaterial
final class ElasticMaterial
Isotropic linear-elastic material.
Constructors
const ElasticMaterial({required this.youngs, required this.poisson})import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
const steel = ElasticMaterial(youngs: 200e9, poisson: 0.3);
print('Lamé λ = ${steel.lambda.toStringAsExponential(3)}, μ = ${steel.mu.toStringAsExponential(3)} Pa');
}Lamé λ = 1.154e+11, μ = 7.692e+10 Pa
Properties
double get muPlaneStressFem
final class PlaneStressFem
2-D linear elasticity in plane stress on constant-strain triangles (CST, the P1 element): K = \sum t A B^{T} D B assembled into CSR, Dirichlet conditions by elimination, PCG with IC(0) (riptide_numerics_sparse). Nodes are (x, y) pairs in nodes; triangles index triples.
Constructors
PlaneStressFem(this.nodes, this.triangles, this.material, {this.thickness = 1})import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
// A 4 × 1 cantilever, clamped at x = 0, pulled down at the far end.
final mesh = PlaneStressFem.crossedRectangle(8, 2, 4, 1);
final fem = PlaneStressFem(mesh.nodes, mesh.triangles, const ElasticMaterial(youngs: 1000, poisson: 0.3));
final n = mesh.nodes.length ~/ 2;
final forces = Float64List(2 * n);
final fixed = <int, double>{};
for (var i = 0; i < n; i++) {
if (mesh.nodes[2 * i] == 0) {
fixed[2 * i] = 0;
fixed[2 * i + 1] = 0;
}
if (mesh.nodes[2 * i] == 4 && mesh.nodes[2 * i + 1] == 0.5) forces[2 * i + 1] = -1;
}
final sol = fem.solve(forces, fixed);
final u = sol.displacement;
var tip = 0.0;
for (var i = 0; i < n; i++) {
tip = math.min(tip, u[2 * i + 1]);
}
print('tip deflection ${f(tip)} after ${sol.iterations} CG iterations');
}tip deflection -0.2255 after 36 CG iterations
Static
static ({Float64List nodes, Int32List triangles}) crossedRectangle(int nx, int ny, double w, double h)A structured nx × ny mesh of a w × h rectangle, each cell split into 4 triangles around its centre (the "crossed" pattern, which bends much better than 2-triangle cells). Node (i, j) of the corner grid is j \cdot (nx + 1) + i; centre nodes follow.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final m = PlaneStressFem.crossedRectangle(3, 2, 3, 2);
print('${m.nodes.length ~/ 2} nodes, ${m.triangles.length ~/ 3} triangles');
}18 nodes, 24 triangles
Properties
final Float64List nodesfinal Int32List trianglesfinal ElasticMaterial materialfinal double thicknessint get nodeCountMethods
FemSolution solve(Float64List forces, Map<int, double> fixed, {double tolerance = 1e-12})Solves K u = f with nodal forces (fx, fy per node) and fixed dofs (2 \cdot \mathrm{node} + component → value).
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
// A 4 × 1 cantilever, clamped at x = 0, pulled down at the far end.
final mesh = PlaneStressFem.crossedRectangle(8, 2, 4, 1);
final fem = PlaneStressFem(mesh.nodes, mesh.triangles, const ElasticMaterial(youngs: 1000, poisson: 0.3));
final n = mesh.nodes.length ~/ 2;
final forces = Float64List(2 * n);
final fixed = <int, double>{};
for (var i = 0; i < n; i++) {
if (mesh.nodes[2 * i] == 0) {
fixed[2 * i] = 0;
fixed[2 * i + 1] = 0;
}
if (mesh.nodes[2 * i] == 4 && mesh.nodes[2 * i + 1] == 0.5) forces[2 * i + 1] = -1;
}
final sol = fem.solve(forces, fixed);
print('${sol.iterations} iterations; displacement of node 0 ${sol.displacement[0]}');
}36 iterations; displacement of node 0 0.0
TetFem
final class TetFem
3-D linear elasticity on linear tetrahedra (constant strain): K = \sum V B^{T} D B.
Constructors
TetFem(this.nodes, this.tets, this.material)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final mesh = TetFem.box(4, 1, 1, 4, 1, 1);
final fem = TetFem(mesh.nodes, mesh.tets, const ElasticMaterial(youngs: 1000, poisson: 0.3));
final n = mesh.nodes.length ~/ 3;
final forces = Float64List(3 * n);
final fixed = <int, double>{};
for (var i = 0; i < n; i++) {
if (mesh.nodes[3 * i] == 0) {
for (var c = 0; c < 3; c++) {
fixed[3 * i + c] = 0;
}
}
if (mesh.nodes[3 * i] == 4) forces[3 * i + 1] = -0.25;
}
final sol = fem.solve(forces, fixed);
var tip = 0.0;
for (var i = 0; i < n; i++) {
tip = math.min(tip, sol.displacement[3 * i + 1]);
}
print('3-D cantilever tip deflection ${f(tip)}');
}3-D cantilever tip deflection -0.0664
Static
static ({Float64List nodes, Int32List tets}) box(int nx, int ny, int nz, double w, double h, double dz)A box nx×ny×nz cells of size w×h×dz, 6 tetrahedra per cell (Kuhn split, conforming).
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final m = TetFem.box(2, 1, 1, 2, 1, 1);
print('${m.nodes.length ~/ 3} nodes, ${m.tets.length ~/ 4} tetrahedra (6 per cell)');
}12 nodes, 12 tetrahedra (6 per cell)
Properties
final Float64List nodesfinal Int32List tetsfinal ElasticMaterial materialint get nodeCountMethods
FemSolution solve(Float64List forces, Map<int, double> fixed, {double tolerance = 1e-12})import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final mesh = TetFem.box(4, 1, 1, 4, 1, 1);
final fem = TetFem(mesh.nodes, mesh.tets, const ElasticMaterial(youngs: 1000, poisson: 0.3));
final n = mesh.nodes.length ~/ 3;
final forces = Float64List(3 * n);
final fixed = <int, double>{};
for (var i = 0; i < n; i++) {
if (mesh.nodes[3 * i] == 0) {
for (var c = 0; c < 3; c++) {
fixed[3 * i + c] = 0;
}
}
if (mesh.nodes[3 * i] == 4) forces[3 * i + 1] = -0.25;
}
print('CG iterations: ${fem.solve(forces, fixed).iterations}');
}CG iterations: 28
Heat
abstract final class Heat
Heat conduction u_{t} = \alpha \nabla^{2}u.
Static
static void explicitStep1d(Float64List u, double alpha, double dx, double dt)One explicit (FTCS) step on a 1-D rod with fixed ends; stable for r = \alpha dt/dx^{2} \le \tfrac{1}{2} (throws otherwise).
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
const n = 41;
final u = Float64List(n);
for (var i = 0; i < n; i++) {
u[i] = (i - 20).abs() < 4 ? 1 : 0; // a hot spot
}
final start = Float64List.fromList(u);
for (var k = 0; k < 200; k++) {
Heat.explicitStep1d(u, 1, 1 / 40, 0.0002);
}
print('peak ${f(u[20])} (from 1), total heat kept: ${f(u.reduce((a, b) => a + b) / start.reduce((a, b) => a + b))}');
}peak 0.2417 (from 1), total heat kept: 0.8362
static void implicitStep1d(Float64List u, double alpha, double dx, double dt, {double theta = 1})One \theta-method step on a 1-D rod with fixed ends: \theta = 1 backward Euler (L-stable), \theta = \tfrac{1}{2} Crank–Nicolson (second order). Unconditionally stable; a tridiagonal solve per step.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
const n = 41;
final u = Float64List(n);
for (var i = 0; i < n; i++) {
u[i] = (i - 20).abs() < 4 ? 1 : 0; // a hot spot
}
final start = Float64List.fromList(u);
for (var k = 0; k < 10; k++) {
Heat.implicitStep1d(u, 1, 1 / 40, 0.004); // 20× the explicit limit, still stable
}
print('peak ${f(u[20])}');
}peak 0.2502
HeatFem2
final class HeatFem2
Transient heat on a P1 triangle mesh: backward Euler (M + dt \alpha K) u^{n+1} = M u^{n} with the lumped mass matrix, Dirichlet nodes held at their values. The FEM counterpart of Heat for arbitrary 2-D shapes.
Constructors
HeatFem2(this.nodes, this.triangles, {required this.alpha})import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final mesh = HeatFem2.unitSquare(8);
final h = HeatFem2(mesh.nodes, mesh.triangles, alpha: 0.1);
final nn = mesh.nodes.length ~/ 2;
final u = Float64List.fromList([for (var i = 0; i < nn; i++) HeatFem2.exactMode(mesh.nodes[2 * i], mesh.nodes[2 * i + 1], 0, 0.1)]);
final fixed = <int, double>{for (var i = 0; i < nn; i++) if (mesh.nodes[2 * i] == 0 || mesh.nodes[2 * i] == 1 || mesh.nodes[2 * i + 1] == 0 || mesh.nodes[2 * i + 1] == 1) i: 0};
for (var k = 0; k < 10; k++) {
h.step(u, 0.05, fixed);
}
final centre = mesh.nodes.length ~/ 4;
print('centre value ${f(u[40])}, exact mode ${f(HeatFem2.exactMode(0.5, 0.5, 0.5, 0.1))}');
}centre value 0.3947, exact mode 0.3727
Static
static ({Float64List nodes, Int32List triangles}) unitSquare(int n)A structured n × n mesh of the unit square (2 triangles per cell).
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final m = HeatFem2.unitSquare(4);
print('${m.nodes.length ~/ 2} nodes, ${m.triangles.length ~/ 3} triangles');
}25 nodes, 32 triangles
static double exactMode(double x, double y, double t, double alpha)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
print([for (final t in [0.0, 0.5, 1.0]) f(HeatFem2.exactMode(0.5, 0.5, t, 0.1))]);
}[1.0000, 0.3727, 0.1389]
Properties
final Float64List nodesfinal Int32List trianglesfinal double alphaMethods
int step(Float64List u, double dt, Map<int, double> fixed)Advances u by dt, keeping fixed nodes at the given temperatures. Returns CG iterations.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final mesh = HeatFem2.unitSquare(8);
final h = HeatFem2(mesh.nodes, mesh.triangles, alpha: 0.1);
final nn = mesh.nodes.length ~/ 2;
final u = Float64List.fromList([for (var i = 0; i < nn; i++) HeatFem2.exactMode(mesh.nodes[2 * i], mesh.nodes[2 * i + 1], 0, 0.1)]);
final fixed = <int, double>{for (var i = 0; i < nn; i++) if (mesh.nodes[2 * i] == 0 || mesh.nodes[2 * i] == 1 || mesh.nodes[2 * i + 1] == 0 || mesh.nodes[2 * i + 1] == 1) i: 0};
final it = h.step(u, 0.05, fixed);
print('one implicit step: $it CG iterations');
}one implicit step: 7 CG iterations
NeighborGrid
final class NeighborGrid
Fixed-radius neighbour search on a dense uniform grid built by counting sort, the layout GPU SPH and particle codes use (Green, "Particle Simulation using CUDA", 2010; Hoetzlein, "Fast Fixed-Radius Nearest Neighbors", 2014):
cellOf[i]: the cell of particle i (cells arecellSizecubes overmin…min+ dims · cellSize; positions outside are clamped to the border cells).cellStart[c]…cellStart[c + 1]: the range ofsortedholding the particles of cell c.sorted: particle indices ordered by cell.
Build is O(n + cells) with no allocation after the first build; forEachNeighbor visits the 27 cells around a point. Reusable by any particle code (SPH here, plasma and granular codes elsewhere).
Constructors
NeighborGrid({required this.minX, required this.minY, required this.minZ, required double maxX, required double maxY, required double maxZ, required this.cellSize})import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final g = NeighborGrid(minX: 0, minY: 0, minZ: 0, maxX: 10, maxY: 10, maxZ: 1, cellSize: 1);
final rng = math.Random(3);
final pos = <double>[for (var i = 0; i < 100; i++) ...[rng.nextDouble() * 10, rng.nextDouble() * 10, 0.5, 0]];
g.build(pos, 100);
var n = 0;
g.forEachNeighbor(5, 5, 0.5, (_) => n++);
print('$n candidates in the cells around (5, 5)');
}13 candidates in the cells around (5, 5)
Properties
final double minXfinal double minYfinal double minZfinal double cellSizefinal int nxfinal int nyfinal int nzint get cellCountlate Uint32List cellStartUint32List cellOfUint32List sortedint get countMethods
int cellIndex(double x, double y, double z)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final g = NeighborGrid(minX: 0, minY: 0, minZ: 0, maxX: 10, maxY: 10, maxZ: 1, cellSize: 1);
final rng = math.Random(3);
final pos = <double>[for (var i = 0; i < 100; i++) ...[rng.nextDouble() * 10, rng.nextDouble() * 10, 0.5, 0]];
g.build(pos, 100);
print('cell of (3.5, 7.2, 0.5): ${g.cellIndex(3.5, 7.2, 0.5)}');
}cell of (3.5, 7.2, 0.5): 73
void build(List<double> pos, int count, {int stride = 4})Bins count particles whose positions are read from pos with stride floats per particle (4 for the vec4 layout, 3 for packed xyz).
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final g = NeighborGrid(minX: 0, minY: 0, minZ: 0, maxX: 10, maxY: 10, maxZ: 1, cellSize: 1);
final rng = math.Random(3);
final pos = <double>[for (var i = 0; i < 100; i++) ...[rng.nextDouble() * 10, rng.nextDouble() * 10, 0.5, 0]];
g.build(pos, 100);
print('built for 100 particles');
}built for 100 particles
int cellX(double x)Cell coordinates of a point (clamped), for callers that walk neighbouring cells themselves (no closure per neighbour; the loop shape GPU kernels use): for each of the 27 cells c around it, for (s = cellStart[c]; s < cellStart[c + 1]; s++) j = sorted[s].
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final g = NeighborGrid(minX: 0, minY: 0, minZ: 0, maxX: 10, maxY: 10, maxZ: 1, cellSize: 1);
final rng = math.Random(3);
final pos = <double>[for (var i = 0; i < 100; i++) ...[rng.nextDouble() * 10, rng.nextDouble() * 10, 0.5, 0]];
g.build(pos, 100);
print(g.cellX(3.7));
}3
int cellY(double y)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final g = NeighborGrid(minX: 0, minY: 0, minZ: 0, maxX: 10, maxY: 10, maxZ: 1, cellSize: 1);
final rng = math.Random(3);
final pos = <double>[for (var i = 0; i < 100; i++) ...[rng.nextDouble() * 10, rng.nextDouble() * 10, 0.5, 0]];
g.build(pos, 100);
print(g.cellY(9.99));
}9
int cellZ(double z)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final g = NeighborGrid(minX: 0, minY: 0, minZ: 0, maxX: 10, maxY: 10, maxZ: 1, cellSize: 1);
final rng = math.Random(3);
final pos = <double>[for (var i = 0; i < 100; i++) ...[rng.nextDouble() * 10, rng.nextDouble() * 10, 0.5, 0]];
g.build(pos, 100);
print(g.cellZ(0.2));
}0
void forEachNeighbor(double x, double y, double z, void Function(int j) visit)Calls visit with every particle index in the 3 \times 3 \times 3 cells around (x, y, z). Callers test the distance.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final g = NeighborGrid(minX: 0, minY: 0, minZ: 0, maxX: 10, maxY: 10, maxZ: 1, cellSize: 1);
final rng = math.Random(3);
final pos = <double>[for (var i = 0; i < 100; i++) ...[rng.nextDouble() * 10, rng.nextDouble() * 10, 0.5, 0]];
g.build(pos, 100);
final near = <int>[];
g.forEachNeighbor(2, 2, 0.5, near.add);
print('${near.length} candidates');
}7 candidates
SphParams
final class SphParams
SPH parameters (SI units).
Constructors
const SphParams({required this.h, this.restDensity = 1000, this.stiffness = 2000, this.viscosity = 1, this.gravityY = -9.81, this.boundaryDamping = 0.5, this.clampNegativePressure = true})import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
const p = SphParams(h: 0.05, viscosity: 2);
print('h ${p.h}, rest density ${p.restDensity}, stiffness ${p.stiffness}, gravity ${p.gravityY}');
}h 0.05, rest density 1000.0, stiffness 2000.0, gravity -9.81
Properties
final double restDensityfinal double stiffnessk in the equation of state p = k (\rho - \rho_{0}) (Pa per kg/m³).
final double gravityYfinal double boundaryDampingFraction of normal velocity kept when a particle hits the domain walls.
final bool clampNegativePressurePressure below zero (tension) is clamped, which avoids particle clumping at free surfaces.
SphFluid
final class SphFluid
Weakly compressible SPH (Müller, Charypar and Gross, "Particle-Based Fluid Simulation for Interactive Applications", SCA 2003): poly6 density, spiky pressure gradient, viscosity Laplacian, linear equation of state, semi-implicit Euler, a box domain whose walls are mirror particles (free slip) plus a reflecting clamp.
Buffer layout (shared with the GPU kernels in riptide_numerics_gpu): all float32, std430-compatible.
| Buffer | Type | Per particle | Notes |
|---|---|---|---|
pos | Float32List | 4 (x, y, z, 0) | vec4 |
vel | Float32List | 4 (x, y, z, 0) | vec4 |
acc | Float32List | 4 (x, y, z, 0) | vec4, written by computeForces |
density | Float32List | 1 | written by computeDensity |
pressure | Float32List | 1 | written by computeDensity |
grid cellStart, sorted, cellOf | Uint32List | see NeighborGrid | counting sort |
Kernel order per step: grid build → density/pressure → forces → integrate (+ walls). Walls: each neighbour within h of a wall also contributes its mirror image (position reflected, normal velocity negated).
Constructors
SphFluid(this.count, this.params, {required this.min, required this.max})import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final fluid = SphFluid(400, const SphParams(h: 0.1), min: (0.0, 0.0, 0.0), max: (1.0, 1.0, 0.1));
final n = fluid.fillBox((0.05, 0.05, 0.0), (0.45, 0.75, 0.1), 0.05);
for (var k = 0; k < 40; k++) {
fluid.step(0.004);
}
print('$n particles, max speed ${f(fluid.maxSpeed)}');
}224 particles, max speed 180.7306
Properties
final int countfinal SphParams paramsfinal (double, double, double) minfinal (double, double, double) maxfinal Float32List posfinal Float32List velfinal Float32List accfinal Float32List densityfinal Float32List pressurefinal Uint8List wallMaskBit m - 1 set when the particle is within h of wall m (1–6: x min, x max, y min, y max, z min, z max), so its mirror image m takes part; written by computeDensity.
final NeighborGrid gridlate final double poly6late final double spikyGradlate final double viscLapdouble get stableDtThe largest stable step by the CFL and viscous limits: \min(0.4 h / c, 0.125 h^{2} \rho_{0} / \mu), c = \sqrt{k} the speed of sound of the linear equation of state.
double get maxSpeedMethods
int fillBox((double, double, double) lo, (double, double, double) hi, double s)Places particles on a cubic lattice of spacing s filling (lo)…(hi) (row by row, up to count); returns how many were placed and sets the mass to \rho_{0} s^{3}.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final fluid = SphFluid(400, const SphParams(h: 0.1), min: (0.0, 0.0, 0.0), max: (1.0, 1.0, 0.1));
final n = fluid.fillBox((0.05, 0.05, 0.0), (0.45, 0.75, 0.1), 0.05);
print('filled $n particles on a 0.05 lattice');
}filled 224 particles on a 0.05 lattice
void computeDensity()\rho_{i} = \sum_{j} m W_{\mathrm{poly6}}(r_{ij}, h) over neighbours and their wall images; p_{i} = k(\rho_{i} - \rho_{0}).
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final fluid = SphFluid(400, const SphParams(h: 0.1), min: (0.0, 0.0, 0.0), max: (1.0, 1.0, 0.1));
final n = fluid.fillBox((0.05, 0.05, 0.0), (0.45, 0.75, 0.1), 0.05);
fluid.computeDensity();
print('density of particle 0: ${f(fluid.density[0])}');
}density of particle 0: 654.8239
void computeForces()a_{i} = \frac{-\sum m \frac{p_{i} + p_{j}}{2\rho_{j}} \nabla W_{\mathrm{spiky}} + \mu \sum m \frac{v_{j} - v_{i}}{\rho_{j}} \nabla^{2}W_{\mathrm{visc}}}{\rho_{i}} + g over neighbours and their wall images. Uses the grid from computeDensity.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final fluid = SphFluid(400, const SphParams(h: 0.1), min: (0.0, 0.0, 0.0), max: (1.0, 1.0, 0.1));
final n = fluid.fillBox((0.05, 0.05, 0.0), (0.45, 0.75, 0.1), 0.05);
fluid.computeDensity();
fluid.computeForces();
print('acceleration of particle 0: (${f(fluid.acc[0])}, ${f(fluid.acc[1])})');
}acceleration of particle 0: (-21.5428, -31.3528)
void integrate(double dt)Semi-implicit Euler and reflecting walls.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final fluid = SphFluid(400, const SphParams(h: 0.1), min: (0.0, 0.0, 0.0), max: (1.0, 1.0, 0.1));
final n = fluid.fillBox((0.05, 0.05, 0.0), (0.45, 0.75, 0.1), 0.05);
fluid.computeDensity();
fluid.computeForces();
fluid.integrate(0.002);
print('stable dt suggestion ${fluid.stableDt.toStringAsExponential(2)}');
}stable dt suggestion 8.94e-4
void step(double dt)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final fluid = SphFluid(400, const SphParams(h: 0.1), min: (0.0, 0.0, 0.0), max: (1.0, 1.0, 0.1));
final n = fluid.fillBox((0.05, 0.05, 0.0), (0.45, 0.75, 0.1), 0.05);
final h = <List<double>>[];
for (var k = 0; k < 50; k++) {
fluid.step(0.004);
var top = 0.0;
for (var i = 0; i < n; i++) {
top = math.max(top, fluid.pos[4 * i + 1]);
}
h.add([k * 0.004, top]);
}
}StableFluid2
final class StableFluid2
Stable fluids on a 2-D staggered (MAC) grid: Stam's method ("Stable Fluids", SIGGRAPH 1999) — implicit viscous diffusion, semi-Lagrangian advection (unconditionally stable) and a pressure projection — on the marker-and-cell layout of Harlow and Welch (1965) as in Bridson, "Fluid Simulation for Computer Graphics" (2nd ed. ch. 2–5), written from those texts.
Why staggered: Stam's GDC 2003 collocated version computes divergence and gradient with central differences but solves a 5-point Laplacian, which don't compose exactly, so its velocity is only approximately divergence-free. Here divergence and gradient are adjoint face differences, the pressure Laplacian is exactly \operatorname{div} \circ \operatorname{grad}, and conjugate gradients solve it to projectTolerance: the result is divergence-free to that tolerance.
Layout (unit cells, n × n): cell (i, j) centre at (i + \tfrac{1}{2}, j + \tfrac{1}{2}) holds pressure and density; u(i, j) at (i, j + \tfrac{1}{2}) for 0 \le i \le n; v(i, j) at (i + \tfrac{1}{2}, j) for 0 \le j \le n. Walls are solid: boundary face velocities are 0. Velocities are in cells per second.
Constructors
StableFluid2(this.n, {this.viscosity = 0, this.diffusion = 0, this.iterations = 40, this.projectTolerance = 1e-8})import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final s = StableFluid2(32, viscosity: 0.0001);
for (var k = 0; k < 20; k++) {
s.addDensity(16, 4, 5);
s.addVelocity(16, 4, 0, 2);
s.step(0.1);
}
print('total density ${f(s.totalDensity)}, max divergence ${s.maxDivergence.toStringAsExponential(2)}');
}total density 89.9995, max divergence 1.39e-9
Properties
final int ndouble viscositydouble diffusionfinal Float64List ufinal Float64List vfinal Float64List densitydouble get totalDensityMethods
int ui(int i, int j)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final s = StableFluid2(32, viscosity: 0.0001);
print('u index of face (3, 5): ${s.ui(3, 5)}, v index ${s.vi(3, 5)}, cell ${s.ci(3, 5)}');
}u index of face (3, 5): 168, v index 163, cell 163
int vi(int i, int j)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final s = StableFluid2(32, viscosity: 0.0001);
print(s.vi(0, 32));
}1024
int ci(int i, int j)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final s = StableFluid2(32, viscosity: 0.0001);
print(s.ci(31, 31));
}1023
void addVelocity(int i, int j, double du, double dv)Adds velocity to the faces around cell (i, j), 0 \le i, j < n.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final s = StableFluid2(32, viscosity: 0.0001);
s.addVelocity(10, 10, 1, 0);
print(s.velocityAt(10.5, 10.5));
}(0.5, 0.0)
void addDensity(int i, int j, double d)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final s = StableFluid2(32, viscosity: 0.0001);
s.addDensity(5, 5, 2);
print(s.totalDensity);
}2.0
void step(double dt)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final s = StableFluid2(32, viscosity: 0.0001);
s.addDensity(16, 16, 10);
s.step(0.1);
print('diffused and advected; total ${f(s.totalDensity)}');
}diffused and advected; total 10.0000
(double, double) velocityAt(double x, double y)Velocity (cells/s) at a point, bilinear from the faces.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final s = StableFluid2(32, viscosity: 0.0001);
s.addVelocity(16, 16, 2, 0);
print([for (final x in [15.0, 16.0, 16.5, 17.0]) s.velocityAt(x, 16.5).$1]);
}[0.0, 1.0, 1.0, 1.0]
double divergence(int i, int j)Divergence of cell (i, j): (u(i + 1) - u(i)) + (v(j + 1) - v(j)).
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final s = StableFluid2(32, viscosity: 0.0001);
s.addVelocity(10, 10, 1, 0);
print('before projection: ${f(s.divergence(10, 10))}');
s.project();
print('after: ${s.divergence(10, 10).abs() < 1e-6}');
}before projection: 0.0000 after: true
int project()Makes the velocity divergence-free: solve A p = -\nabla \cdot u (CG; the right side has zero mean, so the singular Neumann system is consistent), then u - = \nabla p on interior faces. Returns the CG iterations.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final s = StableFluid2(32, viscosity: 0.0001);
s.addVelocity(10, 10, 1, 0);
final it = s.project();
print('$it iterations; max divergence ${s.maxDivergence.toStringAsExponential(2)}');
}126 iterations; max divergence 7.27e-10
Cr3bp
final class Cr3bp
The circular restricted three-body problem in the rotating, non-dimensional frame (Szebehely 1967; Koon, Lo, Marsden and Ross, "Dynamical Systems, the Three-Body Problem and Space Mission Design", 2011): the primaries (Earth at x = -\mu, Moon at x = 1 - \mu) are fixed, lengths are in units of their separation, time in units of 1/(their angular rate), so the period is 2\pi.
The Kids "Orbital Mechanics: Earth and the Moon" course can drive its m06 (the Earth–Moon system), m07 (going to the Moon) and m08 (Lagrange points) lessons with this, and m02–m05 (Kepler, vis-viva, Hohmann, escape) with Kepler.
Constructors
const Cr3bp(this.mu)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
const sys = Cr3bp.earthMoon;
print('μ = ${sys.mu.toStringAsExponential(6)}');
final lp = sys.lagrangePoints();
print('L1 at x = ${f(lp[0].$1)}');
}μ = 1.215058e-2 L1 at x = 0.8369
Static
static const earthMoon = Cr3bp(Bodies.moonMu / (Bodies.earthMu + Bodies.moonMu))Earth–Moon: \mu = \frac{M_{\mathrm{moon}}}{M_{\mathrm{earth}} + M_{\mathrm{moon}}} from the GMs in Bodies.
static const earthMoonLength = Bodies.earthMoonDistanceLength unit (km), time unit (s) and speed unit (km/s) for the Earth–Moon system.
static double get earthMoonTimestatic double get earthMoonSpeedProperties
final double muMethods
double potential(double x, double y, double z)Pseudo-potential \Omega = \frac{x^{2} + y^{2}}{2} + \frac{1 - \mu}{r_{1}} + \frac{\mu}{r_{2}} + \frac{\mu(1 - \mu)}{2}.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
const sys = Cr3bp.earthMoon;
print('Ω at L4: ${f(sys.potential(0.5 - sys.mu, math.sqrt(3) / 2, 0))}');
}Ω at L4: 1.5000
double jacobi(Float64List s)The Jacobi constant C = 2\Omega - v^{2} of state (x, y, z, vx, vy, vz), conserved along trajectories.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
const sys = Cr3bp.earthMoon;
final s = Float64List.fromList([0.5, 0, 0, 0, 0.5, 0]);
final c0 = sys.jacobi(s);
sys.propagate(s, 2);
print('Jacobi constant before ${c0.toStringAsFixed(10)}, after ${sys.jacobi(s).toStringAsFixed(10)}');
}Jacobi constant before 3.9194680027, after 3.9194680027
void derivative(Float64List s, Float64List out)Equations of motion: \ddot{x} - 2\dot{y} = \Omega_{x}, \ddot{y} + 2\dot{x} = \Omega_{y}, \ddot{z} = \Omega_{z}. Writes the derivative of s into out.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
const sys = Cr3bp.earthMoon;
final out = Float64List(6);
sys.derivative(Float64List.fromList([0.5, 0, 0, 0, 0.5, 0]), out);
print('state derivative ${out.map(f).toList()}');
}state derivative [0.0000, 0.5000, 0.0000, -2.2151, 0.0000, 0.0000]
List<(double, double)> lagrangePoints()The five Lagrange points as (x, y): L1–L3 on the x axis by Newton on the quintic's derivative, L4 and L5 at the equilateral points (\tfrac{1}{2} - \mu, \pm\frac{\sqrt{3}}{2}).
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
const sys = Cr3bp.earthMoon;
for (final (i, p) in sys.lagrangePoints().indexed) {
print('L${i + 1}: (${f(p.$1)}, ${f(p.$2)})');
}
}L1: (0.8369, 0.0000) L2: (1.1557, 0.0000) L3: (-1.0051, 0.0000) L4: (0.4878, 0.8660) L5: (0.4878, -0.8660)
int propagate(Float64List state, double time, {double tol = 1e-12})Integrates state (6 values, modified in place) for time non-dimensional time units with part B's adaptive Dormand–Prince 5(4) stepper (riptide_numerics_calculus, a port of SciPy's RK45) at relative and absolute tolerance tol. Returns the number of accepted steps.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
const sys = Cr3bp.earthMoon;
// A small orbit around the Moon in the rotating frame.
final s = Float64List.fromList([1 - sys.mu + 0.05, 0, 0, 0, 0.45, 0]);
final pts = <List<double>>[];
for (var k = 0; k < 120; k++) {
pts.add([s[0], s[1]]);
sys.propagate(s, 0.02);
}
print('after 2.4 time units: (${f(s[0])}, ${f(s[1])})');
}after 2.4 time units: (0.9775, 0.0505)
Bodies
abstract final class Bodies
Gravitational parameters and radii in kilometres and seconds (the units of Vallado's examples).
Static
static const earthMu = 398600.4418static const earthRadius = 6378.137static const moonMu = 4902.800066static const moonRadius = 1737.4static const sunMu = 1.32712440018e11static const earthMoonDistance = 384400.0OrbitalElements
final class OrbitalElements
Classical orbital elements. Angles in radians. For circular or equatorial orbits the undefined angles follow Vallado's convention: \Omega = 0 when equatorial, \omega = 0 when circular, and \nu then measures from the line of nodes (argument of latitude) or from the x axis (true longitude).
Constructors
const OrbitalElements({required this.a, required this.e, required this.i, required this.raan, required this.argPeriapsis, required this.trueAnomaly})import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final el = OrbitalElements(a: 10000, e: 0.2, i: 0.5, raan: 1, argPeriapsis: 0.3, trueAnomaly: 2);
print(el);
print('semi-latus rectum p = ${f(el.p)} km');
}OrbitalElements(a: 10000.0, e: 0.2, i: 0.5, Ω: 1.0, ω: 0.3, ν: 2.0) semi-latus rectum p = 9600.0000 km
Properties
final double aSemi-major axis (negative for hyperbolas), eccentricity, inclination, right ascension of the ascending node, argument of periapsis, true anomaly.
final double eSemi-major axis (negative for hyperbolas), eccentricity, inclination, right ascension of the ascending node, argument of periapsis, true anomaly.
final double iSemi-major axis (negative for hyperbolas), eccentricity, inclination, right ascension of the ascending node, argument of periapsis, true anomaly.
final double raanSemi-major axis (negative for hyperbolas), eccentricity, inclination, right ascension of the ascending node, argument of periapsis, true anomaly.
final double argPeriapsisSemi-major axis (negative for hyperbolas), eccentricity, inclination, right ascension of the ascending node, argument of periapsis, true anomaly.
final double trueAnomalySemi-major axis (negative for hyperbolas), eccentricity, inclination, right ascension of the ascending node, argument of periapsis, true anomaly.
Methods
double period(double mu)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final el = OrbitalElements(a: 10000, e: 0.2, i: 0.5, raan: 1, argPeriapsis: 0.3, trueAnomaly: 2);
print('${f(el.period(Bodies.earthMu) / 3600)} h');
}2.7644 h
String toString()import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final el = OrbitalElements(a: 10000, e: 0.2, i: 0.5, raan: 1, argPeriapsis: 0.3, trueAnomaly: 2);
print(el.toString());
}OrbitalElements(a: 10000.0, e: 0.2, i: 0.5, Ω: 1.0, ω: 0.3, ν: 2.0)
Kepler
abstract final class Kepler
Kepler's equation, conversions between anomalies, and two-body propagation.
Static
static double eccentricAnomaly(double meanAnomaly, double e)Solves M = E - e \sin E for the eccentric anomaly (0 \le e < 1) by Newton's method with Danby's start E_{0} = M + 0.85 e \operatorname{sign}(\sin M); converges to machine precision in ≤ 6 iterations for all e < 1.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
const e = 0.6;
final ea = Kepler.eccentricAnomaly(1, e);
print('M = 1: E = ${f(ea)}, check E − e sin E = ${f(ea - e * math.sin(ea))}');
}M = 1: E = 1.5997, check E − e sin E = 1.0000
static double hyperbolicAnomaly(double meanAnomaly, double e)Solves M = e \sinh H - H for the hyperbolic anomaly (e > 1).
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
const e = 1.5;
final h = Kepler.hyperbolicAnomaly(2, e);
print('H = ${f(h)}, check e sinh H − H = ${f(e * (math.exp(h) - math.exp(-h)) / 2 - h)}');
}H = 1.6127, check e sinh H − H = 2.0000
static double trueFromEccentric(double ea, double e)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
const e = 0.6;
print('E = 1 -> ν = ${f(Kepler.trueFromEccentric(1, e))}');
}E = 1 -> ν = 1.6592
static double eccentricFromTrue(double nu, double e)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
const e = 0.6;
print('ν = 2 -> E = ${f(Kepler.eccentricFromTrue(2, e))}');
}ν = 2 -> E = 1.3232
static double trueFromHyperbolic(double h, double e)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
print(f(Kepler.trueFromHyperbolic(1, 1.5)));
}1.6036
static double hyperbolicFromTrue(double nu, double e)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
print(f(Kepler.hyperbolicFromTrue(1, 1.5)));
}0.4987
static double meanFromTrue(double nu, double e)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
const e = 0.6;
print('ν = π/2 -> M = ${f(Kepler.meanFromTrue(math.pi / 2, e))}');
}ν = π/2 -> M = 0.4473
static double trueFromMean(double m, double e)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
const e = 0.6;
print('M = π/4 -> ν = ${f(Kepler.trueFromMean(math.pi / 4, e))}');
print('round trip: ${f(Kepler.meanFromTrue(Kepler.trueFromMean(0.7, e), e))}');
}M = π/4 -> ν = 2.0466 round trip: 0.7000
static (double, double) stumpff(double psi)Stumpff functions c_{2}(\psi) = \frac{1 - \cos\sqrt{\psi}}{\psi} and c_{3}(\psi) = \frac{\sqrt{\psi} - \sin\sqrt{\psi}}{\sqrt{\psi 3}} (with series near 0).
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
for (final psi in [-1.0, 0.0, 1.0]) {
final (c2, c3) = Kepler.stumpff(psi);
print('ψ = $psi: c2 = ${f(c2)}, c3 = ${f(c3)}');
}
}ψ = -1.0: c2 = 0.5431, c3 = 0.1752 ψ = 0.0: c2 = 0.5000, c3 = 0.1667 ψ = 1.0: c2 = 0.4597, c3 = 0.1585
static (Vec3d, Vec3d) propagate(Vec3d r, Vec3d v, double dt, {double mu = Bodies.earthMu})Propagates a two-body state (r km, v km/s) by dt seconds with universal variables (Vallado, Algorithm 8 KEPLER, with its initial guesses), one formulation for every conic. Vallado's plain Newton iteration can diverge for transfers close to a full period, so here it is safeguarded: whole periods are removed first, the root is bracketed (the time equation is monotonic in \chi) and a step that leaves the bracket bisects. Returns (r, v).
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
// An orbit with perigee 7000 km and apogee 20000 km, propagated in 30-minute steps.
final el = OrbitalElements(a: 13500, e: 6500 / 13500, i: 0, raan: 0, argPeriapsis: 0, trueAnomaly: 0);
final (r0, v0) = Kepler.stateFromElements(el);
final pts = <List<double>>[];
for (var i = 0; i <= 30; i++) {
final (r, _) = Kepler.propagate(r0, v0, el.period(Bodies.earthMu) * i / 30);
pts.add([r.x, r.y]);
}
print('period ${f(el.period(Bodies.earthMu) / 3600)} h; back at perigee: ${d3(Kepler.propagate(r0, v0, el.period(Bodies.earthMu)).$1)}');
}period 4.3362 h; back at perigee: (7000.0000, 0.0000, 0.0000)
static OrbitalElements elementsFromState(Vec3d r, Vec3d v, {double mu = Bodies.earthMu})Vallado's RV2COE: state vector (km, km/s) to classical elements.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final el = Kepler.elementsFromState(const Vec3d(7000, 0, 0), const Vec3d(0, 8, 1));
print(el);
}OrbitalElements(a: 8153.69926356321, e: 0.1414939681082911, i: 0.1243549945467616, Ω: 0.0, ω: 0.0, ν: 0.0)
static (Vec3d, Vec3d) stateFromElements(OrbitalElements el, {double mu = Bodies.earthMu})Vallado's COE2RV: classical elements to state vector (km, km/s).
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final el = OrbitalElements(a: 26560, e: 0.01, i: 55 * math.pi / 180, raan: 0, argPeriapsis: 0, trueAnomaly: 1);
final (r, v) = Kepler.stateFromElements(el);
print('GPS-like orbit: r = ${d3(r)} km, v = ${d3(v)} km/s');
}GPS-like orbit: r = (14271.8829, 12748.9641, 18207.4077) km, v = (-3.2600, 1.2228, 1.7464) km/s
static double period(double a, {double mu = Bodies.earthMu})Orbital period (s) of semi-major axis a (km).
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
print('ISS (a = 6778 km): ${f(Kepler.period(6778) / 60)} min');
print('geostationary: ${f(Kepler.period(42164) / 3600)} h');
}ISS (a = 6778 km): 92.5576 min geostationary: 23.9343 h
static double visViva(double r, double a, {double mu = Bodies.earthMu})Vis-viva: speed (km/s) at radius r on an orbit of semi-major axis a.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
print('speed at perigee of a 7000 × 20000 km orbit: ${f(Kepler.visViva(7000, 13500))} km/s');
}speed at perigee of a 7000 × 20000 km orbit: 9.1848 km/s
static double escapeSpeed(double r, {double mu = Bodies.earthMu})Escape speed (km/s) at radius r.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
print('from the surface: ${f(Kepler.escapeSpeed(Bodies.earthRadius))} km/s');
}from the surface: 11.1799 km/s
static double circularSpeed(double r, {double mu = Bodies.earthMu})Circular-orbit speed (km/s) at radius r.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
print('low orbit: ${f(Kepler.circularSpeed(6778))} km/s');
}low orbit: 7.6686 km/s
static ({double dv1, double dv2, double time}) hohmann(double r1, double r2, {double mu = Bodies.earthMu})Hohmann transfer between circular coplanar orbits of radii r1 → r2 (km): the two burns (km/s) and the transfer time (s, half the transfer ellipse's period).
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final h = Kepler.hohmann(6778, 42164);
print('LEO to GEO: Δv1 ${f(h.dv1)}, Δv2 ${f(h.dv2)} km/s, ${f(h.time / 3600)} h');
}LEO to GEO: Δv1 2.3975, Δv2 1.4565 km/s, 5.2912 h
ParticleState
final class ParticleState
Point particles in structure-of-arrays typed data (double precision): position and velocity interleaved xyz (3 per particle), plus mass and charge. Shared by the SPH, orbital and plasma code (riptide_plasma_cpu's pushers implement ParticleStepper); see ParticleStepper for the stepping contract.
Constructors
ParticleState(this.count)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final s = ParticleState(3);
print('positions ${s.position.length} values, masses ${s.mass}, charges ${s.charge}');
s.velocity[0] = 2;
print('kinetic energy ${s.kineticEnergy}');
}positions 9 values, masses [1.0, 1.0, 1.0], charges [0.0, 0.0, 0.0] kinetic energy 2.0
Properties
final int countfinal Float64List positionfinal Float64List velocityfinal Float64List chargePer-particle mass (kg; 1 by default) and charge (C; 0 by default).
double get kineticEnergyParticleStepper
abstract interface class ParticleStepper
One time step of a particle system. Implementations own any scratch they need, so stepping allocates nothing.
Contract: step advances state.position, state.velocity and state.time by dt. Steppers that only need forces call ForceField; steppers with their own physics (a Boris pusher reading E and B fields) may ignore it. The steppers here are thin adapters over riptide_numerics_calculus: SymplecticStepper over its SymplecticIntegrator, RungeKutta4 over its Rk4Stepper.
Methods
void step(ParticleState state, ForceField force, double dt)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final ball = ParticleState(1);
ball.velocity[0] = 10;
ball.velocity[1] = 10;
void gravity(ParticleState s, double t, Float64List f) {
f[0] = 0;
f[1] = -9.81 * s.mass[0];
f[2] = 0;
}
final List<ParticleStepper> all = [SemiImplicitEuler(), VelocityVerlet(), RungeKutta4()];
for (final st in all) {
final b = ParticleState(1)..velocity[0] = 10..velocity[1] = 10;
while (b.position[1] >= 0) {
st.step(b, gravity, 0.05);
}
print('${st.runtimeType.toString().padRight(17)} lands at x = ${f(b.position[0])}');
}
}SemiImplicitEuler lands at x = 20.0000 VelocityVerlet lands at x = 20.5000 RungeKutta4 lands at x = 20.5000
SymplecticStepper
base class SymplecticStepper implements ParticleStepper
Symplectic stepping by part B's SymplecticIntegrator (velocity Verlet, leapfrog, Yoshida 4 and 6): bounded energy error over long runs. Forces must depend on positions only (separable Hamiltonians); the force field is called at state.time for every substage.
Constructors
SymplecticStepper([this.method = SymplecticMethod.velocityVerlet])import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray' show SymplecticMethod;
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final ball = ParticleState(1);
ball.velocity[0] = 10;
ball.velocity[1] = 10;
void gravity(ParticleState s, double t, Float64List f) {
f[0] = 0;
f[1] = -9.81 * s.mass[0];
f[2] = 0;
}
final st = SymplecticStepper(SymplecticMethod.velocityVerlet);
final path = <List<double>>[];
while (ball.position[1] >= 0) {
path.add([ball.position[0], ball.position[1]]);
st.step(ball, gravity, 0.05);
}
print('lands near x = ${f(ball.position[0])} (exact 2·10·10/9.81 = ${f(200 / 9.81)})');
}lands near x = 20.5000 (exact 2·10·10/9.81 = 20.3874)
Properties
final SymplecticMethod methodMethods
void reset()Call when positions are changed from outside, so a cached force is recomputed.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
// A spring, stepped; reset() drops the cached force after the state is changed by hand.
final s = ParticleState(1)..position[0] = 1;
void spring(ParticleState p, double t, Float64List f) {
f[0] = -p.position[0];
f[1] = 0;
f[2] = 0;
}
final st = SymplecticStepper();
st.step(s, spring, 0.1);
s.position[0] = 2;
st.reset();
st.step(s, spring, 0.1);
print('x = ${f(s.position[0])}');
}x = 1.9800
void step(ParticleState s, ForceField force, double dt)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
import 'package:riptide_numerics_calculus/riptide_numerics_calculus.ray' show SymplecticMethod;
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final s = ParticleState(1)..position[0] = 1;
void spring(ParticleState p, double t, Float64List f) {
f[0] = -p.position[0];
f[1] = 0;
f[2] = 0;
}
final st = SymplecticStepper(SymplecticMethod.yoshida4);
final e = <List<double>>[];
for (var i = 0; i < 300; i++) {
st.step(s, spring, 0.1);
e.add([s.time, 0.5 * s.velocity[0] * s.velocity[0] + 0.5 * s.position[0] * s.position[0]]);
}
print('energy after 300 steps: ${e.last[1].toStringAsFixed(8)} (start 0.5)');
}energy after 300 steps: 0.50000374 (start 0.5)
VelocityVerlet
final class VelocityVerlet extends SymplecticStepper
Velocity Verlet (kick–drift–kick): second order, symplectic, one force evaluation per step.
Constructors
VelocityVerlet()import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final ball = ParticleState(1);
ball.velocity[0] = 10;
ball.velocity[1] = 10;
void gravity(ParticleState s, double t, Float64List f) {
f[0] = 0;
f[1] = -9.81 * s.mass[0];
f[2] = 0;
}
final st = VelocityVerlet();
final path = <List<double>>[];
while (ball.position[1] >= 0) {
path.add([ball.position[0], ball.position[1]]);
st.step(ball, gravity, 0.05);
}
print('lands near x = ${f(ball.position[0])} (exact 2·10·10/9.81 = ${f(200 / 9.81)})');
}lands near x = 20.5000 (exact 2·10·10/9.81 = 20.3874)
SemiImplicitEuler
final class SemiImplicitEuler implements ParticleStepper
Semi-implicit (symplectic) Euler: v += a dt, x + = v dt. First order; kept for its one-line cost.
Methods
void step(ParticleState s, ForceField force, double dt)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final ball = ParticleState(1);
ball.velocity[0] = 10;
ball.velocity[1] = 10;
void gravity(ParticleState s, double t, Float64List f) {
f[0] = 0;
f[1] = -9.81 * s.mass[0];
f[2] = 0;
}
final st = SemiImplicitEuler();
final path = <List<double>>[];
while (ball.position[1] >= 0) {
path.add([ball.position[0], ball.position[1]]);
st.step(ball, gravity, 0.05);
}
print('lands near x = ${f(ball.position[0])} (exact 2·10·10/9.81 = ${f(200 / 9.81)})');
}lands near x = 20.0000 (exact 2·10·10/9.81 = 20.3874)
RungeKutta4
final class RungeKutta4 implements ParticleStepper
Classic fourth-order Runge–Kutta on (x, v) by part B's Rk4Stepper: accurate for smooth, velocity-dependent forces (drag, magnetic), not symplectic.
Methods
void step(ParticleState s, ForceField force, double dt)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final ball = ParticleState(1);
ball.velocity[0] = 10;
ball.velocity[1] = 10;
void gravity(ParticleState s, double t, Float64List f) {
f[0] = 0;
f[1] = -9.81 * s.mass[0];
f[2] = 0;
}
final st = RungeKutta4();
final path = <List<double>>[];
while (ball.position[1] >= 0) {
path.add([ball.position[0], ball.position[1]]);
st.step(ball, gravity, 0.05);
}
print('lands near x = ${f(ball.position[0])} (exact 2·10·10/9.81 = ${f(200 / 9.81)})');
}lands near x = 20.5000 (exact 2·10·10/9.81 = 20.3874)
BodyType
enum BodyType
How a body moves: dynamic bodies respond to forces and contacts; static bodies never move; kinematic bodies move by the velocity you set and push dynamic bodies without being pushed back.
Values
dynamicstatickinematicRigidBody
final class RigidBody
A rigid body. SI units: metres, kilograms, seconds, radians. position is the centre of mass; orientation maps the body frame to the world frame.
Constructors
factory RigidBody.dynamic(Collider collider, {double density = 1000, double? mass, Vec3d position = Vec3d.zero, Quatd orientation = Quatd.identity})A dynamic body whose mass comes from density (kg/m³), or exactly mass when given (inertia scaled to it).
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final b = RigidBody.dynamic(const BoxCollider(Vec3d(0.5, 0.5, 0.5)), density: 500, position: const Vec3d(0, 3, 0));
print('mass ${f(b.mass)} kg, type ${b.type.name}');
}mass 500.0000 kg, type dynamic
factory RigidBody.static(Collider collider, {Vec3d position = Vec3d.zero, Quatd orientation = Quatd.identity})import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final g = RigidBody.static(PlaneCollider(Vec3d.unitY, 0));
print('static: inverse mass ${g.invMass}');
}static: inverse mass 0.0
factory RigidBody.kinematic(Collider collider, {Vec3d position = Vec3d.zero, Quatd orientation = Quatd.identity})import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final k = RigidBody.kinematic(const BoxCollider(Vec3d(2, 0.1, 2)));
k.linearVelocity = const Vec3d(1, 0, 0);
print('${k.type.name}: moves at a set velocity, ignores forces; inverse mass ${k.invMass}');
}kinematic: moves at a set velocity, ignores forces; inverse mass 0.0
Properties
final Collider colliderfinal BodyType typeObject? userDatadouble massdouble invMassMat3d inertiaLocalMat3d invInertiaLocalMat3d invInertiaWorldI^{-1} in world frame, R I^{-1}_{\mathrm{local}} R^{T}; refreshed every step.
Vec3d positionQuatd orientationVec3d linearVelocityVec3d angularVelocityVec3d forceVec3d torquedouble frictiondouble restitutiondouble linearDampingdouble angularDampingdouble gravityScaleint collisionGroupBits of the groups this body is in, and the groups it collides with.
int collisionMaskbool awakedouble sleepTimebool get isDynamicAabb get boundsdouble get kineticEnergyVec3d get linearMomentumVec3d get angularMomentumAngular momentum about the world origin: r \times m v + I \omega.
Methods
void updateInertia()Recomputes invInertiaWorld from the orientation.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final b = RigidBody.dynamic(const BoxCollider(Vec3d(1, 0.5, 0.25)), mass: 2, position: const Vec3d(1, 0, 0));
b.orientation = Quatd.axisAngle(Vec3d.unitZ, math.pi / 2);
b.updateInertia();
print('world inverse inertia diagonal ${[f(b.invInertiaWorld.at(0, 0)), f(b.invInertiaWorld.at(1, 1)), f(b.invInertiaWorld.at(2, 2))]}');
}world inverse inertia diagonal [1.4118, 4.8000, 1.2000]
Vec3d velocityAt(Vec3d p)Velocity of the material point at world position p.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final b = RigidBody.dynamic(const BoxCollider(Vec3d(1, 0.5, 0.25)), mass: 2, position: const Vec3d(1, 0, 0));
b.angularVelocity = const Vec3d(0, 0, 2);
print('point (2, 0, 0) moves at ${d3(b.velocityAt(const Vec3d(2, 0, 0)))}');
}point (2, 0, 0) moves at (0.0000, 2.0000, 0.0000)
Vec3d toWorld(Vec3d local)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final b = RigidBody.dynamic(const BoxCollider(Vec3d(1, 0.5, 0.25)), mass: 2, position: const Vec3d(1, 0, 0));
b.orientation = Quatd.axisAngle(Vec3d.unitZ, math.pi / 2);
print('local (1, 0, 0) -> world ${d3(b.toWorld(Vec3d.unitX))}');
}local (1, 0, 0) -> world (1.0000, 1.0000, 0.0000)
Vec3d toLocal(Vec3d world)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final b = RigidBody.dynamic(const BoxCollider(Vec3d(1, 0.5, 0.25)), mass: 2, position: const Vec3d(1, 0, 0));
b.orientation = Quatd.axisAngle(Vec3d.unitZ, math.pi / 2);
print('world (1, 1, 0) -> local ${d3(b.toLocal(const Vec3d(1, 1, 0)))}');
}world (1, 1, 0) -> local (1.0000, 0.0000, 0.0000)
void applyForce(Vec3d f, {Vec3d? at})import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final w = PhysicsWorld(gravity: Vec3d.zero);
final b0 = RigidBody.dynamic(const BoxCollider(Vec3d(1, 0.5, 0.25)), mass: 2, position: const Vec3d(1, 0, 0));
final b = w.add(b0);
final path = <List<double>>[];
for (var i = 0; i < 30; i++) {
b.applyForce(const Vec3d(4, 0, 0)); // 2 m/s² on 2 kg
w.step(0.05);
path.add([w.time, b.position.x]);
}
print('x after 1.5 s: ${f(b.position.x)} (1 + ½·2·1.5² = 3.25)');
}x after 1.5 s: 3.3250 (1 + ½·2·1.5² = 3.25)
void applyTorque(Vec3d t)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final w = PhysicsWorld(gravity: Vec3d.zero);
final b0 = RigidBody.dynamic(const BoxCollider(Vec3d(1, 0.5, 0.25)), mass: 2, position: const Vec3d(1, 0, 0));
final b = w.add(b0);
for (var i = 0; i < 10; i++) {
b.applyTorque(const Vec3d(0, 0, 1));
w.step(0.1);
}
print('spin about z: ${f(b.angularVelocity.z)} rad/s');
}spin about z: 1.2000 rad/s
void applyImpulse(Vec3d j, {Vec3d? at})Applies impulse j (N \cdot s) at world point at (the centre of mass when null).
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final w = PhysicsWorld(gravity: Vec3d.zero);
final b0 = RigidBody.dynamic(const BoxCollider(Vec3d(1, 0.5, 0.25)), mass: 2, position: const Vec3d(1, 0, 0));
final b = w.add(b0);
b.applyImpulse(const Vec3d(0, 2, 0), at: const Vec3d(2, 0, 0));
print('linear ${d3(b.linearVelocity)}, angular ${d3(b.angularVelocity)}');
}linear (0.0000, 1.0000, 0.0000), angular (0.0000, 0.0000, 2.4000)
DynamicAabbTree
final class DynamicAabbTree
A dynamic AABB tree (the structure of Box2D's b2DynamicTree, written from Catto's description): leaves hold "fat" boxes inflated by margin so small motions don't touch the tree; insertion picks the sibling by the surface-area cost; AVL-style rotations keep it balanced. Insert, remove and move are O(\log n); overlap queries descend only boxes that overlap.
riptide_numerics_spatial (part C) builds static, flattened BVHs for queries and rendering; this tree is the incremental one bodies need every step. They could share node storage later.
Constructors
DynamicAabbTree({this.margin = 0.05})import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final t = DynamicAabbTree(margin: 0.1);
final ids = [for (var k = 0; k < 6; k++) t.insert(Aabb(Vec3d(k * 1.5, 0, 0), Vec3d(k * 1.5 + 1, 1, 1)), k)];
final hits = <int>[];
t.query(const Aabb(Vec3d(2, 0, 0), Vec3d(5, 1, 1)), hits.add);
print('boxes hit by [2, 5]: ${hits..sort()}');
}boxes hit by [2, 5]: [1, 2, 3]
Properties
final double marginint get rootint get heightTree height (0 for a single leaf); a balanced tree of n leaves is about log2 n.
Methods
Aabb fatBounds(int id)The fat box of proxy id.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final t = DynamicAabbTree(margin: 0.1);
final ids = [for (var k = 0; k < 6; k++) t.insert(Aabb(Vec3d(k * 1.5, 0, 0), Vec3d(k * 1.5 + 1, 1, 1)), k)];
final fb = t.fatBounds(ids[0]);
print('stored box ${d3(fb.min)} – ${d3(fb.max)} (inflated by the margin)');
}stored box (-0.1000, -0.1000, -0.1000) – (1.1000, 1.1000, 1.1000) (inflated by the margin)
int userData(int id)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final t = DynamicAabbTree(margin: 0.1);
final ids = [for (var k = 0; k < 6; k++) t.insert(Aabb(Vec3d(k * 1.5, 0, 0), Vec3d(k * 1.5 + 1, 1, 1)), k)];
print([for (final id in ids) t.userData(id)]);
}[0, 1, 2, 3, 4, 5]
int insert(Aabb box, int data)Inserts box for data; returns the proxy id.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final t = DynamicAabbTree();
final id = t.insert(const Aabb(Vec3d(0, 0, 0), Vec3d(1, 1, 1)), 42);
print('node $id holds ${t.userData(id)}, valid tree: ${t.validate()}');
}node 0 holds 42, valid tree: true
void remove(int id)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final t = DynamicAabbTree(margin: 0.1);
final ids = [for (var k = 0; k < 6; k++) t.insert(Aabb(Vec3d(k * 1.5, 0, 0), Vec3d(k * 1.5 + 1, 1, 1)), k)];
t.remove(ids[2]);
final hits = <int>[];
t.query(const Aabb(Vec3d(2, 0, 0), Vec3d(5, 1, 1)), hits.add);
print('after removing box 2: ${hits..sort()}, valid ${t.validate()}');
}after removing box 2: [1, 3], valid true
bool move(int id, Aabb box)Updates proxy id to box; reinserts only when it left its fat box. Returns true when it moved in the tree.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final t = DynamicAabbTree(margin: 0.1);
final ids = [for (var k = 0; k < 6; k++) t.insert(Aabb(Vec3d(k * 1.5, 0, 0), Vec3d(k * 1.5 + 1, 1, 1)), k)];
print('small move stays inside the fat box: ${t.move(ids[0], const Aabb(Vec3d(0.05, 0, 0), Vec3d(1.05, 1, 1)))}');
print('big move reinserts: ${t.move(ids[0], const Aabb(Vec3d(20, 0, 0), Vec3d(21, 1, 1)))}');
}small move stays inside the fat box: false big move reinserts: true
void query(Aabb box, void Function(int data) hit)Calls hit with the user data of every leaf whose fat box overlaps box.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final t = DynamicAabbTree(margin: 0.1);
final ids = [for (var k = 0; k < 6; k++) t.insert(Aabb(Vec3d(k * 1.5, 0, 0), Vec3d(k * 1.5 + 1, 1, 1)), k)];
var n = 0;
t.query(Aabb.everything, (_) => n++);
print('everything: $n boxes');
}everything: 6 boxes
bool validate()Checks parent links, heights and that every node box encloses its children (tests).
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final t = DynamicAabbTree(margin: 0.1);
final ids = [for (var k = 0; k < 6; k++) t.insert(Aabb(Vec3d(k * 1.5, 0, 0), Vec3d(k * 1.5 + 1, 1, 1)), k)];
print(t.validate());
}true
Aabb
final class Aabb
An axis-aligned box in double precision (broadphase bounds).
Constructors
const Aabb(this.min, this.max)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
const a = Aabb(Vec3d(0, 0, 0), Vec3d(2, 2, 2)), b = Aabb(Vec3d(1, 1, 1), Vec3d(3, 3, 3)), c = Aabb(Vec3d(0.5, 0.5, 0.5), Vec3d(1, 1, 1));
print('a: ${d3(a.min)} – ${d3(a.max)}, surface area ${a.area}');
}a: (0.0000, 0.0000, 0.0000) – (2.0000, 2.0000, 2.0000), surface area 24.0
Static
static const everything = Aabb(Vec3d(-1e30, -1e30, -1e30), Vec3d(1e30, 1e30, 1e30))Properties
final Vec3d minfinal Vec3d maxMethods
bool overlaps(Aabb o)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
const a = Aabb(Vec3d(0, 0, 0), Vec3d(2, 2, 2)), b = Aabb(Vec3d(1, 1, 1), Vec3d(3, 3, 3)), c = Aabb(Vec3d(0.5, 0.5, 0.5), Vec3d(1, 1, 1));
print('a and b: ${a.overlaps(b)}, b and c: ${b.overlaps(c)}');
}a and b: true, b and c: true
bool contains(Aabb o)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
const a = Aabb(Vec3d(0, 0, 0), Vec3d(2, 2, 2)), b = Aabb(Vec3d(1, 1, 1), Vec3d(3, 3, 3)), c = Aabb(Vec3d(0.5, 0.5, 0.5), Vec3d(1, 1, 1));
print('a contains c: ${a.contains(c)}, b contains c: ${b.contains(c)}');
}a contains c: true, b contains c: false
Aabb union(Aabb o)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
const a = Aabb(Vec3d(0, 0, 0), Vec3d(2, 2, 2)), b = Aabb(Vec3d(1, 1, 1), Vec3d(3, 3, 3)), c = Aabb(Vec3d(0.5, 0.5, 0.5), Vec3d(1, 1, 1));
final u = a.union(b);
print('${d3(u.min)} – ${d3(u.max)}');
}(0.0000, 0.0000, 0.0000) – (3.0000, 3.0000, 3.0000)
Aabb inflate(double m)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
const a = Aabb(Vec3d(0, 0, 0), Vec3d(2, 2, 2)), b = Aabb(Vec3d(1, 1, 1), Vec3d(3, 3, 3)), c = Aabb(Vec3d(0.5, 0.5, 0.5), Vec3d(1, 1, 1));
final i = c.inflate(0.25);
print('${d3(i.min)} – ${d3(i.max)}');
}(0.2500, 0.2500, 0.2500) – (1.2500, 1.2500, 1.2500)
Collider
sealed class Collider
A collision shape in its body's local frame. The body origin is the shape's centre of mass (compounds re-centre their children), so inertia tensors are about the origin.
Constructors
const Collider()import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
// Every shape answers bounds, mass properties and a convex view.
final List<Collider> shapes = [const SphereCollider(1), const BoxCollider(Vec3d(1, 1, 1)), const CapsuleCollider(0.5, 0.5)];
for (final s in shapes) {
print('${s.runtimeType.toString().padRight(16)} mass at ρ = 1: ${f(s.massProperties(1).mass)}');
}
}SphereCollider mass at ρ = 1: 4.1888 BoxCollider mass at ρ = 1: 8.0000 CapsuleCollider mass at ρ = 1: 1.3090
Methods
Aabb bounds(Vec3d p, Quatd q)World bounds at pose (p, q).
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final Collider c = const BoxCollider(Vec3d(2, 1, 1));
final b = c.bounds(Vec3d.zero, Quatd.axisAngle(Vec3d.unitZ, math.pi / 4));
print('min ${d3(b.min)}, max ${d3(b.max)}');
}min (-2.1213, -2.1213, -1.0000), max (2.1213, 2.1213, 1.0000)
MassProperties massProperties(double density)Mass properties at uniform density (kg/m³).
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final Collider c = const SphereCollider(0.1);
print('steel ball, r = 10 cm: ${f(c.massProperties(7850).mass)} kg');
}steel ball, r = 10 cm: 32.8820 kg
Convex? convexAt(Vec3d p, Quatd q)A support-function view for GJK/EPA at a pose (float32, riptide_math's Convex).
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final Collider c = const SphereCollider(1);
print('support +y at (0, 3, 0): ${c.convexAt(const Vec3d(0, 3, 0), Quatd.identity)!.support(Vec3(0, 1, 0)).y}');
}support +y at (0, 3, 0): 4.0
SphereCollider
final class SphereCollider extends Collider
Constructors
const SphereCollider(this.radius)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = const SphereCollider(0.5);
const p = Vec3d(1, 2, 0);
final q = Quatd.axisAngle(Vec3d.unitZ, math.pi / 6);
final b = c.bounds(p, q);
print('bounds at (1, 2) turned 30°: min ${d3(b.min)}, max ${d3(b.max)}');
}bounds at (1, 2) turned 30°: min (0.5000, 1.5000, -0.5000), max (1.5000, 2.5000, 0.5000)
Properties
final double radiusMethods
Aabb bounds(Vec3d p, Quatd q)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = const SphereCollider(0.5);
for (final deg in [0.0, 45.0]) {
final b = c.bounds(Vec3d.zero, Quatd.axisAngle(Vec3d.unitZ, deg * math.pi / 180));
print('turned $deg°: half size ${d3((b.max - b.min) * 0.5)}');
}
}turned 0.0°: half size (0.5000, 0.5000, 0.5000) turned 45.0°: half size (0.5000, 0.5000, 0.5000)
MassProperties massProperties(double density)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = const SphereCollider(0.5);
final m = c.massProperties(1000);
print('mass ${f(m.mass)} kg, centre ${d3(m.center)}');
print('inertia diagonal ${[f(m.inertia.at(0, 0)), f(m.inertia.at(1, 1)), f(m.inertia.at(2, 2))]}');
}mass 523.5988 kg, centre (0.0000, 0.0000, 0.0000) inertia diagonal [52.3599, 52.3599, 52.3599]
Convex convexAt(Vec3d p, Quatd q)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = const SphereCollider(0.5);
final cv = c.convexAt(const Vec3d(2, 0, 0), Quatd.identity)!;
final s = cv.support(Vec3(1, 0, 0));
print('farthest point along +x: (${f(s.x)}, ${f(s.y)}, ${f(s.z)})');
final pts = [for (var k = 0; k < 24; k++) cv.support(Vec3(math.cos(k * math.pi / 12), math.sin(k * math.pi / 12), 0))];
}farthest point along +x: (2.5000, 0.0000, 0.0000)
BoxCollider
final class BoxCollider extends Collider
Constructors
const BoxCollider(this.halfExtents)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = const BoxCollider(Vec3d(1, 0.5, 0.5));
const p = Vec3d(1, 2, 0);
final q = Quatd.axisAngle(Vec3d.unitZ, math.pi / 6);
final b = c.bounds(p, q);
print('bounds at (1, 2) turned 30°: min ${d3(b.min)}, max ${d3(b.max)}');
}bounds at (1, 2) turned 30°: min (-0.1160, 1.0670, -0.5000), max (2.1160, 2.9330, 0.5000)
Properties
final Vec3d halfExtentsMethods
Aabb bounds(Vec3d p, Quatd q)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = const BoxCollider(Vec3d(1, 0.5, 0.5));
for (final deg in [0.0, 45.0]) {
final b = c.bounds(Vec3d.zero, Quatd.axisAngle(Vec3d.unitZ, deg * math.pi / 180));
print('turned $deg°: half size ${d3((b.max - b.min) * 0.5)}');
}
}turned 0.0°: half size (1.0000, 0.5000, 0.5000) turned 45.0°: half size (1.0607, 1.0607, 0.5000)
MassProperties massProperties(double density)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = const BoxCollider(Vec3d(1, 0.5, 0.5));
final m = c.massProperties(1000);
print('mass ${f(m.mass)} kg, centre ${d3(m.center)}');
print('inertia diagonal ${[f(m.inertia.at(0, 0)), f(m.inertia.at(1, 1)), f(m.inertia.at(2, 2))]}');
}mass 2000.0000 kg, centre (0.0000, 0.0000, 0.0000) inertia diagonal [333.3333, 833.3333, 833.3333]
Convex convexAt(Vec3d p, Quatd q)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = const BoxCollider(Vec3d(1, 0.5, 0.5));
final cv = c.convexAt(const Vec3d(2, 0, 0), Quatd.identity)!;
final s = cv.support(Vec3(1, 0, 0));
print('farthest point along +x: (${f(s.x)}, ${f(s.y)}, ${f(s.z)})');
final pts = [for (var k = 0; k < 24; k++) cv.support(Vec3(math.cos(k * math.pi / 12), math.sin(k * math.pi / 12), 0))];
}farthest point along +x: (3.0000, 0.5000, 0.5000)
CapsuleCollider
final class CapsuleCollider extends Collider
A capsule along the local Y axis: the segment (0, ±halfHeight, 0) swept by a sphere of radius.
Constructors
const CapsuleCollider(this.halfHeight, this.radius)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = const CapsuleCollider(0.6, 0.3);
const p = Vec3d(1, 2, 0);
final q = Quatd.axisAngle(Vec3d.unitZ, math.pi / 6);
final b = c.bounds(p, q);
print('bounds at (1, 2) turned 30°: min ${d3(b.min)}, max ${d3(b.max)}');
}bounds at (1, 2) turned 30°: min (0.4000, 1.1804, -0.3000), max (1.6000, 2.8196, 0.3000)
Properties
final double halfHeightfinal double radiusMethods
(Vec3d, Vec3d) segment(Vec3d p, Quatd q)The segment end points in world space.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = const CapsuleCollider(1, 0.25);
final (a, b) = c.segment(Vec3d.zero, Quatd.axisAngle(Vec3d.unitZ, math.pi / 2));
print('core segment ${d3(a)} – ${d3(b)}');
}core segment (-1.0000, 0.0000, 0.0000) – (1.0000, 0.0000, 0.0000)
Aabb bounds(Vec3d p, Quatd q)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = const CapsuleCollider(0.6, 0.3);
for (final deg in [0.0, 45.0]) {
final b = c.bounds(Vec3d.zero, Quatd.axisAngle(Vec3d.unitZ, deg * math.pi / 180));
print('turned $deg°: half size ${d3((b.max - b.min) * 0.5)}');
}
}turned 0.0°: half size (0.3000, 0.9000, 0.3000) turned 45.0°: half size (0.7243, 0.7243, 0.3000)
MassProperties massProperties(double density)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = const CapsuleCollider(0.6, 0.3);
final m = c.massProperties(1000);
print('mass ${f(m.mass)} kg, centre ${d3(m.center)}');
print('inertia diagonal ${[f(m.inertia.at(0, 0)), f(m.inertia.at(1, 1)), f(m.inertia.at(2, 2))]}');
}mass 452.3893 kg, centre (0.0000, 0.0000, 0.0000) inertia diagonal [108.4038, 19.3396, 108.4038]
Convex convexAt(Vec3d p, Quatd q)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = const CapsuleCollider(0.6, 0.3);
final cv = c.convexAt(const Vec3d(2, 0, 0), Quatd.identity)!;
final s = cv.support(Vec3(1, 0, 0));
print('farthest point along +x: (${f(s.x)}, ${f(s.y)}, ${f(s.z)})');
final pts = [for (var k = 0; k < 24; k++) cv.support(Vec3(math.cos(k * math.pi / 12), math.sin(k * math.pi / 12), 0))];
}farthest point along +x: (2.3000, -0.6000, 0.0000)
ConvexHullCollider
final class ConvexHullCollider extends Collider
The convex hull of points (local frame). The points are re-centred on the hull's centre of mass when built.
Constructors
factory ConvexHullCollider(List<Vec3d> points)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = ConvexHullCollider([Vec3d.zero, const Vec3d(1, 0, 0), const Vec3d(0, 1, 0), const Vec3d(0, 0, 1)]);
const p = Vec3d(1, 2, 0);
final q = Quatd.axisAngle(Vec3d.unitZ, math.pi / 6);
final b = c.bounds(p, q);
print('bounds at (1, 2) turned 30°: min ${d3(b.min)}, max ${d3(b.max)}');
}bounds at (1, 2) turned 30°: min (0.4085, 1.6585, -0.2500), max (1.7745, 2.5245, 0.7500)
Properties
final Float32x4List pointsHull vertices in the local frame (centre of mass at the origin), as float32 lanes for GJK.
Methods
Aabb bounds(Vec3d p, Quatd q)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = ConvexHullCollider([Vec3d.zero, const Vec3d(1, 0, 0), const Vec3d(0, 1, 0), const Vec3d(0, 0, 1)]);
for (final deg in [0.0, 45.0]) {
final b = c.bounds(Vec3d.zero, Quatd.axisAngle(Vec3d.unitZ, deg * math.pi / 180));
print('turned $deg°: half size ${d3((b.max - b.min) * 0.5)}');
}
}turned 0.0°: half size (0.5000, 0.5000, 0.5000) turned 45.0°: half size (0.7071, 0.3536, 0.5000)
MassProperties massProperties(double density)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = ConvexHullCollider([Vec3d.zero, const Vec3d(1, 0, 0), const Vec3d(0, 1, 0), const Vec3d(0, 0, 1)]);
final m = c.massProperties(1000);
print('mass ${f(m.mass)} kg, centre ${d3(m.center)}');
print('inertia diagonal ${[f(m.inertia.at(0, 0)), f(m.inertia.at(1, 1)), f(m.inertia.at(2, 2))]}');
}mass 166.6667 kg, centre (0.0000, 0.0000, 0.0000) inertia diagonal [12.5000, 12.5000, 12.5000]
Convex convexAt(Vec3d p, Quatd q)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = ConvexHullCollider([Vec3d.zero, const Vec3d(1, 0, 0), const Vec3d(0, 1, 0), const Vec3d(0, 0, 1)]);
final cv = c.convexAt(const Vec3d(2, 0, 0), Quatd.identity)!;
final s = cv.support(Vec3(1, 0, 0));
print('farthest point along +x: (${f(s.x)}, ${f(s.y)}, ${f(s.z)})');
final pts = [for (var k = 0; k < 24; k++) cv.support(Vec3(math.cos(k * math.pi / 12), math.sin(k * math.pi / 12), 0))];
}farthest point along +x: (2.7500, -0.2500, -0.2500)
Iterable<Vec3d> worldPoints(Vec3d p, Quatd q)World-space vertices at a pose.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = ConvexHullCollider([Vec3d.zero, const Vec3d(1, 0, 0), const Vec3d(0, 1, 0), const Vec3d(0.3, 0.3, 1)]);
final pts = c.worldPoints(const Vec3d(2, 0, 0), Quatd.axisAngle(Vec3d.unitZ, 0.5)).toList();
print([for (final p in pts) d3(p)]);
}[(1.8706, -0.4410, -0.2500), (2.7482, 0.0384, -0.2500), (1.3912, 0.4366, -0.2500), (1.9900, -0.0339, 0.7500)]
PlaneCollider
final class PlaneCollider extends Collider
An infinite plane {x: n \cdot x = offset} in world space. Only for static bodies (the body's pose is ignored).
Constructors
PlaneCollider(Vec3d normal, this.offset)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = PlaneCollider(Vec3d.unitY, 0);
const p = Vec3d(1, 2, 0);
final q = Quatd.axisAngle(Vec3d.unitZ, math.pi / 6);
final b = c.bounds(p, q);
print('bounds at (1, 2) turned 30°: min ${d3(b.min)}, max ${d3(b.max)}');
}bounds at (1, 2) turned 30°: min (-1e+30, -1e+30, -1e+30), max (1e+30, 1e+30, 1e+30)
Properties
final Vec3d normalfinal double offsetMethods
Aabb bounds(Vec3d p, Quatd q)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = PlaneCollider(Vec3d.unitY, 0);
for (final deg in [0.0, 45.0]) {
final b = c.bounds(Vec3d.zero, Quatd.axisAngle(Vec3d.unitZ, deg * math.pi / 180));
print('turned $deg°: half size ${d3((b.max - b.min) * 0.5)}');
}
}turned 0.0°: half size (1e+30, 1e+30, 1e+30) turned 45.0°: half size (1e+30, 1e+30, 1e+30)
MassProperties massProperties(double density)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = PlaneCollider(Vec3d.unitY, 0);
final m = c.massProperties(1000);
print('a plane is static: mass ${m.mass}');
}a plane is static: mass 0.0
Convex? convexAt(Vec3d p, Quatd q)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = PlaneCollider(Vec3d.unitY, 0);
print('convexAt: ${c.convexAt(Vec3d.zero, Quatd.identity)} (an infinite plane is not a bounded convex)');
}convexAt: null (an infinite plane is not a bounded convex)
CompoundCollider
final class CompoundCollider extends Collider
Several shapes on one body. The constructor moves the children so the compound's centre of mass (at uniform density) is the body origin; shift is how far they moved (add it to a body position given for the old origin).
Constructors
factory CompoundCollider(List<CompoundChild> children)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = CompoundCollider([(shape: const SphereCollider(0.4), offset: const Vec3d(-0.6, 0, 0), rotation: Quatd.identity), (shape: const BoxCollider(Vec3d(0.3, 0.3, 0.3)), offset: const Vec3d(0.6, 0, 0), rotation: Quatd.identity)]);
const p = Vec3d(1, 2, 0);
final q = Quatd.axisAngle(Vec3d.unitZ, math.pi / 6);
final b = c.bounds(p, q);
print('bounds at (1, 2) turned 30°: min ${d3(b.min)}, max ${d3(b.max)}');
}bounds at (1, 2) turned 30°: min (0.1363, 1.3323, -0.4000), max (1.9853, 2.7421, 0.4000)
Properties
final List<CompoundChild> childrenfinal Vec3d shiftMethods
(Vec3d, Quatd) childPose(int i, Vec3d p, Quatd q)Child i's world pose for a body at (p, q).
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = CompoundCollider([(shape: const SphereCollider(0.4), offset: const Vec3d(-0.6, 0, 0), rotation: Quatd.identity), (shape: const BoxCollider(Vec3d(0.3, 0.3, 0.3)), offset: const Vec3d(0.6, 0, 0), rotation: Quatd.identity)]);
final (p, q) = c.childPose(1, const Vec3d(0, 0, 0), Quatd.axisAngle(Vec3d.unitZ, math.pi / 2));
print('child 1 world position ${d3(p)}');
}child 1 world position (0.0000, 0.6646, 0.0000)
Aabb bounds(Vec3d p, Quatd q)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = CompoundCollider([(shape: const SphereCollider(0.4), offset: const Vec3d(-0.6, 0, 0), rotation: Quatd.identity), (shape: const BoxCollider(Vec3d(0.3, 0.3, 0.3)), offset: const Vec3d(0.6, 0, 0), rotation: Quatd.identity)]);
for (final deg in [0.0, 45.0]) {
final b = c.bounds(Vec3d.zero, Quatd.axisAngle(Vec3d.unitZ, deg * math.pi / 180));
print('turned $deg°: half size ${d3((b.max - b.min) * 0.5)}');
}
}turned 0.0°: half size (0.9500, 0.4000, 0.4000) turned 45.0°: half size (0.8364, 0.8364, 0.4000)
MassProperties massProperties(double density)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = CompoundCollider([(shape: const SphereCollider(0.4), offset: const Vec3d(-0.6, 0, 0), rotation: Quatd.identity), (shape: const BoxCollider(Vec3d(0.3, 0.3, 0.3)), offset: const Vec3d(0.6, 0, 0), rotation: Quatd.identity)]);
final m = c.massProperties(1000);
print('mass ${f(m.mass)} kg, centre ${d3(m.center)}');
print('inertia diagonal ${[f(m.inertia.at(0, 0)), f(m.inertia.at(1, 1)), f(m.inertia.at(2, 2))]}');
}mass 484.0826 kg, centre (0.0000, 0.0000, 0.0000) inertia diagonal [30.1173, 202.3697, 202.3697]
Convex? convexAt(Vec3d p, Quatd q)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = CompoundCollider([(shape: const SphereCollider(0.4), offset: const Vec3d(-0.6, 0, 0), rotation: Quatd.identity), (shape: const BoxCollider(Vec3d(0.3, 0.3, 0.3)), offset: const Vec3d(0.6, 0, 0), rotation: Quatd.identity)]);
// A compound of several children is not one convex shape: narrowphase tests each child instead.
print('convexAt: ${c.convexAt(Vec3d.zero, Quatd.identity)}');
final one = CompoundCollider([(shape: const SphereCollider(0.5), offset: const Vec3d(1, 0, 0), rotation: Quatd.identity)]);
final cv = one.convexAt(Vec3d.zero, Quatd.identity);
print('a single child: ${cv == null ? 'null' : 'support(+x) x = ${cv.support(Vec3(1, 0, 0)).x}'}');
}convexAt: null a single child: null
ManifoldPoint
final class ManifoldPoint
One persistent contact point between two bodies. Anchors are stored in each body's frame so the point can be re-evaluated after the bodies move (position correction, manifold persistence) and matched across steps for warm starting.
Constructors
ManifoldPoint(this.localA, this.localB, this.depth)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final a = RigidBody.static(const BoxCollider(Vec3d(2, 0.5, 2)));
final b = RigidBody.dynamic(const BoxCollider(Vec3d(0.5, 0.5, 0.5)), position: const Vec3d(0, 0.95, 0));
b.linearVelocity = const Vec3d(0, -1, 0);
final m = ContactManifold(a, b, 0, 0)..normal = Vec3d.unitY;
m.points.add(ManifoldPoint(const Vec3d(0, 0.5, 0), const Vec3d(0, -0.5, 0), 0.05));
final p = m.points.first;
print('depth ${p.depth}, local points ${d3(p.localA)} and ${d3(p.localB)}');
}depth 0.05, local points (0.0000, 0.5000, 0.0000) and (0.0000, -0.5000, 0.0000)
Properties
Vec3d localAThe point on A's surface deepest inside B, and on B's surface deepest inside A, in body frames.
Vec3d localBThe point on A's surface deepest inside B, and on B's surface deepest inside A, in body frames.
double depthdouble normalImpulsedouble tangentImpulse1double tangentImpulse2Vec3d rAVec3d rBdouble normalMassdouble tangentMass1double tangentMass2double velocityBiasContactManifold
final class ContactManifold
The contact manifold of a body pair: one normal (A to B) and up to 4 points.
Constructors
ContactManifold(this.a, this.b, this.shapeA, this.shapeB)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final a = RigidBody.static(const BoxCollider(Vec3d(2, 0.5, 2)));
final b = RigidBody.dynamic(const BoxCollider(Vec3d(0.5, 0.5, 0.5)), position: const Vec3d(0, 0.95, 0));
b.linearVelocity = const Vec3d(0, -1, 0);
final m = ContactManifold(a, b, 0, 0)..normal = Vec3d.unitY;
m.points.add(ManifoldPoint(const Vec3d(0, 0.5, 0), const Vec3d(0, -0.5, 0), 0.05));
print('${m.points.length} point, normal ${d3(m.normal)}, friction ${m.friction}');
}1 point, normal (0.0000, 1.0000, 0.0000), friction 0.5
Properties
final RigidBody afinal RigidBody bVec3d normalfinal pointsVec3d t1Vec3d t2double frictiondouble restitutionMethods
Vec3d worldA(ManifoldPoint p)Builds world anchors from the stored local ones.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final a = RigidBody.static(const BoxCollider(Vec3d(2, 0.5, 2)));
final b = RigidBody.dynamic(const BoxCollider(Vec3d(0.5, 0.5, 0.5)), position: const Vec3d(0, 0.95, 0));
b.linearVelocity = const Vec3d(0, -1, 0);
final m = ContactManifold(a, b, 0, 0)..normal = Vec3d.unitY;
m.points.add(ManifoldPoint(const Vec3d(0, 0.5, 0), const Vec3d(0, -0.5, 0), 0.05));
print('on A: ${d3(m.worldA(m.points.first))}');
}on A: (0.0000, 0.5000, 0.0000)
Vec3d worldB(ManifoldPoint p)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final a = RigidBody.static(const BoxCollider(Vec3d(2, 0.5, 2)));
final b = RigidBody.dynamic(const BoxCollider(Vec3d(0.5, 0.5, 0.5)), position: const Vec3d(0, 0.95, 0));
b.linearVelocity = const Vec3d(0, -1, 0);
final m = ContactManifold(a, b, 0, 0)..normal = Vec3d.unitY;
m.points.add(ManifoldPoint(const Vec3d(0, 0.5, 0), const Vec3d(0, -0.5, 0), 0.05));
print('on B: ${d3(m.worldB(m.points.first))}');
}on B: (0.0000, 0.4500, 0.0000)
SolverSettings
final class SolverSettings
Solver settings. Defaults follow Box2D v2.4: 8 velocity and 3 position iterations, 5 mm slop, 0.2 correction.
Constructors
const SolverSettings({this.velocityIterations = 10, this.positionIterations = 4, this.slop = 0.005, this.baumgarte = 0.2, this.maxCorrection = 0.2, this.restitutionThreshold = 1.0, this.warmStarting = true})import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
const s = SolverSettings(velocityIterations: 20, slop: 0.001);
print('${s.velocityIterations} velocity iterations, slop ${s.slop}, baumgarte ${s.baumgarte}');
}20 velocity iterations, slop 0.001, baumgarte 0.2
Properties
final int velocityIterationsfinal int positionIterationsfinal double slopPenetration allowed without correction (m), so resting contacts stay touching.
final double maxCorrectionfinal double restitutionThresholdApproach speed (m/s) below which restitution is ignored, so resting bodies don't jitter.
final bool warmStartingContactSolver
final class ContactSolver
Sequential impulses (Catto, GDC 2005–2009): per contact, a normal impulse clamped to push only, two friction impulses clamped to the Coulomb pyramid \mu\lambda_{n}, restitution as a velocity bias, accumulated across iterations and warm started from the last step. Penetration is removed afterwards on positions (solvePositions), so the velocity solve adds no energy (elastic collisions conserve it).
Constructors
ContactSolver(this.settings)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final a = RigidBody.static(const BoxCollider(Vec3d(2, 0.5, 2)));
final b = RigidBody.dynamic(const BoxCollider(Vec3d(0.5, 0.5, 0.5)), position: const Vec3d(0, 0.95, 0));
b.linearVelocity = const Vec3d(0, -1, 0);
final m = ContactManifold(a, b, 0, 0)..normal = Vec3d.unitY;
m.points.add(ManifoldPoint(const Vec3d(0, 0.5, 0), const Vec3d(0, -0.5, 0), 0.05));
final s = ContactSolver(const SolverSettings());
s.prepare([m]);
s.solveVelocities([m]);
print('approach speed removed: v_y = ${f(b.linearVelocity.y)}');
}approach speed removed: v_y = 0.0000
Properties
final SolverSettings settingsMethods
void prepare(List<ContactManifold> manifolds)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final a = RigidBody.static(const BoxCollider(Vec3d(2, 0.5, 2)));
final b = RigidBody.dynamic(const BoxCollider(Vec3d(0.5, 0.5, 0.5)), position: const Vec3d(0, 0.95, 0));
b.linearVelocity = const Vec3d(0, -1, 0);
final m = ContactManifold(a, b, 0, 0)..normal = Vec3d.unitY;
m.points.add(ManifoldPoint(const Vec3d(0, 0.5, 0), const Vec3d(0, -0.5, 0), 0.05));
ContactSolver(const SolverSettings()).prepare([m]);
print('effective mass along the normal: ${f(m.points.first.normalMass)} kg');
}effective mass along the normal: 1000.0000 kg
void solveVelocities(List<ContactManifold> manifolds)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final a = RigidBody.static(const BoxCollider(Vec3d(2, 0.5, 2)));
final b = RigidBody.dynamic(const BoxCollider(Vec3d(0.5, 0.5, 0.5)), position: const Vec3d(0, 0.95, 0));
b.linearVelocity = const Vec3d(0, -1, 0);
final m = ContactManifold(a, b, 0, 0)..normal = Vec3d.unitY;
m.points.add(ManifoldPoint(const Vec3d(0, 0.5, 0), const Vec3d(0, -0.5, 0), 0.05));
final s = ContactSolver(const SolverSettings());
s.prepare([m]);
s.solveVelocities([m]);
print('normal impulse ${f(m.points.first.normalImpulse)} N·s');
}normal impulse 1000.0000 N·s
double solvePositions(List<ContactManifold> manifolds)Non-linear Gauss–Seidel on positions (Box2D's solvePositionConstraints): moves and rotates bodies to remove penetration beyond SolverSettings.slop, without touching velocities. Returns the deepest remaining penetration.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final a = RigidBody.static(const BoxCollider(Vec3d(2, 0.5, 2)));
final b = RigidBody.dynamic(const BoxCollider(Vec3d(0.5, 0.5, 0.5)), position: const Vec3d(0, 0.95, 0));
b.linearVelocity = const Vec3d(0, -1, 0);
final m = ContactManifold(a, b, 0, 0)..normal = Vec3d.unitY;
m.points.add(ManifoldPoint(const Vec3d(0, 0.5, 0), const Vec3d(0, -0.5, 0), 0.05));
final s = ContactSolver(const SolverSettings());
final err = s.solvePositions([m]);
print('largest penetration before correction: ${f(err)}; box moved up to y = ${f(b.position.y)}');
}largest penetration before correction: 0.0500; box moved up to y = 0.9590
Joint
sealed class Joint
A constraint between two bodies, solved with the contacts by sequential impulses. Position drift is fed back as a Baumgarte velocity bias (\frac{\beta}{dt} \cdot C).
Constructors
Joint(this.a, this.b)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final w = PhysicsWorld(gravity: const Vec3d(0, -9.81, 0));
final a = w.add(RigidBody.static(const SphereCollider(0.05), position: const Vec3d(0, 2, 0)));
final b = w.add(RigidBody.dynamic(const BoxCollider(Vec3d(0.4, 0.1, 0.1)), position: const Vec3d(0.5, 2, 0)));
final Joint j = BallJoint(a, b, const Vec3d(0, 2, 0));
print('joint between ${j.a.type.name} and ${j.b.type.name} bodies');
}joint between static and dynamic bodies
Properties
final RigidBody afinal RigidBody bMethods
void prepare(double dt, {required bool warmStart})import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final w = PhysicsWorld(gravity: const Vec3d(0, -9.81, 0));
final a = w.add(RigidBody.static(const SphereCollider(0.05), position: const Vec3d(0, 2, 0)));
final b = w.add(RigidBody.dynamic(const BoxCollider(Vec3d(0.4, 0.1, 0.1)), position: const Vec3d(0.5, 2, 0)));
final Joint j = DistanceJoint(a, b, const Vec3d(0, 2, 0), const Vec3d(0.5, 2, 0));
j.prepare(0.01, warmStart: true);
print('ok');
}ok
void solveVelocity()import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final w = PhysicsWorld(gravity: const Vec3d(0, -9.81, 0));
final a = w.add(RigidBody.static(const SphereCollider(0.05), position: const Vec3d(0, 2, 0)));
final b = w.add(RigidBody.dynamic(const BoxCollider(Vec3d(0.4, 0.1, 0.1)), position: const Vec3d(0.5, 2, 0)));
b.linearVelocity = const Vec3d(1, 0, 0);
final Joint j = DistanceJoint(a, b, const Vec3d(0, 2, 0), const Vec3d(0.5, 2, 0));
j.prepare(0.01, warmStart: false);
j.solveVelocity();
print('stretching speed removed: v = ${d3(b.linearVelocity)}');
}stretching speed removed: v = (0.0000, 0.0000, 0.0000)
BallJoint
final class BallJoint extends Joint
Ball-and-socket: the anchor points coincide (3 linear constraints).
Constructors
BallJoint(super.a, super.b, Vec3d anchor)anchor in world space at creation.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final w = PhysicsWorld(gravity: const Vec3d(0, -9.81, 0));
final a = w.add(RigidBody.static(const SphereCollider(0.05), position: const Vec3d(0, 2, 0)));
final b = w.add(RigidBody.dynamic(const BoxCollider(Vec3d(0.4, 0.1, 0.1)), position: const Vec3d(0.5, 2, 0)));
w.addJoint(BallJoint(a, b, const Vec3d(0, 2, 0)));
for (var i = 0; i < 90; i++) {
w.step(1 / 60);
}
print('after 1.5 s the bar end is at ${d3(b.toWorld(const Vec3d(-0.5, 0, 0)))} (anchor (0, 2, 0))');
print('bar centre ${d3(b.position)}');
}after 1.5 s the bar end is at (0.0019, 1.9915, 0.0000) (anchor (0, 2, 0)) bar centre (0.2876, 1.5811, 0.0000)
Properties
final Vec3d localAfinal Vec3d localBMethods
void prepare(double dt, {required bool warmStart})import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final w = PhysicsWorld(gravity: const Vec3d(0, -9.81, 0));
final a = w.add(RigidBody.static(const SphereCollider(0.05), position: const Vec3d(0, 2, 0)));
final b = w.add(RigidBody.dynamic(const BoxCollider(Vec3d(0.4, 0.1, 0.1)), position: const Vec3d(0.5, 2, 0)));
final j = BallJoint(a, b, const Vec3d(0, 2, 0));
j.prepare(1 / 60, warmStart: false);
print('prepared: anchors and effective masses computed for one step');
j.solveVelocity();
print('b velocity after one solve ${d3(b.linearVelocity)}');
}prepared: anchors and effective masses computed for one step b velocity after one solve (0.0000, 0.0000, 0.0000)
void solveVelocity()import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final w = PhysicsWorld(gravity: const Vec3d(0, -9.81, 0));
final a = w.add(RigidBody.static(const SphereCollider(0.05), position: const Vec3d(0, 2, 0)));
final b = w.add(RigidBody.dynamic(const BoxCollider(Vec3d(0.4, 0.1, 0.1)), position: const Vec3d(0.5, 2, 0)));
b.linearVelocity = const Vec3d(0, 0, 0);
b.angularVelocity = const Vec3d(0, 0, 3);
final j = BallJoint(a, b, const Vec3d(0, 2, 0));
j.prepare(1 / 60, warmStart: false);
for (var k = 0; k < 10; k++) {
j.solveVelocity();
}
print('anchor velocity after solving: ${d3(b.velocityAt(const Vec3d(0, 2, 0)) - a.velocityAt(const Vec3d(0, 2, 0)))}');
}anchor velocity after solving: (0.0000, 0.0000, 0.0000)
DistanceJoint
final class DistanceJoint extends Joint
Keeps the anchors at length apart (a rigid rod; 1 constraint along the line between them).
Constructors
DistanceJoint(super.a, super.b, Vec3d anchorA, Vec3d anchorB, {double? length})import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final w = PhysicsWorld(gravity: const Vec3d(0, -9.81, 0));
final a = w.add(RigidBody.static(const SphereCollider(0.05), position: const Vec3d(0, 2, 0)));
final b = w.add(RigidBody.dynamic(const BoxCollider(Vec3d(0.4, 0.1, 0.1)), position: const Vec3d(0.5, 2, 0)));
w.addJoint(DistanceJoint(a, b, const Vec3d(0, 2, 0), const Vec3d(0.5, 2, 0)));
for (var i = 0; i < 90; i++) {
w.step(1 / 60);
}
print('after 1.5 s the bar end is at ${d3(b.toWorld(const Vec3d(-0.5, 0, 0)))} (anchor (0, 2, 0))');
print('bar centre ${d3(b.position)}');
}after 1.5 s the bar end is at (-0.0237, 1.8262, 0.0000) (anchor (0, 2, 0)) bar centre (0.4763, 1.8262, 0.0000)
Properties
final Vec3d localAfinal Vec3d localBfinal double lengthMethods
void prepare(double dt, {required bool warmStart})import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final w = PhysicsWorld(gravity: const Vec3d(0, -9.81, 0));
final a = w.add(RigidBody.static(const SphereCollider(0.05), position: const Vec3d(0, 2, 0)));
final b = w.add(RigidBody.dynamic(const BoxCollider(Vec3d(0.4, 0.1, 0.1)), position: const Vec3d(0.5, 2, 0)));
final j = DistanceJoint(a, b, const Vec3d(0, 2, 0), const Vec3d(0.5, 2, 0));
j.prepare(1 / 60, warmStart: false);
print('prepared: anchors and effective masses computed for one step');
j.solveVelocity();
print('b velocity after one solve ${d3(b.linearVelocity)}');
}prepared: anchors and effective masses computed for one step b velocity after one solve (0.0000, 0.0000, 0.0000)
void solveVelocity()import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final w = PhysicsWorld(gravity: const Vec3d(0, -9.81, 0));
final a = w.add(RigidBody.static(const SphereCollider(0.05), position: const Vec3d(0, 2, 0)));
final b = w.add(RigidBody.dynamic(const BoxCollider(Vec3d(0.4, 0.1, 0.1)), position: const Vec3d(0.5, 2, 0)));
b.linearVelocity = const Vec3d(0, 0, 0);
b.angularVelocity = const Vec3d(0, 0, 3);
final j = DistanceJoint(a, b, const Vec3d(0, 2, 0), const Vec3d(0.5, 2, 0));
j.prepare(1 / 60, warmStart: false);
for (var k = 0; k < 10; k++) {
j.solveVelocity();
}
print('anchor velocity after solving: ${d3(b.velocityAt(const Vec3d(0, 2, 0)) - a.velocityAt(const Vec3d(0, 2, 0)))}');
}anchor velocity after solving: (0.0000, -1.5000, 0.0000)
HingeJoint
final class HingeJoint extends Joint
A hinge: a ball joint plus 2 angular constraints keeping body B's axis aligned with body A's, so the only relative rotation is about the axis.
Constructors
HingeJoint(super.a, super.b, Vec3d anchor, Vec3d axis)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final w = PhysicsWorld(gravity: const Vec3d(0, -9.81, 0));
final a = w.add(RigidBody.static(const SphereCollider(0.05), position: const Vec3d(0, 2, 0)));
final b = w.add(RigidBody.dynamic(const BoxCollider(Vec3d(0.4, 0.1, 0.1)), position: const Vec3d(0.5, 2, 0)));
w.addJoint(HingeJoint(a, b, const Vec3d(0, 2, 0), Vec3d.unitZ));
for (var i = 0; i < 90; i++) {
w.step(1 / 60);
}
print('after 1.5 s the bar end is at ${d3(b.toWorld(const Vec3d(-0.5, 0, 0)))} (anchor (0, 2, 0))');
print('bar centre ${d3(b.position)}');
}after 1.5 s the bar end is at (0.0019, 1.9915, 0.0000) (anchor (0, 2, 0)) bar centre (0.2876, 1.5811, 0.0000)
Properties
final Vec3d axisAfinal Vec3d axisBdouble get twistParameterThe hinge's twist as a Cayley parameter, tan(angle/2): read off the relative rotation's quaternion with one division (swing–twist), no trigonometry. Monotonic in the angle on (-\pi, \pi), so limits given as parameters compare directly; ±infinity at a half turn.
double get angleThe hinge angle of B relative to A about the axis, in radians in (-\pi, \pi] (the boundary form of twistParameter, for display and radians-based APIs).
Methods
void prepare(double dt, {required bool warmStart})import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final w = PhysicsWorld(gravity: const Vec3d(0, -9.81, 0));
final a = w.add(RigidBody.static(const SphereCollider(0.05), position: const Vec3d(0, 2, 0)));
final b = w.add(RigidBody.dynamic(const BoxCollider(Vec3d(0.4, 0.1, 0.1)), position: const Vec3d(0.5, 2, 0)));
final j = HingeJoint(a, b, const Vec3d(0, 2, 0), Vec3d.unitZ);
j.prepare(1 / 60, warmStart: false);
print('prepared: anchors and effective masses computed for one step');
j.solveVelocity();
print('b velocity after one solve ${d3(b.linearVelocity)}');
}prepared: anchors and effective masses computed for one step b velocity after one solve (0.0000, 0.0000, 0.0000)
void solveVelocity()import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final w = PhysicsWorld(gravity: const Vec3d(0, -9.81, 0));
final a = w.add(RigidBody.static(const SphereCollider(0.05), position: const Vec3d(0, 2, 0)));
final b = w.add(RigidBody.dynamic(const BoxCollider(Vec3d(0.4, 0.1, 0.1)), position: const Vec3d(0.5, 2, 0)));
b.linearVelocity = const Vec3d(0, 0, 0);
b.angularVelocity = const Vec3d(0, 0, 3);
final j = HingeJoint(a, b, const Vec3d(0, 2, 0), Vec3d.unitZ);
j.prepare(1 / 60, warmStart: false);
for (var k = 0; k < 10; k++) {
j.solveVelocity();
}
print('anchor velocity after solving: ${d3(b.velocityAt(const Vec3d(0, 2, 0)) - a.velocityAt(const Vec3d(0, 2, 0)))}');
}anchor velocity after solving: (0.0000, 0.0000, 0.0000)
FixedJoint
final class FixedJoint extends Joint
Welds two bodies: point constraint + 3 angular constraints holding their relative orientation.
Constructors
FixedJoint(super.a, super.b, Vec3d anchor)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final w = PhysicsWorld(gravity: const Vec3d(0, -9.81, 0));
final a = w.add(RigidBody.static(const SphereCollider(0.05), position: const Vec3d(0, 2, 0)));
final b = w.add(RigidBody.dynamic(const BoxCollider(Vec3d(0.4, 0.1, 0.1)), position: const Vec3d(0.5, 2, 0)));
w.addJoint(FixedJoint(a, b, const Vec3d(0, 2, 0)));
for (var i = 0; i < 90; i++) {
w.step(1 / 60);
}
print('after 1.5 s the bar end is at ${d3(b.toWorld(const Vec3d(-0.5, 0, 0)))} (anchor (0, 2, 0))');
print('bar centre ${d3(b.position)}');
}after 1.5 s the bar end is at (0.0000, 2.0000, 0.0000) (anchor (0, 2, 0)) bar centre (0.5000, 2.0000, 0.0000)
Methods
void prepare(double dt, {required bool warmStart})import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final w = PhysicsWorld(gravity: const Vec3d(0, -9.81, 0));
final a = w.add(RigidBody.static(const SphereCollider(0.05), position: const Vec3d(0, 2, 0)));
final b = w.add(RigidBody.dynamic(const BoxCollider(Vec3d(0.4, 0.1, 0.1)), position: const Vec3d(0.5, 2, 0)));
final j = FixedJoint(a, b, const Vec3d(0, 2, 0));
j.prepare(1 / 60, warmStart: false);
print('prepared: anchors and effective masses computed for one step');
j.solveVelocity();
print('b velocity after one solve ${d3(b.linearVelocity)}');
}prepared: anchors and effective masses computed for one step b velocity after one solve (0.0000, 0.0000, 0.0000)
void solveVelocity()import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final w = PhysicsWorld(gravity: const Vec3d(0, -9.81, 0));
final a = w.add(RigidBody.static(const SphereCollider(0.05), position: const Vec3d(0, 2, 0)));
final b = w.add(RigidBody.dynamic(const BoxCollider(Vec3d(0.4, 0.1, 0.1)), position: const Vec3d(0.5, 2, 0)));
b.linearVelocity = const Vec3d(0, 0, 0);
b.angularVelocity = const Vec3d(0, 0, 3);
final j = FixedJoint(a, b, const Vec3d(0, 2, 0));
j.prepare(1 / 60, warmStart: false);
for (var k = 0; k < 10; k++) {
j.solveVelocity();
}
print('anchor velocity after solving: ${d3(b.velocityAt(const Vec3d(0, 2, 0)) - a.velocityAt(const Vec3d(0, 2, 0)))}');
}anchor velocity after solving: (0.0000, 0.0441, 0.0000)
BroadphaseKind
enum BroadphaseKind
Which broadphase finds candidate pairs.
Values
treeIncremental dynamic AABB tree (default; best when most bodies move a little each step).
sweepAndPruneSweep and prune on X, rebuilt each step (riptide_math's Broadphase); fine for a few hundred bodies.
PhysicsWorld
final class PhysicsWorld
A rigid-body world: integrate forces, find contacts (broadphase, narrowphase, persistent manifolds), solve contacts and joints by sequential impulses, integrate positions, then correct penetration on positions.
Step with a fixed step dt (\frac{1}{60} s is typical); SI units throughout.
Constructors
PhysicsWorld({this.gravity = const Vec3d(0, -9.81, 0), this.settings = const SolverSettings(), this.broadphase = BroadphaseKind.tree, this.gyroscopic = true, this.sleeping = false})import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final w = PhysicsWorld();
w.add(RigidBody.static(PlaneCollider(Vec3d.unitY, 0)));
final ball = w.add(RigidBody.dynamic(const SphereCollider(0.5), position: const Vec3d(0, 5, 0))..restitution = 0.6);
final path = <List<double>>[];
for (var i = 0; i < 240; i++) {
w.step(1 / 60);
path.add([w.time, ball.position.y]);
}
print('after 4 s: height ${f(ball.position.y)}');
}after 4 s: height 0.5028
Properties
Vec3d gravityfinal SolverSettings settingsfinal BroadphaseKind broadphasefinal bool gyroscopicIntegrate the gyroscopic term \omega \times I\omega implicitly (Catto 2015), so free spinning bodies keep their angular momentum. Without it, \omega stays constant in world frame, which is wrong for asymmetric bodies.
final bool sleepingPut bodies to sleep after sleepDelay s below sleepLinear / sleepAngular; contacts wake them.
double sleepLineardouble sleepAngulardouble sleepDelayfinal bodiesfinal jointsdouble timedouble get potentialEnergyGravitational potential energy relative to the origin (J).
Vec3d get linearMomentumVec3d get angularMomentumMethods
RigidBody add(RigidBody body)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final w = PhysicsWorld();
w.add(RigidBody.static(PlaneCollider(Vec3d.unitY, 0)));
final ball = w.add(RigidBody.dynamic(const SphereCollider(0.5), position: const Vec3d(0, 5, 0))..restitution = 0.6);
print('${w.bodies.length} bodies; the ball got id ${ball.id}');
}2 bodies; the ball got id 1
Joint addJoint(Joint j)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final w = PhysicsWorld();
final anchor = w.add(RigidBody.static(const SphereCollider(0.05), position: const Vec3d(0, 3, 0)));
final bob = w.add(RigidBody.dynamic(const SphereCollider(0.2), position: const Vec3d(1, 3, 0)));
w.addJoint(DistanceJoint(anchor, bob, const Vec3d(0, 3, 0), const Vec3d(1, 3, 0)));
final path = <List<double>>[];
for (var i = 0; i < 120; i++) {
w.step(1 / 60);
path.add([bob.position.x, bob.position.y]);
}
print('rope length kept: ${f((bob.position - anchor.position).length)}');
}rope length kept: 1.0102
void step(double dt)Advances the world by dt seconds.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final w = PhysicsWorld();
w.add(RigidBody.static(PlaneCollider(Vec3d.unitY, 0)));
final ball = w.add(RigidBody.dynamic(const SphereCollider(0.5), position: const Vec3d(0, 5, 0))..restitution = 0.6);
for (var i = 0; i < 60; i++) {
w.step(1 / 60);
}
print('t = ${f(w.time)}, kinetic ${f(w.kineticEnergy)} J');
}t = 1.0000, kinetic 7529.2519 J
List<RigidBody> queryAabb(Aabb box)Bodies whose (fat) bounds overlap box.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final w = PhysicsWorld();
w.add(RigidBody.static(PlaneCollider(Vec3d.unitY, 0)));
final ball = w.add(RigidBody.dynamic(const SphereCollider(0.5), position: const Vec3d(0, 5, 0))..restitution = 0.6);
final hits = w.queryAabb(const Aabb(Vec3d(-1, 4, -1), Vec3d(1, 6, 1)));
print('bodies in the box around the ball: ${hits.length}');
}bodies in the box around the ball: 2
XpbdBody
final class XpbdBody
A particle system solved with extended position-based dynamics (Macklin, Müller and Chentanez, "XPBD", 2016) using small substeps with one constraint iteration each (Macklin et al. "Small Steps in Physics Simulation", 2019): stiffness is set by compliance \alpha (m/N; 0 = rigid) and doesn't depend on the step or iteration count.
Constraints: distance (stretch and shear; bending as distance across two cells for cloth), tetrahedral volume (soft solids), and collision with rigid bodies' shapes (plane, sphere, capsule, box; one-way: the rigid bodies aren't pushed back yet).
Constructors
XpbdBody(int count)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
// A rope of 10 particles, the first pinned.
final r = XpbdBody(10);
for (var i = 0; i < 10; i++) {
r.setPosition(i, Vec3d(i * 0.2, 0, 0));
if (i > 0) r.addDistance(i - 1, i);
}
r.invMass[0] = 0;
for (var k = 0; k < 60; k++) {
r.step(1 / 60);
}
final pts = [for (var i = 0; i < 10; i++) r.position(i)];
print('tip after 1 s: ${d3(pts.last)}; max strain ${r.maxStrain().toStringAsExponential(2)}');
}tip after 1 s: (-1.6038, -0.8027, 0.0000); max strain 1.66e-3
Properties
final Float64List xPositions, previous positions and velocities (interleaved xyz) and inverse masses (0 = pinned).
final Float64List prevPositions, previous positions and velocities (interleaved xyz) and inverse masses (0 = pinned).
final Float64List vPositions, previous positions and velocities (interleaved xyz) and inverse masses (0 = pinned).
final Float64List invMassPositions, previous positions and velocities (interleaved xyz) and inverse masses (0 = pinned).
int get countVec3d gravitydouble frictionFriction coefficient against colliders (position-level, Müller et al. 2007 style).
int get distanceConstraintCountint get volumeConstraintCountdouble get volumeCurrent total volume of the tetrahedra (each counted with its rest orientation, so inverted tets subtract).
double get restVolumedouble get kineticEnergyMethods
Vec3d position(int i)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final r = XpbdBody(2)..setPosition(1, const Vec3d(1, 2, 3));
print(d3(r.position(1)));
}(1.0000, 2.0000, 3.0000)
void setPosition(int i, Vec3d p)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final r = XpbdBody(3);
for (var i = 0; i < 3; i++) {
r.setPosition(i, Vec3d(i.toDouble(), 0, 0));
}
print(r.x);
}[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 2.0, 0.0, 0.0]
void addDistance(int i, int j, {double compliance = 0})Adds a distance constraint between i and j at their current separation.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final r = XpbdBody(2)..setPosition(1, const Vec3d(1, 0, 0));
r.addDistance(0, 1, compliance: 1e-3);
r.gravity = Vec3d.zero;
r.setPosition(1, const Vec3d(2, 0, 0)); // stretched to twice its rest length
r.step(1 / 60);
print('distance after one step: ${f((r.position(1) - r.position(0)).length)}');
}distance after one step: 1.7157
void addVolume(int a, int b, int c, int d, {double compliance = 0})Adds a tetrahedral volume constraint (vertices in any order; the rest volume keeps its sign).
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final b = XpbdBody(4);
b.setPosition(1, const Vec3d(1, 0, 0));
b.setPosition(2, const Vec3d(0, 1, 0));
b.setPosition(3, const Vec3d(0, 0, 1));
b.addVolume(0, 1, 2, 3);
print('rest volume ${f(b.restVolume)} (1/6)');
}rest volume 0.1667 (1/6)
double maxStrain({double maxCompliance = 0})Largest relative stretch \frac{|l - l_{0}|}{l_{0}} over the distance constraints with compliance ≤ maxCompliance (by default the rigid ones: compliant bending constraints shorten wherever the cloth folds).
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final cloth = SoftBodies.cloth(nx: 6, ny: 6, width: 1, height: 1);
for (var k = 0; k < 30; k++) {
cloth.step(1 / 60);
}
print('largest relative stretch ${cloth.maxStrain().toStringAsExponential(2)}');
}largest relative stretch 0.00e+0
void step(double dt, {int substeps = 10})Advances dt seconds in substeps substeps (each: predict, solve every constraint once, update velocities).
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final box = SoftBodies.softBox(n: 2, size: 0.5, origin: const Vec3d(0, 1, 0));
box.colliders.add(RigidBody.static(PlaneCollider(Vec3d.unitY, 0)));
final h = <List<double>>[];
for (var k = 0; k < 90; k++) {
box.step(1 / 60);
h.add([k / 60, box.position(0).y]);
}
print('volume kept: ${f(box.volume / box.restVolume)}');
}volume kept: 0.9997
SoftBodies
abstract final class SoftBodies
Builders for common XPBD bodies.
Static
static XpbdBody cloth({required int nx, required int ny, required double width, required double height, Vec3d origin = Vec3d.zero, double areaDensity = 0.2, double stretchCompliance = 0, double shearCompliance = 1e-6, double bendCompliance = 1e-3})A rectangular cloth of nx × ny particles spanning width × height in the XZ plane at origin, with structural, shear and bending (distance across two cells) constraints. Particle masses from areaDensity (kg/m²).
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final c = SoftBodies.cloth(nx: 8, ny: 8, width: 2, height: 2, origin: const Vec3d(0, 2, 0));
for (var i = 0; i < 8; i++) {
c.invMass[i * 8 + 7] = 0; // pin one edge
}
for (var k = 0; k < 60; k++) {
c.step(1 / 60);
}
print('${c.count} particles');
}64 particles
static XpbdBody softBox({required int n, required double size, Vec3d origin = Vec3d.zero, double density = 100, double edgeCompliance = 1e-4, double volumeCompliance = 0})A soft box of n³ cells (each split into 5 tetrahedra) with edge and volume constraints; density kg/m³.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final b = SoftBodies.softBox(n: 2, size: 1);
print('${b.count} particles, rest volume ${f(b.restVolume)}');
}27 particles, rest volume 1.0000
SparseBuilder
final class SparseBuilder
Accumulates (row, col, value) triplets, summing duplicates (FEM assembly), and compresses to Csr.
Constructors
SparseBuilder(this.n)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final s = SparseBuilder(3);
for (var i = 0; i < 3; i++) {
s.add(i, i, 2);
if (i > 0) s.add(i, i - 1, -1);
if (i < 2) s.add(i, i + 1, -1);
}
final a = s.build();
print('${a.rows} × ${a.cols}, ${a.nnz} nonzeros');
}3 × 3, 7 nonzeros
Properties
final int nMethods
void add(int r, int c, double v)import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final s = SparseBuilder(3);
for (var i = 0; i < 3; i++) {
s.add(i, i, 2);
if (i > 0) s.add(i, i - 1, -1);
if (i < 2) s.add(i, i + 1, -1);
}
s.add(0, 0, 1); // entries add up
print('A[0, 0] = ${s.build().toDense()[0]}');
}A[0, 0] = 3.0
void applyDirichlet(Map<int, double> fixed, Float64List rhs)Applies Dirichlet conditions u[i] = \mathrm{value}[i] for each fixed i: moves the known columns to rhs, zeroes their rows and columns and puts 1 on the diagonal, keeping the matrix symmetric for CG.
import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray' show CsrMatrix;
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final s = SparseBuilder(3);
for (var i = 0; i < 3; i++) {
s.add(i, i, 2);
if (i > 0) s.add(i, i - 1, -1);
if (i < 2) s.add(i, i + 1, -1);
}
final rhs = Float64List.fromList([0, 0, 0]);
s.applyDirichlet({0: 1, 2: 3}, rhs);
final x = Float64List(3);
solveSpd(s.build(), rhs, x);
print('with u0 = 1, u2 = 3: u = $x');
}with u0 = 1, u2 = 3: u = [1.0, 1.9999999999999998, 3.0]
CsrMatrix build()import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_math/riptide_math.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray' show CsrMatrix;
String f(double d) => (d.abs() < 5e-9 ? 0.0 : d).toStringAsFixed(4);
String d3(Vec3d v) => '(${f(v.x)}, ${f(v.y)}, ${f(v.z)})';
void main() {
final s = SparseBuilder(3);
for (var i = 0; i < 3; i++) {
s.add(i, i, 2);
if (i > 0) s.add(i, i - 1, -1);
if (i < 2) s.add(i, i + 1, -1);
}
print(s.build().toDense());
}[2.0, -1.0, 0.0, -1.0, 2.0, -1.0, 0.0, -1.0, 2.0]
Constants
abstract final class Constants
Physical constants in SI units: CODATA 2018 recommended values (Tiesinga, Mohr, Newell and Taylor, "CODATA recommended values of the fundamental physical constants: 2018", Rev. Mod. Phys. 93, 025010 (2021); https://physics.nist.gov/cuu/Constants/). Since the 2019 SI redefinition, c, h, e, k_{B} and N_{A} are exact. Astronomical values: IAU 2012 (au), IAU 2015 Resolution B3 (nominal solar/Earth values), IERS 2010 / WGS 84 (Earth GM and radius), JPL DE430 (lunar GM).
relativeUncertainty lists the CODATA standard relative uncertainty of each measured constant (0 = exact).
Static
static const reducedPlanck = 1.054571817e-34Reduced Planck constant \hbar = \frac{h}{2\pi} (J \cdot s).
static const gas = 8.314462618Molar gas constant R = N_{A} k_{B} (\frac{J}{mol \cdot K}).
static const stefanBoltzmann = 5.670374419e-8Stefan–Boltzmann constant \sigma (\frac{W}{m^{2} \cdot K^{4}}).
static const gravitational = 6.67430e-11Newtonian constant of gravitation G (\frac{m^{3}}{kg \cdot s^{2}}).
static const vacuumPermeability = 1.25663706212e-6Vacuum magnetic permeability \mu_{0} (\frac{N}{A^{2}}).
static const vacuumPermittivity = 8.8541878128e-12Vacuum electric permittivity \varepsilon_{0} = \frac{1}{\mu_{0}c^{2}} (\frac{F}{m}).
static const coulomb = 8.9875517923e9Coulomb constant \frac{1}{4\pi\varepsilon_{0}} (N \cdot \frac{m^{2}}{C^{2}}).
static const atomicMass = 1.66053906660e-27Atomic mass constant m_{u} = 1 Da (kg).
static const fineStructure = 7.2973525693e-3Fine-structure constant \alpha (dimensionless).
static const classicalElectronRadius = 2.8179403262e-15Classical electron radius r_{e} (m).
static const electronRestEnergyEv = 0.51099895000e6Electron rest energy m_{e} c^{2} (eV).
static const protonRestEnergyEv = 938.27208816e6Proton rest energy m_{p} c^{2} (eV).
static const electronChargeToMass = -1.75882001076e11Electron charge-to-mass quotient -\frac{e}{m_{e}} (\frac{C}{kg}).
static const standardGravity = 9.80665Standard acceleration of gravity g_{n} (m/s², exact by convention).
static const standardAtmosphere = 101325.0Standard atmosphere (Pa, exact by convention).
static const astronomicalUnit = 149597870700.0Astronomical unit (m, exact, IAU 2012 Resolution B2).
static const earthGM = 3.986004418e14Earth's GM (\frac{m^{3}}{s^{2}}, IERS 2010 / WGS 84, includes the atmosphere).
static const relativeUncertaintyCODATA 2018 standard relative uncertainties of the measured constants above.
Dimension
final class Dimension
Units of measure, two ways:
- Typed quantities (
Length,Time,Speed,Force, …): extension types over a double in SI base units, erased at compile time (no allocation, no overhead). Only dimensionally valid operators exist, soLength / Timeis aSpeed,Mass * Accelerationis aForce, andLength + Timedoes not compile. Quantitywith a run-timeDimension(exponents of the 7 SI base units) for anything the typed set doesn't cover; mismatched additions throw.
Every typed quantity converts to a Quantity with .q. Exponents of the SI base units: metre, kilogram, second, ampere, kelvin, mole, candela.
Constructors
const Dimension({this.m = 0, this.kg = 0, this.s = 0, this.a = 0, this.k = 0, this.mol = 0, this.cd = 0})import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const torque = Dimension(m: 2, kg: 1, s: -2);
print('torque dimension: $torque');
print('same as energy: ${torque == Dimension.energy}');
const molarMass = Dimension(kg: 1, mol: -1);
print('molar mass: $molarMass');
print('dimensionless: ${const Dimension()}');
}torque dimension: m^2·kg·s^-2 same as energy: true molar mass: kg·mol^-1 dimensionless: 1
Static
static const none = Dimension()static const length = Dimension(m: 1)static const mass = Dimension(kg: 1)static const time = Dimension(s: 1)static const current = Dimension(a: 1)static const temperature = Dimension(k: 1)static const amount = Dimension(mol: 1)static const luminousIntensity = Dimension(cd: 1)static const speed = Dimension(m: 1, s: -1)static const acceleration = Dimension(m: 1, s: -2)static const force = Dimension(m: 1, kg: 1, s: -2)static const energy = Dimension(m: 2, kg: 1, s: -2)static const power = Dimension(m: 2, kg: 1, s: -3)static const pressure = Dimension(m: -1, kg: 1, s: -2)static const charge = Dimension(s: 1, a: 1)static const voltage = Dimension(m: 2, kg: 1, s: -3, a: -1)Properties
final int mfinal int kgfinal int sfinal int afinal int kfinal int molfinal int cdint get hashCodeMethods
Dimension pow(int n)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
print('length^2 = ${Dimension.length.pow(2)}');
print('length^3 = ${Dimension.length.pow(3)}');
print('time^-1 = ${Dimension.time.pow(-1)}');
print('speed^2 = ${Dimension.speed.pow(2)}');
print('anything^0 = ${Dimension.force.pow(0)}');
}length^2 = m^2 length^3 = m^3 time^-1 = s^-1 speed^2 = m^2·s^-2 anything^0 = 1
String toString()import 'package:riptide_physics/units.ray';
void main() {
print('force: ${Dimension.force}');
print('pressure: ${Dimension.pressure}');
print('voltage: ${Dimension.voltage}');
print('none: ${Dimension.none}');
}force: m·kg·s^-2 pressure: m^-1·kg·s^-2 voltage: m^2·kg·s^-3·A^-1 none: 1
Operators
Dimension operator *(Dimension o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final f = Dimension.mass * Dimension.acceleration;
print('mass × acceleration = $f');
print('is a force: ${f == Dimension.force}');
print('force × length = ${Dimension.force * Dimension.length} (energy)');
}mass × acceleration = m·kg·s^-2 is a force: true force × length = m^2·kg·s^-2 (energy)
Dimension operator /(Dimension o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final v = Dimension.length / Dimension.time;
print('length / time = $v, a speed: ${v == Dimension.speed}');
print('energy / time = ${Dimension.energy / Dimension.time} (power)');
print('force / force = ${Dimension.force / Dimension.force}');
}length / time = m·s^-1, a speed: true energy / time = m^2·kg·s^-3 (power) force / force = 1
bool operator ==(Object other)import 'package:riptide_physics/units.ray';
void main() {
final a = Dimension.power / Dimension.current;
print('power / current = $a');
print('== voltage: ${a == Dimension.voltage}');
print('energy == torque-like m²·kg·s⁻²: ${Dimension.energy == const Dimension(m: 2, kg: 1, s: -2)}');
print('speed == acceleration: ${Dimension.speed == Dimension.acceleration}');
}power / current = m^2·kg·s^-3·A^-1 == voltage: true energy == torque-like m²·kg·s⁻²: true speed == acceleration: false
Quantity
final class Quantity
A value with a run-time dimension, in SI base units.
Constructors
const Quantity(this.value, this.dimension)import 'package:riptide_physics/units.ray';
void main() {
const g = Quantity(9.80665, Dimension.acceleration);
const m = Quantity(70, Dimension.mass);
print('g = $g');
print('m = $m');
print('weight = ${m * g}');
}g = 9.80665 m·s^-2 m = 70.0 kg weight = 686.4654999999999 m·kg·s^-2
Properties
final double valuefinal Dimension dimensionMethods
Quantity scale(double s)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const lap = Quantity(400, Dimension.length);
print('one lap: $lap');
print('25 laps: ${lap.scale(25)}');
print('half lap: ${lap.scale(0.5)}');
}one lap: 400.0 m 25 laps: 10000.0 m half lap: 200.0 m
Quantity pow(int n)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const side = Quantity(3, Dimension.length);
print('side = $side');
print('area = ${side.pow(2)}');
print('volume = ${side.pow(3)}');
print('1/side = ${side.pow(-1)}');
}side = 3.0 m area = 9.0 m^2 volume = 27.0 m^3 1/side = 0.3333333333333333 m^-1
double inUnit(Quantity unit)The value in unit (which must have the same dimension).
import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final marathon = const Length.km(42.195).q;
print('marathon in miles: ${marathon.inUnit(const Length.miles(1).q).toStringAsFixed(3)}');
print('marathon in feet: ${marathon.inUnit(const Length.feet(1).q).toStringAsFixed(0)}');
try {
marathon.inUnit(const Time(1).q);
} on ArgumentError catch (e) {
print('in seconds: ${e.message}');
}
}marathon in miles: 26.219 marathon in feet: 138435 in seconds: dimension mismatch: m vs s
String toString()import 'package:riptide_physics/units.ray';
void main() {
print(const Quantity(1.5, Dimension.energy));
print(const Quantity(2, Dimension(m: 1, s: -1)));
print(const Quantity(3, Dimension.none));
}1.5 m^2·kg·s^-2 2.0 m·s^-1 3.0 1
Operators
Quantity operator +(Quantity o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final a = const Length(3).q, b = const Length.cm(50).q;
print('3 m + 50 cm = ${a + b}');
try {
print(a + const Time(1).q);
} on ArgumentError catch (e) {
print('3 m + 1 s: ${e.message}');
}
}3 m + 50 cm = 3.5 m 3 m + 1 s: dimension mismatch: m vs s
Quantity operator -(Quantity o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final full = const Energy.kilojoules(10).q, used = const Energy(2500).q;
print('left: ${full - used}');
print('left in kJ: ${(full - used).inUnit(const Energy.kilojoules(1).q)}');
}left: 7500.0 m^2·kg·s^-2 left in kJ: 7.5
Quantity operator *(Quantity o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final f = const Force(20).q, d = const Length(5).q;
final work = f * d;
print('20 N × 5 m = $work');
print('is energy: ${work.dimension == Dimension.energy}');
}20 N × 5 m = 100.0 m^2·kg·s^-2 is energy: true
Quantity operator /(Quantity o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final d = const Length.km(100).q, t = const Time.hours(1.25).q;
final v = d / t;
print('100 km / 1.25 h = $v');
print('in km/h: ${v.inUnit(const Speed.kmh(1).q)}');
}100 km / 1.25 h = 22.22222222222222 m·s^-1 in km/h: 80.0
bool operator <(Quantity o)import 'package:riptide_physics/units.ray';
void main() {
final mile = const Length.miles(1).q, km = const Length.km(1.5).q;
print('1 mile < 1.5 km: ${mile < km}');
try {
print(mile < const Mass(1).q);
} on ArgumentError catch (e) {
print('mile < 1 kg: ${e.message}');
}
}1 mile < 1.5 km: false mile < 1 kg: dimension mismatch: m vs kg
bool operator >(Quantity o)import 'package:riptide_physics/units.ray';
void main() {
final a = const Pressure.atmospheres(1).q, b = const Pressure.bar(1).q;
print('1 atm > 1 bar: ${a > b}');
print('difference: ${(a - b).value.toStringAsFixed(0)} Pa');
}1 atm > 1 bar: true difference: 1325 Pa
Length
extension type const Length(double m)
Length (m).
Constructors
const Length.km(double v)import 'raya:convert';
import 'package:riptide_physics/units.ray';
void main() {
const d = Length.km(5);
print('5 km = ${d.m} m');
print(' = ${d.miles.toStringAsFixed(3)} miles');
}5 km = 5000.0 m
= 3.107 milesconst Length.cm(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const h = Length.cm(180);
print('180 cm = ${h.m} m = ${h.feet.toStringAsFixed(2)} ft');
print('plus 5 cm = ${(h + const Length.cm(5)).m} m');
}180 cm = 1.8 m = 5.91 ft plus 5 cm = 1.85 m
const Length.mm(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const bolt = Length.mm(12);
print('12 mm = ${bolt.m} m');
print('in inches: ${bolt.ratio(const Length.inches(1)).toStringAsFixed(4)}');
}12 mm = 0.012 m in inches: 0.4724
const Length.miles(double v)import 'raya:convert';
import 'package:riptide_physics/units.ray';
void main() {
const d = Length.miles(26.2);
print('26.2 miles = ${d.km.toStringAsFixed(3)} km');
}26.2 miles = 42.165 km
const Length.feet(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const everest = Length.feet(29032);
print('29,032 ft = ${everest.m.toStringAsFixed(1)} m');
print(' = ${everest.miles.toStringAsFixed(3)} miles');
}29,032 ft = 8849.0 m
= 5.498 milesconst Length.inches(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const screen = Length.inches(13.3);
print('13.3 in = ${screen.m.toStringAsFixed(5)} m = ${(screen.m * 100).toStringAsFixed(2)} cm');
}13.3 in = 0.33782 m = 33.78 cm
const Length.nauticalMiles(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const leg = Length.nauticalMiles(60);
print('60 nmi = ${leg.km} km');
print('one degree of latitude ≈ 60 nmi ≈ ${leg.miles.toStringAsFixed(1)} statute miles');
}60 nmi = 111.12 km one degree of latitude ≈ 60 nmi ≈ 69.0 statute miles
const Length.au(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const mars = Length.au(1.524);
print('Mars orbit: ${mars.km.toStringAsExponential(4)} km');
final light = mars.m / Constants.speedOfLight;
print('sunlight reaches Mars in ${(light / 60).toStringAsFixed(1)} minutes');
}Mars orbit: 2.2799e+8 km sunlight reaches Mars in 12.7 minutes
const Length.lightYears(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const proxima = Length.lightYears(4.2465);
print('Proxima Centauri: ${proxima.au.toStringAsFixed(0)} AU');
print(' = ${proxima.km.toStringAsExponential(4)} km');
}Proxima Centauri: 268553 AU
= 4.0175e+13 kmProperties
double get kmdouble get milesdouble get feetdouble get auQuantity get qMethods
Area times(Length o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const w = Length(4), h = Length(2.5);
final a = w.times(h);
print('4 m × 2.5 m = ${a.m2} m²');
print('× 3 m high = ${a.times(const Length(3)).m3} m³');
}4 m × 2.5 m = 10.0 m² × 3 m high = 30.0 m³
Speed per(Time t)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final v = const Length.km(42.195).per(const Time.hours(2) + const Time.minutes(1) + const Time(9));
print('marathon record pace: ${v.mps.toStringAsFixed(3)} m/s = ${v.kmh.toStringAsFixed(2)} km/h');
}marathon record pace: 5.805 m/s = 20.90 km/h
double ratio(Length o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final r = const Length.km(1).ratio(const Length.miles(1));
print('1 km / 1 mile = ${r.toStringAsFixed(5)}');
print('earth radius / moon distance = ${const Length(Constants.earthRadius).ratio(const Length(Constants.earthMoonDistance)).toStringAsFixed(5)}');
}1 km / 1 mile = 0.62137 earth radius / moon distance = 0.01659
Operators
Length operator +(Length o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final total = const Length.km(1) + const Length.miles(1) + const Length.feet(100);
print('1 km + 1 mile + 100 ft = ${total.m.toStringAsFixed(2)} m');
}1 km + 1 mile + 100 ft = 2639.82 m
Length operator -(Length o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final left = const Length.km(42.195) - const Length.km(30);
print('still to run: ${left.km.toStringAsFixed(3)} km = ${left.miles.toStringAsFixed(2)} miles');
}still to run: 12.195 km = 7.58 miles
Length operator *(double s)import 'raya:convert';
import 'package:riptide_physics/units.ray';
void main() {
const stride = Length(0.78);
print('10,000 steps = ${(stride * 10000).km} km');
}10,000 steps = 7.8 km
Time
extension type const Time(double s)
Time (s).
Constructors
const Time.ms(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const frame = Time.ms(16.667);
print('one frame: ${frame.s} s');
print('frames per second: ${frame.inverse.hertz.toStringAsFixed(2)}');
}one frame: 0.016667 s frames per second: 60.00
const Time.minutes(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const t = Time.minutes(90);
print('90 min = ${t.s} s = ${t.hours} h');
}90 min = 5400.0 s = 1.5 h
const Time.hours(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const t = Time.hours(36);
print('36 h = ${t.days} days = ${t.minutes} min');
}36 h = 1.5 days = 2160.0 min
const Time.days(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const sidereal = Time(Constants.siderealDay);
print('sidereal day = ${sidereal.hours.toStringAsFixed(4)} h');
print('solar - sidereal = ${(const Time.days(1) - sidereal).s.toStringAsFixed(1)} s');
}sidereal day = 23.9345 h solar - sidereal = 235.9 s
const Time.years(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const y = Time.years(1);
print('Julian year = ${y.s} s = ${y.days} days');
print('light-year = ${(Constants.speedOfLight * y.s).toStringAsExponential(6)} m');
}Julian year = 31557600.0 s = 365.25 days light-year = 9.460730e+15 m
Properties
double get minutesdouble get hoursdouble get daysFrequency get inverseQuantity get qOperators
Time operator +(Time o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final t = const Time.hours(2) + const Time.minutes(45) + const Time(30);
print('2 h 45 min 30 s = ${t.s} s = ${t.hours.toStringAsFixed(4)} h');
}2 h 45 min 30 s = 9930.0 s = 2.7583 h
Time operator -(Time o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final rest = const Time.days(1) - const Time.hours(8);
print('awake: ${rest.hours} h');
}awake: 16.0 h
Time operator *(double k)import 'raya:convert';
import 'package:riptide_physics/units.ray';
void main() {
const lap = Time(72.5);
print('20 laps: ${(lap * 20).minutes.toStringAsFixed(2)} min');
}20 laps: 24.17 min
Mass
extension type const Mass(double kg)
Mass (kg).
Constructors
const Mass.grams(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const coin = Mass.grams(5.67);
print('quarter: ${coin.kg} kg');
print('1000 quarters: ${(coin * 1000).pounds.toStringAsFixed(2)} lb');
}quarter: 0.00567 kg 1000 quarters: 12.50 lb
const Mass.tonnes(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const truck = Mass.tonnes(18);
print('18 t = ${truck.kg} kg = ${truck.pounds.toStringAsFixed(0)} lb');
}18 t = 18000.0 kg = 39683 lb
const Mass.pounds(double v)import 'raya:convert';
import 'package:riptide_physics/units.ray';
void main() {
const m = Mass.pounds(150);
print('150 lb = ${m.kg.toStringAsFixed(3)} kg');
}150 lb = 68.039 kg
Properties
double get poundsQuantity get qMethods
Force times(Acceleration a)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const m = Mass(75);
print('weight on Earth: ${m.times(const Acceleration.g(1)).newtons.toStringAsFixed(1)} N');
print('weight on the Moon: ${m.times(const Acceleration(1.62)).newtons.toStringAsFixed(1)} N');
}weight on Earth: 735.5 N weight on the Moon: 121.5 N
Momentum withSpeed(Speed v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final p = const Mass(0.145).withSpeed(const Speed.mph(95));
print('fastball momentum: ${p.kgMps.toStringAsFixed(3)} kg·m/s');
}fastball momentum: 6.158 kg·m/s
Density per(Volume v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final rho = const Mass(19.3).per(const Volume.litres(1));
print('19.3 kg per litre = ${rho.kgPerM3} kg/m³ (gold)');
}19.3 kg per litre = 19300.0 kg/m³ (gold)
Operators
Mass operator +(Mass o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final total = const Mass(70) + const Mass.pounds(20) + const Mass.grams(500);
print('rider + pack + bottle = ${total.kg.toStringAsFixed(3)} kg');
}rider + pack + bottle = 79.572 kg
Mass operator -(Mass o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final fuel = const Mass.tonnes(549) - const Mass.tonnes(25.6);
print('Falcon 9 minus dry mass: ${fuel.kg} kg');
}Falcon 9 minus dry mass: 523400.0 kg
Mass operator *(double s)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const brick = Mass(2.3);
print('500 bricks: ${(brick * 500).kg} kg');
}500 bricks: 1150.0 kg
Temperature
extension type const Temperature(double kelvin)
Thermodynamic temperature (K).
Constructors
const Temperature.celsius(double c)import 'raya:convert';
import 'package:riptide_physics/units.ray';
void main() {
const body = Temperature.celsius(37);
print('37 °C = ${body.kelvin} K = ${body.fahrenheit.toStringAsFixed(1)} °F');
}37 °C = 310.15 K = 98.6 °F
const Temperature.fahrenheit(double f)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const t = Temperature.fahrenheit(-40);
print('-40 °F = ${t.celsius} °C (the two scales meet)');
print('451 °F = ${const Temperature.fahrenheit(451).celsius.toStringAsFixed(1)} °C');
}-40 °F = -40.0 °C (the two scales meet) 451 °F = 232.8 °C
Properties
double get celsiusdouble get fahrenheitQuantity get qArea
extension type const Area(double m2)
Area (m^{2}).
Properties
Quantity get qMethods
Volume times(Length l)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const floor = Area(12);
final v = floor.times(const Length(2.4));
print('12 m² × 2.4 m = ${v.m3} m³ = ${v.litres} L');
}12 m² × 2.4 m = 28.799999999999997 m³ = 28799.999999999996 L
Operators
Area operator +(Area o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final a = const Length(4).times(const Length(3)) + const Length(2).times(const Length(2));
print('L-shaped room: ${a.m2} m²');
}L-shaped room: 16.0 m²
Volume
extension type const Volume(double m3)
Volume (m^{3}).
Constructors
const Volume.litres(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const tank = Volume.litres(60);
print('60 L = ${tank.m3} m³');
print('mass of that much water: ${const Density(1000).of(tank).kg} kg');
}60 L = 0.06 m³ mass of that much water: 60.0 kg
Properties
double get litresQuantity get qOperators
Volume operator +(Volume o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final v = const Volume.litres(1.5) + const Volume(0.002);
print('1.5 L + 0.002 m³ = ${v.litres} L');
}1.5 L + 0.002 m³ = 3.5 L
Speed
extension type const Speed(double mps)
Speed (m/s).
Constructors
const Speed.kmh(double v)import 'raya:convert';
import 'package:riptide_physics/units.ray';
void main() {
const v = Speed.kmh(100);
print('100 km/h = ${v.mps.toStringAsFixed(3)} m/s = ${v.mph.toStringAsFixed(2)} mph');
}100 km/h = 27.778 m/s = 62.14 mph
const Speed.mph(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const v = Speed.mph(60);
print('60 mph = ${v.kmh.toStringAsFixed(3)} km/h');
}60 mph = 96.561 km/h
const Speed.knots(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const v = Speed.knots(450);
print('450 kn = ${v.kmh.toStringAsFixed(1)} km/h = ${v.mph.toStringAsFixed(1)} mph');
}450 kn = 833.4 km/h = 517.9 mph
const Speed.kmps(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const iss = Speed.kmps(7.66);
print('ISS: ${iss.kmh.toStringAsFixed(0)} km/h');
print('one orbit (42,000 km) takes ${(iss.over(const Time.minutes(1)).km).toStringAsFixed(1)} km per minute');
}ISS: 27576 km/h one orbit (42,000 km) takes 459.6 km per minute
Properties
double get kmhdouble get mphQuantity get qMethods
Length over(Time t)import 'raya:convert';
import 'package:riptide_physics/units.ray';
void main() {
const v = Speed.kmh(90);
print('in 20 minutes: ${v.over(const Time.minutes(20)).km} km');
}in 20 minutes: 30.0 km
Acceleration per(Time t)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final a = const Speed.kmh(100).per(const Time(2.6));
print('0–100 km/h in 2.6 s: ${a.mps2.toStringAsFixed(2)} m/s² = ${a.inG.toStringAsFixed(2)} g');
}0–100 km/h in 2.6 s: 10.68 m/s² = 1.09 g
Operators
Speed operator +(Speed o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final ground = const Speed.knots(480) + const Speed.knots(110);
print('airspeed + tailwind = ${ground.kmh.toStringAsFixed(1)} km/h');
}airspeed + tailwind = 1092.7 km/h
Speed operator -(Speed o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final closing = const Speed.kmh(130) - const Speed.kmh(110);
print('overtaking at ${closing.mps.toStringAsFixed(3)} m/s');
}overtaking at 5.556 m/s
Speed operator *(double s)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const sound = Speed(343);
print('Mach 2 = ${(sound * 2).kmh.toStringAsFixed(0)} km/h');
}Mach 2 = 2470 km/h
Acceleration
extension type const Acceleration(double mps2)
Acceleration (m/s²).
Constructors
const Acceleration.g(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const a = Acceleration.g(3);
print('3 g = ${a.mps2} m/s²');
print('after 2 s: ${a.over(const Time(2)).kmh.toStringAsFixed(1)} km/h');
}3 g = 29.41995 m/s² after 2 s: 211.8 km/h
Properties
double get inGQuantity get qMethods
Speed over(Time t)import 'raya:convert';
import 'package:riptide_physics/units.ray';
void main() {
const g = Acceleration.g(1);
print('falling 3 s: ${g.over(const Time(3)).mps.toStringAsFixed(2)} m/s');
}falling 3 s: 29.42 m/s
Operators
Acceleration operator +(Acceleration o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final total = const Acceleration.g(1) + const Acceleration(2);
print('lift accelerating up at 2 m/s² feels like ${total.inG.toStringAsFixed(3)} g');
}lift accelerating up at 2 m/s² feels like 1.204 g
Force
extension type const Force(double newtons)
Force (N).
Constructors
const Force.kilonewtons(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const thrust = Force.kilonewtons(845);
print('one Merlin engine: ${thrust.newtons} N');
print('accelerates 50 t at ${thrust.on(const Mass.tonnes(50)).mps2.toStringAsFixed(2)} m/s²');
}one Merlin engine: 845000.0 N accelerates 50 t at 16.90 m/s²
const Force.poundsForce(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const f = Force.poundsForce(100);
print('100 lbf = ${f.newtons.toStringAsFixed(2)} N');
}100 lbf = 444.82 N
Properties
Quantity get qMethods
Energy through(Length d)import 'raya:convert';
import 'package:riptide_physics/units.ray';
void main() {
const weight = Force(686);
print('climbing 3 m: ${weight.through(const Length(3)).joules} J');
}climbing 3 m: 2058.0 J
Pressure per(Area a)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final p = const Force(700).per(const Area(0.0001));
print('700 N on a 1 cm² heel: ${p.pascals} Pa = ${p.atmospheres.toStringAsFixed(1)} atm');
}700 N on a 1 cm² heel: 7000000.0 Pa = 69.1 atm
Acceleration on(Mass m)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final a = const Force(5000).on(const Mass(1250));
print('5 kN on 1250 kg: ${a.mps2} m/s²');
}5 kN on 1250 kg: 4.0 m/s²
Operators
Force operator +(Force o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final net = const Force(120) + const Force(-45);
print('push + friction = ${net.newtons} N');
}push + friction = 75.0 N
Force operator -(Force o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final net = const Force.kilonewtons(7.6) - const Mass.tonnes(0.549).times(const Acceleration.g(1));
print('thrust minus weight: ${net.newtons.toStringAsFixed(1)} N');
}thrust minus weight: 2216.1 N
Force operator *(double s)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const one = Force(800);
print('nine engines: ${(one * 9).newtons} N');
}nine engines: 7200.0 N
Energy
extension type const Energy(double joules)
Energy (J).
Constructors
const Energy.kilojoules(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const e = Energy.kilojoules(3600);
print('3600 kJ = ${e.kilowattHours} kWh');
}3600 kJ = 1.0 kWh
const Energy.electronVolts(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const photon = Energy.electronVolts(2.25);
print('green photon: ${photon.joules.toStringAsExponential(4)} J');
final lambda = Constants.planck * Constants.speedOfLight / photon.joules;
print('wavelength: ${(lambda * 1e9).toStringAsFixed(1)} nm');
}green photon: 3.6049e-19 J wavelength: 551.0 nm
const Energy.kilowattHours(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const battery = Energy.kilowattHours(75);
print('75 kWh = ${battery.joules.toStringAsExponential(3)} J');
print('runs a 2 kW heater for ${(battery.joules / const Power.kilowatts(2).watts / 3600)} h');
}75 kWh = 2.700e+8 J runs a 2 kW heater for 37.5 h
const Energy.calories(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const snack = Energy.calories(250000); // 250 kcal
print('250 kcal = ${snack.joules} J = ${snack.kilowattHours.toStringAsFixed(3)} kWh');
}250 kcal = 1046000.0 J = 0.291 kWh
Properties
double get electronVoltsdouble get kilowattHoursQuantity get qMethods
Power per(Time t)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final p = const Energy.kilojoules(500).per(const Time.minutes(10));
print('500 kJ in 10 minutes = ${p.watts.toStringAsFixed(1)} W');
}500 kJ in 10 minutes = 833.3 W
Operators
Energy operator +(Energy o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const m = Mass(2), v = 3.0, h = 5.0;
final ke = Energy(0.5 * m.kg * v * v);
final pe = m.times(const Acceleration.g(1)).through(const Length(h));
print('kinetic ${ke.joules} J + potential ${pe.joules.toStringAsFixed(2)} J = ${(ke + pe).joules.toStringAsFixed(2)} J');
}kinetic 9.0 J + potential 98.07 J = 107.07 J
Energy operator -(Energy o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final lost = const Energy(1000) - const Energy(870);
print('energy lost to heat: ${lost.joules} J (13 %)');
}energy lost to heat: 130.0 J (13 %)
Energy operator *(double s)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const daily = Energy.kilowattHours(12);
print('a month: ${(daily * 30).kilowattHours} kWh');
}a month: 360.0 kWh
Power
extension type const Power(double watts)
Power (W).
Constructors
const Power.kilowatts(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const p = Power.kilowatts(150);
print('150 kW = ${(p.watts / const Power.horsepower(1).watts).toStringAsFixed(1)} hp');
}150 kW = 201.2 hp
const Power.horsepower(double v)import 'raya:convert';
import 'package:riptide_physics/units.ray';
void main() {
const p = Power.horsepower(300);
print('300 hp = ${(p.watts / 1000).toStringAsFixed(1)} kW');
}300 hp = 223.7 kW
Properties
Quantity get qMethods
Energy over(Time t)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const bulb = Power(10);
print('10 W for a day: ${bulb.over(const Time.days(1)).kilowattHours} kWh');
}10 W for a day: 0.24 kWh
Operators
Power operator +(Power o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final total = const Power.kilowatts(2) + const Power(750) + const Power.horsepower(1);
print('total load: ${total.watts.toStringAsFixed(1)} W');
}total load: 3495.7 W
Pressure
extension type const Pressure(double pascals)
Pressure (Pa).
Constructors
const Pressure.kilopascals(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const tyre = Pressure.kilopascals(230);
print('230 kPa = ${(tyre.pascals / const Pressure.psi(1).pascals).toStringAsFixed(1)} psi');
}230 kPa = 33.4 psi
const Pressure.bar(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const p = Pressure.bar(1);
print('1 bar = ${p.atmospheres.toStringAsFixed(5)} atm');
}1 bar = 0.98692 atm
const Pressure.atmospheres(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
// Water adds about 1 atm every 10.3 m of depth.
for (final depth in [0.0, 10.0, 30.0]) {
final p = const Pressure.atmospheres(1) + Pressure(1000 * Constants.standardGravity * depth);
print('depth ${depth.toStringAsFixed(0)} m: ${p.atmospheres.toStringAsFixed(2)} atm');
}
}depth 0 m: 1.00 atm depth 10 m: 1.97 atm depth 30 m: 3.90 atm
const Pressure.psi(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const p = Pressure.psi(32);
print('32 psi = ${(p.pascals / 1000).toStringAsFixed(1)} kPa = ${p.atmospheres.toStringAsFixed(3)} atm');
}32 psi = 220.6 kPa = 2.177 atm
Properties
double get atmospheresQuantity get qMethods
Force over(Area a)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final f = const Pressure.atmospheres(1).over(const Area(1));
print('air pushes on 1 m² with ${f.newtons} N (${(f.newtons / Constants.standardGravity).toStringAsFixed(0)} kg-force)');
}air pushes on 1 m² with 101325.0 N (10332 kg-force)
Operators
Pressure operator +(Pressure o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final absolute = const Pressure.psi(32) + const Pressure.atmospheres(1);
print('gauge 32 psi = absolute ${(absolute.pascals / 1000).toStringAsFixed(1)} kPa');
}gauge 32 psi = absolute 322.0 kPa
Frequency
extension type const Frequency(double hertz)
Frequency (Hz).
Properties
Time get periodQuantity get qAngle
extension type const Angle(double radians)
Plane angle (rad; dimensionless in SI).
Constructors
const Angle.degrees(double d)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const a = Angle.degrees(90);
print('90° = ${a.radians} rad');
print('back: ${a.degrees}°');
}90° = 1.5707963267948966 rad back: 90.0°
Properties
double get degreesMethods
AngularVelocity per(Time t)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final w = const Angle.degrees(360).per(const Time.minutes(1));
print('one turn a minute: ${w.radPerS.toStringAsFixed(5)} rad/s = ${w.rpm} rpm');
}one turn a minute: 0.10472 rad/s = 1.0 rpm
Operators
Angle operator +(Angle o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final a = const Angle.degrees(30) + const Angle(1);
print('30° + 1 rad = ${a.degrees.toStringAsFixed(3)}°');
}30° + 1 rad = 87.296°
Angle operator -(Angle o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final a = const Angle.degrees(180) - const Angle.degrees(45);
print('180° - 45° = ${a.degrees}° = ${a.radians.toStringAsFixed(5)} rad');
}180° - 45° = 135.0° = 2.35619 rad
AngularVelocity
extension type const AngularVelocity(double radPerS)
Angular velocity (rad/s).
Constructors
const AngularVelocity.rpm(double v)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
const w = AngularVelocity.rpm(7200);
print('7200 rpm = ${w.radPerS.toStringAsFixed(2)} rad/s');
print('rim speed of a 9.5 cm disk: ${(w.radPerS * 0.0475).toStringAsFixed(2)} m/s');
}7200 rpm = 753.98 rad/s rim speed of a 9.5 cm disk: 35.81 m/s
Properties
double get rpmQuantity get qDensity
extension type const Density(double kgPerM3)
Density (kg/m³).
Properties
Quantity get qMethods
Mass of(Volume v)import 'raya:convert';
import 'package:riptide_physics/units.ray';
void main() {
const steel = Density(7850);
print('1 L of steel: ${steel.of(const Volume.litres(1)).kg} kg');
}1 L of steel: 7.8500000000000005 kg
Momentum
extension type const Momentum(double kgMps)
Momentum (kg·m/s).
Properties
Quantity get qOperators
Momentum operator +(Momentum o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final a = const Mass(2).withSpeed(const Speed(3));
final b = const Mass(1).withSpeed(const Speed(-4));
final total = a + b;
print('total momentum: ${total.kgMps} kg·m/s');
print('velocity after they stick: ${total.kgMps / 3} m/s');
}total momentum: 2.0 kg·m/s velocity after they stick: 0.6666666666666666 m/s
Charge
extension type const Charge(double coulombs)
Electric charge (C).
Properties
Quantity get qOperators
Charge operator +(Charge o)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final q = const Charge(Constants.elementaryCharge) + const Charge(-Constants.elementaryCharge);
print('proton + electron: ${q.coulombs} C');
print('1 mol of electrons: ${(Constants.avogadro * Constants.elementaryCharge).toStringAsFixed(1)} C');
}proton + electron: 0.0 C 1 mol of electrons: 96485.3 C
Voltage
extension type const Voltage(double volts)
Voltage (V).
Properties
Quantity get qMethods
Energy across(Charge c)import 'package:riptide_physics/units.ray';
import 'raya:convert';
void main() {
final e = const Voltage(1).across(const Charge(Constants.elementaryCharge));
print('1 V across one electron charge: ${e.joules} J = ${e.electronVolts} eV');
print('12 V battery moving 2 C: ${const Voltage(12).across(const Charge(2)).joules} J');
}1 V across one electron charge: 1.602176634e-19 J = 1.0 eV 12 V battery moving 2 C: 24.0 J