// mandelbrot.cpp

#include <iostream>
#include <fstream>

using namespace std;

fstream picture;

int steps(int maxi, double c1, double c2) {
	double z1=0;
	double z2=0;
	double a;
	double b;
	int step=0;
	int i=0;
	do {
		i+=1;
		a=z1*z1;
		b=z2*z2;
		z2=c2+2*z1*z2;
		z1=c1+a-b;
		if ((a+b)>9) step=i;
	}
	while ((!step) && (i<maxi));
	return step;
}

int bmpx(int i) {
	int ret=i;
	while (ret%4) ret++;
	return ret;
}

void pb(char b) {
	picture.write((char*) &b,sizeof(char));
}

void hilo(int m, int b[4]) {
	int l=m;
	int i;
	for (i=0; i<4; i++) {
		b[i]=l;
		l=(l>>8);
	}
	b[2]-=(b[3]<<8);
	b[1]-=(b[2]<<8)+(b[3]<<16);
	b[0]-=(b[1]<<8)+(b[2]<<16)+(b[3]<<24);
}

void header(int x, int y) {
	int res;
	int size;
	int b[4];
	res=bmpx(x)*y;
	size=1078+res;
	pb((char) 66);
	pb((char) 77);
	hilo(size,b);
	pb((char) b[0]);
	pb((char) b[1]);
	pb((char) b[2]);
	pb((char) b[3]);
	pb((char) 0);
	pb((char) 0);
	pb((char) 0);
	pb((char) 0);
	pb((char) 54);
	pb((char) 4);
	pb((char) 0);
	pb((char) 0);
	pb((char) 40);
	pb((char) 0);
	pb((char) 0);
	pb((char) 0);
	hilo(x,b);
	pb((char) b[0]);
	pb((char) b[1]);
	pb((char) b[2]);
	pb((char) b[3]);
	hilo(y,b);
	pb((char) b[0]);
	pb((char) b[1]);
	pb((char) b[2]);
	pb((char) b[3]);
	pb((char) 1);
	pb((char) 0);
	pb((char) 8);
	pb((char) 0);
	pb((char) 0);
	pb((char) 0);
	pb((char) 0);
	pb((char) 0);
	hilo(res,b);
	pb((char) b[0]);
	pb((char) b[1]);
	pb((char) b[2]);
	pb((char) b[3]);
	hilo(3780,b);
	pb((char) b[0]);
	pb((char) b[1]);
	pb((char) b[2]);
	pb((char) b[3]);
	pb((char) b[0]);
	pb((char) b[1]);
	pb((char) b[2]);
	pb((char) b[3]);
	pb((char) 0);
	pb((char) 1);
	pb((char) 0);
	pb((char) 0);
	pb((char) 0);
	pb((char) 0);
	pb((char) 0);
	pb((char) 0);
}

int cut(int z) {
	int ret=z;
	if (z>255) ret=255;
	return ret;
}

void palette() {
	int i;
	char p;
	for (i=0; i<256; i++) {
		p=(char) cut(i<<3);
		pb(p);
		p=(char) cut(i<<2);
		pb(p);
		p=(char) cut(i<<1);
		pb(p);
		pb((char) 0);
	}
}

int main() {
	int i;
	int j;
	int x;
	int y;
	int maxi;
	int x_bmpx;
	double c1;
	double c2;
	double prz=0;
	unsigned f;
	cout << "\nresolution x : ";
	cin >> x;
	cout << "maximum number of steps : ";
	cin >> maxi;
	y=(3*x)/4;
	cout << "creating " << x << "x" << y << " mandelbrot.bmp\n";
	picture.open("mandelbrot.bmp", ios::out|ios::binary);
	header(x,y);
	cout << "writing palette\n";
	palette();
	cout << "calculating picture\n";
	cout.precision(1);
	cout.setf(ios::fixed);
	x_bmpx=bmpx(x);
	for (j=y-1; j>=0; j--) {
		for (i=0; i<x; i++) {
			c1=-2.2+(3.2*i)/x;
			c2=-1.2+(3.2*j)/x;
			f=cut(steps(maxi,c1,c2));
			pb((char) f);
		}
		for (i=x; i<x_bmpx; i++)
			pb((char) 0);
		prz+=(100.0/y);
		cout << "\r[" << prz << "%]";
	}
	picture.close();
	cout << "\nready. (Marcus)\n";
	return 0;
}

   zurück