feat!: implement main using diverge

This commit is contained in:
2026-07-18 00:47:59 +02:00
parent 27085c4ec1
commit 635119e27a
+58 -30
View File
@@ -1,19 +1,51 @@
#include "stdio.h"
#include "math.h"
#include "stdint.h"
#include "stdbool.h"
#define MAX_DEPTH 50
#define WIDTH 3
#define HEIGHT 2
#define WIDTH 420
#define HEIGHT 360
/////////////////////
// complex numbers //
/////////////////////
#define X_MIN -1.0
#define X_MAX 1.0
#define Y_MIN -1.0
#define Y_MAX 1.0
#define SIZE (WIDTH * HEIGHT)
typedef struct Complex {
double real, imag;
} Complex;
typedef struct Color {
uint8_t r, g, b;
} Color;
int diverge(Complex c);
Color color_map(int depth);
void write_ppm(char *path, Color img[SIZE]);
int main() {
Color img[SIZE];
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
double x = ((double)j / (double)WIDTH) * (X_MAX - X_MIN) + X_MIN;
double y = ((double)i / (double)HEIGHT) * (Y_MAX - Y_MIN) + Y_MIN;
Complex c = {.real = x, .imag = y};
int depth = diverge(c);
img[i * WIDTH + j] = color_map(depth);
}
}
write_ppm("mandelbrot.c.ppm", img);
return 1;
}
/////////////////////
// complex numbers //
/////////////////////
void cx_print(Complex z) {
printf("%f + %f i", z.real, z.imag);
}
@@ -34,28 +66,10 @@ static inline double cx_abs(Complex z) {
// mandelbrot //
////////////////
Complex f(Complex z, Complex c) {
static inline Complex f(Complex z, Complex c) {
return cx_add(cx_square(z), c);
}
////////////////
// ppm-writer //
////////////////
typedef struct Color {
uint8_t r, g, b;
} Color;
void write_ppm(char *path, Color img[HEIGHT * WIDTH]) {
FILE *fptr;
fptr = fopen(path, "w");
fprintf(fptr, "P3\n%d %d\n255\n", WIDTH, HEIGHT);
for (int i = 0; i < WIDTH * HEIGHT; i++) {
fprintf(fptr, "%d %d %d\n", img[i].r, img[i].g, img[i].b);
}
fclose(fptr);
}
// return iteration count, MAX_DEPTH if diverge
int diverge(Complex c) {
int counter = 0;
@@ -65,11 +79,25 @@ int diverge(Complex c) {
return counter;
}
int main() {
Color img[WIDTH * HEIGHT] = {
(Color){255, 0, 0}, (Color){0, 255, 0}, (Color){0, 0, 255},
(Color){255, 0, 0}, (Color){0, 255, 0}, (Color){0, 0, 255}
Color color_map(int depth) {
bool cond = depth % 2 == 0;
return (Color){
cond ? 255 : 0,
cond ? 255 : 0,
cond ? 255 : 0
};
write_ppm("test.ppm", img);
return 1;
}
////////////////
// ppm-writer //
////////////////
void write_ppm(char *path, Color img[SIZE]) {
FILE *fptr;
fptr = fopen(path, "w");
fprintf(fptr, "P3\n%d %d\n255\n", WIDTH, HEIGHT);
for (int i = 0; i < SIZE; i++)
fprintf(fptr, "%d %d %d\n", img[i].r, img[i].g, img[i].b);
printf("successfully wrote to %s\n", path);
fclose(fptr);
}