8 struct SDL_Surface *screen;
9 double origo_x, origo_y;
10 int motion_x, motion_y;
15 static void putpixel(struct SDL_Surface *screen, const int x, const int y,
16 const unsigned char r, const unsigned char g,
17 const unsigned char b)
19 int offset = y * screen->pitch + x * 4;
20 unsigned char *buf = screen->pixels;
27 #define MAX_ITERATION 1000
29 int get_mandelbrot_iterations(double x0, double y0)
31 double x = 0, y = 0, xtemp;
34 while ((x * x + y * y < 2 * 2) && iteration < MAX_ITERATION) {
36 xtemp = x * x - y * y + x0;
46 int draw_mandelbrot(struct SDL_Surface *screen, double x1, double x2,
49 double x0, y0, xlen, ylen, xstep, ystep;
50 int iteration, xs, ys;
52 printf("Drawing area (%f, %f)(%f, %f)\n", x1, y1, x2, y2);
56 xstep = xlen / (double)screen->w;
57 ystep = ylen / (double)screen->h;
60 #pragma omp parallel for private(xs, ys, x0, y0)
61 for (ys = 0; ys < screen->h; ys++) {
64 for (xs = 0; xs < screen->w; xs++) {
65 iteration = get_mandelbrot_iterations(x0, y0);
67 if (iteration == MAX_ITERATION)
68 putpixel(screen, xs, ys, 255, 255, 255);
70 putpixel(screen, xs, ys,
71 iteration * 8, iteration,
81 static int read_events(struct context *ctx)
84 int wait = 1, ret, exit = 0, delayed_exit = 0;
88 SDL_WaitEvent(&event);
91 ret = SDL_PollEvent(&event);
100 switch (event.key.keysym.sym) {
108 switch (event.key.keysym.sym) {
113 case SDL_MOUSEBUTTONDOWN:
114 if (event.button.button == 4) {
117 } else if (event.button.button == 5) {
121 ctx->scroll_enabled = 1;
124 case SDL_MOUSEBUTTONUP:
125 ctx->scroll_enabled = 0;
128 case SDL_MOUSEMOTION:
129 if (!ctx->scroll_enabled)
132 ctx->motion_x -= event.motion.xrel;
133 ctx->motion_y -= event.motion.yrel;
136 case SDL_VIDEORESIZE:
138 SDL_SetVideoMode(event.resize.w,
151 printf("\nExiting. Good bye!\n");
155 static void loop(struct context *ctx)
160 aspect_ratio = ctx->screen->w / ctx->screen->h;
161 ctx->origo_x += ctx->motion_x / ctx->zoom / ctx->screen->w;
162 ctx->origo_y += ctx->motion_y / ctx->zoom / ctx->screen->h;
163 ctx->motion_x = ctx->motion_y = 0;
165 draw_mandelbrot(ctx->screen,
166 ctx->origo_x - aspect_ratio / ctx->zoom,
167 ctx->origo_x + aspect_ratio / ctx->zoom,
168 ctx->origo_y - 1 / ctx->zoom,
169 ctx->origo_y + 1 / ctx->zoom);
170 } while (!read_events(ctx));
173 int main(int argc, char *argv[])
176 int flags = SDL_DOUBLEBUF | SDL_HWSURFACE | SDL_RESIZABLE;
177 int xres = 800, yres = 600;
179 memset(&ctx, 0, sizeof(ctx));
182 if (SDL_Init(SDL_INIT_VIDEO) != 0) {
183 fprintf(stderr, "Unable to initialize SDL: %s\n",
190 ctx.screen = SDL_SetVideoMode(xres, yres, 32, flags);
191 if (ctx.screen == NULL) {
192 fprintf(stderr, "Unable to set video mode: %s\n",
197 SDL_WM_SetCaption(argv[0], NULL);