Omnimaga

General Discussion => Technology and Development => Computer Programming => Topic started by: BlakPilar on September 15, 2011, 05:19:51 pm

Title: Bresenham's line algorithm help
Post by: BlakPilar on September 15, 2011, 05:19:51 pm
EDIT: Nevermind, I solved it. I fixed my interpretation in case anyone else needs to use it.

I've been looking at Bresenham's line algorithm for something that I'm working on, and I can't seem to get it to work. I tried using the first sample algorithm that is on the wikipedia page, but my line stays stationary. I tried making my own one based on the article itself, but it only works in two positions (the line is either horizontal or perfectly diagonal).

Article: [wikipedia]http://en.wikipedia.org/wiki/Bresenham's_line_algorithm#The_algorithm[/wikipedia]
Spoiler For their algorithm:
function line(x0, x1, y0, y1)
     int deltax := x1 - x0
     int deltay := y1 - y0
     real error := 0
     real deltaerr := abs (deltay / deltax)    // Assume deltax != 0 (line is not vertical),
           // note that this division needs to be done in a way that preserves the fractional part
     int y := y0
     for x from x0 to x1
         plot(x,y)
         error := error + deltaerr
         if error ≥ 0.5 then
             y := y + 1
             error := error - 1.0
Spoiler For my translated version of their algorithm:
int deltaX = x2 - x1;
            int deltaY = y2 - y1;
            double error = 0;
            double deltaErr = (double)(Math.Abs((double)deltaY / (double)deltaX));
            int y = y1;
            for (int x = x1; x <= x2; x++)
            {
                this.PxlOn(x, y);
                error += deltaErr;
                if (error >= 0.5)
                {
                    y++;
                    error--;
                }
            }
Spoiler For my algorithm:
            for (int x = x1; x <= x2; x++)
            {
                int y = (((y2 - y1) / (x2 - x1)) * (x - x1)) + y1;
                this.PxlOn(x, y);
            }
            //x1 in mine is equivalent to x0 in theirs. x2 in mine is x1 in theirs.
I've attached what my algorithm (not my translation of theirs) looks like.