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;
54 xstep = xlen / (double)screen->w;
55 ystep = ylen / (double)screen->h;
58 #pragma omp parallel for private(xs, ys, x0, y0)
59 for (ys = 0; ys < screen->h; ys++) {
62 for (xs = 0; xs < screen->w; xs++) {
63 iteration = get_mandelbrot_iterations(x0, y0);
65 if (iteration == MAX_ITERATION)
66 putpixel(screen, xs, ys, 255, 255, 255);
68 putpixel(screen, xs, ys,
69 iteration * 8, iteration,
79 static int read_events(struct context *ctx)
82 int wait = 1, ret, exit = 0, delayed_exit = 0;
86 SDL_WaitEvent(&event);
89 ret = SDL_PollEvent(&event);
98 switch (event.key.keysym.sym) {
106 switch (event.key.keysym.sym) {
111 case SDL_MOUSEBUTTONDOWN:
112 if (event.button.button == 4) {
115 } else if (event.button.button == 5) {
119 ctx->scroll_enabled = 1;
122 case SDL_MOUSEBUTTONUP:
123 ctx->scroll_enabled = 0;
126 case SDL_MOUSEMOTION:
127 if (!ctx->scroll_enabled)
130 ctx->motion_x -= event.motion.xrel;
131 ctx->motion_y -= event.motion.yrel;
134 case SDL_VIDEORESIZE:
136 SDL_SetVideoMode(event.resize.w,
149 printf("\nExiting. Good bye!\n");
153 static void loop(struct context *ctx)
158 aspect_ratio = ctx->screen->w / ctx->screen->h;
159 ctx->origo_x += ctx->motion_x / ctx->zoom / ctx->screen->w;
160 ctx->origo_y += ctx->motion_y / ctx->zoom / ctx->screen->h;
161 ctx->motion_x = ctx->motion_y = 0;
163 draw_mandelbrot(ctx->screen,
164 ctx->origo_x - aspect_ratio / ctx->zoom,
165 ctx->origo_x + aspect_ratio / ctx->zoom,
166 ctx->origo_y - 1 / ctx->zoom,
167 ctx->origo_y + 1 / ctx->zoom);
168 printf("Drawing area (%f, %f)(%f, %f), zoom %d\n",
169 x1, y1, x2, y2, 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);