From b2bd93ce391765f296fca4ab4705fc62e0c62060 Mon Sep 17 00:00:00 2001 From: Abdelrahman Said Date: Fri, 22 Mar 2024 00:26:01 +0000 Subject: [PATCH] Implement basic xorshift PRNG --- xorshift.c | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 xorshift.c diff --git a/xorshift.c b/xorshift.c new file mode 100644 index 0000000..2c88676 --- /dev/null +++ b/xorshift.c @@ -0,0 +1,63 @@ +#include "aliases.h" +#include "ppm.h" +#include +#include +#include +#include +#include + +typedef struct { + u64 x; + u64 y; + u64 z; + u64 w; +} XORShiftBasic; + +u64 xor_shift_basic_generate(XORShiftBasic *state); + +int main(int argc, char *argv[]) { + struct timespec ts = {0}; + clock_gettime(CLOCK_MONOTONIC_RAW, &ts); + + srand48(ts.tv_nsec); + + XORShiftBasic state = { + .x = lrand48(), + .y = lrand48(), + .z = lrand48(), + .w = lrand48(), + }; + + u64 w = 1024; + u64 h = 1024; + u64 length = w * h; + + Pixel data[length]; + for (u64 y = 0; y < h; ++y) { + for (u64 x = 0; x < w; ++x) { + u64 i = y * w + x; + + u8 pixel = xor_shift_basic_generate(&state) % UINT8_MAX; + data[i] = (Pixel){ + .r = pixel, + .g = pixel, + .b = pixel, + }; + } + } + + write_p6_ppm("./outputs/xorshift.ppm", w, h, data); + + return EXIT_SUCCESS; +} + +u64 xor_shift_basic_generate(XORShiftBasic *state) { + u64 t = state->x ^ (state->x << 11); + + state->x = state->y; + state->y = state->z; + state->z = state->w; + state->w = (state->w ^ (state->w >> 19)) ^ (t ^ (t >> 8)); + + return state->w; +}