资源描述:
《OpenGL生成指定的直线DDA算法和Bresenham算法.doc》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、1.实验目的:(1)学会使用OpenGL生成指定的直线。(2)掌握生成直线的DDA算法和Bresenham算法。2.实验内容:运用DDA和Bresenham算法画出一条直线,3.实验算法分析:DDA算法:利用两点确定斜率,及在8个象限中的坐标增量的规律生成直线;Bresenham算法:1、将直线光栅化,计算误差初值Pi=2dy-dx,求出下一点的位置;2、如果Pi>0,则y(i+1)=yi+1,否则y(i+1)=yi;3、画出点,继而迭代求出各点,最终生成直线。4.程序源代码:DDA算法:#include
2、voidinit(void){glClearColor(1.0,1.0,1.0,1.0);gluOrtho2D(0.0,50.0,0.0,50.0);}intabs(intx){inty;if(x<=0)y=-x;elsey=x;returny;}voidset_pixel(floatx,floaty){glPointSize(5);glBegin(GL_POINTS);glVertex2f(x,y);glEnd();}voiddda_line(intxa,intya,intxb,intyb){floatdelta_x,del
3、ta_y,x,y;intdx,dy,steps,k;dx=xb-xa;dy=yb-ya;if(abs(dx)>abs(dy))steps=abs(dx);elsesteps=abs(dy);delta_x=(float)dx/(float)steps;delta_y=(float)dy/(float)steps;x=xa;y=ya;set_pixel(x,y);for(k=1;k<=steps;k++){x+=delta_x;y+=delta_y;set_pixel(x,y);}}voiddisplay(void){glCle
4、ar(GL_COLOR_BUFFER_BIT);glColor3f(0.5,1.0,0.5);dda_line(25,25,5,45);glPointSize(6.0);glBegin(GL_POINTS);glVertex2f(1.0,1.0);glEnd();glFlush();}intmain(intargc,char**argv){glutInit(&argc,argv);glutInitDisplayMode(GLUT_SINGLE
5、GLUT_RGB);glutInitWindowSize(250,250);glut
6、InitWindowPosition(500,250);glutCreateWindow("OpenGL框架之直线与点");init();glutDisplayFunc(display);glutMainLoop();return0;}Bresenham算法:#includevoidinit(void){glClearColor(1.0,1.0,1.0,1.0);gluOrtho2D(0.0,50.0,0.0,50.0);}intabs(intx){inty;if(x<=0)y=-x;elsey=x;re
7、turny;}voidset_pixel(floatx,floaty){glPointSize(5);glBegin(GL_POINTS);glVertex2f(x,y);glEnd();}voidvoidline(intx1,inty1,intx2,inty2){intdx;intdy;intx;inty;intp;intconst1;intconst2;intinc;inttmp;dx=x2-x1;dy=y2-y1;if(dx*dy>=0)inc=1;elseinc=-1;if(abs(dx)>abs(dy)){if(dx
8、<0){tmp=x1;x1=x2;x2=tmp;tmp=y1;y1=y2;y2=tmp;dx=-dx;dy=-dy;}p=2*dy-dx;const1=2*dy;const2=2*(dy-dx);x=x1;y=y1;set_pixel(x,y);while(x9、=2*dx-dy;const1=2*dx;const2=2*(dx-dy);x=x1;y=y1;set_pixel(x,y);while(y