/* CSCI 480 HW 1 Chin-Kai Chang 7557011081 chinkaic@usc.edu Usage: drawline x1 y1 x2 y2 Or for extra point test drawline x1 y1 x2 y2 r1 g1 b1 r2 g2 b2 All number should be in 0~255, There is no number checked */ #include #include #define OUTFILE "out.ppm" const int XRES=256; const int YRES=256; using namespace std; typedef struct { int r; int g; int b; }PIXEL; class Drawline{ public: PIXEL graph[XRES][YRES]; void drawline(int x1,int y1,int x2,int y2); void drawline(int x1,int y1,int x2,int y2,PIXEL start,PIXEL end); void setpixel(int x,int y); void setpixel(int x,int y,float r,float g,float b) ; void output(void); void initGraph(void); } ; //Draw with default Color void Drawline::drawline(int x1,int y1,int x2,int y2) { int dx, dy, d, incE, incNE, x, y, slope; //Swap point if(x1 > x2) { drawline(x2,y2,x1,y1); return; } dx = x2 - x1; dy = y2 - y1; if(dy < 0) { slope = -1; dy = -dy; }else{ slope = 1; } //Draw vertical line if(dx==0) { for(int i=0;i<=dy;i++) { setpixel(x1,y1); y1+=slope; } }else{ d = 2*dy - dx; incE = 2*dy; incNE = 2*(dy - dx); y = y1; for (x=x1; x<=x2; x++) { setpixel(x, y); if (d>0) { d += incNE; y +=slope; } else { d += incE; } } } } //Draw with Color Change for Extra point void Drawline::drawline(int x1,int y1,int x2,int y2,PIXEL start,PIXEL end) { int dx, dy, d, incE, incNE, x, y, slope; float dr,dg,db,sr,sg,sb,r,g,b; if(x1 > x2) { drawline(x2,y2,x1,y1,end,start); return; } dx = x2 - x1; dy = y2 - y1; r = start.r/255; g = start.g/255; b = start.b/255; dr = start.r - end.r; dg = start.g - end.g; db = start.b - end.b; if(dx != 0){ sr = dr/((float)dx*255); sg = dg/((float)dx*255); sb = db/((float)dx*255); } else{ sr = dr/((float)dy*255); sg = dg/((float)dy*255); sb = db/((float)dy*255); } if(dy < 0) { slope = -1; dy = -dy; }else{ slope = 1; } if(dx==0) { for(int i=0;i<=dy;i++) { setpixel(x1,y1,r,g,b); r -=sr; g -=sg; b -=sb; y1+=slope; } }else{ d = 2*dy - dx; incE = 2*dy; incNE = 2*(dy - dx); y = y1; for (x=x1; x<=x2; x++) { setpixel(x,y,r,g,b); r -=sr; g -=sg; b -=sb; if (d>0) { d += incNE; y +=slope; } else { d += incE; } } } } void Drawline::setpixel(int x,int y) { graph[y][x].r = 0 ; graph[y][x].g = 0 ; graph[y][x].b = 0 ; } void Drawline::setpixel(int x,int y,float r,float g,float b) { graph[y][x].r = (int)(r*255) ; graph[y][x].g = (int)(g*255) ; graph[y][x].b = (int)(b*255) ; } void Drawline::output(void) { FILE *fp; fp = fopen(OUTFILE, "w"); fprintf(fp,"P3\n") ; fprintf(fp,"%d %d\n",XRES,YRES) ; fprintf(fp,"255\n"); for(int i=0;i