RiptideRiptide
Download Riptide SDKInstall Riptorch
Menu
Raya docs · Geometry, physics and speed

Physics

Rigid bodies with contacts and joints, cloth and soft bodies, SPH and stable fluids, finite elements and heat, orbital mechanics and typed units.

import 'package:riptide_physics/riptide_physics.ray';
import 'package:riptide_physics/units.ray';
66 classes355 functions and methods242 of 668 documented277 runnable examples

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

AreaFilesContents
Rigid bodiesrigid/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
Broadphaserigid/broadphase.rayDynamicAabbTree (fat AABBs, surface-area insertion cost, AVL rotations) and sweep-and-prune over riptide_math's Broadphase
Narrowphaserigid/narrowphase.raysphere–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
Solverrigid/contact.ray, rigid/joint.raysequential 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)
Rotationrigid/world.rayimplicit-midpoint gyroscopic term (preserves kinetic energy and \|L\| exactly), exact quaternion integration, optional sleeping
Soft bodiessoft/xpbd.rayXpbdBody (small-step XPBD: distance, tetrahedral volume, collision with rigid shapes by signed distance, friction), SoftBodies.cloth, SoftBodies.softBox
Fluidsfluid/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)
FEMfem/fem.rayPlaneStressFem (CST triangles), TetFem (linear tetrahedra, Kuhn box meshes), Heat (1-D FTCS, backward Euler, Crank–Nicolson), HeatFem2 (P1 triangles, lumped mass, backward Euler)
Orbitalorbital/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)
Particlesparticles/ParticleState (SoA position, velocity, mass, charge), ParticleStepper interface, SymplecticStepper / VelocityVerlet and RungeKutta4 over part B's integrators, SemiImplicitEuler
Unitsunits/ (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): stableDt gives 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

lambertfunction
(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.

Example
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]);
  }
}
Output
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.

Example
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));
}
Output
[(0, 1), (2, 3)]
collidefunction
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.

Example
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)}');
}
Output
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).

Example
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)}');
}
Output
closest (3.0000, 0.0000, 0.0000) and (3.0000, 1.0000, 0.0000)
boxBoxfunction
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.

Example
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))}');
}
Output
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).

Example
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)}'}');
  }
}
Output
(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)
solveSpdfunction
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.

Example
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');
}
Output
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.

Example
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);
}
Output
[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.

ForceFieldtypedef
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).

ContactSettypedef
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

final class ElasticMaterial

Isotropic linear-elastic material.

Constructors

ElasticMaterialconstructor
const ElasticMaterial({required this.youngs, required this.poisson})
Example
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');
}
Output
Lamé λ = 1.154e+11, μ = 7.692e+10 Pa

Properties

youngsfield
final double youngs

Young's modulus E (Pa) and Poisson's ratio \nu.

poissonfield
final double poisson

Young's modulus E (Pa) and Poisson's ratio \nu.

lambdagetter
double get lambda

Lamé parameters \lambda and \mu (shear modulus).

mugetter
double get mu
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

PlaneStressFemconstructor
PlaneStressFem(this.nodes, this.triangles, this.material, {this.thickness = 1})
Example
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');
}
Output
tip deflection -0.2255 after 36 CG iterations

Static

crossedRectanglestaticmethod
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.

Example
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');
}
Output
18 nodes, 24 triangles

Properties

nodesfield
final Float64List nodes
final Int32List triangles
final ElasticMaterial material
final double thickness
nodeCountgetter
int get nodeCount

Methods

solvemethod
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).

Example
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]}');
}
Output
36 iterations; displacement of node 0 0.0
class

TetFem

final class TetFem

3-D linear elasticity on linear tetrahedra (constant strain): K = \sum V B^{T} D B.

Constructors

TetFemconstructor
TetFem(this.nodes, this.tets, this.material)
Example
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)}');
}
Output
3-D cantilever tip deflection -0.0664

Static

boxstaticmethod
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).

Example
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)');
}
Output
12 nodes, 12 tetrahedra (6 per cell)

Properties

nodesfield
final Float64List nodes
tetsfield
final Int32List tets
final ElasticMaterial material
nodeCountgetter
int get nodeCount

Methods

solvemethod
FemSolution solve(Float64List forces, Map<int, double> fixed, {double tolerance = 1e-12})
Example
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}');
}
Output
CG iterations: 28
class

Heat

abstract final class Heat

Heat conduction u_{t} = \alpha \nabla^{2}u.

Static

explicitStep1dstaticmethod
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).

Example
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))}');
}
Output
peak 0.2417 (from 1), total heat kept: 0.8362
implicitStep1dstaticmethod
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.

Example
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])}');
}
Output
peak 0.2502
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

HeatFem2constructor
HeatFem2(this.nodes, this.triangles, {required this.alpha})
Example
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))}');
}
Output
centre value 0.3947, exact mode 0.3727

Static

unitSquarestaticmethod
static ({Float64List nodes, Int32List triangles}) unitSquare(int n)

A structured n × n mesh of the unit square (2 triangles per cell).

Example
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');
}
Output
25 nodes, 32 triangles
exactModestaticmethod
static double exactMode(double x, double y, double t, double alpha)
Example
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))]);
}
Output
[1.0000, 0.3727, 0.1389]

Properties

nodesfield
final Float64List nodes
final Int32List triangles
alphafield
final double alpha

Methods

stepmethod
int step(Float64List u, double dt, Map<int, double> fixed)

Advances u by dt, keeping fixed nodes at the given temperatures. Returns CG iterations.

Example
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');
}
Output
one implicit step: 7 CG iterations
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 are cellSize cubes over min…min + dims · cellSize; positions outside are clamped to the border cells).
  • cellStart[c] … cellStart[c + 1]: the range of sorted holding 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

NeighborGridconstructor
NeighborGrid({required this.minX, required this.minY, required this.minZ, required double maxX, required double maxY, required double maxZ, required this.cellSize})
Example
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)');
}
Output
13 candidates in the cells around (5, 5)

Properties

minXfield
final double minX
minYfield
final double minY
minZfield
final double minZ
final double cellSize
nxfield
final int nx
nyfield
final int ny
nzfield
final int nz
cellCountgetter
int get cellCount
late Uint32List cellStart
cellOffield
Uint32List cellOf
sortedfield
Uint32List sorted
countgetter
int get count

Methods

cellIndexmethod
int cellIndex(double x, double y, double z)
Example
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)}');
}
Output
cell of (3.5, 7.2, 0.5): 73
buildmethod
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).

Example
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');
}
Output
built for 100 particles
cellXmethod
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].

Example
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));
}
Output
3
cellYmethod
int cellY(double y)
Example
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));
}
Output
9
cellZmethod
int cellZ(double z)
Example
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));
}
Output
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.

Example
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');
}
Output
7 candidates
final class SphParams

SPH parameters (SI units).

Constructors

SphParamsconstructor
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})
Example
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}');
}
Output
h 0.05, rest density 1000.0, stiffness 2000.0, gravity -9.81

Properties

hfield
final double h

Smoothing radius (m); also the neighbour grid's cell size.

final double restDensity
final double stiffness

k in the equation of state p = k (\rho - \rho_{0}) (Pa per kg/m³).

final double viscosity

Dynamic viscosity \mu (Pa \cdot s).

final double gravityY
final double boundaryDamping

Fraction of normal velocity kept when a particle hits the domain walls.

final bool clampNegativePressure

Pressure below zero (tension) is clamped, which avoids particle clumping at free surfaces.

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.

BufferTypePer particleNotes
posFloat32List4 (x, y, z, 0)vec4
velFloat32List4 (x, y, z, 0)vec4
accFloat32List4 (x, y, z, 0)vec4, written by computeForces
densityFloat32List1written by computeDensity
pressureFloat32List1written by computeDensity
grid cellStart, sorted, cellOfUint32Listsee NeighborGridcounting 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

SphFluidconstructor
SphFluid(this.count, this.params, {required this.min, required this.max})
Example
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)}');
}
Output
224 particles, max speed 180.7306

Properties

countfield
final int count
paramsfield
final SphParams params
minfield
final (double, double, double) min
maxfield
final (double, double, double) max
posfield
final Float32List pos
velfield
final Float32List vel
accfield
final Float32List acc
densityfield
final Float32List density
final Float32List pressure
final Uint8List wallMask

Bit 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.

gridfield
final NeighborGrid grid
massfield
double mass

Particle mass (kg); fillBox sets it to \rho_{0} s^{3} for lattice spacing s.

poly6field
late final double poly6
late final double spikyGrad
viscLapfield
late final double viscLap
stableDtgetter
double get stableDt

The 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.

maxSpeedgetter
double get maxSpeed

Methods

fillBoxmethod
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}.

Example
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');
}
Output
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}).

Example
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])}');
}
Output
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.

Example
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])})');
}
Output
acceleration of particle 0: (-21.5428, -31.3528)
integratemethod
void integrate(double dt)

Semi-implicit Euler and reflecting walls.

Example
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)}');
}
Output
stable dt suggestion 8.94e-4
stepmethod
void step(double dt)
Example
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]);
  }
}
Output
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

StableFluid2constructor
StableFluid2(this.n, {this.viscosity = 0, this.diffusion = 0, this.iterations = 40, this.projectTolerance = 1e-8})
Example
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)}');
}
Output
total density 89.9995, max divergence 1.39e-9

Properties

nfield
final int n
double viscosity
double diffusion
int iterations

Gauss–Seidel sweeps for the diffusion solves.

double projectTolerance

Relative residual at which the pressure CG stops.

ufield
final Float64List u
vfield
final Float64List v
densityfield
final Float64List density
pressuregetter
Float64List get pressure

Pressure from the last projection (cells²/s units).

double get maxDivergence

The largest |\nabla \cdot u| over all cells.

double get totalDensity

Methods

uimethod
int ui(int i, int j)
Example
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)}');
}
Output
u index of face (3, 5): 168, v index 163, cell 163
vimethod
int vi(int i, int j)
Example
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));
}
Output
1024
cimethod
int ci(int i, int j)
Example
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));
}
Output
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.

Example
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));
}
Output
(0.5, 0.0)
void addDensity(int i, int j, double d)
Example
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);
}
Output
2.0
stepmethod
void step(double dt)
Example
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)}');
}
Output
diffused and advected; total 10.0000
(double, double) velocityAt(double x, double y)

Velocity (cells/s) at a point, bilinear from the faces.

Example
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]);
}
Output
[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)).

Example
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}');
}
Output
before projection: 0.0000
after: true
projectmethod
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.

Example
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)}');
}
Output
126 iterations; max divergence 7.27e-10
class

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

Cr3bpconstructor
const Cr3bp(this.mu)
Example
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)}');
}
Output
μ = 1.215058e-2
L1 at x = 0.8369

Static

earthMoonconstant
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.earthMoonDistance

Length unit (km), time unit (s) and speed unit (km/s) for the Earth–Moon system.

earthMoonTimestaticgetter
static double get earthMoonTime
earthMoonSpeedstaticgetter
static double get earthMoonSpeed

Properties

mufield
final double mu

Methods

potentialmethod
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}.

Example
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))}');
}
Output
Ω at L4: 1.5000
jacobimethod
double jacobi(Float64List s)

The Jacobi constant C = 2\Omega - v^{2} of state (x, y, z, vx, vy, vz), conserved along trajectories.

Example
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)}');
}
Output
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.

Example
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()}');
}
Output
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}).

Example
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)})');
  }
}
Output
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)
propagatemethod
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.

Example
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])})');
}
Output
after 2.4 time units: (0.9775, 0.0505)
class

Bodies

abstract final class Bodies

Gravitational parameters and radii in kilometres and seconds (the units of Vallado's examples).

Static

earthMuconstant
static const earthMu = 398600.4418
earthRadiusconstant
static const earthRadius = 6378.137
moonMuconstant
static const moonMu = 4902.800066
moonRadiusconstant
static const moonRadius = 1737.4
sunMuconstant
static const sunMu = 1.32712440018e11
static const earthMoonDistance = 384400.0
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

OrbitalElementsconstructor
const OrbitalElements({required this.a, required this.e, required this.i, required this.raan, required this.argPeriapsis, required this.trueAnomaly})
Example
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');
}
Output
OrbitalElements(a: 10000.0, e: 0.2, i: 0.5, Ω: 1.0, ω: 0.3, ν: 2.0)
semi-latus rectum p = 9600.0000 km

Properties

afield
final double a

Semi-major axis (negative for hyperbolas), eccentricity, inclination, right ascension of the ascending node, argument of periapsis, true anomaly.

efield
final double e

Semi-major axis (negative for hyperbolas), eccentricity, inclination, right ascension of the ascending node, argument of periapsis, true anomaly.

ifield
final double i

Semi-major axis (negative for hyperbolas), eccentricity, inclination, right ascension of the ascending node, argument of periapsis, true anomaly.

raanfield
final double raan

Semi-major axis (negative for hyperbolas), eccentricity, inclination, right ascension of the ascending node, argument of periapsis, true anomaly.

final double argPeriapsis

Semi-major axis (negative for hyperbolas), eccentricity, inclination, right ascension of the ascending node, argument of periapsis, true anomaly.

final double trueAnomaly

Semi-major axis (negative for hyperbolas), eccentricity, inclination, right ascension of the ascending node, argument of periapsis, true anomaly.

pgetter
double get p

Semi-latus rectum p = a(1 - e^{2}).

Methods

periodmethod
double period(double mu)
Example
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');
}
Output
2.7644 h
toStringmethod
String toString()
Example
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());
}
Output
OrbitalElements(a: 10000.0, e: 0.2, i: 0.5, Ω: 1.0, ω: 0.3, ν: 2.0)
class

Kepler

abstract final class Kepler

Kepler's equation, conversions between anomalies, and two-body propagation.

Static

eccentricAnomalystaticmethod
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.

Example
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))}');
}
Output
M = 1: E = 1.5997, check E − e sin E = 1.0000
hyperbolicAnomalystaticmethod
static double hyperbolicAnomaly(double meanAnomaly, double e)

Solves M = e \sinh H - H for the hyperbolic anomaly (e > 1).

Example
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)}');
}
Output
H = 1.6127, check e sinh H − H = 2.0000
trueFromEccentricstaticmethod
static double trueFromEccentric(double ea, double e)
Example
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))}');
}
Output
E = 1 -> ν = 1.6592
eccentricFromTruestaticmethod
static double eccentricFromTrue(double nu, double e)
Example
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))}');
}
Output
ν = 2 -> E = 1.3232
trueFromHyperbolicstaticmethod
static double trueFromHyperbolic(double h, double e)
Example
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)));
}
Output
1.6036
hyperbolicFromTruestaticmethod
static double hyperbolicFromTrue(double nu, double e)
Example
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)));
}
Output
0.4987
meanFromTruestaticmethod
static double meanFromTrue(double nu, double e)
Example
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))}');
}
Output
ν = π/2 -> M = 0.4473
trueFromMeanstaticmethod
static double trueFromMean(double m, double e)
Example
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))}');
}
Output
M = π/4 -> ν = 2.0466
round trip: 0.7000
stumpffstaticmethod
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).

Example
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)}');
  }
}
Output
ψ = -1.0: c2 = 0.5431, c3 = 0.1752
ψ = 0.0: c2 = 0.5000, c3 = 0.1667
ψ = 1.0: c2 = 0.4597, c3 = 0.1585
propagatestaticmethod
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).

Example
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)}');
}
Output
period 4.3362 h; back at perigee: (7000.0000, 0.0000, 0.0000)
elementsFromStatestaticmethod
static OrbitalElements elementsFromState(Vec3d r, Vec3d v, {double mu = Bodies.earthMu})

Vallado's RV2COE: state vector (km, km/s) to classical elements.

Example
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);
}
Output
OrbitalElements(a: 8153.69926356321, e: 0.1414939681082911, i: 0.1243549945467616, Ω: 0.0, ω: 0.0, ν: 0.0)
stateFromElementsstaticmethod
static (Vec3d, Vec3d) stateFromElements(OrbitalElements el, {double mu = Bodies.earthMu})

Vallado's COE2RV: classical elements to state vector (km, km/s).

Example
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');
}
Output
GPS-like orbit: r = (14271.8829, 12748.9641, 18207.4077) km, v = (-3.2600, 1.2228, 1.7464) km/s
periodstaticmethod
static double period(double a, {double mu = Bodies.earthMu})

Orbital period (s) of semi-major axis a (km).

Example
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');
}
Output
ISS (a = 6778 km): 92.5576 min
geostationary: 23.9343 h
visVivastaticmethod
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.

Example
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');
}
Output
speed at perigee of a 7000 × 20000 km orbit: 9.1848 km/s
escapeSpeedstaticmethod
static double escapeSpeed(double r, {double mu = Bodies.earthMu})

Escape speed (km/s) at radius r.

Example
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');
}
Output
from the surface: 11.1799 km/s
circularSpeedstaticmethod
static double circularSpeed(double r, {double mu = Bodies.earthMu})

Circular-orbit speed (km/s) at radius r.

Example
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');
}
Output
low orbit: 7.6686 km/s
hohmannstaticmethod
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).

Example
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');
}
Output
LEO to GEO: Δv1 2.3975, Δv2 1.4565 km/s, 5.2912 h
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

ParticleStateconstructor
ParticleState(this.count)
Example
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}');
}
Output
positions 9 values, masses [1.0, 1.0, 1.0], charges [0.0, 0.0, 0.0]
kinetic energy 2.0

Properties

countfield
final int count
final Float64List position
final Float64List velocity
massfield
final Float64List mass

Per-particle mass (kg; 1 by default) and charge (C; 0 by default).

chargefield
final Float64List charge

Per-particle mass (kg; 1 by default) and charge (C; 0 by default).

timefield
double time

Simulation time (s).

double get kineticEnergy
momentumgetter
(double, double, double) get momentum

Total momentum (px, py, pz).

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

stepmethod
void step(ParticleState state, ForceField force, double dt)
Example
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])}');
  }
}
Output
SemiImplicitEuler lands at x = 20.0000
VelocityVerlet    lands at x = 20.5000
RungeKutta4       lands at x = 20.5000
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])
Example
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)})');
}
Output
lands near x = 20.5000 (exact 2·10·10/9.81 = 20.3874)

Properties

methodfield
final SymplecticMethod method

Methods

resetmethod
void reset()

Call when positions are changed from outside, so a cached force is recomputed.

Example
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])}');
}
Output
x = 1.9800
stepmethod
void step(ParticleState s, ForceField force, double dt)
Example
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)');
}
Output
energy after 300 steps: 0.50000374 (start 0.5)
final class VelocityVerlet extends SymplecticStepper

Velocity Verlet (kick–drift–kick): second order, symplectic, one force evaluation per step.

Constructors

VelocityVerletconstructor
VelocityVerlet()
Example
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)})');
}
Output
lands near x = 20.5000 (exact 2·10·10/9.81 = 20.3874)
final class SemiImplicitEuler implements ParticleStepper

Semi-implicit (symplectic) Euler: v += a dt, x + = v dt. First order; kept for its one-line cost.

Methods

stepmethod
void step(ParticleState s, ForceField force, double dt)
Example
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)})');
}
Output
lands near x = 20.0000 (exact 2·10·10/9.81 = 20.3874)
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

stepmethod
void step(ParticleState s, ForceField force, double dt)
Example
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)})');
}
Output
lands near x = 20.5000 (exact 2·10·10/9.81 = 20.3874)
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

dynamicvalue
dynamic
staticvalue
static
kinematic
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).

Example
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}');
}
Output
mass 500.0000 kg, type dynamic
factory RigidBody.static(Collider collider, {Vec3d position = Vec3d.zero, Quatd orientation = Quatd.identity})
Example
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}');
}
Output
static: inverse mass 0.0
factory RigidBody.kinematic(Collider collider, {Vec3d position = Vec3d.zero, Quatd orientation = Quatd.identity})
Example
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}');
}
Output
kinematic: moves at a set velocity, ignores forces; inverse mass 0.0

Properties

final Collider collider
typefield
final BodyType type
idfield
int id

Index in its world (set when added).

Object? userData
massfield
double mass
invMassfield
double invMass
Mat3d inertiaLocal
Mat3d invInertiaLocal
Mat3d invInertiaWorld

I^{-1} in world frame, R I^{-1}_{\mathrm{local}} R^{T}; refreshed every step.

Vec3d position
Quatd orientation
Vec3d linearVelocity
Vec3d angularVelocity
forcefield
Vec3d force
torquefield
Vec3d torque
double friction
double restitution
double linearDamping
double angularDamping
double gravityScale
int collisionGroup

Bits of the groups this body is in, and the groups it collides with.

int collisionMask
awakefield
bool awake
double sleepTime
isDynamicgetter
bool get isDynamic
Mat3d get inertiaWorld

The world inertia tensor R I R^{T}.

boundsgetter
Aabb get bounds
double get kineticEnergy
Vec3d get linearMomentum
Vec3d get angularMomentum

Angular momentum about the world origin: r \times m v + I \omega.

Methods

void updateInertia()

Recomputes invInertiaWorld from the orientation.

Example
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))]}');
}
Output
world inverse inertia diagonal [1.4118, 4.8000, 1.2000]
Vec3d velocityAt(Vec3d p)

Velocity of the material point at world position p.

Example
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)))}');
}
Output
point (2, 0, 0) moves at (0.0000, 2.0000, 0.0000)
toWorldmethod
Vec3d toWorld(Vec3d local)
Example
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))}');
}
Output
local (1, 0, 0) -> world (1.0000, 1.0000, 0.0000)
toLocalmethod
Vec3d toLocal(Vec3d world)
Example
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)))}');
}
Output
world (1, 1, 0) -> local (1.0000, 0.0000, 0.0000)
void applyForce(Vec3d f, {Vec3d? at})
Example
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)');
}
Output
x after 1.5 s: 3.3250 (1 + ½·2·1.5² = 3.25)
void applyTorque(Vec3d t)
Example
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');
}
Output
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).

Example
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)}');
}
Output
linear (0.0000, 1.0000, 0.0000), angular (0.0000, 0.0000, 2.4000)
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

DynamicAabbTreeconstructor
DynamicAabbTree({this.margin = 0.05})
Example
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()}');
}
Output
boxes hit by [2, 5]: [1, 2, 3]

Properties

marginfield
final double margin
rootgetter
int get root
heightgetter
int get height

Tree height (0 for a single leaf); a balanced tree of n leaves is about log2 n.

Methods

fatBoundsmethod
Aabb fatBounds(int id)

The fat box of proxy id.

Example
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)');
}
Output
stored box (-0.1000, -0.1000, -0.1000) – (1.1000, 1.1000, 1.1000) (inflated by the margin)
userDatamethod
int userData(int id)
Example
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)]);
}
Output
[0, 1, 2, 3, 4, 5]
insertmethod
int insert(Aabb box, int data)

Inserts box for data; returns the proxy id.

Example
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()}');
}
Output
node 0 holds 42, valid tree: true
removemethod
void remove(int id)
Example
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()}');
}
Output
after removing box 2: [1, 3], valid true
movemethod
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.

Example
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)))}');
}
Output
small move stays inside the fat box: false
big move reinserts: true
querymethod
void query(Aabb box, void Function(int data) hit)

Calls hit with the user data of every leaf whose fat box overlaps box.

Example
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');
}
Output
everything: 6 boxes
validatemethod
bool validate()

Checks parent links, heights and that every node box encloses its children (tests).

Example
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());
}
Output
true
class

Aabb

final class Aabb

An axis-aligned box in double precision (broadphase bounds).

Constructors

Aabbconstructor
const Aabb(this.min, this.max)
Example
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}');
}
Output
a: (0.0000, 0.0000, 0.0000) – (2.0000, 2.0000, 2.0000), surface area 24.0

Static

everythingconstant
static const everything = Aabb(Vec3d(-1e30, -1e30, -1e30), Vec3d(1e30, 1e30, 1e30))

Properties

minfield
final Vec3d min
maxfield
final Vec3d max
areagetter
double get area

Surface area (the SAH cost of a tree node).

Methods

overlapsmethod
bool overlaps(Aabb o)
Example
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)}');
}
Output
a and b: true, b and c: true
containsmethod
bool contains(Aabb o)
Example
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)}');
}
Output
a contains c: true, b contains c: false
unionmethod
Aabb union(Aabb o)
Example
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)}');
}
Output
(0.0000, 0.0000, 0.0000) – (3.0000, 3.0000, 3.0000)
inflatemethod
Aabb inflate(double m)
Example
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)}');
}
Output
(0.2500, 0.2500, 0.2500) – (1.2500, 1.2500, 1.2500)
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

Colliderconstructor
const Collider()
Example
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)}');
  }
}
Output
SphereCollider   mass at ρ = 1: 4.1888
BoxCollider      mass at ρ = 1: 8.0000
CapsuleCollider  mass at ρ = 1: 1.3090

Methods

boundsmethod
Aabb bounds(Vec3d p, Quatd q)

World bounds at pose (p, q).

Example
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)}');
}
Output
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³).

Example
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');
}
Output
steel ball, r = 10 cm: 32.8820 kg
convexAtmethod
Convex? convexAt(Vec3d p, Quatd q)

A support-function view for GJK/EPA at a pose (float32, riptide_math's Convex).

Example
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}');
}
Output
support +y at (0, 3, 0): 4.0
final class SphereCollider extends Collider

Constructors

SphereColliderconstructor
const SphereCollider(this.radius)
Example
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)}');
}
Output
bounds at (1, 2) turned 30°: min (0.5000, 1.5000, -0.5000), max (1.5000, 2.5000, 0.5000)

Properties

radiusfield
final double radius

Methods

boundsmethod
Aabb bounds(Vec3d p, Quatd q)
Example
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)}');
  }
}
Output
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)
Example
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))]}');
}
Output
mass 523.5988 kg, centre (0.0000, 0.0000, 0.0000)
inertia diagonal [52.3599, 52.3599, 52.3599]
convexAtmethod
Convex convexAt(Vec3d p, Quatd q)
Example
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))];
}
Output
farthest point along +x: (2.5000, 0.0000, 0.0000)
final class BoxCollider extends Collider

Constructors

BoxColliderconstructor
const BoxCollider(this.halfExtents)
Example
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)}');
}
Output
bounds at (1, 2) turned 30°: min (-0.1160, 1.0670, -0.5000), max (2.1160, 2.9330, 0.5000)

Properties

final Vec3d halfExtents

Methods

boundsmethod
Aabb bounds(Vec3d p, Quatd q)
Example
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)}');
  }
}
Output
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)
Example
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))]}');
}
Output
mass 2000.0000 kg, centre (0.0000, 0.0000, 0.0000)
inertia diagonal [333.3333, 833.3333, 833.3333]
convexAtmethod
Convex convexAt(Vec3d p, Quatd q)
Example
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))];
}
Output
farthest point along +x: (3.0000, 0.5000, 0.5000)
final class CapsuleCollider extends Collider

A capsule along the local Y axis: the segment (0, ±halfHeight, 0) swept by a sphere of radius.

Constructors

CapsuleColliderconstructor
const CapsuleCollider(this.halfHeight, this.radius)
Example
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)}');
}
Output
bounds at (1, 2) turned 30°: min (0.4000, 1.1804, -0.3000), max (1.6000, 2.8196, 0.3000)

Properties

final double halfHeight
radiusfield
final double radius

Methods

segmentmethod
(Vec3d, Vec3d) segment(Vec3d p, Quatd q)

The segment end points in world space.

Example
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)}');
}
Output
core segment (-1.0000, 0.0000, 0.0000) – (1.0000, 0.0000, 0.0000)
boundsmethod
Aabb bounds(Vec3d p, Quatd q)
Example
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)}');
  }
}
Output
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)
Example
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))]}');
}
Output
mass 452.3893 kg, centre (0.0000, 0.0000, 0.0000)
inertia diagonal [108.4038, 19.3396, 108.4038]
convexAtmethod
Convex convexAt(Vec3d p, Quatd q)
Example
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))];
}
Output from the Raya VM
farthest point along +x: (2.3000, -0.6000, 0.0000)
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)
Example
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)}');
}
Output
bounds at (1, 2) turned 30°: min (0.4085, 1.6585, -0.2500), max (1.7745, 2.5245, 0.7500)

Properties

pointsfield
final Float32x4List points

Hull vertices in the local frame (centre of mass at the origin), as float32 lanes for GJK.

final Uint32List triangles

Hull triangles (3 indices each), outward winding.

Methods

boundsmethod
Aabb bounds(Vec3d p, Quatd q)
Example
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)}');
  }
}
Output
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)
Example
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))]}');
}
Output
mass 166.6667 kg, centre (0.0000, 0.0000, 0.0000)
inertia diagonal [12.5000, 12.5000, 12.5000]
convexAtmethod
Convex convexAt(Vec3d p, Quatd q)
Example
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))];
}
Output
farthest point along +x: (2.7500, -0.2500, -0.2500)
Iterable<Vec3d> worldPoints(Vec3d p, Quatd q)

World-space vertices at a pose.

Example
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)]);
}
Output
[(1.8706, -0.4410, -0.2500), (2.7482, 0.0384, -0.2500), (1.3912, 0.4366, -0.2500), (1.9900, -0.0339, 0.7500)]
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

PlaneColliderconstructor
PlaneCollider(Vec3d normal, this.offset)
Example
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)}');
}
Output
bounds at (1, 2) turned 30°: min (-1e+30, -1e+30, -1e+30), max (1e+30, 1e+30, 1e+30)

Properties

normalfield
final Vec3d normal
offsetfield
final double offset

Methods

boundsmethod
Aabb bounds(Vec3d p, Quatd q)
Example
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)}');
  }
}
Output
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)
Example
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}');
}
Output
a plane is static: mass 0.0
convexAtmethod
Convex? convexAt(Vec3d p, Quatd q)
Example
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)');
}
Output
convexAt: null (an infinite plane is not a bounded convex)
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)
Example
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)}');
}
Output
bounds at (1, 2) turned 30°: min (0.1363, 1.3323, -0.4000), max (1.9853, 2.7421, 0.4000)

Properties

final List<CompoundChild> children
shiftfield
final Vec3d shift

Methods

childPosemethod
(Vec3d, Quatd) childPose(int i, Vec3d p, Quatd q)

Child i's world pose for a body at (p, q).

Example
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)}');
}
Output
child 1 world position (0.0000, 0.6646, 0.0000)
boundsmethod
Aabb bounds(Vec3d p, Quatd q)
Example
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)}');
  }
}
Output
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)
Example
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))]}');
}
Output
mass 484.0826 kg, centre (0.0000, 0.0000, 0.0000)
inertia diagonal [30.1173, 202.3697, 202.3697]
convexAtmethod
Convex? convexAt(Vec3d p, Quatd q)
Example
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}'}');
}
Output
convexAt: null
a single child: null
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

ManifoldPointconstructor
ManifoldPoint(this.localA, this.localB, this.depth)
Example
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)}');
}
Output
depth 0.05, local points (0.0000, 0.5000, 0.0000) and (0.0000, -0.5000, 0.0000)

Properties

localAfield
Vec3d localA

The point on A's surface deepest inside B, and on B's surface deepest inside A, in body frames.

localBfield
Vec3d localB

The point on A's surface deepest inside B, and on B's surface deepest inside A, in body frames.

depthfield
double depth
double normalImpulse
double tangentImpulse1
double tangentImpulse2
rAfield
Vec3d rA
rBfield
Vec3d rB
double normalMass
double tangentMass1
double tangentMass2
double velocityBias
final class ContactManifold

The contact manifold of a body pair: one normal (A to B) and up to 4 points.

Constructors

ContactManifoldconstructor
ContactManifold(this.a, this.b, this.shapeA, this.shapeB)
Example
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}');
}
Output
1 point, normal (0.0000, 1.0000, 0.0000), friction 0.5

Properties

afield
final RigidBody a
bfield
final RigidBody b
shapeAfield
final int shapeA

Leaf indices inside compound shapes (0 otherwise).

shapeBfield
final int shapeB

Leaf indices inside compound shapes (0 otherwise).

normalfield
Vec3d normal
pointsfield
final points
t1field
Vec3d t1
t2field
Vec3d t2
double friction
double restitution

Methods

worldAmethod
Vec3d worldA(ManifoldPoint p)

Builds world anchors from the stored local ones.

Example
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))}');
}
Output
on A: (0.0000, 0.5000, 0.0000)
worldBmethod
Vec3d worldB(ManifoldPoint p)
Example
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))}');
}
Output
on B: (0.0000, 0.4500, 0.0000)
final class SolverSettings

Solver settings. Defaults follow Box2D v2.4: 8 velocity and 3 position iterations, 5 mm slop, 0.2 correction.

Constructors

SolverSettingsconstructor
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})
Example
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}');
}
Output
20 velocity iterations, slop 0.001, baumgarte 0.2

Properties

final int velocityIterations
final int positionIterations
slopfield
final double slop

Penetration allowed without correction (m), so resting contacts stay touching.

final double baumgarte

Fraction of the penetration removed per position iteration.

final double maxCorrection
final double restitutionThreshold

Approach speed (m/s) below which restitution is ignored, so resting bodies don't jitter.

final bool warmStarting
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

ContactSolverconstructor
ContactSolver(this.settings)
Example
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)}');
}
Output
approach speed removed: v_y = 0.0000

Properties

final SolverSettings settings

Methods

preparemethod
void prepare(List<ContactManifold> manifolds)
Example
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');
}
Output
effective mass along the normal: 1000.0000 kg
void solveVelocities(List<ContactManifold> manifolds)
Example
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');
}
Output
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.

Example
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)}');
}
Output
largest penetration before correction: 0.0500; box moved up to y = 0.9590
class

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

Jointconstructor
Joint(this.a, this.b)
Example
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');
}
Output
joint between static and dynamic bodies

Properties

afield
final RigidBody a
bfield
final RigidBody b
double baumgarte

Fraction of the position error removed per step.

Methods

preparemethod
void prepare(double dt, {required bool warmStart})
Example
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');
}
Output
ok
void solveVelocity()
Example
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)}');
}
Output
stretching speed removed: v = (0.0000, 0.0000, 0.0000)
final class BallJoint extends Joint

Ball-and-socket: the anchor points coincide (3 linear constraints).

Constructors

BallJointconstructor
BallJoint(super.a, super.b, Vec3d anchor)

anchor in world space at creation.

Example
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)}');
}
Output
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

localAfield
final Vec3d localA
localBfield
final Vec3d localB

Methods

preparemethod
void prepare(double dt, {required bool warmStart})
Example
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)}');
}
Output
prepared: anchors and effective masses computed for one step
b velocity after one solve (0.0000, 0.0000, 0.0000)
void solveVelocity()
Example
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)))}');
}
Output
anchor velocity after solving: (0.0000, 0.0000, 0.0000)
final class DistanceJoint extends Joint

Keeps the anchors at length apart (a rigid rod; 1 constraint along the line between them).

Constructors

DistanceJointconstructor
DistanceJoint(super.a, super.b, Vec3d anchorA, Vec3d anchorB, {double? length})
Example
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)}');
}
Output
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

localAfield
final Vec3d localA
localBfield
final Vec3d localB
lengthfield
final double length

Methods

preparemethod
void prepare(double dt, {required bool warmStart})
Example
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)}');
}
Output
prepared: anchors and effective masses computed for one step
b velocity after one solve (0.0000, 0.0000, 0.0000)
void solveVelocity()
Example
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)))}');
}
Output
anchor velocity after solving: (0.0000, -1.5000, 0.0000)
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

HingeJointconstructor
HingeJoint(super.a, super.b, Vec3d anchor, Vec3d axis)
Example
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)}');
}
Output
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

axisAfield
final Vec3d axisA
axisBfield
final Vec3d axisB
double get twistParameter

The 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.

anglegetter
double get angle

The 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

preparemethod
void prepare(double dt, {required bool warmStart})
Example
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)}');
}
Output
prepared: anchors and effective masses computed for one step
b velocity after one solve (0.0000, 0.0000, 0.0000)
void solveVelocity()
Example
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)))}');
}
Output
anchor velocity after solving: (0.0000, 0.0000, 0.0000)
final class FixedJoint extends Joint

Welds two bodies: point constraint + 3 angular constraints holding their relative orientation.

Constructors

FixedJointconstructor
FixedJoint(super.a, super.b, Vec3d anchor)
Example
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)}');
}
Output
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

preparemethod
void prepare(double dt, {required bool warmStart})
Example
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)}');
}
Output
prepared: anchors and effective masses computed for one step
b velocity after one solve (0.0000, 0.0000, 0.0000)
void solveVelocity()
Example
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)))}');
}
Output
anchor velocity after solving: (0.0000, 0.0441, 0.0000)
enum BroadphaseKind

Which broadphase finds candidate pairs.

Values

treevalue
tree

Incremental dynamic AABB tree (default; best when most bodies move a little each step).

sweepAndPrune

Sweep and prune on X, rebuilt each step (riptide_math's Broadphase); fine for a few hundred bodies.

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

PhysicsWorldconstructor
PhysicsWorld({this.gravity = const Vec3d(0, -9.81, 0), this.settings = const SolverSettings(), this.broadphase = BroadphaseKind.tree, this.gyroscopic = true, this.sleeping = false})
Example
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)}');
}
Output
after 4 s: height 0.5028

Properties

gravityfield
Vec3d gravity
final SolverSettings settings
final BroadphaseKind broadphase
final bool gyroscopic

Integrate 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 sleeping

Put bodies to sleep after sleepDelay s below sleepLinear / sleepAngular; contacts wake them.

double sleepLinear
double sleepAngular
double sleepDelay
bodiesfield
final bodies
jointsfield
final joints
manifoldsgetter
Iterable<ContactManifold> get manifolds

The contact manifolds found in the last step.

timefield
double time
double get kineticEnergy

Total kinetic energy of the dynamic bodies (J).

double get potentialEnergy

Gravitational potential energy relative to the origin (J).

Vec3d get linearMomentum
Vec3d get angularMomentum

Methods

addmethod
RigidBody add(RigidBody body)
Example
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}');
}
Output
2 bodies; the ball got id 1
addJointmethod
Joint addJoint(Joint j)
Example
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)}');
}
Output
rope length kept: 1.0102
stepmethod
void step(double dt)

Advances the world by dt seconds.

Example
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');
}
Output
t = 1.0000, kinetic 7529.2519 J
queryAabbmethod
List<RigidBody> queryAabb(Aabb box)

Bodies whose (fat) bounds overlap box.

Example
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}');
}
Output
bodies in the box around the ball: 2
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

XpbdBodyconstructor
XpbdBody(int count)
Example
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)}');
}
Output
tip after 1 s: (-1.6038, -0.8027, 0.0000); max strain 1.66e-3

Properties

xfield
final Float64List x

Positions, previous positions and velocities (interleaved xyz) and inverse masses (0 = pinned).

prevfield
final Float64List prev

Positions, previous positions and velocities (interleaved xyz) and inverse masses (0 = pinned).

vfield
final Float64List v

Positions, previous positions and velocities (interleaved xyz) and inverse masses (0 = pinned).

invMassfield
final Float64List invMass

Positions, previous positions and velocities (interleaved xyz) and inverse masses (0 = pinned).

countgetter
int get count
gravityfield
Vec3d gravity
dampingfield
double damping

Velocity damping per second (0 = none).

double friction

Friction coefficient against colliders (position-level, Müller et al. 2007 style).

double thickness

Particle radius for collisions (m).

final colliders

Rigid bodies the particles collide with.

int get distanceConstraintCount
int get volumeConstraintCount
volumegetter
double get volume

Current total volume of the tetrahedra (each counted with its rest orientation, so inverted tets subtract).

double get restVolume
double get kineticEnergy

Methods

positionmethod
Vec3d position(int i)
Example
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)));
}
Output
(1.0000, 2.0000, 3.0000)
void setPosition(int i, Vec3d p)
Example
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);
}
Output
[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.

Example
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)}');
}
Output
distance after one step: 1.7157
addVolumemethod
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).

Example
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)');
}
Output
rest volume 0.1667 (1/6)
maxStrainmethod
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).

Example
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)}');
}
Output
largest relative stretch 0.00e+0
stepmethod
void step(double dt, {int substeps = 10})

Advances dt seconds in substeps substeps (each: predict, solve every constraint once, update velocities).

Example
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)}');
}
Output
volume kept: 0.9997
abstract final class SoftBodies

Builders for common XPBD bodies.

Static

clothstaticmethod
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²).

Example
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');
}
Output
64 particles
softBoxstaticmethod
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³.

Example
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)}');
}
Output
27 particles, rest volume 1.0000
final class SparseBuilder

Accumulates (row, col, value) triplets, summing duplicates (FEM assembly), and compresses to Csr.

Constructors

SparseBuilderconstructor
SparseBuilder(this.n)
Example
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');
}
Output
3 × 3, 7 nonzeros

Properties

nfield
final int n

Methods

addmethod
void add(int r, int c, double v)
Example
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]}');
}
Output
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.

Example
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');
}
Output
with u0 = 1, u2 = 3: u = [1.0, 1.9999999999999998, 3.0]
buildmethod
CsrMatrix build()
Example
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());
}
Output
[2.0, -1.0, 0.0, -1.0, 2.0, -1.0, 0.0, -1.0, 2.0]
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

speedOfLightconstant
static const speedOfLight = 299792458.0

Speed of light in vacuum c (m/s).

planckconstant
static const planck = 6.62607015e-34

Planck constant h (J \cdot s).

static const reducedPlanck = 1.054571817e-34

Reduced Planck constant \hbar = \frac{h}{2\pi} (J \cdot s).

static const elementaryCharge = 1.602176634e-19

Elementary charge e (C).

boltzmannconstant
static const boltzmann = 1.380649e-23

Boltzmann constant k_{B} (J/K).

avogadroconstant
static const avogadro = 6.02214076e23

Avogadro constant N_{A} (\frac{1}{mol}).

gasconstant
static const gas = 8.314462618

Molar gas constant R = N_{A} k_{B} (\frac{J}{mol \cdot K}).

static const stefanBoltzmann = 5.670374419e-8

Stefan–Boltzmann constant \sigma (\frac{W}{m^{2} \cdot K^{4}}).

electronVoltconstant
static const electronVolt = 1.602176634e-19

Electron volt (J).

static const gravitational = 6.67430e-11

Newtonian constant of gravitation G (\frac{m^{3}}{kg \cdot s^{2}}).

static const vacuumPermeability = 1.25663706212e-6

Vacuum magnetic permeability \mu_{0} (\frac{N}{A^{2}}).

static const vacuumPermittivity = 8.8541878128e-12

Vacuum electric permittivity \varepsilon_{0} = \frac{1}{\mu_{0}c^{2}} (\frac{F}{m}).

coulombconstant
static const coulomb = 8.9875517923e9

Coulomb constant \frac{1}{4\pi\varepsilon_{0}} (N \cdot \frac{m^{2}}{C^{2}}).

electronMassconstant
static const electronMass = 9.1093837015e-31

Electron mass m_{e} (kg).

protonMassconstant
static const protonMass = 1.67262192369e-27

Proton mass m_{p} (kg).

neutronMassconstant
static const neutronMass = 1.67492749804e-27

Neutron mass m_{n} (kg).

deuteronMassconstant
static const deuteronMass = 3.3435837724e-27

Deuteron mass m_{d} (kg).

alphaMassconstant
static const alphaMass = 6.6446573357e-27

Alpha particle mass m_{\alpha} (kg).

atomicMassconstant
static const atomicMass = 1.66053906660e-27

Atomic mass constant m_{u} = 1 Da (kg).

static const fineStructure = 7.2973525693e-3

Fine-structure constant \alpha (dimensionless).

rydbergconstant
static const rydberg = 10973731.568160

Rydberg constant R\infty (\frac{1}{m}).

bohrRadiusconstant
static const bohrRadius = 5.29177210903e-11

Bohr radius a_{0} (m).

static const classicalElectronRadius = 2.8179403262e-15

Classical electron radius r_{e} (m).

static const electronRestEnergyEv = 0.51099895000e6

Electron rest energy m_{e} c^{2} (eV).

static const protonRestEnergyEv = 938.27208816e6

Proton rest energy m_{p} c^{2} (eV).

static const electronChargeToMass = -1.75882001076e11

Electron charge-to-mass quotient -\frac{e}{m_{e}} (\frac{C}{kg}).

static const standardGravity = 9.80665

Standard acceleration of gravity g_{n} (m/s², exact by convention).

static const standardAtmosphere = 101325.0

Standard atmosphere (Pa, exact by convention).

static const astronomicalUnit = 149597870700.0

Astronomical unit (m, exact, IAU 2012 Resolution B2).

lightYearconstant
static const lightYear = 9460730472580800.0

Light year (m, Julian year × c).

parsecconstant
static const parsec = 3.0856775814913673e16

Parsec (m).

earthGMconstant
static const earthGM = 3.986004418e14

Earth's GM (\frac{m^{3}}{s^{2}}, IERS 2010 / WGS 84, includes the atmosphere).

earthRadiusconstant
static const earthRadius = 6378137.0

Earth's equatorial radius (m, WGS 84).

moonGMconstant
static const moonGM = 4.9028000661e12

Moon's GM (\frac{m^{3}}{s^{2}}, JPL DE430).

static const earthMoonDistance = 384400e3

Mean Earth–Moon distance (m).

sunGMconstant
static const sunGM = 1.3271244e20

Sun's GM (\frac{m^{3}}{s^{2}}, IAU 2015 nominal).

siderealDayconstant
static const siderealDay = 86164.0905

Sidereal day (s).

static const relativeUncertainty

CODATA 2018 standard relative uncertainties of the measured constants above.

final class Dimension

Units of measure, two ways:

  1. 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, so Length / Time is a Speed, Mass * Acceleration is a Force, and Length + Time does not compile.
  2. Quantity with a run-time Dimension (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

Dimensionconstructor
const Dimension({this.m = 0, this.kg = 0, this.s = 0, this.a = 0, this.k = 0, this.mol = 0, this.cd = 0})
Example
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()}');
}
Output
torque dimension: m^2·kg·s^-2
same as energy:   true
molar mass:       kg·mol^-1
dimensionless:    1

Static

noneconstant
static const none = Dimension()
lengthconstant
static const length = Dimension(m: 1)
massconstant
static const mass = Dimension(kg: 1)
timeconstant
static const time = Dimension(s: 1)
currentconstant
static const current = Dimension(a: 1)
temperatureconstant
static const temperature = Dimension(k: 1)
amountconstant
static const amount = Dimension(mol: 1)
static const luminousIntensity = Dimension(cd: 1)
speedconstant
static const speed = Dimension(m: 1, s: -1)
accelerationconstant
static const acceleration = Dimension(m: 1, s: -2)
forceconstant
static const force = Dimension(m: 1, kg: 1, s: -2)
energyconstant
static const energy = Dimension(m: 2, kg: 1, s: -2)
powerconstant
static const power = Dimension(m: 2, kg: 1, s: -3)
pressureconstant
static const pressure = Dimension(m: -1, kg: 1, s: -2)
chargeconstant
static const charge = Dimension(s: 1, a: 1)
voltageconstant
static const voltage = Dimension(m: 2, kg: 1, s: -3, a: -1)

Properties

mfield
final int m
kgfield
final int kg
sfield
final int s
afield
final int a
kfield
final int k
molfield
final int mol
cdfield
final int cd
hashCodegetter
int get hashCode

Methods

powmethod
Dimension pow(int n)
Example
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)}');
}
Output
length^2 = m^2
length^3 = m^3
time^-1  = s^-1
speed^2  = m^2·s^-2
anything^0 = 1
toStringmethod
String toString()
Example
import 'package:riptide_physics/units.ray';

void main() {
  print('force:    ${Dimension.force}');
  print('pressure: ${Dimension.pressure}');
  print('voltage:  ${Dimension.voltage}');
  print('none:     ${Dimension.none}');
}
Output
force:    m·kg·s^-2
pressure: m^-1·kg·s^-2
voltage:  m^2·kg·s^-3·A^-1
none:     1

Operators

operator *operator
Dimension operator *(Dimension o)
Example
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)');
}
Output
mass × acceleration = m·kg·s^-2
is a force: true
force × length = m^2·kg·s^-2 (energy)
operator /operator
Dimension operator /(Dimension o)
Example
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}');
}
Output
length / time = m·s^-1, a speed: true
energy / time = m^2·kg·s^-3 (power)
force / force = 1
operator ==operator
bool operator ==(Object other)
Example
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}');
}
Output
power / current = m^2·kg·s^-3·A^-1
== voltage: true
energy == torque-like m²·kg·s⁻²: true
speed == acceleration: false
final class Quantity

A value with a run-time dimension, in SI base units.

Constructors

Quantityconstructor
const Quantity(this.value, this.dimension)
Example
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}');
}
Output
g = 9.80665 m·s^-2
m = 70.0 kg
weight = 686.4654999999999 m·kg·s^-2

Properties

valuefield
final double value
final Dimension dimension

Methods

scalemethod
Quantity scale(double s)
Example
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)}');
}
Output
one lap:  400.0 m
25 laps:  10000.0 m
half lap: 200.0 m
powmethod
Quantity pow(int n)
Example
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)}');
}
Output
side   = 3.0 m
area   = 9.0 m^2
volume = 27.0 m^3
1/side = 0.3333333333333333 m^-1
inUnitmethod
double inUnit(Quantity unit)

The value in unit (which must have the same dimension).

Example
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}');
  }
}
Output
marathon in miles: 26.219
marathon in feet:  138435
in seconds: dimension mismatch: m vs s
toStringmethod
String toString()
Example
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));
}
Output
1.5 m^2·kg·s^-2
2.0 m·s^-1
3.0 1

Operators

operator +operator
Quantity operator +(Quantity o)
Example
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}');
  }
}
Output
3 m + 50 cm = 3.5 m
3 m + 1 s: dimension mismatch: m vs s
operator -operator
Quantity operator -(Quantity o)
Example
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)}');
}
Output
left: 7500.0 m^2·kg·s^-2
left in kJ: 7.5
operator *operator
Quantity operator *(Quantity o)
Example
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}');
}
Output
20 N × 5 m = 100.0 m^2·kg·s^-2
is energy: true
operator /operator
Quantity operator /(Quantity o)
Example
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)}');
}
Output
100 km / 1.25 h = 22.22222222222222 m·s^-1
in km/h: 80.0
operator <operator
bool operator <(Quantity o)
Example
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}');
  }
}
Output
1 mile < 1.5 km: false
mile < 1 kg: dimension mismatch: m vs kg
operator >operator
bool operator >(Quantity o)
Example
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');
}
Output
1 atm > 1 bar: true
difference: 1325 Pa
extension type

Length

extension type const Length(double m)

Length (m).

Constructors

Length.kmconstructor
const Length.km(double v)
Example
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');
}
Output
5 km = 5000.0 m
     = 3.107 miles
Length.cmconstructor
const Length.cm(double v)
Example
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');
}
Output
180 cm = 1.8 m = 5.91 ft
plus 5 cm = 1.85 m
Length.mmconstructor
const Length.mm(double v)
Example
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)}');
}
Output
12 mm = 0.012 m
in inches: 0.4724
Length.milesconstructor
const Length.miles(double v)
Example
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');
}
Output
26.2 miles = 42.165 km
Length.feetconstructor
const Length.feet(double v)
Example
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');
}
Output
29,032 ft = 8849.0 m
          = 5.498 miles
Length.inchesconstructor
const Length.inches(double v)
Example
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');
}
Output
13.3 in = 0.33782 m = 33.78 cm
const Length.nauticalMiles(double v)
Example
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');
}
Output
60 nmi = 111.12 km
one degree of latitude ≈ 60 nmi ≈ 69.0 statute miles
Length.auconstructor
const Length.au(double v)
Example
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');
}
Output
Mars orbit: 2.2799e+8 km
sunlight reaches Mars in 12.7 minutes
const Length.lightYears(double v)
Example
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');
}
Output
Proxima Centauri: 268553 AU
                = 4.0175e+13 km

Properties

kmgetter
double get km
milesgetter
double get miles
feetgetter
double get feet
augetter
double get au
qgetter
Quantity get q

Methods

timesmethod
Area times(Length o)
Example
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³');
}
Output
4 m × 2.5 m = 10.0 m²
× 3 m high = 30.0 m³
permethod
Speed per(Time t)
Example
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');
}
Output
marathon record pace: 5.805 m/s = 20.90 km/h
ratiomethod
double ratio(Length o)
Example
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)}');
}
Output
1 km / 1 mile = 0.62137
earth radius / moon distance = 0.01659

Operators

operator +operator
Length operator +(Length o)
Example
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');
}
Output
1 km + 1 mile + 100 ft = 2639.82 m
operator -operator
Length operator -(Length o)
Example
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');
}
Output
still to run: 12.195 km = 7.58 miles
operator *operator
Length operator *(double s)
Example
import 'raya:convert';
import 'package:riptide_physics/units.ray';

void main() {
  const stride = Length(0.78);
  print('10,000 steps = ${(stride * 10000).km} km');
}
Output
10,000 steps = 7.8 km
extension type

Time

extension type const Time(double s)

Time (s).

Constructors

Time.msconstructor
const Time.ms(double v)
Example
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)}');
}
Output
one frame: 0.016667 s
frames per second: 60.00
Time.minutesconstructor
const Time.minutes(double v)
Example
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');
}
Output
90 min = 5400.0 s = 1.5 h
Time.hoursconstructor
const Time.hours(double v)
Example
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');
}
Output
36 h = 1.5 days = 2160.0 min
Time.daysconstructor
const Time.days(double v)
Example
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');
}
Output
sidereal day = 23.9345 h
solar - sidereal = 235.9 s
Time.yearsconstructor
const Time.years(double v)
Example
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');
}
Output
Julian year = 31557600.0 s = 365.25 days
light-year = 9.460730e+15 m

Properties

minutesgetter
double get minutes
hoursgetter
double get hours
daysgetter
double get days
inversegetter
Frequency get inverse
qgetter
Quantity get q

Operators

operator +operator
Time operator +(Time o)
Example
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');
}
Output
2 h 45 min 30 s = 9930.0 s = 2.7583 h
operator -operator
Time operator -(Time o)
Example
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');
}
Output
awake: 16.0 h
operator *operator
Time operator *(double k)
Example
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');
}
Output
20 laps: 24.17 min
extension type

Mass

extension type const Mass(double kg)

Mass (kg).

Constructors

Mass.gramsconstructor
const Mass.grams(double v)
Example
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');
}
Output
quarter: 0.00567 kg
1000 quarters: 12.50 lb
Mass.tonnesconstructor
const Mass.tonnes(double v)
Example
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');
}
Output
18 t = 18000.0 kg = 39683 lb
Mass.poundsconstructor
const Mass.pounds(double v)
Example
import 'raya:convert';
import 'package:riptide_physics/units.ray';

void main() {
  const m = Mass.pounds(150);
  print('150 lb = ${m.kg.toStringAsFixed(3)} kg');
}
Output
150 lb = 68.039 kg

Properties

poundsgetter
double get pounds
qgetter
Quantity get q

Methods

timesmethod
Force times(Acceleration a)
Example
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');
}
Output
weight on Earth: 735.5 N
weight on the Moon: 121.5 N
withSpeedmethod
Momentum withSpeed(Speed v)
Example
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');
}
Output
fastball momentum: 6.158 kg·m/s
permethod
Density per(Volume v)
Example
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)');
}
Output
19.3 kg per litre = 19300.0 kg/m³ (gold)

Operators

operator +operator
Mass operator +(Mass o)
Example
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');
}
Output
rider + pack + bottle = 79.572 kg
operator -operator
Mass operator -(Mass o)
Example
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');
}
Output
Falcon 9 minus dry mass: 523400.0 kg
operator *operator
Mass operator *(double s)
Example
import 'package:riptide_physics/units.ray';
import 'raya:convert';

void main() {
  const brick = Mass(2.3);
  print('500 bricks: ${(brick * 500).kg} kg');
}
Output
500 bricks: 1150.0 kg
extension type

Temperature

extension type const Temperature(double kelvin)

Thermodynamic temperature (K).

Constructors

const Temperature.celsius(double c)
Example
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');
}
Output
37 °C = 310.15 K = 98.6 °F
const Temperature.fahrenheit(double f)
Example
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');
}
Output
-40 °F = -40.0 °C (the two scales meet)
451 °F = 232.8 °C

Properties

celsiusgetter
double get celsius
double get fahrenheit
qgetter
Quantity get q
extension type

Area

extension type const Area(double m2)

Area (m^{2}).

Properties

qgetter
Quantity get q

Methods

timesmethod
Volume times(Length l)
Example
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');
}
Output
12 m² × 2.4 m = 28.799999999999997 m³ = 28799.999999999996 L

Operators

operator +operator
Area operator +(Area o)
Example
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²');
}
Output
L-shaped room: 16.0 m²
extension type

Volume

extension type const Volume(double m3)

Volume (m^{3}).

Constructors

Volume.litresconstructor
const Volume.litres(double v)
Example
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');
}
Output
60 L = 0.06 m³
mass of that much water: 60.0 kg

Properties

litresgetter
double get litres
qgetter
Quantity get q

Operators

operator +operator
Volume operator +(Volume o)
Example
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');
}
Output
1.5 L + 0.002 m³ = 3.5 L
extension type

Speed

extension type const Speed(double mps)

Speed (m/s).

Constructors

Speed.kmhconstructor
const Speed.kmh(double v)
Example
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');
}
Output
100 km/h = 27.778 m/s = 62.14 mph
Speed.mphconstructor
const Speed.mph(double v)
Example
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');
}
Output
60 mph = 96.561 km/h
Speed.knotsconstructor
const Speed.knots(double v)
Example
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');
}
Output
450 kn = 833.4 km/h = 517.9 mph
Speed.kmpsconstructor
const Speed.kmps(double v)
Example
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');
}
Output
ISS: 27576 km/h
one orbit (42,000 km) takes 459.6 km per minute

Properties

kmhgetter
double get kmh
mphgetter
double get mph
qgetter
Quantity get q

Methods

overmethod
Length over(Time t)
Example
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');
}
Output
in 20 minutes: 30.0 km
permethod
Acceleration per(Time t)
Example
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');
}
Output
0–100 km/h in 2.6 s: 10.68 m/s² = 1.09 g

Operators

operator +operator
Speed operator +(Speed o)
Example
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');
}
Output
airspeed + tailwind = 1092.7 km/h
operator -operator
Speed operator -(Speed o)
Example
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');
}
Output
overtaking at 5.556 m/s
operator *operator
Speed operator *(double s)
Example
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');
}
Output
Mach 2 = 2470 km/h
extension type

Acceleration

extension type const Acceleration(double mps2)

Acceleration (m/s²).

Constructors

Acceleration.gconstructor
const Acceleration.g(double v)
Example
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');
}
Output
3 g = 29.41995 m/s²
after 2 s: 211.8 km/h

Properties

inGgetter
double get inG
qgetter
Quantity get q

Methods

overmethod
Speed over(Time t)
Example
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');
}
Output
falling 3 s: 29.42 m/s

Operators

operator +operator
Acceleration operator +(Acceleration o)
Example
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');
}
Output
lift accelerating up at 2 m/s² feels like 1.204 g
extension type

Force

extension type const Force(double newtons)

Force (N).

Constructors

const Force.kilonewtons(double v)
Example
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²');
}
Output
one Merlin engine: 845000.0 N
accelerates 50 t at 16.90 m/s²
const Force.poundsForce(double v)
Example
import 'package:riptide_physics/units.ray';
import 'raya:convert';

void main() {
  const f = Force.poundsForce(100);
  print('100 lbf = ${f.newtons.toStringAsFixed(2)} N');
}
Output
100 lbf = 444.82 N

Properties

qgetter
Quantity get q

Methods

throughmethod
Energy through(Length d)
Example
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');
}
Output
climbing 3 m: 2058.0 J
permethod
Pressure per(Area a)
Example
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');
}
Output
700 N on a 1 cm² heel: 7000000.0 Pa = 69.1 atm
onmethod
Acceleration on(Mass m)
Example
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²');
}
Output
5 kN on 1250 kg: 4.0 m/s²

Operators

operator +operator
Force operator +(Force o)
Example
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');
}
Output
push + friction = 75.0 N
operator -operator
Force operator -(Force o)
Example
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');
}
Output
thrust minus weight: 2216.1 N
operator *operator
Force operator *(double s)
Example
import 'package:riptide_physics/units.ray';
import 'raya:convert';

void main() {
  const one = Force(800);
  print('nine engines: ${(one * 9).newtons} N');
}
Output
nine engines: 7200.0 N
extension type

Energy

extension type const Energy(double joules)

Energy (J).

Constructors

const Energy.kilojoules(double v)
Example
import 'package:riptide_physics/units.ray';
import 'raya:convert';

void main() {
  const e = Energy.kilojoules(3600);
  print('3600 kJ = ${e.kilowattHours} kWh');
}
Output
3600 kJ = 1.0 kWh
const Energy.electronVolts(double v)
Example
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');
}
Output
green photon: 3.6049e-19 J
wavelength: 551.0 nm
const Energy.kilowattHours(double v)
Example
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');
}
Output
75 kWh = 2.700e+8 J
runs a 2 kW heater for 37.5 h
Energy.caloriesconstructor
const Energy.calories(double v)
Example
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');
}
Output
250 kcal = 1046000.0 J = 0.291 kWh

Properties

double get electronVolts
double get kilowattHours
qgetter
Quantity get q

Methods

permethod
Power per(Time t)
Example
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');
}
Output
500 kJ in 10 minutes = 833.3 W

Operators

operator +operator
Energy operator +(Energy o)
Example
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');
}
Output
kinetic 9.0 J + potential 98.07 J = 107.07 J
operator -operator
Energy operator -(Energy o)
Example
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 %)');
}
Output
energy lost to heat: 130.0 J (13 %)
operator *operator
Energy operator *(double s)
Example
import 'package:riptide_physics/units.ray';
import 'raya:convert';

void main() {
  const daily = Energy.kilowattHours(12);
  print('a month: ${(daily * 30).kilowattHours} kWh');
}
Output
a month: 360.0 kWh
extension type

Power

extension type const Power(double watts)

Power (W).

Constructors

Power.kilowattsconstructor
const Power.kilowatts(double v)
Example
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');
}
Output
150 kW = 201.2 hp
Power.horsepowerconstructor
const Power.horsepower(double v)
Example
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');
}
Output
300 hp = 223.7 kW

Properties

qgetter
Quantity get q

Methods

overmethod
Energy over(Time t)
Example
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');
}
Output
10 W for a day: 0.24 kWh

Operators

operator +operator
Power operator +(Power o)
Example
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');
}
Output
total load: 3495.7 W
extension type

Pressure

extension type const Pressure(double pascals)

Pressure (Pa).

Constructors

const Pressure.kilopascals(double v)
Example
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');
}
Output
230 kPa = 33.4 psi
Pressure.barconstructor
const Pressure.bar(double v)
Example
import 'package:riptide_physics/units.ray';
import 'raya:convert';

void main() {
  const p = Pressure.bar(1);
  print('1 bar = ${p.atmospheres.toStringAsFixed(5)} atm');
}
Output
1 bar = 0.98692 atm
const Pressure.atmospheres(double v)
Example
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');
  }
}
Output
depth 0 m: 1.00 atm
depth 10 m: 1.97 atm
depth 30 m: 3.90 atm
Pressure.psiconstructor
const Pressure.psi(double v)
Example
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');
}
Output
32 psi = 220.6 kPa = 2.177 atm

Properties

double get atmospheres
qgetter
Quantity get q

Methods

overmethod
Force over(Area a)
Example
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)');
}
Output
air pushes on 1 m² with 101325.0 N (10332 kg-force)

Operators

operator +operator
Pressure operator +(Pressure o)
Example
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');
}
Output
gauge 32 psi = absolute 322.0 kPa
extension type

Frequency

extension type const Frequency(double hertz)

Frequency (Hz).

Properties

periodgetter
Time get period
qgetter
Quantity get q
extension type

Angle

extension type const Angle(double radians)

Plane angle (rad; dimensionless in SI).

Constructors

Angle.degreesconstructor
const Angle.degrees(double d)
Example
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}°');
}
Output
90° = 1.5707963267948966 rad
back: 90.0°

Properties

degreesgetter
double get degrees

Methods

permethod
AngularVelocity per(Time t)
Example
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');
}
Output
one turn a minute: 0.10472 rad/s = 1.0 rpm

Operators

operator +operator
Angle operator +(Angle o)
Example
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)}°');
}
Output
30° + 1 rad = 87.296°
operator -operator
Angle operator -(Angle o)
Example
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');
}
Output
180° - 45° = 135.0° = 2.35619 rad
extension type

AngularVelocity

extension type const AngularVelocity(double radPerS)

Angular velocity (rad/s).

Constructors

const AngularVelocity.rpm(double v)
Example
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');
}
Output
7200 rpm = 753.98 rad/s
rim speed of a 9.5 cm disk: 35.81 m/s

Properties

rpmgetter
double get rpm
qgetter
Quantity get q
extension type

Density

extension type const Density(double kgPerM3)

Density (kg/m³).

Properties

qgetter
Quantity get q

Methods

ofmethod
Mass of(Volume v)
Example
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');
}
Output
1 L of steel: 7.8500000000000005 kg
extension type

Momentum

extension type const Momentum(double kgMps)

Momentum (kg·m/s).

Properties

qgetter
Quantity get q

Operators

operator +operator
Momentum operator +(Momentum o)
Example
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');
}
Output
total momentum: 2.0 kg·m/s
velocity after they stick: 0.6666666666666666 m/s
extension type

Charge

extension type const Charge(double coulombs)

Electric charge (C).

Properties

qgetter
Quantity get q

Operators

operator +operator
Charge operator +(Charge o)
Example
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');
}
Output
proton + electron: 0.0 C
1 mol of electrons: 96485.3 C
extension type

Voltage

extension type const Voltage(double volts)

Voltage (V).

Properties

qgetter
Quantity get q

Methods

acrossmethod
Energy across(Charge c)
Example
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');
}
Output
1 V across one electron charge: 1.602176634e-19 J = 1.0 eV
12 V battery moving 2 C: 24.0 J