view src/Mandelbrot.cpp @ 4:df02a7de7fe2

I think I've got the Abstract Factory code working pretty robustly now, though I still need to make the factory singletons thread-safe
author Eris Caffee <discordia@eldalin.com>
date Tue, 26 Oct 2010 02:03:47 -0500
parents 0f4ad525f49a
children d691ce98f406
line source
1 ////////////////////////////////////////////////////////////////////////////////
2 //
3 // (C) 2010 Sarah Eris Horsley Caffee
4 //
5 // mandelbrot - A simple Mandelbrot Set viewer.
6 //
7 // Mandelbrot.cpp
8 // Mandelbrot set calculator class implementation
9 //
10 ////////////////////////////////////////////////////////////////////////////////
12 #include <string>
14 #include "Mandelbrot.h"
17 ////////////////////////////////////////////////////////////////////////////////
19 Mandelbrot::Mandelbrot()
20 {
21 re_min = -2.5;
22 im_max = 2.5;
23 size = 5.0;
24 max_iter = 50;
25 calc_needed = true;
26 display_name = "Mandelbrot set";
27 fractal_name = "Mandelbrot set";
28 }
31 ////////////////////////////////////////////////////////////////////////////////
32 bool Mandelbrot::init(SDL_Surface * surf)
33 {
34 if (!surf)
35 {
36 return false;
37 }
38 else
39 {
40 surface = surf;
41 }
42 calc_needed = true;
43 return true;
44 }
47 ////////////////////////////////////////////////////////////////////////////////
49 bool Mandelbrot::calc_set()
50 {
51 if (!surface) return false;
53 // Code from http://warp.povusers.org/Mandelbrot/
55 if (calc_needed)
56 {
57 double re_scale = (size)/(surface->w-1);
58 double im_scale = (size)/(surface->h-1);
60 int r, g, b;
62 Uint32 black = SDL_MapRGB(surface->format, 0, 0, 0);
63 Uint32 color;
64 int halfway = max_iter/2 - 1;
65 float step = (float) 255 / halfway;
67 unsigned x, y, n;
69 for(y = 0; y < surface->h; ++y)
70 {
71 double c_im = im_max - y * im_scale;
72 for(x = 0; x < surface->w; ++x)
73 {
74 double c_re = re_min + x * re_scale;
76 double z_re = c_re, z_im = c_im;
77 bool in_set = true;
78 for(n=0; n < max_iter; ++n)
79 {
80 double z_re2 = z_re * z_re, z_im2 = z_im * z_im;
81 if(z_re2 + z_im2 > 4)
82 {
83 in_set = false;
84 break;
85 }
86 z_im = 2 * z_re * z_im + c_im;
87 z_re = z_re2 - z_im2 + c_re;
88 }
89 if(in_set)
90 {
91 draw_pixel(x, y, &black);
92 }
93 else
94 {
95 if (n <= halfway)
96 {
97 b = n * step;
98 r = g = 0;
99 }
100 else
101 {
102 b = 255;
103 r = g = (n - halfway) * step;
104 }
105 color = SDL_MapRGB(surface->format, r, g, b);
106 draw_pixel(x, y, &color);
107 }
108 }
109 }
110 }
112 calc_needed = false;
113 return true;
114 }
117 ////////////////////////////////////////////////////////////////////////////////
118 std::string const & Mandelbrot::get_fractal_name() const
119 {
120 return fractal_name;
121 }
124 ////////////////////////////////////////////////////////////////////////////////
126 void Mandelbrot::draw_pixel(int x, int y, Uint32 * color)
127 {
128 Fractal::draw_pixel(x, y, color);
129 }