Last active
August 18, 2019 02:39
-
-
Save pedrominicz/f298eadf8159a346c026b6c17b4b731c to your computer and use it in GitHub Desktop.
Noise!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <limits.h> | |
#include <stdint.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#define WIDTH 150 | |
#define HEIGHT 150 | |
#define POINTS 60 | |
struct point { | |
int x, y; | |
}; | |
uint8_t noise[WIDTH][HEIGHT]; | |
uint32_t random_u32(void) { | |
static uint32_t seed = 1; | |
seed ^= seed << 13; | |
seed ^= seed >> 17; | |
seed ^= seed << 5; | |
return seed; | |
} | |
void print(void) { | |
int zoom = 5; | |
printf("P2\n"); | |
printf("%d %d\n", WIDTH * zoom, HEIGHT * zoom); | |
printf("255\n"); | |
for(int i = 0; i < HEIGHT * zoom; ++i) { | |
int x = i / zoom; | |
for(int j = 0; j < WIDTH * zoom; ++j) { | |
int y = j / zoom; | |
printf("%d ", noise[x][y]); | |
} | |
printf("\n"); | |
} | |
} | |
static inline int max(int a, int b) { return a > b ? a : b; } | |
static inline int min(int a, int b) { return a < b ? a : b; } | |
static inline int square(int x) { return x * x; } | |
static inline int root(int x) { | |
if(x < 0) return 0; | |
int i = 0; | |
while(1) { | |
if(i * i > x) return i; | |
++i; | |
} | |
} | |
int compare(const void* a, const void* b) { | |
return *(int*)a - *(int*)b; | |
} | |
int main(void) { | |
struct point p[POINTS] = {0}; | |
for(int i = 0; i < POINTS; ++i) { | |
p[i].x = random_u32() % (WIDTH * 2); | |
p[i].y = random_u32() % (HEIGHT * 2); | |
p[i].x -= WIDTH / 2; | |
p[i].y -= HEIGHT / 2; | |
} | |
for(int x = 0; x < WIDTH; ++x) { | |
for(int y = 0; y < HEIGHT; ++y) { | |
int d[POINTS]; | |
for(int i = 0; i < POINTS; ++i) { | |
int delta_x = x - p[i].x; | |
int delta_y = y - p[i].y; | |
d[i] = root(square(delta_x) + square(delta_y)); | |
} | |
qsort(d, POINTS, sizeof(int), compare); | |
noise[x][y] = min(max(d[1], 0), 255); | |
} | |
} | |
print(); | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
gcc -pedantic -Wall -Wextra -Werror noise.c || exit | |
./a.out | feh - | |
rm -f a.out |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment