#include "screen.h" const char MANDEL_CHARS[] = "`.,:;!^=*?$%@HHHHHHHHHHBBBBBBBBBWWWWWWWWWWW#######"; const int NUM_MANDEL_CHARS = 50; const int BAILOUT = 100; const int INDENT = 10; // Determine the number of iterations necessary to escape the Mandelbrot // function, if it's possible at that point. int computeMandel( double x, double y ) { double a = 0.0; double b = 0.0; for( int iter = 0; iter < BAILOUT; iter++ ) { double new_a = a * a - b * b + x; double new_b = 2 * a * b + y; a = new_a; b = new_b; if( a * a + b * b >= 4 ) { return iter; } } return -1; } // Fill in a region of the screen with a portion of the Mandelbrot set. // (m_left, m_top) is the top left corner of the region to compute. // The region has width m_width and height m_height. The set should be // drawn in a rectangle on the screen at (col,row) of width 'width' and // height 'height'. void drawMandel( Screen& screen, double m_left, double m_top, double m_width, double m_height, int col, int row, int width, int height ) { for( int idy = 0; idy < height; idy++ ) { double vfrac = (double)idy / (double)height; double y = m_top - vfrac * m_height; for( int idx = 0; idx < width; idx++ ) { double hfrac = (double)idx / (double)width; double x = m_left + hfrac * m_width; int iters = computeMandel( x, y ); char ch = ' '; if( iters != -1 ) { ch = MANDEL_CHARS[ ( iters * NUM_MANDEL_CHARS ) / BAILOUT ]; } screen.putChar( col + idx, row + idy, ch ); } } } // Accept a region of the complex plane from the user, and draw a picture // of the Mandelbrot set as it appears in that region. // For a 'good' look at the whole set, try entering -1.4 1 2 2. // // As usual, when you run this program, it will sit there waiting for // input. It won't do anything until you type in four numbers. int main( void ) { double m_left; double m_top; double m_width; double m_height; cin >> m_left >> m_top >> m_width >> m_height; while( cin && cin.get() != '\n' ); Screen screen; // Fill the screen with a background character just to distinguish it // from the window we're going to draw. screen.fill( ':' ); // Draw a rectangle to surround the set. screen.rectangle( INDENT - 1, 1, SCREEN_WIDTH - 1 - 2 * ( INDENT - 1 ), SCREEN_HEIGHT - 4, ' ' ); // Draw the Mandelbrot set inside that rectangle. drawMandel( screen, m_left, m_top, m_width, m_height, INDENT, 2, SCREEN_WIDTH - 1 - 2 * INDENT, SCREEN_HEIGHT - 6 ); // Put up a snazzy title. screen.putCenteredText( SCREEN_HEIGHT - 2, " The Mandelbrot Set " ); screen.print( cout ); cerr << "Press return to exit." << endl; while( cin && cin.get() != '\n' ); return 0; }