The random number generator of DOOM
github.com
github.com
Perlin Noise is still used to this day for generating clouds, natural-looking terrains, and other textures that are pleasing to the human brain.
Python implementation: https://github.com/caseman/noise/blob/master/perlin.py
Excellent talk by its creator: http://www.noisemachine.com/talk1/
Perlin- https://i.imgur.com/ROww6bw.gif Random- https://i.imgur.com/EurTdaZ.gif
(By manipulating the available variables in a Bezier curve.)
But of course homage accounts are more common these days.
Turns out that good randomness didn't seem random to people. They might hear three songs in a row from the same album and think "that's not right, it should be random!" Of course, humans often have a different idea of what "random" is.
There is a difference between randomly picking an element from a list and reordering a list in a random order. This is not a matter of how random really are the random numbers.
The values in the DOOM table could have been generated by Carmack throwing a dice many times for all we know and just tabulated the results.
But that does not make the question why the DOOM solution is so much smaller than the perlin noise code more valid. It is simply not the same thing. One is a table of set of generated data, the other a generator of data that can be tabulated.
First, check out Catacomb (1989). I think this is the oldest of Carmack's games for which source code has been released. This game uses a lagged fibonacci generator:
https://github.com/FlatRockSoft/Catacomb/blob/master/CATASM....
This makes sense, it's a generator that requires little memory and no expensive operations such as multiplications. You'll probably also find it in Softdisk's Apple II releases.
Carmack's first 3D game is Hovertank 3D, released in 1991. The LFG still exists, but now a "table-based RND generator" also appears. This seems to be the first appearance of the "Doom RNG".
https://github.com/FlatRockSoft/Hovertank3D/blob/master/IDAS...
The LFG is used when setting up the map, while the table-based is used for enemy AI during gameplay. Obviously every cycle counts when trying to do 3D on a 286.
The same year also saw the release of Keen Dreams, in which only the table-based RNG survives:
https://github.com/keendreams/keen/blob/master/id_us_a.asm
(The state variables of the LFG are still defined, but the code is missing.)
According to a comment in the Catacomb source, the LFG logic was derived from a macro supplied with the Merlin assembler for Apple 2 GS computers:
;this routine was converted from
;the Random macro on Merlin GS" The Doom pseudorandom number generator is simplistic yet adequate for gameplay. Its simplicity has the virtue of speed.
The file m_random.c in the Doom source code contains a static table 256 bytes long containing numbers between 0 and 255 in a fixed, scrambled order. There is an index to this table which starts at zero. Each call to the function P_Random advances the index by one (wrapping around to zero after 255) and returns the table entry at that index.
There is another function, M_Random, that is identical except that it uses its own independent index. P_Random is used in play simulation situations, such as calculating hit damage. M_Random is used otherwise.
The reason for the existence of two individual indexes is to maintain multiplayer synchronisation: for example, M_Random is used to apply a random pitch variation to sounds. As two players may not hear the same sound effect (they may be in different parts of the level), using a single index would cause the game to become desynchronised. To use a model-view-controller analogy, P_Random is used for random number generation at the 'model', while M_Random is used for random number generation at the 'view'.
The function M_ClearRandom resets both functions' indexes to zero. It is called during initialization of each new level so that demos will be the same each time they are played, and so that multiplayer games are synchronised.
Although the table is 256 bytes long, it does not contain all of the numbers between 0 and 255 inclusive. For example, 0 appears twice and 1 does not appear at all; 145 appears five times, more than any other number. Thus the values are not uniformly distributed, but in fact they are nearly so. The mean value is 128.852, whereas it would be 127.500 if all values were equally likely. All of this suggests that the table was generated using a conventional pseudorandom number generator of reasonable quality. "
[0]: http://doom.wikia.com/wiki/Pseudorandom_number_generator
edit: here's a much better article contributed by user aciuix in this thread : http://doomwiki.org/wiki/Pseudorandom_number_generator
The "random number generator" isn't actually the table, but rather the table <-> the amount of times the function is actually called (aka player input as a source of randomness).
If the game were coded in such a way that there are more deterministic random calls (enemy seeding at beginning of a level, etc) then it would feel less random. If it were coded in a way that there are more non-deterministic random calls (enemy spawning based on table index when a player enters a room) then it would feel more random.
The table is deterministic, but the exact value returned for any given event X is the product of how many random() calling events happened before event X.
Or, in the ideal engineering way: achieve the minimal randomness required for player belief, and use the saved computational overhead on my interesting things (e.g. graphics).
The period here is unusually short, but it is enough for the use case.
If you want a non-predictable random bit source, you have to sample a quantum phenomenon using dedicated hardware.
What I don't understand is the following line:
prndindex = (prndindex+1)&0xff;
(I'm not a C programmer.) AFAIK, the &0xff is a pointer - but what precisely does it do?It's essentially the same[0] as `prndindex = (prndinex+1) % 256`, except bitwise AND takes less effort to compute.
Modulo is essentially[1]: `mod = a - b * (a / b)` unless the compiler can manage to use bitwise shifting/masks instead.
Back when Doom was popular, the bitmask would have been much more efficient.
[0] http://stackoverflow.com/q/3072665/2967113 [1] I'm not 100% positive that's how it's implemented with an IDIV instruction.
This difference means that the AND is still faster than the MOD when used on signed integers, if the compiler is not smart enough to prove that the input will never be negative.
For example, with gcc 4.7.3 the resulting assembly is
movl %edi, %edx
sarl $31, %edx
shrl $24, %edx
leal (%rdi, %rdx), %eax
andl $255, %eax
subl %edx, %eax
I.e., six instructions instead of one. This is still faster than using a divide.The difference is that the AND is a binary operator — i.e., it takes two arguments:
A & B
whereas the address-of operator "&" is a "unary" operator; it only takes one argument: &A
There can be something before it in a more complete context, such as: x = 3 + &y;
(though this is more often conventionally written the other way "&y + 3"; I only use this for demonstration)But here "+" is the binary operator. (You can't have two binary operators in a row; that would be like "3 + * 2", which is nonsensical.) This is similar to "3 + -2": the negative here is a unary operator, the "+" here is the binary operator "add"
> there are two operators (one taking the address of something, the result of which is a pointer, another taking a bitwise AND); they both use the same symbol "&".
Don't you just love C? ;-) (On a serious note, I've been meaning to learn it for some time, but didn't yet get down to the nitty-gritty.)
For Doom speed was more important than length of the sequence so they just made it a lookup table.
If there's a purpose behind the table being constructed with those omissions/repetitions it's lost on me.
I had begun to wonder if certain values caused issues when used in code and it was deemed easier to just not get certain values back.
That's crazy talk though.
A few numbers like 239 and 242 occur 3 times. And a bunch do not occur at all.
https://github.com/ValveSoftware/halflife/blob/master/dlls/u...
Note that this is only used for certain parts of the game. For others it uses a closed source non-table based generator.
Another poster[1] links to a Doom wiki article[2], which explains,
> The reason for the existence of two individual indexes is to maintain multiplayer synchronisation
If you sync the PRNG's state at the beginning of the game, you can simply transmit the other client's input (such as keyboard/mouse): since each PRNG is in the same state on all the players' machines, you don't need to distribute over the network the results of PRNG choices: each client can just compute it locally. So long as all the code uses the PRNG's output stream for the same purposes, in the same order, everything is deterministic (while appearing to be random).
Milliseconds played would also likely require some sort of OS/hardware interaction, to get to a timer. This is an add, an AND, and a memory lookup: likely significantly quicker (bear in mind the hardware Doom was created with/for). (Perhaps there are cycle counts, but I'm not sure that instruction was a thing yet? Though it was more reliable then…)
Also see this post: https://news.ycombinator.com/item?id=9429889
This may also present the advantage of being tweakable to avoid repeated sequences that better generator may naturally produce but are not perceived as 'random enough' by humans.
This must be pretty fast (and compact) code: rndindex = (rndindex+1)&0xff; return rndtable[rndindex];
The example C code at https://en.wikipedia.org/wiki/Linear_feedback_shift_register looks like it would compile to more bytes, and require more CPU cycles to execute.
Based on https://en.wikipedia.org/wiki/Linear_congruential_generator it seems LCGs also micro-optimize for memory rather than CPU performance.
Doom was probably squeezing every last cycle out of 386 @ 25 MHz machines to render frames, but they did have at least 4MB–8MB RAM; 256 bytes seems a good trade-off.
Imagine I want to sample [0,2), then I can use the following table: [0,0,0,1,1,0,1,1]. This has cycle length 8. Much longer cycles can be obtained, it just requires the state of the prng to be larger than range being sampled.
It is not, at least not the way you (and me) are interpreting it. A RNG's period is bounded by the number of states it has, internally[1]:
> The period is bounded by the number of the states
> If a PRNG's internal state contains n bits, its period can be no longer than 2 ^ n results, and may be much shorter.
Our state in the Doom generator is the variable rndindex (or prndindex; we have two generators here); rndindex holds an index in [0, 256) (it is 8 bits), hence we have at most that many states (2 ^ 8, or 256). (I'm assuming the table does not repeat itself, as that would be silly, so in this case, the period is exactly 256 outputs long.)
[1]: https://en.wikipedia.org/wiki/Pseudorandom_number_generator#...
I say this because I have investigated many crypto libraries for usage and nearly every one of them (especially openssl) have random generators that depend on global state. The attitude of not caring about correctness and thread safety is just pervasive.
I would have thought it was quite well known among the tech crowd, even non-gamers.
Tech is a very ahistorical discipline. We don't look back at the "old masters". We reinvent things every generation (or in Javascript land, every week).
DOOM was one of those games that relied on stretching the hardware to its limits to produce previously-unseen visual effects. The only thing that mattered was getting pixels on the screen as fast as possible.
Edit: no, of course there weren't any mutex primitives in DOS/4GW. It's a single-process single-thread bare metal environment. You have to realise that, in 1993 PC gaming, shared memory multithreading was simply not something that developers would ever encounter. It had no concievable advantages as you had only one CPU, not even a graphics accelerator. Games generally wouldn't multitask either; again, this predates consumer availability of Win32 and certainly is several years before DirectX.