Design spec (pre-build)

The design as written before building, kept for reference.

25 min read

Data layout#

Structure of arrays, one row per environment.

The state is stored in Bullet units (BT, 1 BT = 50 uu) exactly as RocketSim stores it, so rounding happens at the same places. Conversion to uu (×50, a multiplication) happens only at output.

Ball (B1)#

ArraydtypeBytesNotes
posvec3 f3212BT, unquantised end-of-tick value (quantisation happens at the start of the next tick)
quatvec4 f32 (x,y,z,w)16Integration state, re-derived from rot every tick (not persistent)
rotmat33 f3236Needed because q and R are not round-trip exact. Used by the contact frame
velvec3 f3212BT/s
angvelvec3 f3212rad/s
modeu8 → i3240 = the_void, 1 = soccar. Each env picks its own mode, so a whole scenario suite runs as one batch
ticki324Ticks since set_state
scored_ticki324First tick with |y| > 5124.25 + 91.25 uu, else −1
Manifold slotsK per env≈ K·168body i32 (−1 = free), npts i32, last_touch_tick i32, and 4 points × {local_a vec3, local_b vec3, normal vec3, dist f32}. World positions are recomputed by refresh, never stored. The builder must confirm this against persistent_manifold.rs; if some path reads a stored world position that refresh does not recompute, the field is added (answered by the build: As-built design)
EventsE per envE·24 + 4point_uu vec3, normal vec3, count i32. Overwritten every tick (or appended to history in record mode)
Diagnostics4×i3216Overflow counters: candidate buffer, manifold slots, event buffer, solver iteration cap reached
ScratchMAX_CAND × i32—Mesh candidate list, used during one tick only

With K = 6, E = 8 and MAX_CAND = 64 (as built: K = 8, E = 32 in traces / 8 in the API, MAX_CAND = 306, and 6 diagnostic counters), persistent state is about 1.2 KB per env, so about 1.2 GB at 1M envs, which fits in 12 GB. Most of it (the manifolds) is only touched by envs in contact. The hot path reads about 100 B per env per tick.

Cars (C1+, sketch)#

The full field list is in the car spec (Appendix B):

  • C1: about 160 B per car of rigid body, controls, flags and timers;

  • C2: plus about 80 B for wheels (4 × {contact valid, normal, is_in_contact_with_world, srv});

  • C3: plus car–static manifolds (about 250 B per active pair);

  • C4: plus a car–ball manifold and last_extra_hit_tick;

  • C5: plus car–car manifolds (≤ 28 pairs for 8 cars), bump cooldowns, demo timers and the per-arena wyrand RNG state.

Layout is [n_envs, max_cars] SoA with per-car valid bits. Thread mapping: one thread per arena for anything that touches the shared solver island (C4/C5). Per-car threads are allowed only for C1/C2 work that is provably independent.

As built in C1: a flat per-car SoA (gpusim.carsim.Cars), with car c of env e at row e·cars_per_env + c, and one thread per car. The state is position, world quaternion, matrix columns, velocity, ω, a flag word, jump_ticks, 11 f32 timers and flip_rel_torque. It runs as a separate kernel from the ball.

Arena geometry on the GPU#

Representation: 16 wp.Mesh BVHs plus 4 analytic planes. No SDF.#

Rule: Bullet's sphere-vs-triangle contact is fully determined per triangle:

  • one-sided (front face only, d ≥ 0);

  • face region vs edge region by exact tests;

  • normal = (c − closest)/dist;

  • depth = dist − r;

  • then the internal-edge correction rotates the normal using precomputed per-edge angles between neighbouring triangles of the same mesh.

To reproduce that, the GPU needs the actual triangles, with RocketSim's f32 vertex values, triangle indices and per-triangle edge metadata.

Why not an SDF (precomputed signed distance grid):

  • It smooths away exactly what matters. It has no notion of a "front face" (it is two-sided by construction), no per-triangle normals, and no internal-edge info.

  • Trilinear interpolation error at practical resolutions (≥ 2–4 uu cells for a 12k×10k×2k uu arena, i.e. hundreds of MB) is far above the 0.01 uu quantisation grid. It would fall short of the agreement already achieved, by orders of magnitude.

  • Contacts at mesh seams depend on which persisted manifold points survive (see D2 in Sim vs real differences: once the ball's rotation is carried over correctly, ramp steps are 99.2 % consistent with the real game, and the residue is mostly at mesh seams). An SDF cannot represent that seam behaviour at all.

An SDF stays a possible later fast path for the B-roll-on-floor case, but only if the B1 measurements show the exact path is the bottleneck. It would be labelled as an approximation.

Layout:

  • One wp.Mesh per body, 16 in total. Each is built from the vertices exactly as Bullet stores them:

    • goal pieces (AABB centre |y| > 102.4 BT) store v − (0, ±102.4, 0) computed in f32;

    • all other pieces store the file vertices unchanged.

  • Queries in body-local space, center_local = p − t_body, as in sphere_concave_collision_alg.rs. This keeps the f32 rounding identical. A mesh id array (wp.uint64[16]) is indexed by body.

  • Body order = RocketSim's read_dir order on NTFS: mesh_0, mesh_1, mesh_10 … mesh_15, mesh_2 … mesh_9, i.e. byte-wise sorted file names. This order sets contact and summation order. It is filesystem dependent in RocketSim (Linux would differ), so it is recorded in the trace details.

  • Per-triangle metadata (device arrays indexed by body and triangle):

    • the front normal, computed with glam's op order;

    • the three edge angles and flags from generate_internal_edge_info;

    • the BVH DFS leaf rank. These come from the oracle (Offline data: the oracle) and are cached in gpu-sim/.cache/.

  • Planes (floor z=0 +Z, ceiling z=2048 −Z, wall x=−4096 +X, wall x=+4096 −X, in that order, as body indices 16–19) are analytic. They have no mesh and no BVH.

  • Body AABBs for the broadphase gate:

    • mesh: the whole-mesh AABB plus translation, expanded by 0.02 BT;

    • plane: unbounded on two axes; along the normal axis [−∞, t + 0.2] or [t − 0.2, +∞].

    • The builder must confirm the mesh AABB rule against bvh_triangle_mesh_shape.rs (whether a margin is included). Answered by the build: the oracle dumps RocketSim's own proxy AABBs (As-built design).

Candidate triangles and visit order#

RocketSim walks each mesh's quantised BVH depth first and calls the sphere test per triangle in leaf order. On the GPU:

  1. Call wp.mesh_query_aabb(mesh_b, center_local − h, center_local + h) with h = r + 0.08 + 0.01 BT. The 0.01 is a safety pad: Bullet's quantised leaf boxes are padded outward, so any triangle Bullet would test whose AABB lies within the unpadded box is also found here. Extra candidates are harmless, because the exact test rejects them at r + 0.0381.

  2. Collect the triangle indices into the per-env scratch list. If it overflows, increment a diagnostic counter, which then becomes a trace warning.

  3. Insertion-sort by leaf rank (Bullet's DFS leaf order). The order only matters for manifold slot assignment and float summation order. --candidate-order index keeps triangle-index order instead, so the effect can be measured.

  4. Run the exact Bullet sphere–triangle test on each candidate in that order.

Offline data: the oracle#

internal_edge_utility, TriangleInfoMap and shared::bvh are pub(crate) inside rocketsim, so they cannot be called from the published API. Rather than port about 1,000 lines of preprocessing and hope it matches, B1 builds a small oracle:

  • gpu-sim/tools/make_oracle.py copies vendor/rocketsim (read-only source) into gpu-sim/.cache/oracle/rocketsim, and widens only the visibility of the modules it needs (mod bullet → pub mod bullet, pub(crate) mod bvh → pub mod bvh, and so on). No logic is changed. A copy of PATCHES.md is kept and the patch is recorded.

  • gpu-sim/tools/oracle/ is a Rust binary with an empty [workspace] table so it stays out of the root workspace, and CARGO_TARGET_DIR=gpu-sim/.cache/oracle/target. It:

    1. dumps, per mesh body: local f32 vertices, indices, triangle normals, edge info (angles and flags) and DFS leaf rank, to .cache/arena-<mesh_fingerprint>-<oracle_hash>.npz;

    2. (stretch) dumps per-tick ball manifolds (body, slot, local_a, local_b, normal, dist) for a scenario. This gives tick-level contact diffs for the mesh path;

    3. runs the CPU throughput baseline on the same workload file the GPU benchmark uses (Performance methodology), so ball-only multi-thread numbers come from identical states.

  • Fallback (not needed: the visibility patch sufficed, and S6 was never used) if the visibility patch grows beyond module-level pub: a Python port of generate_internal_edge_info and of Bullet's median-of-variance BVH partition. It is validated by its effect on mesh-scenario traces and labelled as a port in trace details.

Derived arrays never leave gpu-sim/.cache/ (gitignored). They are keyed by the collision_mesh_hash fingerprint, so a different mesh dump cannot use a stale cache.

Per-tick kernel pipeline (ball, mirrors Arena::step_tick)#

Each step below runs in one thread per env, in this order. Letters match RocketSim's step order in Appendix A.

StepWhatRocketSim source
AClear accumulatorsarena/base.rs:595
BClamp: |v| ≤ 120 BT/s, |ω| ≤ 6 rad/s (normalize_or_zero·max)rigid_body.rs:458-466
CQuantise pos (round half up, 0.01 uu grid), vel (truncate + ±0.001 uu/s), ω (P1: truncate on a 1e-4 grid + ±1e-5). The rotation is not quantisedshared/quantize.rs:44-67
DBall pre-tick: no-op in Soccarball/base.rs:138-234
E1Gravity into the accumulator: ext = (0,0,−13)·dtdiscrete_dynamics_world.rs:132-139
E2Damping v *= 0.9997462034 (bits 0x3f7fef5e); predicted position for the broadphase AABB:141-149, rigid_body.rs:358-369
E3Collide with the start-of-tick transform: broadphase gate per static body in visit order. Meshes: AABB query → sorted candidates → sphere–triangle → add_contact_point (fires the callback: special flag, event record, internal-edge adjust) → refresh. Planes: support point → fresh manifold → merge into cacheData layout of Appendix A
E4Solve: split-impulse rows per penetrating point; one averaged synthetic normal row + one friction row; 10 iterations, literal loopseq_impulse_constraint_solver.rs
E5Integrate: p += v·dt, quaternion update, R = from_quat(q), q = from_mat3a(R)transform_util.rs:12-37, rigid_body.rs:372-390
FEvents: one BallHitWorld{pos_b·50, normal} per added point, pre-edge-correctionarena/base.rs:657-666
GOutput: pos·50, vel·50, ω, R, tick++, goal checkball/base.rs:236-245

The trace records the unquantised post-integration state. A recorded |v| can therefore exceed 6000 uu/s, and |ω| can exceed 6, by one tick's worth (the reference shows ω = −8.03 at tick 424 of ball-lob-side-wall). The GPU must not clamp at output.

Contact resolution vs Bullet's sequential-impulse solver#

For a dynamic body made of one sphere against static geometry, RocketSim's solver turns into something small and exactly portable. This is why B1 can aim at bit-agreement, not just closeness:

  • There is only one dynamic body. The "island" is the ball. Every row writes only the ball's dv, dω, push and turn. There is no coupling to other bodies and no graph colouring, so the serial loop in one thread is Bullet's algorithm, not an approximation of it.

  • skip_separated_special_rows. In ball-only mode, every ball–world point is "special". Only split-impulse rows are made per penetrating point (d < 0). The velocity solve uses one synthetic row: normal = the normalised mean of all point normals; lever = −mean |rel1| along it; friction μ̄ = 0.35, restitution ē = 0.6; with one friction direction. Only the last contact row (the synthetic one) is iterated.

  • No warm starting in practice. The stored applied impulse is always 0 (item 1 of Appendix A). The solve therefore depends only on this tick's manifold, and nothing from the previous tick's solver state has to be kept.

  • Convergence. With one row plus one friction row, the 10-iteration loop usually converges in the first pass. The GPU still runs the literal loop, with the same exact r == 0 early exit, because it is cheap and removes a class of ulp differences.

What makes it hard is not the solver but the contact set fed into it:

  • persistent 4-point manifolds per static body, with points kept up to 1.905 uu apart;

  • the area-maximising eviction (sort_cached_points);

  • manifolds stay frozen while the broadphase pair is apart;

  • internal-edge normal correction;

  • the averaging across bodies at seams (mesh 10/11 at x≈4100, and ramp mesh plus floor plane).

All of these are ported, not approximated. Where the GPU must bound something Bullet leaves unbounded (manifold slots per env K, candidates per query, events per tick), the bound is counted. Any run where a bound was hit gets a trace warning.

When cars arrive (C3–C5) this stops being simple:

  • ball-only mode is off, so split rows are made for all special points and all normal rows are solved;

  • warm starting carries impulses for car points;

  • car, ball and world rows share one island and are solved in Bullet's row order.

The plan is a per-arena serial solver thread that reproduces Bullet's row order (Staged milestones C4/C5). Approximations such as Jacobi or graph-coloured batching are allowed only as named simplifications with measured error.

Floating point and determinism#

Matching CPU arithmetic as far as Warp allows:

  • fuse_fp=False (NVRTC --fmad=false) on every gpusim module. Rust and glam do not fuse, so contraction would cause 1-ulp drift. fast_math=False, so division and sqrt are IEEE correctly rounded, the same as SSE divps and sqrtps.

  • Operation order: glam SSE2 grouping is written out by hand in @wp.func helpers. Warp's built-in dot, cross, quat multiply and normalize are not used in physics code, because their order is not guaranteed.

    • dot3 ((x·x′ + y·y′) + z·z′); dot4 ((x+z) + (y+w)); solver bdot = x + (y + z);

    • glam mul_quat, from_quat, from_mat3a;

    • normalize divides by the length, while normalize_or_zero and try_normalize multiply by 1/len. Each helper is unit-tested bit for bit against the numpy float32 reference model.

  • Transcendentals:

    • damping uses the hard-coded constant 0x3f7fef5e (no powf);

    • sin and cos in the integrator use one of two modes:

      • trig="f64" (default): computed in f64, then rounded to f32. This is correctly rounded in practice;

      • trig="f32": CUDA sinf/cosf, which have a few ulp of error.

    • Both modes are measured against RocketSim. The probe showed correctly rounded trig does not explain the one remaining 1-ulp transient on ball-roll-x-slow-long.

  • Integer conversions: f32→i32 truncates toward zero, as Rust as i32 does. Rust saturates out-of-range values; CUDA is undefined there. Values that large never occur on the 1e4 ω grid, but a debug assertion checks.

Expected agreement:

  • Planes and the_void: bit-exact per tick is the target; one quantisation step is the acceptance limit (Validation methodology).

  • Meshes: same contact set and onset ticks. Errors stay at ulp level until a chaotic amplification (a seam, a near-tangent contact) separates the runs. The tick where that happens is reported, not hidden.

Determinism (to verify in B1, not assumed):

  • Run to run: identical bits for the same device, driver, Warp version, kernel source and inputs. There are no atomics or reductions across threads; the candidate order is sorted, not traversal-dependent; and there are no data races, since one thread owns one env.

  • Batch-position invariance: env i gives the same bits whether the batch holds 1, 4,096 or 1M envs, and whatever its neighbours are doing. This is tested by placing the same scenario at several indices.

  • Across GPUs, drivers or Warp versions: not guaranteed. NVRTC versions can change code generation. A trace records the Warp version, driver, device name and a hash of the kernel source, and a version bump re-runs the suite.

  • CPU device (device="cpu", Warp's clang backend) is supported for tests without CUDA. Its contraction behaviour is measured, not assumed.

Events#

  • BallHitWorld: one per contact point added in a tick (not per manifold, not per tick).

    • It fires for a ball resting on the floor (every tick) and for points from several bodies at once (tick 424 of ball-lob-side-wall has three: two at the mesh 10/11 seam and one on the +X wall plane).

    • Payload: contact_point_uu = pos_b·50 and contact_normal = the normal before internal-edge correction. Order: body visit order, then candidate order.

    • Retained points that are merely refreshed do not fire.

  • Buffer: E slots per env per tick plus a count. Overflow increments a counter and becomes a warning. Events must never be dropped silently.

    • The original plan was E = 8.

    • A follow-up review found RocketSim reporting 16 events in one tick for a ball placed beside the side wall, and up to 93 for random states.

    • Traces (run/batch) therefore use E = 32; the API and benchmark default stays 8 (Bounds sized by the sweep).

  • Sampling: with every_n_ticks > 1, events are accumulated into the next recorded sample, as sim-runner does, so physlab compare's contact-tick lists stay comparable.

  • Training use (later): the RL path needs only per-env flags or counts (for example "touched a wall this agent step"), reduced on the device. Full event payloads are a validation feature, enabled by record=True.

Trace export (reuses physlab compare / report)#

GPU traces follow crates/scenario-schema/src/trace.rs (schema version 1) exactly:

  • the first line is {"record":"meta",…}, then one {"record":"sample",…} per recorded tick;

  • tick 0 = state after setup and warmup; fields position_uu, linear_velocity_uu_s, angular_velocity_rad_s; events tagged "type":"ball_hit_world".

Meta fieldGPU value
runner.name"gpu-warp"
runner.versiongpusim package version, e.g. "0.1.0"
runner.detailswarp_version, device (name, sm, driver, CUDA), collision_mesh_hash (same fingerprint algorithm as sim_runner::collision_mesh_fingerprint, so traces from both runners can be checked against the same dump), mesh_body_order, reference = "rocketsim 0.2.11 + vendor patches (P1)", fp_mode, trig_mode, candidate_order, kernel_hash, geometry_source (oracle / port), game_mode (Soccar / TheVoid, spelled as sim-runner spells it), batch_size, env_index
scenario_hashScenario::content_hash() reproduced in Python: FNV-1a 64 over the serde_json serialisation of the parsed scenario, with serde's field order and skip rules and Rust's shortest f32 formatting. Tested against the hash in every RocketSim reference trace. A mismatch fails the run; it is never silently written
warningsEvery active simplification (The roadmap's register), every bound that was hit, the sim-runner warnings that apply (goal entered at tick N; the_void is simulator-only; truncated last interval), and "experimental GPU simulator (gpu-warp); see apps/web/src/content/docs/gpu/index.md"

Floats are written as the shortest decimal that round-trips to the same f32, as Rust's ryu does. NaN or ∞ aborts the run with an error rather than writing invalid JSON.

Validation methodology#

Oracles, cheapest first#

LevelOracleWhat it checks
L0gpu-sim/tests/refmodel/ball_ref.py: the float32 numpy port of the plane-only tick (moved from the scratchpad, where it was bit-exact against RocketSim on 8 scenarios)Each @wp.func (quantise, integrate, quaternion and matrix ops, plane contact, solver) bit for bit on random and recorded inputs
L1RocketSim traces of the_void and plane-only scenarios (physlab run)Full tick bit-exactness. A non-zero difference means a porting bug
L2RocketSim traces of mesh scenarios, plus (stretch) the oracle's per-tick manifold dumpsContact set, slots, edge correction, seams
L3Real-game captures in recordings/*.real-game.*.jsonl (all 37 ball scenarios have them)GPU vs real reported next to RocketSim vs real: the GPU must not be worse than its reference

Scenario set for the ball stages#

  • The_void: scenarios/void/void-ball-drop.json.

  • Planes only:

    • floor: drop-center-500, drop-high-1800, roll-x-, roll-diag-, spin-*;

    • ceiling: ball-ceiling;

    • side-wall plane: ball-wall-glance, if it stays off the meshes. The runner classifies each scenario by whether any mesh body's broadphase gate ever opened, and reports that classification rather than relying on the names.

  • Meshes:

    • ramp-* (drop, roll, sweep, sweep-off): mesh seams and persisted ramp contacts;

    • ball-corner, ball-lob-side-wall (mesh 10/11 seam at tick 424), ball-long-chaotic;

    • scenarios/advanced/a01-ball-backboard, a01-ball-backboard-corner, a01-ball-crossbar (goal meshes with the ±102.4 BT translation).

  • Synthetic:

    • batch-invariance copies of every scenario at env indices {0, 1, 4095, N−1};

    • a randomised "ball-random" workload (also used for benchmarks), compared against the oracle CPU run on the same initial states with N = 1,024 envs.

Metrics and tolerances#

Metrics come from physlab compare:

  • per-horizon errors at 1, 8, 30, 60, 120, 240, 480, 960 and 1800 ticks;

  • first-divergence tick at the default 1.0 uu;

  • contact-tick lists and onset_ticks_match.

In addition, the gpusim batch report gives:

  • bit-exact tick fraction;

  • max error in quantisation units (0.01 uu, 0.01 uu/s, 1e-4 rad/s);

  • first tick with any difference.

ClassAcceptance (B1 exit)Target
the_void, planesmax |Δp| ≤ 0.01 uu, |Δv| ≤ 0.02 uu/s, |Δω| ≤ 2e-4 rad/s over the full duration; contact-tick lists identical100% of ticks bit-exact
Meshes, non-chaoticContact-tick lists identical; position error ≤ 1.0 uu at every horizon ≤ 240Bit-exact until the first chaotic amplification
Meshes, chaotic (long-chaotic, sweeps that graze seams)First-divergence tick reported and ≥ the CPU-vs-perturbed-CPU divergence tick. That baseline comes from RocketSim with ±1 ulp on the initial velocity, run through the oracle. This keeps "chaotic" from becoming an excuse—
Real game (L3)At every horizon, GPU-vs-real error ≤ RocketSim-vs-real error + max(0.05 uu, 10%)Equal
DeterminismRun-to-run and batch-position bit-identical—

Every failure is either fixed or explained with a mechanism in Results and validation. "Close enough" without a mechanism is not an explanation.

Appendix A — RocketSim ball tick reference (0.2.11 + P1, ball-only)#

This is a condensed version of the ball spec produced for this roadmap. All paths are relative to vendor/rocketsim/src. The plane path was checked bit-exact by a float32 Python port on 8 scenarios; the mesh path has been read, not run.

Units and constants

NameValueSource
UU_TO_BT0x3ca3d70a (= 1/50); conversions always multiplyconsts.rs:36-39
dt1/120 = 0x3c088889
Gravity−650 uu/s² → −13 BT/s²; g·dt = 0xbddddddf
Ball radius91.25 uu → r = 0x3fe99999 BT
Mass, inverse mass30, 0x3d088889
Inertia0.4·m·r² = 0x421fdeb8; inverse 0x3cccf76f
Linear damping per tick0x3f7fef5e (= 0.97^dt); no angular damping
Max speed, max ω120 BT/s, 6 rad/s
Combined friction, restitutionmin(0.35, 0.6) = 0.35; max(0.6, 0.3) = 0.6 (static-body rules)
BREAK(r + 0.08)·0.02 = 0x3d1c0ebe (1.905 uu)
Solver10 iterations; ERP2 = 0.8; split impulse always on; turn ERP 0.1; warm-start has no effect (impulse always 0)
Quantisation scalespos 100, vel 100, ω 10000 (P1)

Static world

16 meshes (8,020 triangles; NTFS order). The goal pieces have AABB centre |y| > 102.4 BT and translation (0, ±102.4, 0) BT, with local vertices v − t in f32. They are followed by four planes: floor, ceiling, wall −X (normal +X), wall +X (normal −X). Body indices: meshes 0–15, planes 16–19, ball 20. The_void has no statics.

Tick: A clear accumulators → B clamp → C quantise → E1 ext = g·dt → E2 v *= DAMP, predict p + v·dt for the AABB → E3 collide → E4 solve → E5 integrate → F events → G output.

  • Quantise:

    • p = (floor((p·50)·100 + 0.5) / 100)·UU_TO_BT;

    • v: s = (v·50)·100; r = (i32)s as f32·(1/100); r += sign0(r)·(0.1·(1/100)); v = r·UU_TO_BT;

    • ω: s = ω·10000; r = (i32)s as f32·(1/10000); r += sign0(r)·(0.1·(1/10000));

    • here sign0(0) = 0.

  • Integrate, (p, q, v, ω):

    • p += v·dt;

    • a = |ω|, capped so that a·dt ≤ π/4; h = a·dt·0.5;

    • s = a < 0.001 ? 0.5·dt − dt·dt·dt·0.020833334·a·a : sin(h)/a;

    • q = normalize((ω·s, cos h) ⊗ q), R = from_quat(q), then in E5 q = from_mat3a(R).

  • Broadphase gate:

    • the ball box is the union of p ± (r+0.08) and p_pred ± (r+0.08), expanded by 0.02;

    • each static box is expanded by 0.02;

    • if they do not overlap, nothing happens for that body and its manifold stays frozen.

  • Plane:

    1. Gate on p ± (r+0.08) against the plane AABB.

    2. vtx = r·try_normalize(Rᵀ(−n)); vin = R·vtx + (p − t); dist = n·vin. If dist ≥ BREAK, no point.

    3. world_b = (vin − dist·n) + t; add it to a fresh manifold (callback) and refresh the fresh one.

    4. Merge into the cache:

      • no cache: the fresh one becomes the cache;

      • cache non-empty: refresh it, then either copy the fresh points in (if it is now empty) or add_contact_without_callback each one;

      • no fresh point: refresh the cache and keep the survivors (they still reach the solver, but no event fires).

    5. If the cache is non-empty, it becomes active.

  • Mesh:

    1. c = p − t_b; query c ± (r+0.08); candidates in leaf order.

    2. For each candidate, intersect_sphere_front_precomputed:

      • d = (c − p0)·n_tri; reject if d < 0 or d ≥ r+BREAK;

      • face test with edges (p1−p0, p2−p1, p0−p2): the first two reject on < 0, the third accepts on ≥ 0; inside the face, cp = c − n·d;

      • otherwise the closest point over the three segments (strict < to replace); reject unless it is below (r+BREAK)²;

      • dist² = |c − cp|²; reject if ≥ (r+BREAK)²;

      • if dist² > f32::EPSILON: normal = (c−cp)/dist, depth = dist − r; otherwise normal = n_tri, depth = −r;

      • add_contact_point(normal, cp + t_b, depth, tri) directly into the cached manifold.

    3. After all candidates: if non-empty, refresh; if still non-empty, it becomes active. There is no refresh before the adds.

  • add_contact_point:

    • reject if depth > BREAK;

    • a = b + n·depth; local_a = Rᵀ(a − p); local_b = b − t_b;

    • slot = the nearest existing point with |Δlocal_a|² < BREAK² (replace), else append (≤ 4), else sort_cached_points:

      • keep the deepest point (smallest distance below the new point's);

      • take the largest of the four quadrilateral areas; the first index wins ties;

    • then the callback: mark special; push the event record (pre-correction); for a mesh, run adjust_internal_edge_contacts.

  • refresh:

    • pos_a = R·local_a + p, pos_b = local_b + t_b, d = (pos_a − pos_b)·n;

    • walk from last to first, and swap_remove a point if d > BREAK or |pos_b − (pos_a − n·d)|² > BREAK².

  • Internal-edge correction:

    • edge threshold 0.1 BT; edge t clamped to [0x3727c5ac, 0x3f7fff58];

    • clamp the normal by rotating it about the edge (accept only if the result · n_tri > 0), or mark a concave hit;

    • the first edge uses the original normal, the others re-read the possibly modified normal;

    • at the end, a concave hit with n_tri·n_orig ≥ 0 sets the normal to n_tri;

    • after a normal replacement: pos_b = pos_a − n_new·distance, and local_b is recomputed.

    • Per-mesh edge info: only neighbours that share 2 vertices (distance² < 1e-8) within the same mesh; the last neighbour wins on non-manifold edges.

  • Solver (body sv = v_damped, sω = ω, ext = g·dt):

    • Setup. For every active manifold in order and every point in slot order:

      • rel1 = pos_a − p;

      • if d < 0, add a split row: τ = rel1×n, A = Iw⁻¹ᵀτ, jac = 1/((1/m + n·(A×rel1)) + 0), rhs_pen = ((−d)·0.8·(1/dt))·jac;

      • accumulate Σn, Σ|rel1|, Σμ, Σe and count.

    • Synthetic rows, if count > 0:

      • n̄ = normalize_or_zero(Σn/count), rel1 = n̄·(−L̄);

      • normal row: vel = v + ω×rel1; restitution = max(ē·(−n̄·vel), 0); vdn = n̄·(sv+ext) + τ·(sω+0); rhs = (restitution − (vdn+0))·jac; limits [0, 1e10];

      • friction row: u = (sv+ext) + (sω+0)×rel1; lat = u − n̄(n̄·u); t = |lat|² > EPS ? lat·(1/√|lat|²) : plane_space_1(n̄); c = rel1×t; B = Iw⁻¹ᵀc; jac_t = 1/((1/m + t·(B×rel1)) + 0); rhs_t = (−(t·(sv+ext) + c·sω + 0))·jac_t.

    • Split iterations (≤ 10, skipping converged rows):

      • Δ = rhs_pen − (bdot(n,push) + bdot(τ,turn))·jac; accumulate, clamping at ≥ 0;

      • push += n·(1/m)·Δ, turn += A·Δ;

      • a row converges when (Δ/jac)² == 0.

    • Velocity iterations (10), on the synthetic normal row only:

      • Δ = rhs − (bdot(n̄,dv) + bdot(τ,dω))·jac, accumulated ≥ 0, dv += n̄·(1/m)·Δ, dω += A·Δ;

      • then friction, if λn > 0: limits ±μ̄λn, same update pattern;

      • stop if max(r²) == 0.

    • Finish:

      • if push or turn is non-zero: (p, q, R) = integrate(p, q, push, turn·0.1, dt), then q = from_mat3a(R);

      • v = (sv + dv) + ext; ω = (sω + dω) + 0.

  • glam op order (SSE2, no FMA):

    • dot3 ((x·x′+y·y′)+z·z′); dot4 ((x+z)+(y+w));

    • Mat3A·v = (X·vx + Y·vy) + Z·vz; transposed = three dot products;

    • mul_quat, for l ⊗ r:

      • x = (lx·rw + lw·rx) + (−(lz·ry) + ly·rz)

      • y = (−(lx·rz) + lw·ry) + (lz·rx + ly·rw)

      • z = (lx·ry + lw·rz) + (lz·rw + −(ly·rx))

      • w = (−(lx·rx) + lw·rw) + (−(lz·rz) + −(ly·ry))

    • world inverse inertia R·(Rᵀ ⊙ invI);

    • from_mat3a uses DirectXMath branching (on m22, then m11 ∓ m00).

Appendix B — Car stages, key facts (from the car spec)#

  • Free flight never uses the inertia tensor. Air control, flip torque and auto-roll are Angular impulses with massed=false (direct Δω). Rigid impulses with inertia appear only for wheel suspension and friction (C2) and for solver contacts.

  • Tick order (cars):

    1. per-car clamp (46 BT/s, 5.5 rad/s) and quantise; state.vel and state.ang_vel are re-synced, but state.pos is not;

    2. ball clamp and quantise;

    3. the flip z-damp prepass;

    4. per-car pre_tick_update in index order (car i's wheels can push car j before car j runs);

    5. ball pre-tick;

    6. step_simulation (gravity accumulates last; contacts; solve; integrate);

    7. contact records dispatched after integration (car–ball extra impulse, bump/demo, world_contact_normal);

    8. per-car post-tick and finish_physics_tick (vel_impulse_cache), then boost pads.

  • Must-reproduce subtleties:

    • air-control damping reads the post-quantise state.ang_vel;

    • the order of the accL sum: jump hold → air throttle → boost → gravity;

    • Rust signum(±0) = ±1;

    • flip_rel_torque persists (stale torque);

    • the first tick after set_state uses the exact matrix, later ticks use from_quat(q);

    • a mid-air spawn can flip or double-jump at any time;

    • end-of-tick |v| and |ω| can exceed the caps;

    • (C1 correction) the quaternion is re-derived from the matrix after every integration (set_center_of_mass_trans → set_world_trans). It is not independent persistent state; the spec said it was.

  • C2 core:

    • 4 rays from the hard points along −U, length (sus_rest + radius)·0.02, hits closer than 17.08 uu rejected;

    • suspension F = ((rest − len)·500·inv − (srv<0 ? 25 : 40)·srv)·force_scale;

    • all suspension impulses first, then friction (side impulse from −0.2·…, rolling from engine or brake), with the curves in constant memory;

    • is_on_ground = contacts ≥ 3; sticky force from the previous tick's normals.

  • C3–C5:

    • box–triangle SAT plus manifolds plus warm-started solver;

    • sphere–OBB for the ball; box–box for cars;

    • the RocketSim extra hit impulse and the bump/demo rules (Staged milestones);

    • the per-arena RNG for respawns.

    • Full details and line references are in the car spec this roadmap was written from. A dedicated pass over solver_constraint.rs and box_triangle_sat.rs is required before C3 starts.