首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

分形Koch曲线兑现及扩展

2013-03-22 
分形Koch曲线实现及扩展:注意事项:配置好OpenGL环境。//Koch.h#include GL/glut.h#include math.h#defi

分形Koch曲线实现及扩展:

注意事项:配置好OpenGL环境。
//Koch.h#include <GL/glut.h>#include <math.h>#define PI 3.1415926void Koch(float ax,float ay,float bx,float by, float c);void DrawTrigon(float ax,float ay, float bx,float by,float cx,float cy,float c);
//Koch.cpp#include"Koch.h"//ax,ay,bx,by是直线端点坐标,c是最小分形线段长度void Koch(float ax,float ay,float bx,float by, float c){    if( (bx-ax)*(bx-ax) +(by-ay)*(by-ay) < c*c ){        glBegin(GL_LINES);        glVertex2f(ax,ay);        glVertex2f(bx,by);        glEnd();            }else {        float dx,dy,ex,ey,fx,fy;        dx = ax + (bx - ax)/3;         dy = ay + (by - ay)/3;        fx = ax + (bx - ax)*2/3;        fy = ay + (by - ay)*2/3;        float l = sqrt( (fx - dx)*(fx - dx)+ (fy-dy)*(fy-dy) );        //get the angle         double angle = atan( (fy - dy)/(fx - dx) );        if( ( (angle>0&&(fx - dx) <0))||( (angle<0&&(fx - dx) <0)))angle += PI;        ex = dx + cos(angle + PI/3)*l;        ey = dy + sin(angle + PI/3)*l;        Koch(ax,ay,dx,dy,c);         Koch(dx,dy,ex,ey,c);        Koch(ex,ey,fx,fy,c);                   Koch(fx,fy,bx,by,c);    }}//ax,ay,bx,by,cx,cy是三角形顶点坐标,c是最小分形线段长度void DrawTrigon(float ax,float ay, float bx,float by,float cx,float cy,float c){    Koch(ax,ay,bx,by,c);    Koch(bx,by,cx,cy,c);    Koch(cx,cy,ax,ay,c);}

//main.cpp#include "Koch.h"void display(){    glClear(GL_COLOR_BUFFER_BIT);    glColor3f(1.0,1.0,1.0);  /* Koch(0.2,0.5 ,0.8,0.8,0.002);     Koch(0.8,0.8, 0.5,0.2,0.002);     Koch(0.5,0.2, 0.2,0.5,0.002);*/    DrawTrigon(0.2,0.8,0.8,0.8,0.5,0.2,0.005);    glFlush();}void init(){    glClearColor(0.0,0.0,0.0,0.0);    glMatrixMode(GL_PROJECTION);    glLoadIdentity();    glOrtho(0.0,1.0,0.0,1.0,-1.0,1.0);}int main(int argc, char * argv[]){ glutInit(&argc,argv); glutInitWindowSize(800,800); glutInitWindowPosition(100,100); glutCreateWindow("Koch"); init(); glutDisplayFunc(display); glutMainLoop(); return 0;}


热点排行