[CSC 315] Another Integer Line Algorithm

Andrew J. Pounds pounds_aj at mercer.edu
Tue Sep 16 16:50:31 EDT 2014


Today I was asked about another integer line drawing that doesn't suffer 
from some of the "skip" effects that you may have seen. Here it is

void segment ( int X0, int Y0, int X1, int Y1 )

//   This routine was adapted from the book "Interactive Computer
//   Graphics in X" by Theo Pavlidis to work with the OpenGL API

{
    int i, x, y;
    int P, Q, E;
    int dx, dy, sx, sy, sX1, sY1, sx2, sy2;

    dy = Y1 - Y0;
    dx = X1 - X0;


// Use signs of dx and dy to determine line orientation and
// then set dx and dy to their absolute values so we can use
// them as in the simple case of a line drawn in the first
// quadrant of the x-y plane.


    sy = sgn(dy);
    sx = sgn(dx);
    dy = abs(dy);
    dx = abs(dx);

    P = min(dx,dy);
    Q = max(dx,dy);


// If the slope of the line is less than 1, then there will be
// occurrences where we will not increment the y index.  Similarly
// if the slope of the line is greater than 1, then there will be
// occurrences where we will not increment the x index.


    if ( dx > dy )
      { sX1 = sx;  sY1 = 0; }
    else
      { sX1 = 0; sY1 = sy;  }

    sx2 = sx;   sy2 = sy;

// Now set the initial value of the pixel decision variable
// and start iterating through pixel domain alternatively
// turning pixels on or off based on the updated value of
// the decision variable E.  Notice: ALL INTEGER ARITHMETIC!

    E = 2*P-Q;
    x = X0;
    y = Y0;
    for ( i=0; i<Q; i++) {
       writePixel(x,y);
       usleep(100);
       if ( E > 0 ) {
          E += 2*(P-Q);
          x += sx2;
          y += sy2;
         }
       else {
          E += 2*P;
          x += sX1;
          y += sY1;
         }
       }
    writePixel(x,y);
}

-- 
Andrew J. Pounds, Ph.D.  (pounds_aj at mercer.edu)
Professor of Chemistry and Computer Science
Mercer University,  Macon, GA 31207   (478) 301-5627
http://faculty.mercer.edu/pounds_aj



More information about the csc315 mailing list