【计算机图形学】五、Julia集

1. 算法

【计算机图形学】五、Julia集_第1张图片


2. 源代码

#include "stdafx.h"


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

void init()
{
	glClearColor(1.0,1.0,1.0,0.0);
	
	glMatrixMode(GL_PROJECTION);
	gluOrtho2D(-0.2,1.2,-0.5,0.5);
}

typedef struct 
{
	float x,y;
}complexNumber;

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

void JuliaPt(complexNumber lambda,complexNumber* z)
{
	complexNumber discr;
	float magnitudeSq,discrMag;
    magnitudeSq=lambda.x*lambda.x+lambda.y*lambda.y;
	discr.x=1.0-4.0*(z->x*lambda.x+z->y*lambda.y)/magnitudeSq;
	discr.y=4.0*(z->x*lambda.y-z->y*lambda.x)/magnitudeSq;
	discrMag=sqrt(discr.x*discr.x+discr.y*discr.y);

	if(discrMag+discr.x<0)
		z->x=0;
	else
		z->x=sqrt((discrMag+discr.x)/2.0);

	if(discrMag-discr.x<0)
		z->y=0;
	else
		z->y=0.5*sqrt((discrMag-discr.x)/2.0);

	if(rand()<RAND_MAX/2)
	{
		z->x=-z->x;
		z->y=-z->y;
	}

	if(discr.y<0)
		z->x=-z->x;

	z->x=0.5*(1-z->x);
}

void Julia(complexNumber lambda,complexNumber z,int ptNum)
{
	int k;
	for(k=0;k<10;k++)
		JuliaPt(lambda,&z);

	for(k=0;k<ptNum;k++)
	{
         JuliaPt(lambda,&z);
		 setPixel(z);
	}
}

void render()
{
	glClear(GL_COLOR_BUFFER_BIT);
	glColor3f(1.0,0.0,0.0);
	
	int ptNum=10000;
	complexNumber lambda={3.0,0.0},z={0.0,0.0};
	
    Julia(lambda,z,ptNum);
	
	glFlush();
}

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

3. 结果

【计算机图形学】五、Julia集_第2张图片


你可能感兴趣的:(【计算机图形学】五、Julia集)