eolib 0.5.0
A core C library for writing applications related to Endless Online
Loading...
Searching...
No Matches
RNG (Random Number Generator)

Overview

The eolib-c RNG module (eolib/rng.h) faithfully emulates the pseudo-random number generator used by the original 32-bit Borland EO game client.

It is a dual-state linear congruential generator with two 32-bit state variables (current_seed and state_high) that together give it an effective period of approximately 2⁶², far longer than a classic single-register LCG.

Seeding

Call eo_srand before using the generator:

eo_srand(my_seed);
void eo_srand(uint32_t seed)
Definition rng.c:6

Internally, the seed is scrambled with the multiplier 22695477 before initialising current_seed, and state_high is reset to zero.

Reproducing the original client behaviour

The original EO client seeded the RNG at startup using (uint32_t)time(NULL). To replicate this:

#include <time.h>
#include "eolib/rng.h"
eo_srand((uint32_t)time(NULL)); // mirrors the original client startup seed

If you pass the same seed on two different runs you will get an identical sequence of random numbers, which is useful for deterministic replay or testing.

Algorithm

Each call to eo_rand performs the following steps:

  1. Compute contributions from the current high-state word and low-state word:
    temp_state_product = state_high ? state_high * 20021 : 0
    temp_seed_product = current_seed * 346
    static uint32_t state_high
    Definition rng.c:3
    static uint32_t current_seed
    Definition rng.c:4
  2. Multiply current_seed by 20021 using 64-bit arithmetic to capture carry:
    full_product = (uint64_t)current_seed * 20021
  3. Add the previous contributions to the high 32 bits of the product:
    seed_hi += temp_state_product + temp_seed_product
  4. Increment the low word and update state:
    current_seed = (uint32_t)full_product + 1
    state_high = seed_hi
  5. Return the upper 31 bits: state_high & 0x7FFFFFFF

The output is always a positive 31-bit integer in [0, 2147483647].

API

Function Description
eo_srand Seed the generator
eo_rand Generate the next pseudo-random 31-bit value
eo_rand_range Generate a value in the inclusive range [min, max]