drew my first mandelbrot today

master
Anton Lydike 5 years ago
parent f932325a27
commit f9b559f3a0

@ -0,0 +1,54 @@
#include <math.h>
typedef struct _mycomplex {
float re;
float im;
} Complex;
inline Complex complex_new(float re, float im) __attribute__ ((always_inline));
inline Complex complex_add(Complex c1, Complex c2) __attribute__ ((always_inline));
inline Complex complex_mult(Complex c1, Complex c2) __attribute__ ((always_inline));
inline double complex_abs(Complex c) __attribute__ ((always_inline));
inline Complex complex_new(float re, float im)
{
Complex c;
c.re = re;
c.im = im;
return c;
}
inline Complex complex_mult(Complex c1, Complex c2)
{
Complex ret;
ret.re = c1.re * c2.re - c1.im * c2.im;
ret.im = c1.re * c2.im + c1.im * c2.re;
return ret;
}
inline Complex complex_add(Complex c1, Complex c2)
{
c1.re += c2.re;
c1.im += c2.im;
return c1;
}
inline Complex complex_conj(Complex c) {
c.im = -c.im;
return c;
}
inline double complex_abs(Complex c)
{
double re, im;
re = c.re;
im = c.im;
return sqrt(re * re + im * im);
}
inline void complex_print(Complex c) {
printf("%.3f + i%.3f", c.re, c.im);
}

@ -1,10 +1,63 @@
#include <stdlib.h> #include <stdlib.h>
#include <stdio.h> #include <stdio.h>
#include <math.h>
#include "images/images.h" #include "images/images.h"
#include "complex.c"
void draw_mandelbrot(int width, int height, int iterations);
void draw_mandelbrot_auto(int width, int iterations);
int test_mandelbrot(Complex c, int iterations);
int main(int argc, char* argv[]) { int main(int argc, char* argv[]) {
int width = 3000;
int iterations = 60;
if (argc > 1) {
width = atoi(argv[1]);
}
if (argc > 2) {
iterations = atoi(argv[2]);
}
draw_mandelbrot_auto(width, iterations);
}
void draw_mandelbrot_auto(int width, int iterations) {
draw_mandelbrot(width, 2 * width / 3, iterations);
}
void draw_mandelbrot(int width, int height, int iterations) {
int center_x = 2 * width / 3;
int center_y = height / 2;
float step = 3.0f / width;
Image img;
image_new(width, height, &img);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
Complex c = complex_new(
(x - center_x) * step,
(y - center_y) * step
);
int ret = test_mandelbrot(c, iterations);
int r = (ret * 160 / iterations);
int g = (ret * 9 / iterations);
int b = (ret * 165 / iterations);
image_set_px(img, x, y, r,g,b);
}
}
image_save_bmp(img, "mandelbrot.bmp");
image_destroy(img);
}
int test_mandelbrot(Complex c, int iterations) {
Complex z = complex_new(0,0);
for (int i = 0; i < iterations; i++) {
z = complex_add(complex_mult(z,z), c); // z^2 + c
if (complex_abs(z) > 2) return i;
}
return 0;
} }

Loading…
Cancel
Save