OpenGL生成指定的直线DDA算法和Bresenham算法.docx
OpenGL生成指定的直线DDA算法和Bresenham算法 1 1. 实验目的: 学会使用OpenGL生成指定的直线。 掌握生成直线的DDA算法和Bresenham算法。 2. 实验内容: 运用DDA和Bresenham算法画出一条直线, 3. 实验算法分析: DDA算法:利用两点确定斜率,及在8个象限中的坐标增量的规律生成直线; Bresenham算法:1、将直线光栅化,计算误差初值Pi=2dy-dx,求出下一点的位置; 2、如果Pi>0,则y=yi+1,否则y=yi; 3、画出点,继而迭代求出各点,最终生成直线。 4. 程序源代码: DDA算法: #include <GL/glut.h> void init(void) glClearColor(1.0,1.0,1.0,1.0); gluOrtho2D(0.0,50.0,0.0,50.0); int abs(int x) int y; if(x<=0) y=-x; else y=x; return y; void set_pixel(float x,float y) glPointSize(5); glBegin(GL_POINTS); glVertex2f(x,y); glEnd; void dda_line(int xa,int ya,int xb,int yb) 2 float delta_x,delta_y,x,y; int dx,dy,steps,k; dx=xb-xa; dy=yb-ya; if(abs(dx)>abs(dy) steps=abs(dx); else steps=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); void display(void) glClear(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; int main(int argc, char* argv) glutInit(&argc,argv); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutInitWindowSize(250,250); glutInitWindowPosition(500,250); 3 glutCreateWindow("OpenGL框架之直线与点"); init; glutDisplayFunc(display); glutMainLoop; return 0; Bresenham算法: #include <GL/glut.h> void init(void) glClearColor(1.0,1.0,1.0,1.0); gluOrtho2D(0.0,50.0,0.0,50.0); int abs(int x) int y; if(x<=0) y=-x; else y=x; return y; void set_pixel(float x,float y) glPointSize(5); glBegin(GL_POINTS); glVertex2f(x,y); glEnd; 4 void voidline(int x1,int y1,int x2,int y2) int dx; int dy; int x; int y; int p; int const1; int const2; int inc; int tmp; dx=x2-x1; dy=y2-y1; if(dx*dy>=0) inc=1; else inc=-1; if (abs(dx)>abs(dy) if(dx<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(x<x2) x+; if(p<0) p+=const1; else y+=inc; p+=const2; 5 set_pixel(x,y); else if(dy<0) tmp=x1; x1=x2; x2=tmp; tmp=y1; y1=y2; y2=tmp; dx=-dx; dy=-dy; p=2*dx-dy; const1=2*dx; const2=2*(dx-dy); x=x1; y=y1; set_pixel(x,y); while(y<y2) y+; if(p<0) p+=const1; else x+=inc; p+=const2; set_pixel(x,y); void display(void) glClear(GL_COLOR_BUFFER_BIT); glColor3f(0.5,1.0,0.5); voidline(25,5,45,45); glPointSize(6.0); 6 glFlush; int main(int argc, char* argv) glutInit(&argc,argv); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutInitWindowSize(250,250); glutInitWindowPosition(500,250); glutCreateWindow("OpenGL框架之直线与点"); init; glutDisplayFunc(display); glutMainLoop; return 0; 5. 运行结果: DDA运行效果图: 7 Bresenham算法效果图: 8