Skip to content

164 deterministic sim 9 collision

Alex Diakovsky edited this page Nov 21, 2026 · 4 revisions

164. Deterministic sim 9: collision in 16.16 (stage S5.3)

Update (document 174): explosion damage boxes now use this document's chain test (type 2, a box), cell by cell.

Update (document 171): the water class now uses this document's shape test. Its whole-unit segment cut has a visible effect there: an object less than a unit before a shore tile's centre on both axes never overlaps the coast shape.

Question: how does the original decide that two things touch (a vehicle and a tile, two vehicles, a shot and anything), exactly, on its integers? And what changes when the port decides it the same way (document 155, issue #133)?

The deterministic simulation series: document 155 is the plan. Documents 156 to 160 are stages S0 to S4. Documents 161 and 162 are S5.1 (vehicle movement), document 163 is S5.2 (projectiles), and this document is S5.3, collision.

Collision was first traced in document 53 (the shapes and what a shell hits), document 54 (what blocks a vehicle) and document 55 (the zones). This document re-reads each function for its exact integer form. Doing so corrected three things documents 53 and 54 had said; both are updated.

Glossary

Term Meaning
16.16, heading, step As in document 161. A shape's numbers are 16.16 too.
shape, chain A collision shape (layout in document 53): type, layer bits, mask, z range, offset, box, vertices. An object's shapes form a chain, in rising z order.
mover The object being moved or tested: a vehicle trying a position, or a shot after its tick. The other object is the one it is tested against.
coarse box A shape's +0x1c box. Every pair test starts by asking whether the two boxes overlap. For a polygon the box is set by hand in the descriptor and is never turned with the heading.
whole-unit cut FUN_0041d670 shifts every coordinate difference right by 16 before multiplying, so it works in whole units.
swept shape The shot's type-4 shape, rebuilt before each test from where the shot was and where it is (FUN_0041e5f0).
cell A 32 x 32 tile (0x200000). Each cell holds its tile's coastal id and a list of the objects standing in it.

The answer, up front

  1. Collision is now integers. Positions, headings, shapes and every test are the original's 16.16 and 22-bit numbers, and each function below is ported one to one. Gates, soldiers, drones, mines and explosion boxes still use the float tests (stage S5.5).
  2. Only the mover's mask is asked (mover.mask & other.layer). Document 53 said both masks must agree, and the port tested both ways. It has been corrected.
  3. A shot is a point in height. Its z range is rebuilt each test from the height it rose or fell in that tick, so the descriptor's ±1.5 is never used. A level shot skims over a shape whose top is just below it. Document 53 said ±1.5 and has been corrected.
  4. The segment test works in whole units. Edges less than a unit apart and parallel count as touching, so a vehicle stops up to about a unit early. A corner clipped by a fraction of a unit can be missed.
  5. A polygon's coarse box is never turned. A Tank turned 45 degrees reaches 13.5 units out at its corners, outside its ±12 box, so a thin obstacle there is never tested and the corner passes through it.
  6. A shot meets a polygon only where it lands. The swept test against a polygon tests the shot's stored vertices, which were never moved to the shot's position. In practice only "the new position is inside" counts, so a fast shot can fly through a vehicle in one tick.
  7. A shot's move can hit several things. Each callback only marks the shot for removal and returns 2, so the scan goes on. Every tile and vehicle the move meets is damaged, and the impact effect is the last one's.
  8. Shots now hit zone shapes. The depot aprons (ids 14 to 17, layer 1) and turret zones (39 to 42) are in a shot's mask (0x43). The port had skipped them.
  9. The cells are scanned in the original's order: own row (centre, left, right), then the row above, then the row below. In each cell, the tile first, then the objects.

A mover's test: the cells are scanned (own row centre, left, right; then above; then below); in each, the tile's chain is walked against the mover's (mover mask only, z order, first hit), the hit shape goes to the coastal callback, then the vehicles in the cell are tested; each pair test starts with the coarse boxes, then the shape-pair geometry built on the whole-unit segment test

Mermaid source
flowchart TB
  M["mover at pos, heading<br/>(a shot: swept shape, FUN_0041e5f0)"] --> SC["cell scan FUN_0042bd40 / FUN_0042bf30<br/>own row: centre, left, right<br/>then row above, then row below"]
  SC --> CELL["one cell: FUN_0042bb10"]
  CELL --> TC["tile chain vs mover chain<br/>FUN_0041e4c0: mover.mask & layer<br/>z order, first hit"]
  TC -- "hit shape" --> CB["coastal callback<br/>&1 blocked, &8 pass the tile"]
  TC -- "no hit" --> OB
  CB --> OB["objects in the cell<br/>(vehicles)"]
  OB --> PT["pair test FUN_0041e060"]
  PT --> CO{"coarse boxes overlap?<br/>(polygon box never turned)"}
  CO -- "no" --> MISS["miss"]
  CO -- "yes" --> GEO["box / polygon / swept point<br/>FUN_0041d8d0, FUN_0041dc10, FUN_0041deb0"]
  GEO --> SEG["segment test FUN_0041d670<br/>differences >> 16"]
Loading

Step 1: the segment test, FUN_0041d670

Every geometric test comes down to "do segments p1-p2 and p3-p4 meet?":

iVar6 = param_4[1] - iVar5 >> 0x10;          // d.y of p3-p4, whole units
iVar1 = iVar7 - *param_1 >> 0x10;            // e.x of p1-p2
iVar10 = param_2[1] - param_1[1] >> 0x10;    // e.y
iVar2 = *param_4 - iVar4 >> 0x10;            // d.x
iVar3 = iVar6 * iVar1 - iVar10 * iVar2;      // den
iVar8 = iVar4 - *param_1 >> 0x10;            // w = p3 - p1
iVar9 = iVar5 - param_1[1] >> 0x10;
iVar10 = iVar10 * iVar8 - iVar9 * iVar1;     // n1
iVar1 = iVar6 * iVar8 - iVar9 * iVar2;       // n2
if (iVar3 == 0) {                            // parallel
  if (iVar10 != 0) return 0;                 // not on one line
  ... x (or y) ranges overlap ? -1 : 0       // collinear
}
// den > 0: 0 <= n1 <= den and 0 <= n2 <= den ; den < 0: mirrored

The port, Collision.cross_fx:

var d1y := (p4.y - p3.y) >> 16
var ex := (p2.x - p1.x) >> 16
var ey := (p2.y - p1.y) >> 16
var d1x := (p4.x - p3.x) >> 16
var den := Fx.wrap32(d1y * ex - ey * d1x)
var wx := (p3.x - p1.x) >> 16
var wy := (p3.y - p1.y) >> 16
var n1 := Fx.wrap32(ey * wx - wy * ex)
var n2 := Fx.wrap32(d1y * wx - wy * d1x)
if den == 0:
	if n1 != 0:
		return 0
	...                                   # the raw x ranges (or y, for a vertical line) decide: -1 or 0
if den > 0:
	return 1 if n1 >= 0 and n1 <= den and n2 >= 0 and n2 <= den else 0
return 1 if n1 <= 0 and den <= n1 and n2 <= 0 and den <= n2 else 0

Translation: the test turns each difference into whole units first (rounding down), then does the usual crossing test with both ends included. Two consequences:

  • Edges less than a unit apart and parallel are "on one line". Their ranges overlap, so they touch. A Tank whose nose stops 0.25 units short of a wall is blocked.
  • The rounding can also lose a crossing. A Tank turned 22.5 degrees whose edge clips a palm trunk's corner by 0.1 unit: the exact crossing parameter is 0.93, but after rounding down it is 40/32, so there is no hit.

Step 2: the shape pairs, FUN_0041e060

FUN_0041e060 dispatches on the two shapes' types. Each branch first asks whether the coarse boxes overlap (FUN_0041d5f0, ends included), then:

Pair Function Hit when
box, box FUN_0041d5f0 the boxes overlap
polygon, box FUN_0041d8d0 the polygon's origin is in the box, or a box edge meets a polygon edge, or the segment from the box's origin to the polygon's meets no polygon edge
polygon, polygon FUN_0041dc10 two edges meet, or the segment between the origins does not leave A and cross B
swept point (4), box FUN_0041deb0 the shot's position is in the box, or the segment it flew meets a box edge
swept point (4), polygon FUN_0041e060 see below

A polygon's vertices are turned by the heading matrix H[heading >> 16] (document 163, step 1), only when the heading has a whole step (heading & 0xffff0000). The coarse box is not turned. The Tank, Jeep and MSV have a ±12 box, and the Heli has (−12, −16, 12, 35). The Tank's corner is 13.5 from its centre, so at 45 degrees it is outside the box. An obstacle that only that corner reaches fails the coarse test and is never tested further.

The swept point against a polygon is the odd one. The edge test passes the shape's stored vertices, prev − cur and 0, without adding the shot's position:

static func swept_hits_poly_fx(o: Vector2i, s: Dictionary, po: Vector2i, heading: int, ps: Dictionary) -> bool:
	if not boxes_fx(o, s["box"], po, ps["box"]):
		return false
	var poly := world_poly_fx(po, heading, ps["verts"])
	var v: PackedInt32Array = s["verts"]
	if segment_meets_edges_fx(Vector2i(v[0], v[1]), Vector2i(v[3], v[4]), poly):   # near the map's corner: never, on a real map
		return true
	return not segment_meets_edges_fx(o, po, poly)   # the shot's position is inside

Translation: a shot hits a vehicle only if it ends a tick inside it. A shot that flies right through in one tick misses, and a shot that skims an edge without ending inside misses. The inside test is "the segment from the shot to the vehicle's centre crosses no edge". With the whole-unit cut, a shot whose line to the centre passes within a unit of a corner can count as inside even when it is several units outside. One case: the Heli, whose side vertices (±10.2, 0) sit straight across from its centre, so a shot on that line counts as inside. The coarse box limits how far out this reaches.

Step 3: two chains, FUN_0041e4c0

if ((*(byte *)((int)param_3 + 0xb) & *(byte *)((int)param_6 + 10)) == 0) return 0;   // mover mask & other layer
while (true) {
  // skip the other's shapes wholly below, the mover's wholly below (z + object height, ends included)
  ...
  if ((puVar4->layer & puVar3->mask) != 0 && FUN_0041e060(...) != 0 && (puVar3->layer | puVar4->layer) != 0) break;
  // step the chain whose current shape starts lower (the mover's on a tie goes to the other's)
}
DAT_0047c914 = puVar3;      // the mover's shape that hit
DAT_0047c918 = puVar4;      // the other's: the coastal callback reads it
return bVar5;

The port, Collision.chains_hit_fx:

if (int(c1[0]["mask"]) & int(c2[0]["layer"])) == 0:
	return {}
...
	if int(a["z0"]) + z1 > int(b["z1"]) + z2:
		j += 1
		continue
	if int(b["z0"]) + z2 > int(a["z1"]) + z1:
		i += 1
		continue
	if (int(b["layer"]) & int(a["mask"])) != 0 and (int(a["layer"]) | int(b["layer"])) != 0 \
			and shapes_hit_fx(p1, h1, a, p2, h2, b, sweep):
		return {"a": a, "b": b}

Translation: the two chains are walked together from the bottom up, and the first pair that meets is the answer. Only the mover's mask is read: the other shape's mask is never asked. So a bush's skirt (mask 4) is met by a vehicle (mask 0x27 holds layer 1). The bush's callback then answers "pass the rest of the tile" for a shape with mask 4, so the outcome is unchanged. A shot (mask 0x43) meets the depot apron and turret zones on layer 1 but not a gate's zone on layer 32. The other's shape that hit is left in DAT_0047c918 for the coastal callback to read. A tile's later shapes are not asked.

Step 4: the shot's shape, FUN_0041e5f0

iVar2 = param_2[2] - param_3[2];            // cur.z - prev.z
if (iVar2 < 0) { shape->z0 = iVar2; shape->z1 = 0; } else { shape->z0 = 0; shape->z1 = iVar2; }
iVar2 = *param_3 - *param_2;  verts[0] = iVar2;   // prev.x - cur.x, and the box's x side
...
verts[1] = param_3[1] - param_2[1];               // prev.y - cur.y; vertex 1 stays (0, 0)
static func shell_shape_fx(prev: Vector2i, prev_z: int, cur: Vector2i, cur_z: int) -> Dictionary:
	var d := Vector2i(prev.x - cur.x, prev.y - cur.y)
	var dz := cur_z - prev_z
	return {"type": SHELL_TYPE, "layer": SHELL_LAYER, "mask": SHELL_MASK, "b8": 0, "b9": 0,
		"z0": mini(dz, 0), "z1": maxi(dz, 0), "off": Vector2i.ZERO,
		"box": PackedInt32Array([mini(d.x, 0), mini(d.y, 0), maxi(d.x, 0), maxi(d.y, 0)]),
		"verts": PackedInt32Array([d.x, d.y, 0, 0, 0, 0]), "src": {}}

Translation: before each test the mover FUN_0042c830 points DAT_0046a7cc at the shot's saved previous position, and the shape is rebuilt from it. Its z range runs from where the shot is now back to where it was, so a level shot is a single height. Its one segment runs from the old position to the new one.

Step 5: the cells, FUN_0042bd40 and FUN_0042bf30

The scan visits the mover's own row (its cell, then left, then right), then the row above, then the row below. A neighbour is skipped at the map's edge (x < 0x200000, x > 0xfdfffff, y < 0x200001, y >= 0xfe00000), or when the mover sits in the far half of its cell and its reach (the draw descriptor's +0xc) is not positive. Every traced reach is positive (shots 0x8000, Tank/Jeep/MSV 0xc0000, Heli 0x1e9999), so all nine cells are always scanned.

func _scan_cells(pos: Vector2i, reach: int, visit: Callable) -> bool:
	var t := Vector2i(pos.x >> 21, pos.y >> 21)
	if _scan_row(pos, reach, t, visit):
		return true
	var fy := pos.y & 0x1f0000
	if (fy - reach < 0x100000 or reach > 0) and pos.y >= CELL_FX + 1:
		if _scan_row(pos, reach, t + Vector2i(0, -1), visit):
			return true
	if (fy + reach > 0xfffff or reach > 0) and pos.y < (level.height - 1) * CELL_FX:
		if _scan_row(pos, reach, t + Vector2i(0, 1), visit):
			return true
	return false

In each cell FUN_0042bb10 first walks the tile's chain (placed at the cell's centre plus the decoration jitter). The first shape that meets goes to the coastal callback: &1 blocks, &8 skips the rest of the tile. Then the mover class's +0x34 tile callback runs, then the objects in the cell with their +0x38 callbacks.

Translation: for a vehicle, the first tile or vehicle that blocks ends the test. A shot's callbacks never end it: the tile callback FUN_00414dd0 damages the tile and queues the shot's removal, and the object callback FUN_00414e60 damages the vehicle, then both return 2. So one tick's move hits everything it meets, in scan order. Every coastal callback returns 0 for a mover that is not a vehicle, so a shot is stopped by any tile shape it meets.

_scan_cells(cur, SHELL_SCAN_REACH, func(t: Vector2i) -> bool:
	if _in_level(t) and not (shooter is Turret and (shooter as Turret).tile == t):
		var th := _tile_shape_hit_fx(chain, cur, cur_z, 0, t)
		if not th.is_empty():
			hits.append({"tile": t, "id": int(th["id"]), "gate": false})
	for o in _vehicles_in_cell(t, shooter):
		if not Collision.chains_hit_fx(cur, cur_z, 0, chain, o.pos_fx, o.z_fx(), o.heading_fx, o.hit_chain_fx).is_empty():
			hits.append({"vehicle": o})
	return false)

The vehicles' shapes

The pack's vehicle shape gains the descriptor's hand-set box. Without one (a mod's vehicle), the port gives it the square that holds the polygon at any heading. The Heli's polygon now has the raw values (0x1e9999, 0xa3333, 0xd9999: 30.6, 10.2, 13.6), not rounded. This is a pack-format change: re-import the original (python tools/import_original.py <game dir> packs/original_pc).

Vehicle Polygon Box
Tank ±7.5 x ±11.25 ±12
Jeep ±4.5 x ±7.5 ±12
MSV ±7.5, −12 to 11.25 ±12
Heli tail boom 30.6 back, 10.2 to each side, 13.6 forward (−12, −16, 12, 35)

What changed in behaviour

The golden check ran the same three things on the old engine and the new one. All three used a fixed match seed on RFMAP001, with the rebuilt pack:

  • a sweep of every vehicle over a 15 x 15 grid round one tile of each coastal id, at three headings;
  • shots across the same tiles at four heights and three directions, and at each vehicle on open ground;
  • a 600-tick scripted drive with firing, for each vehicle.

Every difference was traced to one of the rules above:

  • The drive: the Heli's trace is identical. The Tank (tick 164) and the MSV (tick 189) first part from the old trace where a turned corner reaches a palm trunk: the coarse box misses it now, as in the original. The Jeep (tick 233) is stopped 0.99 units from a trunk by the whole-unit cut. Everything later follows from the new paths.
  • The vehicle sweep: cells blocked now and not before are the whole-unit cut (0.75 short of a trunk, say). Cells free now are the unturned coarse box, or a corner clip the cut loses. The bush skirts are met by the one-way mask and pass, as before.
  • The shot sweep, tiles: at height 8 a shot clears a bush (top 7), at 14 a palm's canopy (15 to 18), and at 2 a bush's skirt (0 to 1). Each is the point height. A shot that starts on a box's edge hits it (ends included).
  • The shot sweep, vehicles: a shot hits a step later (it must end inside), or misses a vehicle it only skimmed. Near a corner in line with the centre, it hits from several units out.

Tests

  • New collision_fx_check.gd (engine):
    • the segment cases and the whole-unit cut;
    • the turned polygon against the float one at all 64 steps;
    • the missing-box default;
    • a Tank against a wall at 11, 12.5 and 13.5, and two Tanks 15 and 16 apart;
    • the 45-degree corner the coarse box misses;
    • the mask rule (zones, gate zones, height);
    • a bush's body met before its skirt;
    • the shot's swept shape and its tunnelling.
  • turret_check.gd and the computer players' gunnery ask shell_hits_fx.
  • The engine and openfire checks pass. crush_sound_check.gd and ruin_access.gd call vehicle_blocked with a 16.16 position and a 22-bit heading.

Known differences from the original, kept

  • The order of objects within a cell: the original's list is in order of arrival, newest first. The port tests a cell's vehicles in the match's order.
  • A vehicle driving into a shot: the vehicle-side test (polygon against a type-4 shape) is not run. Shots are tested after they move.
  • Gates, soldiers, drones, mines, explosion boxes and the turrets' line-of-fire probe still use the float tests with both masks (stage S5.5).

Where the code is

  • Engine game/collision.gd: the 16.16 section, from shape_fx and cross_fx to chains_hit_fx. The float helpers above it remain for the S5.5 objects.
  • Engine game/match_controller.gd: vehicle_blocked, _terrain_hit, shell_hits_fx and _apply_shell_hits, the cell scan _scan_cells / _scan_row, _tile_shape_hit_fx, _vehicles_in_cell.
  • Engine game/vehicle.gd: hit_chain_fx, z_fx(). The drive modules pass pos_fx / heading_fx to blocked_test.
  • Engine game/projectile.gd: prev_fx, prev_z_fx.
  • Engine game/pack.gd: Pack.fx, a pack number as 16.16 (the shapes are converted where the pack is read). game/sim/fx.gd: isqrt_wide, for the square that holds a polygon without a box. Vehicle.polygon_at, an unused float rectangle, is gone. The float lint's baseline is lowered (2082 to 2066 uses).
  • Openfire tools/extract_vehicle_types.py and tools/data/vehicle_types.json: the boxes and the Heli's raw polygon. DumpShapes.java and DumpCoastalShapes.java print the edge bytes.

Commits: engine b648779, openfire e418f27.

Next: S5.4, damage, hit points, fuel, ammo, rearm and refuel.

Clone this wiki locally