As-built design
How gpu-sim is built and how it stays exact.
17 min read
This is the design as built, for stages B1 (ball + arena) and C1 (car free flight); the stages are defined in Staged milestones. The design it started from is the Design spec; where they differ, this page wins.
One thread per arena. step(n) is a single launch; each thread loops n ticks in
RocketSim's order (gpusim/tick.py):
clamp;
quantise (P1);
gravity into the accumulator, then damping;
collide with the start-of-tick transform;
ball-only sequential-impulse solve;
integrate, with the quaternion re-derived from the matrix;
events and the goal check.
State is kept in BT units and f32, exactly as RocketSim stores it. Conversion to uu is a ×50 at output.
The oracle: exact data from RocketSim#
gpu-sim/tools/make_oracle.py copies vendor/rocketsim into gpu-sim/.cache/oracle/rocketsim
and applies 9 visibility-only substitutions, recorded in .cache/oracle/PATCH.txt:
pub mod bullet;pubonArena::bullet_worldandDiscreteDynamicsWorld::collision_world;pubon the grid broadphase'sGridCell,CellGridand their fields;pub modfortriangle_callback,triangle_info_mapandtriangle_shape.
It then builds gpu-sim/tools/oracle (the gpusim-oracle package, with its own empty
[workspace]) against that copy, using the workspace's Cargo.lock versions (glam
0.33.12). No logic is changed. Build time is 8 s.
| Subcommand | Output (all written under gpu-sim/.cache/) |
|---|---|
dump-geometry | For each of the 16 mesh bodies, in RocketSim's body order: Bullet's local triangle points (goal pieces minus their ±102.4 BT translation, computed in f32 by RocketSim), triangle normals, generate_internal_edge_info output (3 angles and flags per triangle), and the BVH leaf visit order. For every static body: its broadphase proxy AABB. Plane aabb_cache. The Heavy broadphase grid: 31×33×6 cells of 7.4 BT, with every cell's ordered static_handles list (9,926 handles) |
dump-manifolds | Per tick: ball state, rotation matrix and quaternion, events, and every persistent manifold (la, lb, normal, distance, world points). Used to debug lockstep |
trig-table | Floating point and the CPU libm |
cpu-bench [--dump-final] | CPU baseline on the same states the GPU benchmark uses, and final states for crosscheck |
ArenaGeometry checks the dump against the .cmf files:
every mesh body maps to exactly one file by bit-exact local geometry;
the goal translation rule holds;
triangle normals recomputed in glam operation order equal Bullet's bit for bit;
the 16 file hashes match
SOCCAR_MESH_HASHES;the body order equals the NTFS name order.
The Python fallback port (port_edgeinfo.py, simplification S6) was not written: the
visibility patch was enough, so the fallback condition never arose.
Broadphase: RocketSim's grid, replayed exactly#
The spec's gate (ball box against each body's expanded AABB, in body-index order) leaves
two differences from RocketSim's ball-only dispatch_singleton_pairs:
RocketSim only visits statics listed in the cell of the ball box's min corner, in that cell's insertion order. That order depends on the first
update_aabbspass (simplification S1).A mesh whose AABB overlaps but which is not listed in the cell keeps its manifold frozen rather than refreshed.
The GPU therefore replays the dumped cell lists:
cell index =
trunc((min − grid_min)/cell), clamped ascvttps2dqandmax(0)do;for each handle in that cell, in order, an
Aabb::intersectstest against the dumped proxy AABB, then the near callback.
This removes S1 entirely.
Contacts, manifolds, solver#
Ported line by line from these files, with glam's SSE2 operation order written out by hand
(wpmath.py):
persistent_manifold.rstriangle_shape.rsconvex_plane_collision_alg.rsthe dispatcher merge in
collision_dispatcher.rsinternal_edge_utility.rsarena_contact_tracker.rsseq_impulse_constraint_solver.rsandsolver_constraint.rs
Mesh path.
wp.mesh_query_aabbover onewp.Meshper body, with one vertex triple per triangle so the face index equals Bullet's triangle index. The query box isc ± (r+0.08+0.01).An insertion sort of the candidates by the BVH leaf rank from the oracle.
The exact one-sided sphere–triangle test.
add_contact_pointwrites into the cached manifold.The callback pushes the event, using the pre-correction normal and
pos_b·50, then runs the internal-edge correction.A refresh.
Bullet's quantised leaf boxes visit a superset of the triangles. Any triangle that can produce a contact has an exact AABB inside the query box, so the contact set is identical and only the order needs the rank.
Plane path. Support point, then a fresh manifold, then that manifold's refresh, then the
dispatcher merge (refresh the cached manifold, then copy or add_contact_without_callback).
Manifold storage.
K slots per env, env-major, with 4 points per slot (
la,lb, normal, distance). World positions are recomputed, asrefreshdoes.The only place that reads an add-time world position is the edge correction's
pos_world_on_a, which still holds that value at the time.A slot is freed when its manifold empties. An empty cached manifold behaves exactly like no manifold in every path.
The active list is built in visit order.
Solver.
One split row per penetrating point. Row data are recomputed on every visit, which is deterministic; only the accumulated impulse is kept.
The special-sample accumulator is initialised with the first sample, not
0 + sample, asaccumulate_special_sampledoes.One synthetic normal row and one friction row.
The literal split and velocity loops, with the exact
residual == 0exits.diagnostics()["solver_iteration_cap"]counts ticks whose 10 velocity iterations ended withoutr == 0. RocketSim stops at 10 too, so this is informational, not a bound.
Floating point and the CPU libm#
The trig mode is chosen with --trig.
wp.set_module_options({"fuse_fp": False, "fast_math": False, "enable_backward": False})
is set in every gpusim module.
Every calling module needs this option, not just the one defining the functions. Warp
compiles a @wp.func into the module of the kernel that calls it. test_wpmath_bitexact.py
shows why: without the line, its CUDA kernels contract a*b+c into FMA and fail. The CPU
device does not contract either way.
Turning off backward code generation cut a cold compile of the tick module from 18–28 s to 0.5 s.
The mechanism behind the last 1-ulp differences (Open questions open question 1):
RocketSim calls Rust's f32
sin/cos, which on Windows are the UCRTsinf/cosf.These are not correctly rounded everywhere. For example,
cosf(0x3bfe9f29)gives0x3f7ffe05, but the correctly rounded value is0x3f7ffe06.At tick 782 of
ball-roll-x-slow-longthat ulp changes the ball's quaternion. Three ticks later it surfaces as a velocity difference of 1.5e-5 uu/s.This was found by running the GPU and
oracle dump-manifoldsin lockstep. The rotation is the first state to differ, then the replayed integrate is checked with each sin/cos variant.The roadmap's earlier "not trig" verdict only compared two correctly rounded implementations (numpy f32 and f64-rounded), never UCRT itself.
--trig crt (default) evaluates sin/cos in f64, rounds to f32, and looks up an
exhaustive exception table:
oracle trig-tableenumerates all 2.16e9 f32 inputs with|x| ≤ πin 1.5 s on 28 threads. That covers integrate's half-angle (≤ π/8) andfrom_axis_anglein the edge correction (≤ π).It records where Rust's f32 result differs from
f32(f64 sin/cos): 89,808 sin and 103,142 cos inputs.The oracle also writes per-2^20-input checksums of the f64-rounded values.
trig.verifyrecomputes them with CUDA's f64 functions: 2,058 chunks × 2 functions, 0 mismatches. So the GPU's own f64 path rounds identically everywhere in the domain.The table is keyed by the hash of
ucrtbase.dll.atan2(internal-edge correction only) has a 2-D domain and no table, so it stays f64-rounded (residual S5).
The other modes:
--trig f64: correctly rounded sin/cos/atan2.--trig f32: CUDAsinf/cosf/atan2f.
Bounds sized by the sweep#
Bounds are sized with gpu-sim cache build.
Sweep conditions: 29,067,103 points on a 20 uu grid over x ±4200, y ±6100, z −100…2150 uu, in 0.53 s. The ball box was widened by 1 BT (= |v|·dt at 6,000 uu/s) when counting gates.
| Quantity | Measured | Bound used (spec rule: max(minimum, 2×measured)) |
|---|---|---|
| Triangle candidates per mesh query | max 153; p99.9 = 70 | MAX_CAND = 306 |
| Simultaneously open gates | max 4, of which 2 are meshes | K = 8 |
| Events per tick (E) | Not swept. A follow-up review measured: up to 8 in the 41-scenario suite (crossbar, ramp sweeps); 16 in a scenario file (gpu-ball-wall-run, tick 1); up to 93 in random states | E = 32 for run/batch traces; E = 8 (sim.DEFAULT_E) for the Python API and bench |
The sweep includes points inside geometry that a ball cannot reach.
E was undersized for traces at first. The original claim was that E = 8 only overflows in the random benchmark, where balls start inside goal and corner geometry. That is wrong:
the shared suite already reaches exactly 8 events in one tick, so there was no margin;
gpu-ball-wall-run(a ball placed rolling beside the side wall) makes RocketSim report 16ball_hit_worldevents at tick 1. With E = 8 the GPU trace lost 8 of them, the trace carried abound hitwarning, andbatchmarked the scenario FAIL. The physics stayed bit-exact, because events never feed back into Soccar physics.
Measured with E = 64 over 600 ticks at 65,536 envs (a scratch script, not kept):
| Workload | Env-ticks with >8 events | >16 | >32 | Max per tick |
|---|---|---|---|---|
| ball-random | 1,537 of 39.3 M | 174 | 21 | 93 |
| Balls rolling or bouncing near walls and the floor seam | 12,134 of 39.3 M | 3,416 | 189 | 91 |
With E = 32, the run/batch default, all 51 scenarios have 0 overflows. Any overflow is
still counted, reported as a trace warning, and fails batch. There is no fixed upper
bound short of MAX_CAND, so E is a memory trade-off: E·24 bytes per env, plus E·24 bytes
per recorded env-tick of history.
Candidate and manifold-slot overflows were 0 in every run, benchmarks included.
Deviations from the B1 spec#
Each deviation comes with its reason.
| Deviation | Reason |
|---|---|
Default --trig crt (a new mode) instead of f64 | f64 leaves 31 ticks in two scenarios 1 ulp off, from UCRT cosf (Floating point and the CPU libm). crt is exact and verified. f64 and f32 remain as options |
| Broadphase replays RocketSim's grid instead of the "body order + AABB" gate | Exact gate set and visit order, and the correct frozen-versus-refreshed behaviour. S1 is gone |
| Manifold slots not kept sorted by body; empty slots freed | The active list records the visit order directly. An empty manifold is equivalent to none |
| Oracle patch also widens 3 struct fields' visibility | The grid lists are private struct fields. The patch is still visibility only; port_edgeinfo.py was not needed |
| Extra modules and commands | runner.py (batch, compare), trig.py, sweep.py; gpu-sim crosscheck; oracle trig-table and cpu-bench --dump-final; set_record_envs so large batches only record the envs that are traced; 6 diagnostic counters instead of 4 (adds contact-tick counters) |
| Env-major manifold layout | A slot-major (coalesced) layout was implemented and measured: −6 % on ball-floor at 262k envs (62.2/61.6 vs 58.0/57.9 M/s, alternating A/B). It was reverted |
Stage C1: car free flight#
The kernel is gpusim/carsim.py.
One thread per car. Cars have no interaction in C1, so car_step_kernel runs one
thread per car and loops n ticks in-kernel, like the ball kernel. Each tick is ported in
RocketSim's order from sim/arena/base.rs step_tick and sim/car/base.rs:
limit_vels(46 BT/s, 5.5 rad/s)and quantise (P1);state.vel/state.ang_velare re-synced,state.posis not;the flip z-damp prepass;
pre_tick_update:update_wheels(only the powerslide state persists in the air);update_jump(generic; ground activation never happens in C1);the continuation branch of
update_auto_flip;update_double_jump_or_flip(dodge impulse with the speed-ratio scales, Rustsignum/sign-bit tests, staleflip_rel_torque);update_air_torque(dodge torque with flip cancel, air control with pitch lock and damping from the post-quantisestate.ang_vel, air throttle);update_boost;
gravity, then the solver finish
v = (v + 0) + acc(the accumulators are summed in RocketSim's order), thenintegrate_trans, with the quaternion re-derived from the matrix;post_tick_update: supersonic state machine, bump timer,prev_controls.
Free flight never touches the inertia tensor. Every gameplay torque is an unmassed
Angular impulse (direct Δω). The car body config only matters through dodge_deadzone,
which is 0.5 for every preset. All six presets are accepted.
Inputs. Inputs are 8-bit quantised exactly as quantize_axis_input(s) (tested against
the Rust formula on 40k inputs, ±0 and ties). The scenario ControlStep timing is
sim-runner's: a step applies to the physics steps that produce ticks
start_tick+1 ..= start_tick+duration, and warmup ticks get neutral inputs.
Initial state is Car::set_state plus the sim-runner probe result for a car touching
nothing:
is_on_ground = false, no wheel contacts, sticky gate cleared;every other gameplay field at
CarState::DEFAULT;the rotation matrix is
Mat3A::from_euler(ZYX, yaw, -pitch, -roll), computed on the device with the same CPU-libm sin/cos (--trig crt, exact for |angle| ≤ π) and glam's formula. The tick-0 quaternion, sign of zero included, equals physlab's in every scenario.
C1 validity predicate (runner.c1_valid_ticks). Tick t is valid only if, at tick
t−1 (contacts are generated from the start-of-step transform):
in Soccar, every car origin is inside the box |x| ≤ 3350, |y| ≤ 3200, 195 ≤ z ≤ 1920 uu;
every car is more than 205 uu from the ball;
every car is more than 205 uu from every other car.
How the box was derived:
Geometry. Checked against every arena triangle's AABB and the four planes: nothing is within 105.5 uu, which is the largest hitbox reach (Hybrid, 97.49 uu) plus box margin, breaking threshold and slack (
tests/test_car_c1.py). Wheel ray tips reach at most 62 uu.Boost pads set the floor. 195 uu (not the 106 the floor alone needs) keeps the end-of-tick origin above every boost pad's pickup cylinder:
max_pad_z= 73 + 95 = 168 uu, plus one tick of travel.
The predicate is conservative. In car-fall-wheels-1000 it ends validity at tick 192,
and RocketSim's car first differs from free flight at tick 210. In a02-flip-reset-setup
it ends at tick 39; the car's wheels land on the ball at tick 81 (car_landed) and its body hits it at tick 85. The runner records the
first invalid tick in the trace. batch judges cars only before it, and judges the ball
only if RocketSim's cars never touch it.
The ball in car scenarios. The ball runs in the B1 kernel as if the cars were absent.
RocketSim, with cars present, solves the ball through its general solver path
(ball_only = false, simplification S10). In every car scenario where RocketSim's car
never touches the ball, the ball was still bit-identical, including all the Soccar
car-air-*/car-fall-* scenarios with a resting ball.
A Warp pitfall found in C1: scalar unary minus loses the sign of zero. In Warp 1.18,
-x on a scalar float32 returns +0 for x = +0, on CUDA and on the CPU device. Vector
negation is correct. Rust's -x flips the sign bit. This showed up as -0.0 versus
0.0 in the tick-0 quaternion of a yaw-only spawn.
wpmath.neg(x)(x·−1, exact for every non-NaN value) is now used inquat_muland everywhere incarsim.pywhere a zero's sign can reach the output.The B1 suite, random crosschecks and tests are unchanged after the switch (still bit-exact).
The other scalar negations in the B1 contact and solver code were left as they are. They have never produced a difference, but they carry the same latent ±0 risk.
Corrections to the car spec found while porting:
The quaternion is not persistent state.
integrate_trans→set_center_of_mass_trans→set_world_transre-derivesworld_quat = Quat::from_mat3a(matrix)every tick. The ball kernel already did this; the car kernel does the same.The C1 box must also clear the boost pads. The spec's 110 uu floor did not.
Oracle for cars. gpu-sim/tools/car-oracle (gpusim-car-oracle car-run) uses only
RocketSim's public API and the same visibility-widened vendor copy as gpusim-oracle.
It gives one TheVoid arena per car, with the ball parked 10⁶ uu away, the same initial states and the same piecewise-constant random inputs as the GPU.
It dumps every car's final state (pos, vel, ω, matrix, boost, flags,
jump_ticks) and times the CPU baseline.It is a separate crate so the arena-geometry cache key, which hashes
gpusim-oracle's source, is unchanged.ensure_car_oraclere-copies the vendor tree whenvendor/rocketsim/srcchanges.
What C1 does not model (all are contacts, so they are outside the valid window):
ground jumps and jump-hold;
auto-flip triggering, auto-roll and sticky forces;
wheel suspension and friction;
world_contact_normal, landings, car–ball extra hits, bumps and demos;boost-pad pickups.
Also out of scope: Dropshot boost recharge (unsupported mode) and non-default mutators.
The is_jumping and auto-flip continuation code is ported, but a mid-air spawn never
reaches it, so it is unexercised.
Simplifications register#
Status at C1.
| ID | Simplification | Status | Measured effect |
|---|---|---|---|
| S1 | Static visit order = body order | Eliminated: RocketSim's grid lists are replayed (Broadphase: RocketSim's grid, replayed exactly) | — |
| S2 | Mesh body order = NTFS name order | Active, recorded in mesh_body_order and the warnings. The oracle confirms RocketSim used this order on this machine | None on this machine; a Linux RocketSim may differ |
| S3 | --candidate-order index | Off by default | Large: see Measured mismatches and their mechanisms |
| S4 | Bounded K, MAX_CAND, E with eviction | Active, counted | K and MAX_CAND: 0 overflows anywhere. E: 0 on the 51 scenarios with the trace default E = 32. E = 8 loses events in reachable states (16 events in gpu-ball-wall-run, up to 93 in random states, Bounds sized by the sweep). Physics never depends on E |
| S8 | Supported scenario subset | Active; the loader refuses everything else | Only arena=standard, gravity=default, physics_hz=120, mode soccar or the_void. Default mutators only. Since C1: cars and controls are accepted; a scenario without a ball gets RocketSim's default ball |
| S5 | Trig differs from the CPU libm | crt: sin/cos exact; only atan2 is f64-rounded | crt: 0 differing ticks; f64: 31/20,100; f32: 33/20,100 (Measured mismatches and their mechanisms) |
| S6 | Python geometry port | Not used (the oracle works) | — |
| S7 | Ball-only | Replaced by S9 at C1: car scenarios run | — |
| S9 | Cars are C1 only: free flight, no car contact of any kind (arena, ball, cars, wheels, boost pads) | Active in every car trace (warning + c1_valid_until_tick) | 0 differences inside the C1-valid window (3,871/3,871 car-ticks, 16,384/16,384 random cars). After the predicate fires: arbitrary (e.g. 1,930 uu by tick 360 in car-fall-wheels-1000); reported, not judged |
| S10 | With cars present the GPU ball still uses RocketSim's ball-only solver path; RocketSim uses its general path (ball_only = false) | Active in Soccar car traces | None measured: the ball is bit-identical in all 15 Soccar car scenarios where no car touches it |
The roadmap's register (pre-build)#
The register as the roadmap planned it, before B1 was built. The table above is the current status.
Every item below that is active is written into meta.warnings and counted in the
batch report.
| ID | Simplification | Expected effect | Default in B1 |
|---|---|---|---|
| S1 | Static visit order = body index order. RocketSim visits in grid-cell static_handles order, which may differ near cell edges | Summation order of near-equal terms only | B1 correction: eliminated. The oracle dumps RocketSim's grid and every cell's ordered handle list, and the GPU replays them for the gate set and the order (Broadphase: RocketSim's grid, replayed exactly) |
| S2 | Mesh body order = NTFS byte-sorted names, as RocketSim on this machine | None on Windows. Would differ from a Linux RocketSim | On (recorded) |
| S3 | --candidate-order index instead of the BVH leaf rank | Manifold slot assignment and summation order | Off (rank from the oracle) |
| S4 | Bounded resources: K manifold slots, MAX_CAND candidates, E events. When K is exceeded, evict the frozen manifold with the oldest last_touch_tick. Bullet keeps all of them | Only if a bound is hit. Counted | On, bounds sized from measured maxima × 2 |
| S5 | trig="f64" (correctly rounded) vs the CPU libm sinf/cosf | ≤ 1 ulp on rotation, occasionally | B1 correction: the default is now crt: f64-rounded plus an exhaustive exception table of the libm's sin/cos for |x| ≤ π. Measured: f64 31 differing ticks out of 20,100; crt 0. Only atan2 (edge correction) stays f64-rounded |
| S6 | Geometry from the Python port instead of the oracle | Edge-info or leaf-rank mismatch, if the port is wrong | Off |
| S7 | Ball-only mode only (no cars in the B-stages) | Not applicable to car scenarios. The loader refuses them | Replaced by S9 at C1 |
| S9 | Cars are C1 only: no car contact with the arena, the ball, other cars, wheels or boost pads | Car and ball states after the first possible contact. The conservative predicate ends the judged window before it; the trace records the tick | On for car scenarios (C1) |
| S10 | With cars present, the GPU ball still uses RocketSim's ball-only solver path; RocketSim uses its general one | None measured: the ball is bit-identical in all 15 Soccar car scenarios where no car touches it | On for Soccar car scenarios (C1) |
Simplifications the ball spec allows but B1 does not take (to keep the bit-exactness diagnostic):
dropping frozen manifolds;
scalar inverse inertia;
a closed-form solve instead of the 10-iteration loop.
They are available as off-by-default flags only if a measured performance need appears.