title: Simplified Bresenham's line algorithm: What does it *exactly* do?
body: <p>Based on Wikipedia's article on Bresenham's line algorithm I've implemented the <a href="http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm#Simplification">simplified version</a> described there, my Java implementation looks like this:</p>
  
  <pre><code>int dx = Math.abs(x2 - x1);
  int dy = Math.abs(y2 - y1);
  
  int sx = (x1 &lt; x2) ? 1 : -1;
  int sy = (y1 &lt; y2) ? 1 : -1;
  
  int err = dx - dy;
  
  while (true) {
      framebuffer.setPixel(x1, y1, Vec3.one);
  
      if (x1 == x2 &amp;&amp; y1 == y2) {
          break;
      }
  
      int e2 = 2 * err;
  
      if (e2 &gt; -dy) {
          err = err - dy;
          x1 = x1 + sx;
      }
  
      if (e2 &lt; dx) {
          err = err + dx;
          y1 = y1 + sy;
      }
  }
  </code></pre>
  
  <p>Now I do understand that <code>err</code> controls the ratio between steps on the x-axis compared to steps on the y-axis - but now that I'm supposed to document what the code is doing I fail to clearly express, what it is for, and why <em>exactly</em> the if-statements are, how they are, and why <code>err</code> is changed in the way as seen in the code.</p>
  
  <p>Wikipedia doesn't point to any more detailled explanations or sources, so I'm wondering:</p>
  
  <p><strong>What precisely does <code>err</code> do and why are <code>dx</code> and <code>dy</code> used in exactly the shown way to maintain the correct ratio between horizontal and vertical steps using this simplified version of Bresenham's line algorithm?</strong></p>