KierannCode / Playground

Project about creating a game engine with SDL from scratch, this is for fun and for my personal experience only
0 stars 0 forks source link

Implement random generation tools #9

Open KierannCode opened 2 years ago

KierannCode commented 2 years ago

Standard C random generator seems to not work properly with threads. SDL2 does not provides any random generation support. Therefore, a thread-safe random generation support is required for this project. It may require a lot of time, but if it cannot be done easily from scratch, the standard C++ library shall be used in the overlay instead.

KierannCode commented 2 years ago

Today i have done some experimentations, i will put the code below because i don't want to implement it until the documentation is fully completed. The main tool is a function that returns a true random bit within at most 1 millisecond. I was not able to reduce this delay without biasing the probabilities. So far, the manual tests were successful : the repartition of 0 and 1 is equally likely, the same goes for two successive bit generation (00, 01, 10 and 11). Here's the code :

unsigned char generateTrueRandomBit() {
    unsigned int i = 0;
    while (OSDL::Timer::getTicks() == OSDL::Timer::getTicks()) {
        ++i;
    }
    return i & 1;
}

Improvements can be made, but true random number generation is not really an objective for this project since every software shall be deterministic. Nevertheless, it could be implemented as an OSDL feature, or used for seeding a pseudo-random number generator (which seem harder to implement)

An example of fast implementation to generate random numbers within a range from 0 to max is :

unsigned int trueRand(unsigned int max) {
    int minBits = 0;
    while (max >> minBits != 0) {
        ++minBits;
    }
    unsigned int result;
    do {
        result = 0;
        for (int i = 0; i < minBits; ++i) {
            result <<= 1;
            result |= generateTrueRandomBit();
        }
    } while (result > max);
    return result;
}