TExcelTAD
Home › Multiplayer Game Networking › Quantization & Delta Compression

Quantization & Delta Compression

Bit-packing (Serialization & Bit-Packing) saves space on small integers. The two biggest savings in a real snapshot come from somewhere else:

  1. Quantization: sending floats with only the precision the game needs.
  2. Delta compression: sending only what changed since a snapshot the client is known to have.

Quantization

A 32-bit float position can describe sub-micrometre steps across the whole solar system. A player in a 1 km arena needs maybe 1 cm of precision. If the range is known, map the value to an integer:

text
bits needed = ceil(log2(range / precision + 1))
encode: q = round((value - min) / precision)
decode: value = min + q * precision

Angles are even cheaper: a yaw angle with 10 bits has 1024 steps, about 0.35° each, which is finer than any player can aim with on a typical server snapshot.

ts · try it yourself
function bitsFor(min: number, max: number, precision: number) {
  return Math.ceil(Math.log2((max - min) / precision + 1));
}
function quantize(v: number, min: number, precision: number) { return Math.round((v - min) / precision); }
function dequantize(q: number, min: number, precision: number) { return min + q * precision; }

const fields = [
  { name: 'x (-512..512 m, 1 cm)', min: -512, max: 512, precision: 0.01, value: 123.4567 },
  { name: 'z (-512..512 m, 1 cm)', min: -512, max: 512, precision: 0.01, value: -77.0049 },
  { name: 'y (0..64 m, 1 cm)',      min: 0, max: 64, precision: 0.01, value: 3.1415 },
  { name: 'yaw (0..360, 10 bits)',  min: 0, max: 360, precision: 360 / 1023, value: 271.3 },
];
let total = 0;
for (const f of fields) {
  const bits = bitsFor(f.min, f.max, f.precision);
  const q = quantize(f.value, f.min, f.precision);
  const back = dequantize(q, f.min, f.precision);
  total += bits;
  console.log(`${f.name.padEnd(24)} ${String(bits).padStart(2)} bits  ${f.value} -> ${q} -> ${back.toFixed(4)} (error ${(back - f.value).toFixed(4)})`);
}
console.log(`total ${total} bits instead of ${fields.length * 32} bits as float32`);
x (-512..512 m, 1 cm)    17 bits  123.4567 -> 63546 -> 123.4600 (error 0.0033)
z (-512..512 m, 1 cm)    17 bits  -77.0049 -> 43500 -> -77.0000 (error 0.0049)
y (0..64 m, 1 cm)        13 bits  3.1415 -> 314 -> 3.1400 (error -0.0015)
yaw (0..360, 10 bits)    10 bits  271.3 -> 771 -> 271.3196 (error 0.0196)
total 57 bits instead of 128 bits as float32

Two rules make quantization safe:

  • Quantize on the server too. If the server keeps simulating with the full float but clients only see the rounded value, predicted clients and the server disagree by a centimetre every tick, and reconciliation keeps correcting nothing. Many engines quantize the authoritative state itself after every tick so that both sides start from the same numbers.
  • Clamp before encoding. A value outside the range wraps around into nonsense. Assert in development builds, clamp in release builds.

Delta compression

In most snapshots, most things didn't change: walls, pickups, idle players, a player's health. Sending the full state every time wastes most of the packet. Instead, the server encodes each snapshot relative to a baseline: an earlier snapshot that the client has acknowledged receiving. For every entity it sends a bit mask of which fields changed, then only those fields.

Why "acknowledged"? Because the previous snapshot might have been lost. A delta against a snapshot the client never got is useless. So the server keeps a short history of snapshots per client, and the client tells it, in every packet, the newest snapshot it received (Reliability over UDP shows how acks travel).

ts · try it yourself
type Ent = { x: number; y: number; hp: number; anim: number };
const FIELDS: (keyof Ent)[] = ['x', 'y', 'hp', 'anim'];
const BITS: Record<keyof Ent, number> = { x: 17, y: 17, hp: 7, anim: 4 };   // quantized widths

function fullBits(snap: Map<number, Ent>) {
  return snap.size * (8 + FIELDS.reduce((s, f) => s + BITS[f], 0));        // 8-bit id + all fields
}
function deltaBits(base: Map<number, Ent> | undefined, snap: Map<number, Ent>) {
  if (!base) return { bits: fullBits(snap), note: 'no baseline: full snapshot' };
  let bits = 0, changed = 0;
  for (const [id, e] of snap) {
    const b = base.get(id);
    if (!b) { bits += 8 + 1 + FIELDS.reduce((s, f) => s + BITS[f], 0); changed++; continue; }  // new entity
    const diff = FIELDS.filter((f) => e[f] !== b[f]);
    if (diff.length === 0) continue;                                // unchanged: costs nothing
    bits += 8 + 1 + FIELDS.length + diff.reduce((s, f) => s + BITS[f], 0);  // id + new? + mask + fields
    changed++;
  }
  return { bits: bits + 8, note: `${changed} of ${snap.size} entities changed` };  // + 8-bit end marker
}

// 20 entities: 3 players run around, everything else is idle.
const snaps: Map<number, Ent>[] = [];
for (let tick = 0; tick < 4; tick++) {
  const m = new Map<number, Ent>();
  for (let id = 0; id < 20; id++) {
    const moving = id < 3;
    m.set(id, { x: 1000 + id * 50 + (moving ? tick * 12 : 0), y: 500 + (moving && id === 0 ? tick * 3 : 0), hp: id === 1 && tick >= 2 ? 80 : 100, anim: moving ? 1 : 0 });
  }
  snaps.push(m);
}

const acked = [undefined, 0, 1, 1];     // the baseline each snapshot was encoded against (snapshot 2 was lost)
for (let t = 0; t < snaps.length; t++) {
  const base = acked[t] === undefined ? undefined : snaps[acked[t]!];
  const d = deltaBits(base, snaps[t]);
  console.log(`snapshot ${t} vs ${acked[t] === undefined ? '-' : acked[t]}: ${String(Math.ceil(d.bits / 8)).padStart(3)} bytes (full: ${Math.ceil(fullBits(snaps[t]) / 8)}) ${d.note}`);
}
snapshot 0 vs -: 133 bytes (full: 133) no baseline: full snapshot
snapshot 1 vs 0:  15 bytes (full: 133) 3 of 20 entities changed
snapshot 2 vs 1:  16 bytes (full: 133) 3 of 20 entities changed
snapshot 3 vs 1:  16 bytes (full: 133) 3 of 20 entities changed

Snapshot 3 is still encoded against snapshot 1 because the client never acknowledged snapshot 2. Here it costs the same 16 bytes, because the same few fields change either way. In general an older baseline means more changed fields and a bigger delta, and when the client hasn't acked anything for a while (say, a burst of loss), the server falls back to a full snapshot. The packet grows, but the client can always decode it, and from 133 bytes down to about 16 is the kind of saving that makes 64-player games possible.

Other tricks

Trick Saves Notes
Send velocities as small deltas bits on positions "moved +12 since baseline" needs fewer bits than an absolute position
Smallest-three quaternions 3D rotations send the 3 smallest components (≈ 9–10 bits each) plus a 2-bit index of the largest; the largest is recovered from x² + y² + z² + w² = 1
Per-entity priority packet space send important or nearby entities every snapshot, far ones every few (Interest Management)
Generic compression (zlib, LZ4) repeated byte patterns helps little on well bit-packed data; useful for big reliable messages such as map data

Test yourself

A position ranges over 0..100 m and needs 1 cm precision. How many bits?

  1. 7
  2. 10
  3. 14
  4. 32

Why must a delta snapshot be encoded against a baseline the client has acknowledged?

  1. Acknowledged snapshots are smaller
  2. Otherwise the baseline may have been lost, and the client can't decode the delta
  3. Because UDP requires it
  4. To encrypt it

What goes wrong if the server simulates with full floats but sends quantized positions?

  1. Nothing
  2. Predicting clients and the server drift apart slightly, causing constant small corrections
  3. The packet becomes larger
  4. The client can't decode it