【コンピュータグラフィックス】六、Mandelbrotセット

2319 ワード

1.アルゴリズム
2.ソースコード
#include "stdafx.h"


#include "GL/glut.h"
#include "stdlib.h"
#include "math.h"

float xmin=-2.00,xmax=0.50;
float ymin=-1.25,ymax=1.25;

void init()
{
	glClearColor(1.0,1.0,1.0,0.0);
	
	glMatrixMode(GL_PROJECTION);
	gluOrtho2D(xmin,xmax,ymin,ymax);
}

typedef struct 
{
	float x,y;
}complexNumber;

typedef struct  
{
	float r,g,b;
}color;

void setPixel(complexNumber z)
{
	glBegin(GL_POINTS);
	glVertex2f(z.x,z.y);
	glEnd();
}

int iterationCount(complexNumber z0,int maxItera)
{
	complexNumber z=z0;
	int count=0;
	
	while((z.x*z.x+z.y*z.y<4.0)&&count<=maxItera)
	{
		z.x=z.x*z.x-z.y*z.y+z0.x;
		z.y=2.0*z.x*z.y+z0.y;
		count++;
	}
	return count;
}

void mandelbrot(int maxItera)
{
	complexNumber z;
	float xIncrement,yIncrement;
	int IteraCount;
	color ptColor;
	
	xIncrement=(xmax-xmin)/maxItera;
	yIncrement=(ymax-ymin)/maxItera;
	
	for(z.x=xmin;z.x<=xmax;z.x+=xIncrement)
		for(z.y=ymin;z.y<=ymax;z.y+=yIncrement)
		{
			IteraCount=iterationCount(z,maxItera);
			if(IteraCount>maxItera)
			{
				ptColor.r=ptColor.g=ptColor.b=0.0;
			}
			else if(IteraCount>maxItera/80)
			{
				ptColor.r=0.5;
				ptColor.g=0.4;
				ptColor.b=0.0;
			}
			else if(IteraCount>maxItera/100)
			{
				ptColor.r=1.0;
				ptColor.g=0.0;
				ptColor.b=0.0;
			}
			else if(IteraCount>maxItera/125)
			{
				ptColor.r=0.5;
				ptColor.g=0.0;
				ptColor.b=0.0;
			}
			else if(IteraCount>maxItera/200)
			{
				ptColor.r=0.8;
				ptColor.g=1.0;
				ptColor.b=0.0;
			}
			else if(IteraCount>maxItera/250)
			{
				ptColor.r=0.0;
				ptColor.g=0.1;
				ptColor.b=0.3;
			}
			else if(IteraCount>maxItera/500)
			{
				ptColor.r=0.8;
				ptColor.g=0.5;
				ptColor.b=0.0;
			}
			else
			{
				ptColor.r=0.0;
				ptColor.g=ptColor.b=1.0;
			}
			
			glColor3f(ptColor.r,ptColor.g,ptColor.b);
			setPixel(z);
		}
}

void render()
{
	glClear(GL_COLOR_BUFFER_BIT);
	
	int maxIetra=1000;
    mandelbrot(maxIetra);
	
	glFlush();
}

int main(int argc, char* argv[])
{
	glutInit(&argc,argv);
	glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
	glutInitWindowPosition(50,100);
	glutInitWindowSize(600,400);
	glutCreateWindow("Mandelbrot");
	
	init();
	glutDisplayFunc(render);
	glutMainLoop();
	
	return 0;
}

3.結果