《OpenGL生成指定的直线DDA算法和Bresenham算法.docx》由会员分享,可在线阅读,更多相关《OpenGL生成指定的直线DDA算法和Bresenham算法.docx(6页珍藏版)》请在三一办公上搜索。
1、OpenGL生成指定的直线DDA算法和Bresenham算法 1 1. 实验目的: 学会使用OpenGL生成指定的直线。 掌握生成直线的DDA算法和Bresenham算法。 2. 实验内容: 运用DDA和Bresenham算法画出一条直线, 3. 实验算法分析: DDA算法:利用两点确定斜率,及在8个象限中的坐标增量的规律生成直线; Bresenham算法:1、将直线光栅化,计算误差初值Pi=2dy-dx,求出下一点的位置; 2、如果Pi0,则y=yi+1,否则y=yi; 3、画出点,继而迭代求出各点,最终生成直线。 4. 程序源代码: DDA算法: #include void init(vo
2、id) 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(xabs(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(
3、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); glutInitWindowPosi
4、tion(500,250); 3 glutCreateWindow(OpenGL框架之直线与点); init; glutDisplayFunc(display); glutMainLoop; return 0; Bresenham算法: #include 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) inc=1; else inc=-1; if (abs(dx)abs(dy) if(dx0) tmp=x1; x1=x2; x2
5、=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(xx2) x+; if(p0) p+=const1; else y+=inc; p+=const2; 5 set_pixel(x,y); else if(dy0) 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*(d
6、x-dy); x=x1; y=y1; set_pixel(x,y); while(yy2) y+; if(p0) 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