70 likes | 153 Views
(7,9). Example 2: Point1 V:(7,9 ) C:( 0,255,0) Point2 V:(12,0) C:(0,255,0). (12,0). Example:. (0,9). (0,0). (18,0). What are the problems with this method? Slope>1. Revised Slope Intercept. DrawLine (Point point1, Point point2){ m=(point2.y-point1.y) / (point2.x-point2.x);
E N D
(7,9) Example 2: Point1 V:(7,9 ) C:( 0,255,0) Point2 V:(12,0) C:(0,255,0) (12,0) Example: (0,9) (0,0) (18,0) What are the problems with this method? Slope>1
Revised Slope Intercept DrawLine (Point point1, Point point2){ m=(point2.y-point1.y) / (point2.x-point2.x); b=point1.y + (-point1.x) * m; if (m>1){ for i = point1.x to < point2.x { SetPixel(i , round(i*m+b)); } } else{ for i = point1.y to point2.y { SetPixel(round(i-b/m), i); } } Which one should we use if m=1? What is the cost per pixel?
Optimization (DDA Algorithm) • Since we increment y by the same amount, we can also inline rounding: • New cost: one floating point addition, one integer addition, one cast. DrawLine (Point point1, Point point2){ m=(point2.y-point1.y) / (point2.x-point2.x); j=point1.y + (-point1.x) * m + 0.5; for i=point1.x to point2.x SetPixel(i , (int)j+=m)); }
Optimizations • In general processing unit: • Addition and Subtraction are faster than Multiplication which is faster than Division • Integer calculations are faster than Floating and double calculations • Logical operation is lighter the math operations • Bitwise operation is the lightest
Bresenham Line Drawing Algorithm Let us consider a line equation y = mx + b could be written as F (x, y) =ax + by + c NE M F(x,y) is zero on the line, positive above the, and negative below the line E if ( d > 0) then we choose NE If ( d < 0 ) then we choose E If ( d == 0) we choose any of them
Bresenham Line Drawing Algorithm What happens to next grid point after xp+2, that depends on whether we select E or NE. If E was selected then NE M E If NE was selected then Since the first point (x0,y0) We can directly calculate d to choose NE or E
public void DrawLine(Point point1, Point point2) { int dy = point2.y - point1.y; int dx = point2.x - point1.x; dy <<= 1; // dy is now 2*dy dx <<= 1; // dx is now 2*dx int fraction = dy - (dx >> 1); // same as 2*dy - dx j=point1.y; for (i=point1.x; i<point2.x; i++) { if (fraction >= 0) { j++; fraction -= dx; // same as fraction -= 2*dx } fraction += dy; // same as fraction -= 2*dy SetPixel(i, j); }