]> git.itanic.dy.fi Git - mandelbrot/blob - mandelbrot.c
Factor out iteration calculation
[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)
38 {
39         double x0, y0;
40         int iteration, xs,ys;
41
42         for (ys = 0, y0 = -1; ys < screen->h;
43              y0 += 2 / (double)screen->h, ys++) {
44                 for (xs = 0, x0 = -2.5; xs < screen->w;
45                      x0 += 3 / (double)screen->w, xs++) {
46
47                         iteration = get_mandelbrot_iterations(x0, y0);
48
49                         if (iteration == MAX_ITERATION)
50                                 putpixel(screen, xs, ys, 255, 255, 255);
51                         else
52                                 putpixel(screen, xs, ys,
53                                         iteration, 0, 0);
54                 }
55                 SDL_Flip(screen);
56         }
57
58         return 0;
59 }
60
61 int main(int argc, char *argv[])
62 {
63         SDL_Surface *screen;
64         int flags = SDL_DOUBLEBUF | SDL_HWSURFACE | SDL_RESIZABLE;
65         int xres = 800, yres = 600;
66
67         if (SDL_Init(SDL_INIT_VIDEO) != 0) {
68                 fprintf(stderr, "Unable to initialize SDL: %s\n",
69                         SDL_GetError());
70
71                 return 1;
72         }
73         atexit(SDL_Quit);
74
75         screen = SDL_SetVideoMode(xres, yres, 32, flags);
76         if (screen == NULL) {
77                 fprintf(stderr, "Unable to set video mode: %s\n",
78                         SDL_GetError());
79                 return 2;
80         }
81
82         SDL_WM_SetCaption(argv[0], NULL);
83
84         draw_mandelbrot(screen);
85
86         yres = read(0, &xres, 1);
87
88         return 0;
89 }