1
0
Fork 0

stdlibs random for life

This commit is contained in:
Pabloader 2025-05-12 08:03:55 +00:00
parent db4a0f5f6f
commit 4cdc19b590
2 changed files with 3 additions and 32 deletions

View File

@ -12,7 +12,7 @@ const step = life.step as CallableFunction;
let pixels: Uint8Array; let pixels: Uint8Array;
export default function main() { export default function main() {
const pixelsPtr = life.initField(Date.now()); const pixelsPtr = life.initField();
pixels = new Uint8Array(life.memory.buffer, pixelsPtr, width * height * 4); pixels = new Uint8Array(life.memory.buffer, pixelsPtr, width * height * 4);
console.log(life, pixels.length); console.log(life, pixels.length);

View File

@ -8,7 +8,6 @@ static uint8_t* field;
static uint8_t* nextField; static uint8_t* nextField;
static uint8_t* pixels; static uint8_t* pixels;
static uint8_t rand8(void);
static int countNeighbours(int x, int y); static int countNeighbours(int x, int y);
EXPORT(getWidth) int get_width(void) { return width; } EXPORT(getWidth) int get_width(void) { return width; }
@ -66,42 +65,14 @@ static int countNeighbours(int x, int y) {
return count; return count;
} }
/** Random generator implementation from https://stackoverflow.com/a/16761955 */
#define STATE_BYTES 7
#define MULT 0x13B /* for STATE_BYTES==6 only */
#define MULT_LO (MULT & 255)
#define MULT_HI (MULT & 256)
static uint8_t rand_state[STATE_BYTES] = {0x87, 0xdd, 0xdc, 0x10, 0x35, 0xbc, 0x5c};
static uint8_t rand8(void) {
static uint16_t c = 0x42;
static uint32_t i = 0;
uint16_t t;
uint8_t x;
x = rand_state[i];
t = (uint16_t)x * MULT_LO + c;
c = t >> 8;
#if MULT_HI
c += x;
#endif
x = t & 255;
rand_state[i] = x;
if (++i >= sizeof(rand_state))
i = 0;
return x;
}
EXPORT(initField) uint8_t* init_field(uint32_t randomSeed) {
*((uint32_t*)&rand_state[STATE_BYTES - sizeof(uint32_t)]) = randomSeed; // Voodoo
EXPORT(initField) uint8_t* init_field(void) {
field = malloc(width * height); field = malloc(width * height);
nextField = malloc(width * height); nextField = malloc(width * height);
pixels = malloc(width * height * 4); pixels = malloc(width * height * 4);
for (int i = 0; i < width * height; i++) { for (int i = 0; i < width * height; i++) {
field[i] = rand8() & 1; field[i] = rand() & 1;
} }
return pixels; return pixels;