]> git.itanic.dy.fi Git - mandelbrot/blob - mandelbrot.c
Take drawing area as an parameter
[mandelbrot] / mandelbrot.c
1 #include <SDL.h>
2 #include <unistd.h>
3 #include <stdio.h>
4 #include <time.h>
5
6 static void putpixel(struct SDL_Surface *screen, const int x, const int y,
7                      const unsigned char r, const unsigned char g,
8                      const unsigned char b)
9 {
10         int offset = y * screen->pitch + x * 4;
11         unsigned char *buf = screen->pixels;
12
13         buf[offset++] = b;
14         buf[offset++] = g;
15         buf[offset]   = r;
16 }
17
18 #define MAX_ITERATION 1000
19
20 int get_mandelbrot_iterations(double x0, double y0)
21 {
22         double x = 0, y = 0, xtemp;
23         int iteration = 0;
24
25         while ((x * x + y * y < 2 * 2) && iteration < MAX_ITERATION) {
26
27                 xtemp = x * x - y * y + x0;
28                 y = 2 * x * y + y0;
29
30                 x = xtemp;
31                 iteration++;
32         }
33
34         return iteration;
35 }
36
37 int draw_mandelbrot(struct SDL_Surface *screen, double x1, double x2,
38                 double y1, double y2)
39 {
40         double x0, y0, xlen, ylen, xstep, ystep;
41         int iteration, xs, ys;
42
43         xlen = x2 - x1;
44         ylen = y2 - y1;
45         xstep = xlen / (double)screen->w;
46         ystep = ylen / (double)screen->h;
47
48         for (ys = 0, y0 = y1; ys < screen->h; y0 += ystep, ys++) {
49                 for (xs = 0, x0 = x1; xs < screen->w; x0 += xstep, xs++) {
50                         iteration = get_mandelbrot_iterations(x0, y0);
51
52                         if (iteration == MAX_ITERATION)
53                                 putpixel(screen, xs, ys, 255, 255, 255);
54                         else
55                                 putpixel(screen, xs, ys,
56                                         iteration, 0, 0);
57                 }
58
59                 SDL_Flip(screen);
60         }
61
62         return 0;
63 }
64
65 int main(int argc, char *argv[])
66 {
67         SDL_Surface *screen;
68         int flags = SDL_DOUBLEBUF | SDL_HWSURFACE | SDL_RESIZABLE;
69         int xres = 800, yres = 600;
70
71         if (SDL_Init(SDL_INIT_VIDEO) != 0) {
72                 fprintf(stderr, "Unable to initialize SDL: %s\n",
73                         SDL_GetError());
74
75                 return 1;
76         }
77         atexit(SDL_Quit);
78
79         screen = SDL_SetVideoMode(xres, yres, 32, flags);
80         if (screen == NULL) {
81                 fprintf(stderr, "Unable to set video mode: %s\n",
82                         SDL_GetError());
83                 return 2;
84         }
85
86         SDL_WM_SetCaption(argv[0], NULL);
87
88         draw_mandelbrot(screen, -2.5, 1, -1, 1);
89
90         yres = read(0, &xres, 1);
91
92         return 0;
93 }