Skip to content

159 deterministic sim 4 the fixed point toolkit

Alex Diakovsky edited this page Nov 18, 2026 · 2 revisions

159. Deterministic sim 4: the fixed-point toolkit (stage S3)

Question: what arithmetic will the integer simulation use, so that a sine, a square root or an angle comes out as the same integer on every machine, and as the same integer the original computed (document 155, issue #133)?

The deterministic simulation series: document 155 is the plan; document 156 is stage S0, the harness; document 157 is stage S1, one fixed tick; document 158 is stage S2, the sim's own random numbers; this document is stage S3.

Traced, and a correction to the plan. Document 155 expected the original's trigonometry to be lookup tables, which the importer would extract into the pack. It isn't: all of the original's maths helpers run on the x87 FPU (FSIN, FCOS, FPATAN, FSQRT, FDIV). Each converts its result back to an integer with the C runtime's _ftol. So there is nothing to extract and nothing goes into the pack. The port computes the same integers with integer arithmetic only, from two exact tables of pure mathematics that live in the engine.

Glossary

Term Meaning
16.16 (Q16.16) A number stored as an integer 65,536 times its value: 0x18000 is 1.5. The original's positions, speeds and trigonometry are all 16.16.
angle unit The original's angles: 0x1000000 (2^24) to a full turn. angle >> 18 is one of the 64 direction steps of 5.625 degrees.
x87 The PC's floating-point unit of 1996, which the original's helpers use for sine, cosine, atan2 and square roots.
_ftol The C runtime's float-to-integer conversion (0x437478): it truncates toward zero and keeps the low 32 bits.
breakpoint The first angle at which the truncated sine reaches a value. 65,536 of them describe the sine exactly.
CORDIC A way to compute an angle by a fixed sequence of shifts, adds and table lookups, all on integers.
Fx The engine's class of these helpers (game/sim/fx.gd).

The answer, up front

  1. The original's maths helpers, traced: fixed multiply (FUN_00410b70), divide (FUN_00410c10), atan2 (FUN_00410b80), cosine (FUN_00410be0), sine (FUN_00410dc0), the two square roots (FUN_00410df0, FUN_00410e20), and the matrix helpers (FUN_00410c60, FUN_00410d00). The multiply and the matrices are integer instructions; everything else runs on the x87, then _ftol.
  2. Fx gives the same integers using integer arithmetic only:
    • the multiply, the divide, both square roots and the matrices are exact integer arithmetic;
    • sine and cosine come from an exact table of 65,536 breakpoints;
    • atan2 is an integer CORDIC carried to 2^-32 of an angle unit.
  3. The tables are computed once, exactly, by tools/gen_fx_tables.py with Python's arbitrary-precision integers (no floating point at all). They are written into game/sim/fx_tables.gd, about 176 KB of generated source.
  4. Checked against the original's own formula:
    • Sine: all 4,194,305 angles of a quarter turn (offline), and about 418,000 angles over three turns in the engine check. 0 differ.
    • atan2: 200,000 random points of every size, plus about 24,000 points one step off an axis or a diagonal (the hardest cases). 0 differ.
  5. Nothing uses Fx yet. Converting the vehicles, shots and the rest of the world to it is S4 and S5.

The original computes on the x87 FPU and truncates with _ftol; the port computes the same integers from exact tables with integer arithmetic only

Mermaid source
flowchart TB
  subgraph O["the original (RFIRE.BIN)"]
    direction TB
    OA["16.16 number or angle (int)"] --> OF["FILD, then scale by<br/>2^-16 and 2 pi / 256"]
    OF --> OX["x87: FSIN, FCOS,<br/>FPATAN, FSQRT, FDIV"]
    OX --> OT["_ftol: truncate,<br/>keep the low 32 bits"]
  end
  subgraph P["the port (Fx)"]
    direction TB
    PA["16.16 number or angle (int)"] --> PS["sin, cos: quadrant,<br/>then 65,536 breakpoints"]
    PA --> PC["atan2: integer<br/>CORDIC, 58 steps"]
    PA --> PQ["sqrt, div, mul:<br/>integer arithmetic"]
  end
  OT -. "the same integer" .- PA
Loading

Step 1: the helpers in RFIRE.BIN

Disassembled with DisasmForce.java 0x410b80 0x410e70. The constants they read, dumped with DumpDwords.java 0x43d000 12:

Address Double Value
0x43d000 0x3ef0000000000000 2^-16
0x43d008 0x40f0000000000000 65536
0x43d010 0x40445f306dc9c883 256 / 2π = 40.7436654...
0x43d018 0 0
0x43d020 0x4070000000000000 256
0x43d028 0x3f9921fb54442d18 2π / 256 = 0.0245436926...

Cosine and sine (FUN_00410be0, FUN_00410dc0, identical except for the instruction):

00410be6  FILD  dword ptr [EBP + 0x8]        ; the angle, an integer
00410be9  FMUL  double ptr [0x0043d000]      ; * 2^-16
00410bef  FMUL  double ptr [0x0043d028]      ; * 2 pi / 256: 2^24 units to a turn
00410bf5  FCOS                               ; (FSIN at 0x410dd5)
00410bf7  FMUL  double ptr [0x0043d008]      ; * 65536: back to 16.16
00410bfd  CALL  0x00437478                   ; _ftol

atan2 (FUN_00410b80(x, y)):

00410b86  FILD  dword ptr [EBP + 0xc]        ; y (second argument) * 2^-16
00410b8f  FILD  dword ptr [EBP + 0x8]        ; x (first argument) * 2^-16
00410b98  CMP   dword ptr [0x004558e4],0x0   ; the compiler's Pentium FDIV-bug switch
00410ba1  FPATAN                             ; atan2(y, x) (or the runtime's safe version at 0x438225)
00410baa  FMUL  double ptr [0x0043d010]      ; * 256 / 2 pi
00410bb0  FCOM  double ptr [0x0043d018]      ; below 0?
00410bc3  FADD  double ptr [0x0043d020]      ;   then + 256 (a full turn)
00410bcf  FMUL  double ptr [0x0043d008]      ; * 65536
00410bd5  CALL  0x00437478                   ; _ftol

Translation: the angle of (x, y) from the x axis, as 0 to 0xFFFFFF. Note the argument order: the first argument is x. The turret's FUN_00410b80(dist, dz) (document 114) is the angle of a rise dz over a run dist.

The square roots: FUN_00410df0(n) loads n zero-extended to 64 bits (so it is unsigned), FSQRT, _ftol: a whole square root. FUN_00410e20(a) scales by 2^-16, FSQRT, scales by 65536: a 16.16 square root.

The divide: FUN_00410c10(a, b) is a / b * 65536, truncated: a 16.16 quotient.

The multiply, FUN_00410b70, uses no FPU at all:

00410b70  MOV   EAX,ECX
00410b72  IMUL  EDX                          ; 64-bit product in EDX:EAX
00410b74  SHRD  EAX,EDX,0x10                 ; >> 16, low 32 bits

_ftol (0x437478) sets the FPU's rounding to "toward zero" (OR AH,0xc), stores a 64-bit integer (FISTP qword), restores the rounding and returns the low 32 bits in EAX.

Step 2: what the port computes

static func mul(a: int, b: int) -> int:
	return wrap32((a * b) >> 16)

static func div(a: int, b: int) -> int:
	if b == 0:
		return 0
	return wrap32((a << 16) / b)   # GDScript's integer `/` truncates toward zero, as _ftol does

static func isqrt(n: int) -> int:
	return _isqrt(n & 0xFFFFFFFF)

static func sqrt(a: int) -> int:
	if a <= 0:
		return 0
	return _isqrt(a << 16)

Translation:

  • Multiply: GDScript's >> on a 64-bit product is the same arithmetic shift as SHRD: it rounds toward minus infinity, so -1/65536 times 1/65536 is -1, not 0. wrap32 keeps the low 32 bits, as the register does.
  • Divide: integer division truncates toward zero, as _ftol does. Division by zero gives the x87's "integer indefinite", whose low 32 bits are 0.
  • Square roots: a whole integer square root (Newton's method on integers). For every argument the game can pass, the x87's FSQRT is exact enough that truncating it gives exactly this. A negative argument to FUN_00410e20 is invalid on the x87, which also ends as 0.

One difference is not reproduced. The x87 (at the 53-bit precision Windows sets) could round a quotient up to the next whole number when the divisor is above 2^22 and the exact quotient is within 2^-22 of that number. The integer divide gives the exact truncation there instead.

Step 3: sine and cosine, exactly

The truncated sine of a quarter turn, s(a) = trunc(sin(2π a / 2^24) * 65536) for a = 0 to 2^22, only ever rises, from 0 to 65,536. So it is fully described by where it steps up: B[v] is the first angle at which it reaches v. Those 65,536 breakpoints are the table. Each is less than 14,751 units after the one before, so the table is stored as 16-bit differences (128 KB, base64 in the generated source).

static func sin(a: int) -> int:
	var r := a & (TURN - 1)
	var t := r & (QUARTER_TURN - 1)
	match r >> 22:
		0:
			return _quarter(t)
		1:
			return _quarter(QUARTER_TURN - t)
		2:
			return -_quarter(t)
		_:
			return -_quarter(QUARTER_TURN - t)

static func cos(a: int) -> int:
	return Fx.sin(a + QUARTER_TURN)

## trunc(sin(2 pi t / 2^24) * 65536) for 0 <= t <= 2^22: how many breakpoints are at or below t.
static func _quarter(t: int) -> int:
	...
	return _sin_b.bsearch(t, false) - 1

Translation: the angle is reduced to a turn, then to a quarter by the sine's symmetries. Truncation toward zero is symmetric too, so the other three quarters are the first one mirrored or negated. The value is the number of breakpoints at or below the angle: one binary search over 65,537 integers.

A trap found while writing it: inside Fx, a bare sin(...) calls Godot's built-in float sin, not Fx.sin, so cos must say Fx.sin.

How the table is made. tools/gen_fx_tables.py computes π (Machin's formula) and the sine (its Taylor series) as integers scaled by 2^320, so every truncation is decided exactly. A double asin is used only to guess where to start each search; the exact sine decides. It runs in about two seconds.

Step 4: atan2

atan2 has two inputs, so no table of breakpoints can describe it. Fx.atan2 handles the axes and the diagonals first: the original returns exact whole units there (0x200000 for (1, 1), checked in double arithmetic). For any other point it runs an integer CORDIC:

	var z := 0
	var steps: Array[int] = FxTables.ATAN
	for i in steps.size():
		var xs := x >> i
		var ys := y >> i
		if y > 0:
			x += ys
			y -= xs
			z += steps[i]
		else:
			x -= ys
			y += xs
			z -= steps[i]
	var total := base + z
	if total < 0:
		total += 1 << 56
	return (total >> 32) & (TURN - 1)

Translation:

  1. The point is turned half a turn if x is negative.
  2. The point is scaled up to about 2^58.
  3. At each of 58 steps, the point is turned toward the x axis by atan(2^-i), a shift and an add, and the turned angle is added up in z.
  4. FxTables.ATAN holds those 58 angles in 2^-32 of an angle unit (2^56 to a turn), computed exactly by the same script.
  5. The sum is within about 2^-27 of a unit of the exact angle, so its whole part is the original's except when the exact angle lies that close to a whole unit. No such point turned up in the checks.

What the original's x87 contributes, and what it doesn't

The truncated x87 results are the "true" values except where an exact result lies within the double's rounding (about 10^-11 of a 16.16 step, or 2^-28 of an angle unit) of a whole number. The port's tables give the exact values. The two can differ only at such a point, and the checks found none: not in all 4.2 million quarter-turn angles of the sine, nor in 224,000 atan2 points.

What matters for netplay is that Fx uses no floating point at all. It gives the same integer on every machine, operating system and build, which a float sin from each platform's maths library does not promise.

Tests

  • New fx_check (engine):

    • hand-worked values for every helper: 1.5 × 1.5, rounding toward minus infinity, 32-bit wrap, division by zero, unsigned isqrt, cos 0 = 1, 45 degrees = 46,340, the axes and diagonals of atan2;
    • square roots on 20,000 values;
    • sine and cosine at about 418,000 angles over three turns, including negative ones;
    • atan2 at 200,000 random points and about 24,000 points one step off an axis or a diagonal;
    • the matrix helpers.

    Everything is compared with the original's formula run in double precision. 0 differ.

  • float_lint_check: sim/fx.gd joins the simulation files; its only floats are the two in to_float, which is for views. The maths pattern no longer counts calls to Fx.sin(...) or the definitions of functions named sin. Baseline 2,228.

  • All 55 engine checks pass, and the openfire checks pass with the engine bumped (nothing in openfire uses Fx yet).

Where the code is

In the engine (alexdia25/openfire-engine):

  • game/sim/fx.gd: Fx
  • game/sim/fx_tables.gd: FxTables (generated; do not edit)
  • tools/gen_fx_tables.py: the generator
  • tests/fx_check.gd

Next: S4, sim state out of the scene nodes (document 160). The vehicles and shots keep their state in plain objects, with views that read it, so that S5 can convert each one to 16.16 and angle units with Fx.

Clone this wiki locally