OpenGL中點演算法和DDA演算法畫直線
阿新 • • 發佈:2019-01-23
#include "stdafx.h" #include<windows.h> #include<GL/gl.h> #include<GL/glu.h> #include<GL/glaux.h> #include<stdio.h> #include<stdlib.h> #include<math.h> #define INF 0x3f3f3f3f void init(){ glClearColor(0.0,0.0,0.0,1.0); } void Set(int x,int y,int c1,int c2,int c3){ glVertex2f(x,y); } void solve(int x0,int y0,int x1,int y1,int d1,int d2,int d,int c1,int c2,int c3){ int x=x0,y=y0; if(x0>x1){ x=x1,x1=x0; y=y1,y1=y0; } glColor3f(c1,c2,c3); glBegin(GL_POINTS); Set(x,y,c1,c2,c3); while(x<x1){ if(d<=0){ y++; d+=d1; } else { d+=d2; } Set(x,y,c1,c2,c3); x++; } glEnd(); } void MidpointLine(int x0,int y0,int x1,int y1,int c1,int c2,int c3){ double k=0.0; int d1,d2,a,b,d; if(x0==x1)k=INF; else { k=1.0*(y0-y1)/(x0-x1); } if(k>1.0){ a=y0-y1,b=x1-x0,d=b+a+b; d1=b+b,d2=2*(a+b); solve(x0,y0,x1,y1,d1,d2,d,c1,c2,c3); } else { a=y0-y1,b=x1-x0,d=a+a+b; d2=a+a,d1=2*(a+b); solve(x0,y0,x1,y1,d1,d2,d,c1,c2,c3); } } void DDA(int x0,int y0,int x1,int y1,int c1,int c2,int c3){ int x=x0,y=y0; double yi=0; if(x0>x1){ x=x1,x1=x0; y=y1,y1=y0; } double m=1.0*(y0-y1)/(x0-x1); double b=y0-m*x0; glColor3f(c1,c2,c3); glBegin(GL_POINTS); Set(x,y,c1,c2,c3); while(x<x1){ yi=m*x+b; Set(x,yi,c1,c2,c3); x++; } glEnd(); } void CALLBACK draw(){ glClear(GL_COLOR_BUFFER_BIT); int x0,y0,x1,y1; x0=y0=30; x1=130,y1=100; MidpointLine(x0,y0,x1,y1,0,1,0); DDA(x0,y0+10,x1,y1+10,0,1,0); glColor3f(1,0,0); glBegin(GL_LINES); glVertex2f(x0,y0+20); glVertex2f(x1,y1+20); glEnd(); glFlush(); } int main(int argc, char* argv[]){ auxInitDisplayMode(AUX_SINGLE|AUX_RGBA); auxInitPosition(100,100,500,500); auxInitWindow("CGOpenGL"); init(); auxMainLoop(draw); return 0; }