```1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 ``` ```// Simple line drawing function #include #include #define WIDTH 1000 #define HEIGHT 1000 void setPixel(int x, int y) { printf("setting (%d, %d) @ videomem[%d] = 1\n", x, y, WIDTH * y + x); } void drawLine(int xFrom, int yFrom, int xTo, int yTo) { // assert(0 <= xFrom && xFrom <= WIDTH); same for xTo, yFrom and yTo // More possible parameter is width of line int dx = xTo - xFrom; int dy = yTo - yFrom; double slope = (0 == dx) ? 0.0 : dy * 1.0 / dx; // FIXME:: INF double invslope = (0 == dy) ? 0.0 : dx * 1.0 / dy; // FIXME:: INF if( abs(dx) >= abs(dy) ) { int f = dx > 0 ? xFrom : xTo; int t = xFrom ^ xTo ^ f; int x; for(x = f; x <= t; ++x) setPixel(x , (int)( (x-xFrom) * slope + yFrom + 0.5) ); } else { // assert(dy); int f = dy > 0 ? yFrom : yTo; int t = yFrom ^ yTo ^ f; int y; for(y = f; y <= t; ++y) setPixel( (int)( (y-yFrom) * invslope + xFrom + 0.5) , y ); } } int main() { #define drawLine_(X0,Y0,X1,Y1) do {printf("\ndrawLine(%d, %d, %d, %d):\n", X0, Y0, X1, Y1); drawLine(X0, Y0, X1, Y1); } while(0) drawLine_(0, 0, 0, 0); drawLine_(0, 0, 0, 1); drawLine_(0, 0, 1, 0); drawLine_(0, 1, 0, 0); drawLine_(1, 0, 0, 0); drawLine_(0, 0, 1, 1); drawLine_(1, 1, 0, 0); drawLine_(10, 15, 17, 27); } ```
 ```1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 ``` ``` drawLine(0, 0, 0, 0): setting (0, 0) @ videomem[0] = 1 drawLine(0, 0, 0, 1): setting (0, 0) @ videomem[0] = 1 setting (0, 1) @ videomem[1000] = 1 drawLine(0, 0, 1, 0): setting (0, 0) @ videomem[0] = 1 setting (1, 0) @ videomem[1] = 1 drawLine(0, 1, 0, 0): setting (0, 0) @ videomem[0] = 1 setting (0, 1) @ videomem[1000] = 1 drawLine(1, 0, 0, 0): setting (0, 0) @ videomem[0] = 1 setting (1, 0) @ videomem[1] = 1 drawLine(0, 0, 1, 1): setting (0, 0) @ videomem[0] = 1 setting (1, 1) @ videomem[1001] = 1 drawLine(1, 1, 0, 0): setting (0, 0) @ videomem[0] = 1 setting (1, 1) @ videomem[1001] = 1 drawLine(10, 15, 17, 27): setting (10, 15) @ videomem[15010] = 1 setting (11, 16) @ videomem[16011] = 1 setting (11, 17) @ videomem[17011] = 1 setting (12, 18) @ videomem[18012] = 1 setting (12, 19) @ videomem[19012] = 1 setting (13, 20) @ videomem[20013] = 1 setting (14, 21) @ videomem[21014] = 1 setting (14, 22) @ videomem[22014] = 1 setting (15, 23) @ videomem[23015] = 1 setting (15, 24) @ videomem[24015] = 1 setting (16, 25) @ videomem[25016] = 1 setting (16, 26) @ videomem[26016] = 1 setting (17, 27) @ videomem[27017] = 1 ```