\documentclass{article}
\usepackage{amssymb}
\usepackage{amsmath}
%\usepackage{slide-article-tom}
\usepackage[landscape]{slide-article-tom}

\usepackage{amsthm}
\newtheorem{thm}{Theorem}

\ifx\pdfoutput\undefined
     \usepackage[dvips]{graphicx}
\else
     \usepackage[pdftex]{graphicx}
     \pdfcompresslevel 9
\fi

\usepackage[all]{xy}
\setlength{\unitlength}{1cm}


\usepackage{fixltx2e}

\usepackage{wrapfig}


\usepackage{tikz}
\usetikzlibrary{backgrounds,calc,arrows,shapes.arrows,shapes.gates.logic.US,shapes.gates.logic.IEC}
\usepackage{calc}
\usepackage{circuitikz}

\tikzset{
%MyCube/.style={scale=1.0,x={(-.4cm,-0.3cm)},y={(0.6cm,-0.3cm)},z={(0.2cm,0.7cm)}},	
MyCube/.style={scale=1.0,x={(-0.55cm,-0.3cm)},y={(1cm,0cm)},z={(0cm,1cm)}},
	MyFaceA/.style={green!70!,draw=black},
	MyFaceB/.style={blue!50!,draw=black},
	MyFaceC/.style={blue!30!green!30!,draw=black}
	}

\newcommand{\cube}[4]{%
	% parameters #1,#2,#3 = coordinates of the center, parameter #4 = length of edge
 	\pgfmathparse{0.5*#4}%
	\let\sd\pgfmathresult{}%
 	\coordinate (A) at ({#1+\sd},{#2+\sd},{#3+\sd});
 	\coordinate (E) at ({#1+\sd},{#2+\sd},{#3-\sd});
	\coordinate (B) at  ({#1+\sd},{#2-\sd},{#3+\sd});
	\coordinate (F) at  ({#1+\sd},{#2-\sd},{#3-\sd});
	\coordinate (C) at  ({#1-0.7*\sd},{#2-0.7*\sd},{#3+\sd});
	\coordinate (G) at  ({#1-\sd},{#2-\sd},{#3-\sd});
 	\coordinate (D) at ({#1-0.7*\sd},{#2+\sd},{#3+\sd});
 	\coordinate (H) at ({#1-0.7*\sd},{#2+\sd},{#3-0.7*\sd});
	\fill[MyFaceA] (A)--(E)--(H)--(D)--cycle;
	\fill[MyFaceB] (A)--(B)--(C)--(D)--cycle;
	\fill[MyFaceC] (A)--(B)--(F)--(E)--cycle;
	\draw (A)--(E)--(H)--(D)--cycle;
	\draw (D)--(C)--(B)--(A);
	\draw (B)--(F)--(E);
}

\usepackage[titles]{tocloft}
\setlength{\cftbeforesecskip}{-2ex}
\setlength{\cftbeforesubsecskip}{-2ex}

\usepackage{hyperref}

\hypersetup{colorlinks,
            linkcolor=blue,
            citecolor=blue,
            %pdfpagemode=FullScreen
            pdfpagemode=UseNone
            }


%\newcommand\@linkcolor{red}
%\newcommand\@linkcolor{blue}
%\newcommand\@anchorcolor{black}
%\newcommand\@citecolor{red}
%\newcommand\@filecolor{cyan}
%\newcommand\@urlcolor{magenta}
%\newcommand\@menucolor{red}
%\newcommand\@pagecolor{red}


\newcommand\pagedone{\newpage}

\newcommand\tthdump[1]{#1}


\newcommand\sectionhead[1]{\begin{center}\section*{#1 \hyperlink{Contents}{\hfil$\leftarrow$}}
             \end{center}
     \addcontentsline{toc}{section}{#1}
     \vspace{-\baselineskip}
     }
     
\newcommand\subsectionhead[1]{\begin{center}\subsection*{#1 \hyperlink{Contents}{\hfil$\leftarrow$}}
             \end{center}
     \addcontentsline{toc}{subsection}{#1}
     \vspace{-\baselineskip}
     }
     
\newcommand\cyrsubsectionhead[1]{\begin{center}\subsection*{#1 \hyperlink{Contents}{\hfil$\leftarrow$}}
             \end{center}
     \addcontentsline{toc}{subsection}{#1}
     \vspace{-\baselineskip}
     }


\newcommand\exercises[1]{\begin{center}\subsection*{#1 -~exercises
            \hyperlink{Contents}{\hfil$\leftarrow$}}\end{center}
    \addcontentsline{toc}{subsection}{#1 (exercises)}
     \vspace{-\baselineskip}
     }
     

\newcommand\quotesection[1]{\begin{center}{\LARGE\hypertarget{#1}
     {#1}\hyperlink{The quotes}{\hfil$\twoheadleftarrow$}}\end{center}}

\newcommand\httimes{\times}

\newcommand\mybigtriangledown{\bigtriangledown}

\newcommand\htvec[1]{\vec{#1}}

\newcommand\myspan{\mathrm{span}}
\newcommand\mymatrix{\mathrm{matrix}}

\newcommand\myreal{\mathbb{R}}

\newcommand\mycomplex{\mathbb{C}}
\newcommand\myfield{\mathbb{F}}
\newcommand\myquaternions{\mathbb{H}}
\newcommand\myrationals{\mathbb{Q}}
\newcommand\myintegers{\mathbb{Z}}

%\newcommand\dim\mathrm{dim}
\newcommand\im{\mathrm{im}}
\newcommand\deriv{\mathrm{D}}
\newcommand\trace{\mathrm{trace}}
\newcommand\detm{\mathrm{det}_m}
\newcommand\detv{\mathrm{det}_v}
\newcommand\perm{\mathrm{perm}}
\newcommand\sign{\mathrm{sign}}

% kets and bras etc.
\newcommand\ket[1]{|{#1}\rangle}
\newcommand\bra[1]{\langle{#1}|}
\newcommand\braket[2]{\langle{#1}|{#2}\rangle}

%boolean operators
\newcommand\myand{$\wedge$ }
\newcommand\myor{$\vee$ }

% defines a 2 element column vector.
\newcommand\col[2]{\left(\begin{array}{c}#1\\#2\end{array}\right)}
\newcommand\tcol[2]{(#1, #2)^T}

\begin{document}
\raggedright

\pagestyle{myfooters}
%\pagestyle{plain}

\thispagestyle{empty}

%Slide 1
\title{{\LARGE\bf The Bresenham Line Algorithm}\newline
}
\author{
\begin{wrapfigure}{r}{0.35\textwidth}
  \vspace{-2cm}
  \begin{center}
    {\fontsize{5}{5}\selectfont  
       http://csustan.csustan.edu/\~\ tom
    }
   {\hyperref{http://csustan.csustan.edu/\~tom}{}{}
     {    \includegraphics[width=0.2\textwidth]{tom-carter-QR-pic.png}
     }
   }
  \end{center}
  \end{wrapfigure}
      Tom Carter \newline
      \newline
     Computer Science \newline
     CSU Stanislaus\newline
\newline
{\hyperref{mailto:tom@csustan.csustan.edu}{}{}
     {tom@csustan.csustan.edu}}
\vfill
{\hyperref{http://csustan.csustan.edu/\~tom/Lecture-Notes/Graphics/Bresenham-Line/Bresenham-Line.pdf}{}{}
     {http://csustan.csustan.edu/\~\ tom/Lecture-Notes/Graphics/Bresenham-Line/Bresenham-Line.pdf}}
}

%\date{Fall, 2011}
\date{\today}


\maketitle

\renewcommand\contentsname{Our general topics:\hypertarget{Contents}{}}
%% \newcommand\listfigurename{List of Figures}
%% \newcommand\listtablename{List of Tables}

\tableofcontents

\pagedone




\sectionhead{Drawing Lines in a Raster}

     One of the most fundamental actions in computer graphics is drawing a (straight) line
     on a raster device.  An optimized algorithm for drawing such a line is the {\em Bresenham
     Line Drawing Algorithm}.  We want the algorithm to be as fast as possible, because in
     practice such an algorithm will be used a lot.  We'll walk our way through a derivation of the algorithm.
     
     The algorithm was originally published as:  Jack E. Bresenham, {\em Algorithm for Computer
     Control of a Digital Plotter}, IBM Systems Journal, 4(1):25-30, 1965.
     
     The {\em raster} is a two-dimensional array of pixels.  We will assume we want to draw a line
     from one pixel to another in our raster ($(X_0, Y_0) \to (X_1, Y_1)$) by turning on optimal
     pixels along the line connecting the end points.

\pagedone

     Here's an example of what this will look like:
     
     \vspace{1.5cm}
      \centerline{\includegraphics[width = 6in]{Line-1}}
      \centerline{\bf \large A line in a raster}
     
\pagedone
     We'll make some simplifying assumptions in the derivation (and pick up some of
     them later \ldots).
     \begin{enumerate}
          \item Our pixel coordinates go from left to right, and bottom to top, the way they
               do in the first quadrant in mathematics.
          \item $X_0 < X_1$, and $Y_0 \le Y_1$.
          \item The slope of the line will be between 0 and 1 (i.e., $0 \le m \le 1$),
               so we will be drawing the line from lower left to upper right; and, for
               any $X$ value between $X_0$ and $X_1$, there will be exactly one
               pixel on.  (Look at the example above \ldots)
          \item Our pixels are either off or on (i.e., no gray-scale \ldots).
     \end{enumerate}
\pagedone
   
\sectionhead{The Bresenham Line Algorithm (simple form)}

     With the assumptions we have made, the most straightforward algorithm is very simple:
     \begin{verbatim}
          For X = X_0 to X_1 step 1
               determine Y value
               SetPixel(X, Y)
          Next X
     \end{verbatim}
     Thus, if we can figure out a fast way to determine the Y value to turn on, we will be done.
     
     We'll do this in an iterative fashion.  As we step along in the X direction, we can see that
     either Y stays the same, or Y increases by 1.  All we really need to do is figure out when
     to increment Y.
     
     Algorithm, version 2:
     \begin{verbatim}
          X = X_0
          Y = Y_0
          SetPixel(X, Y)
          While (X <= _X1)
               X = X + 1
               If we should increment Y
                    Y = Y + 1
               SetPixel(X, Y)
          EndWhile
     \end{verbatim}
     
     Assuming our line is given by $y = mx + b$, what we are doing is setting $Y = round(mx + b)$.
     We will do this iteratively.  Each (unit) step of $x$ will increase $y$ by $m$.
     If we let $fraction$ be the amount $y$ has increased since the last time we incremented, then
     we want to increment $Y$ when $fraction \ge \frac{1}{2}$.
\pagedone
     So our algorithm looks like:
     \begin{verbatim}
          X = X_0
          Y = Y_0
          fraction = start_value
          fraction_increment = (Y_1 - Y_0) / (X_1 - X_0)
          SetPixel(X, Y)
          While (X <= X_1)
               X = X + 1
               fraction = fraction + fraction_increment
               If fraction >= 1/2
                    Y = Y + 1
                    fraction = fraction - 1
               SetPixel(X, Y)
          EndWhile
     \end{verbatim}
\pagedone
     There are some aspects of this that are slower than we want.  In particular, we really don't want to be doing
     any floating point arithmetic, or floating point comparisons.
     
     First, we have
          $$m = \frac{Y_1 - Y_0}{X_1 - X_0}$$
     To get rid of the fraction (so we can work with integers), we'll multiply by $X_1 - X_0$.
     
     To get rid of the comparison to $\frac{1}{2}$, we'll multiply by 2.
     
     Putting these two together, we will use
          \begin{align*}
               fraction\_ increment & = m * 2 * (X_1 - X_0) \\
                           & = \frac{Y_1 - Y_0}{X_1 - X_0} * 2 * (X_1 - X_0) \\
                           & = 2 * (Y_1 - Y_0)
          \end{align*}
\pagedone
     Also, we generally would prefer to compare to 0 rather than compare to 1.  What this all means is that our
     algorithm will now be:
     \begin{verbatim}
          X = X0
          Y = Y0
          fraction = start_value
          fraction_increment = 2 * (Y_1 - Y_0)
          SetPixel(X, Y)
          While (X <= X1)
               X = X + 1
               fraction = fraction + fraction_increment
               If fraction >= 0
                    Y = Y + 1
                    fraction = fraction - 2 * (X_1 - X_0)
               SetPixel(X, Y)
          EndWhile
     \end{verbatim}   
\pagedone
     The one other thing we need to do is figure out {\em start\_value}.
     
     What we really have is that {\em fraction} is a {\em decision variable}.  We have
     started with our decision variable (after k steps in the $X$ direction) as
          \begin{align*}
               DV(k) & = ((Y_0 + (k + 1) * m) \text{ mod } 1) - \frac{1}{2} \\
                         & = (((k + 1) * m) \text{ mod } 1) - \frac{1}{2} \\
          \end{align*}
     The + 1 reflects the fact that we want to start on the right hand side of the first
     pixel (in the $X$ direction), and then move forward at each step to the right side
     of the next pixel.  The $- \frac{1}{2}$ normalizes us so that our decision
     variable will cause us to increment $Y$ when we have moved up $\frac{1}{2}$
     a pixel (or more).  That is, we want our decision variable to be between $- \frac{1}{2}$
     and $\frac{1}{2}$.
     
     When we do the conversion so that we are working in integers, and compare with 0,
     our decision variable becomes:
          \begin{align*}
               fraction(k)  & = (((k + 1) * m * 2 * (X_1 - X_0)) \\
                                     &\ \ \ \ \ \ \text{ mod } 2 * (X_1 - X_0)) - \frac{1}{2} * 2 * (X_1 - X_0) \\
                                 & = (((k + 1) * \frac{Y_1 - Y_0}{X_1 - X_0} * 2 * (X_1 - X_0)) \\
                                     &\ \ \ \ \ \ \text{ mod } 2 * (X_1 - X_0)) - \frac{1}{2} * 2 * (X_1 - X_0) \\
                                 & = (((k + 1) * (Y_1 - Y_0) * 2 ) \\
                                     &\ \ \ \ \ \ \text{ mod } (2 * (X_1 - X_0))) - (X_1 - X_0) \\
                                 & = ((k * 2 * (Y_1 - Y_0) + 2 * (Y_1 - Y_0)) \\
                                     &\ \ \ \ \ \ \text{ mod } (2 * (X_1 - X_0)) - (X_1 - X_0) \\
          \end{align*}
     Thus, when $k = 0$, we have
          \begin{align*}
               fraction(0) & = ((0 * 2 * (Y_1 - Y_0) + 2 * (Y_1 - Y_0)) \\
                                     &\ \ \ \ \ \ \text{ mod } (2 * (X_1 - X_0)) - (X_1 - X_0) \\
                                 & = ((2 * (Y_1 - Y_0)) \\
                                     &\ \ \ \ \ \ \text{ mod } (2 * (X_1 - X_0)) - (X_1 - X_0) \\
                                 & = 2 * (Y_1 - Y_0) - (X_1 - X_0) \\
          \end{align*}
\pagedone
\sectionhead{The Bresenham Line Algorithm (all together)}
     Now we can finalize everything.  If we want to deal with positive or negative slope lines, we just adjust the step size
     to be +1 or -1.  If we want to deal with slopes greater than 1 (or less the -1), we just interchange X and Y, and do our step
     increment (or decrement) using Y instead of X, etc.
\pagedone
     So, our final algorithm looks like:
     \begin{verbatim}
void lineBresenham(int x0, int y0, int x1, int y1)
{
    int dx, dy;
    int stepx, stepy;
	
    dx = x1 - x0;
    dy = y1 - y0;
	
    if (dy < 0) { dy = -dy;  stepy = -1; } else { stepy = 1; }
    if (dx < 0) { dx = -dx;  stepx = -1; } else { stepx = 1; }
    dy <<= 1;                            /* dy is now 2*dy */
    dx <<= 1;                            /* dx is now 2*dx */
    if ((0 <= x0) && (x0 < RDim) && (0 <= y0) && (y0 < RDim))
		theRaster[x0][y0] = 1;
    if (dx > dy) {
        int fraction = dy - (dx >> 1); 
        while (x0 != x1) {
            x0 += stepx;
            if (fraction >= 0) {
                y0 += stepy;
                fraction -= dx; 
            }
            fraction += dy;   
            if ((0 <= x0) && (x0 < RDim) && (0 <= y0) && (y0 < RDim))
                theRaster[x0][y0] = 1;
        }
    } else {
        int fraction = dx - (dy >> 1);
        while (y0 != y1) {
            if (fraction >= 0) {
                x0 += stepx;
                fraction -= dy;
            }
            y0 += stepy;
            fraction += dx;
            if ((0 <= x0) && (x0 < RDim) && (0 <= y0) && (y0 < RDim))
                theRaster[x0][y0] = 1;
    }
}
     \end{verbatim}
\pagedone
\sectionhead{Some Additional Notes}
     There are other approaches to deriving the Bresenham Line Algorithm.  Various parts
     are the same, but some details are presented differently.
     
     With the assumptions above, we want to choose whether to keep the Y value the
     same or to move Y up a step when we take the next X step.  We can make
     that decision based on the difference (``distance'') of those two pixels from
     the ``true value'' along the line.
     
     We can let $y$ be the ``true value'' along the line, and $Y(k)$ be the Y value we are at
     (after step $k$ has been taken).
\pagedone
     We can thus look at what would happen if we keep $Y(k + 1) = Y(k)$
          $$D_1(k) = y - Y(k)$$
     versus setting $Y(k + 1) = Y(k) + 1$:
          $$D_2 (k)= (Y(k) + 1) - y.$$
     We can use these to make our decision:
          \begin{itemize}
               \item If $D_1(k) \le D_2(k)$, we move to $(X(k) + 1, Y(k))$ (i.e., move right)
               
               \item if $D_1(k) > D_2(k)$, we move to $(X(k) + 1, Y(k) + 1)$ (i.e., move right and up)
          \end{itemize}
\pagedone
     Said differently (comparing with 0 \ldots):
          \begin{itemize}
               \item If $D_1(k) - D_2(k) \le 0$, we move to $(X(k) + 1, Y(k))$ (i.e., move right)
               
               \item if $D_1(k) - D_2(k) > 0$, we move to $(X(k) + 1, Y(k) + 1)$ (i.e., move right and up)
          \end{itemize}
     We can calculate (using $y = m * x + b)$:
          \begin{align*}
               D_1(k) - D_2(k) & = (y - Y(k)) - ((Y(k) + 1) - y.) \\
                                 & = y - Y(k) - (Y(k)+1) + y \\
                                 & = 2 * y - 2 * Y(k) - 1 \\
                                 & = 2 * (m * (X(k) + 1) + b) - 2 * Y(k) - 1 \\
                                 & = 2 * m * (X(k) + 1) - 2 * Y(k) + 2 * b - 1
          \end{align*}
          
     Substituting in $b = Y_0 - m X_0$ and $m = \frac{Y_1 - Y_0}{X_1 - X_0} = \frac{\Delta Y}{\Delta X}$, we have
          \begin{align*}
               D_1(k) - D_2(k) & = 2 m (X(k) + 1) - 2 Y(k) + 2 b - 1 \\
                                         & = 2 m (X(k) + 1) - 2 Y(k) + 2 (Y_0 - m X_0) - 1 \\
                                         & = 2 \frac{\Delta Y}{\Delta X} (X(k) + 1) - 2 Y(k) + 2 (Y_0 - \frac{\Delta Y}{\Delta X} X_0) - 1 \\
          \end{align*}
     We don't want to do division (floating point operation), so we let $D(k) = \Delta X (D_1(k) - D_2(k))$, and
     we have:
          \begin{align*}
               D(k) & = \Delta X (D_1(k) - D_2(k)) \\
                       & = \Delta X ( 2 \frac{\Delta Y}{\Delta X} (X(k) + 1) - 2 Y(k) + 2 (Y_0 - \frac{\Delta Y}{\Delta X} X_0) - 1) \\
                       & = 2 \Delta Y (X(k) + 1) - 2 \Delta X * Y(k) + 2 \Delta X * Y_0 - 2 \Delta Y * X_0 -  \Delta X \\
                       & = 2 \Delta Y * X(k) - 2 \Delta X * Y(k)  \\
                       & \ \ \ \ \ \ \ \ + 2 \Delta Y + 2 \Delta X * Y_0 - 2 \Delta Y * X_0 -  \Delta X \\
          \end{align*}
     We can write this as:
            $$D(k) = 2 \Delta Y * X(k) - 2 \Delta X * Y(k) + c $$
     where $c =  2 \Delta Y + 2 \Delta X * Y_0 - 2 \Delta Y * X_0 -  \Delta X$ is a constant, depending only on the input values
     of $(X_0, Y_0)$ and $(X_1, Y_1)$.
     
     Note that since we are assuming $X_0 < X_1$, we have $\Delta X > 0$, and so the decision criterion is still the same.
     
     Now all we need to do is calculate $D(k)$, compare with $0$, and we know which pixel to select next.  We can actually do
     this iteratively (note: $X(k + 1) - X(k) = 1$):
          \begin{align*}
               D(k + 1) - D(k) & = (2 \Delta Y * X(k + 1) - 2 \Delta X * Y(k + 1) + c)  \\
                                       & \ \ \ \ \ \ \ \ - (2 \Delta Y * X(k) - 2 \Delta X * Y(k) + c ) \\
                                       & = 2 \Delta Y (X(k + 1) - X(k)) - 2 \Delta X ((Y(k + 1) - Y(k)) \\
                                       & = 2 \Delta Y - 2 \Delta X ((Y(k + 1) - Y(k)) \\
          \end{align*}
     
     There are two cases for $(Y(k + 1) - Y(k)$.  Either $(Y(k + 1) = Y(k)$ (if $D(k) \le 0)$, or $(Y(k + 1) = Y(k) + 1$.
     
     Thus, the increment in $D(k)$ is $2 \Delta Y$ if $D(k) \le 0$, or $2 \Delta Y - 2 \Delta X$ otherwise.
     
     The only other thing we need is to find the initial value, $D(0)$.  We can calculate this as
          \begin{align*}
               D(0) & = 2 \Delta Y * X(0) - 2 \Delta X * Y(0) + c \\
                       & = 2 \Delta Y * X_0 - 2 \Delta X * Y_0 + c \\
                       & = 2 \Delta Y * X_0 - 2 \Delta X * Y_0 + 2 \Delta Y + 2 \Delta X * Y_0 - 2 \Delta Y * X_0 -  \Delta X \\
                       & = 2 \Delta Y -  \Delta X \\
          \end{align*}
% \footnotesize
% \bibliographystyle{plain} 
% 
%
%
%\marginpar{\hyperlink{Contents}{\hfil$\leftarrow$}}
%
%\vspace{-\baselineskip}
%\vspace{-\baselineskip}
%\vspace{-\baselineskip}
% 
% \begin{thebibliography}{12}
%
%\addcontentsline{toc}{section}{References}
%
%\bibitem{feld}
%Feld, Scott L. (1991), \\
%Why your friends have more friends than you do, \\
%American Journal of Sociology 96 (6): 1464-1477, \\
%\href{http://dx.doi.org/10.1086\%2F229693}
%           {doi:10.1086/229693, JSTOR 2781907}
%
%\bibitem{newman}
%Newman, M.E.J. (2002), \\
%Random Graphs as Models of Networks,\\
%SFI WORKING PAPER: 2002-02-005, \\
%\href{http://www.santafe.edu/media/workingpapers/02-02-005.pdf}
%          {http://www.santafe.edu/media/workingpapers/02-02-005.pdf}
%
%\end{thebibliography}

\hyperlink{Contents}{\hfil To top $\leftarrow$}


\end{document}
