AS3 Bresenhams line algorithm

here is an implementation of the bresenhams line algorithm. I tried to avoid the Math.abs, which I found in most source or pseudo codes. I think, this couldn’t be much faster in AS3. I’m developing a custom line algorithm, cause its the first step trying to code an own texture mapper, since the one I used is ported from C.

Here it is:

private function bresenham( x0: int, y0: int, x1: int, y1: int, value: int ): void
{
	var error: int;

	var dx: int = x1 - x0;
	var dy: int = y1 - y0;

	var yi: int = 1;

	if( dx < dy )
	{
		//-- swap end points
		x0 ^= x1; x1 ^= x0; x0 ^= x1;
		y0 ^= y1; y1 ^= y0; y0 ^= y1;
	}

	if( dx < 0 )
	{
		dx = -dx; yi = -yi;
	}

	if( dy < 0 )
	{
		dy = -dy; yi = -yi;
	}

	if( dy > dx )
	{
		error = -( dy >> 1 );

		for( ; y1 < y0 ; y1++ )
		{
			output.setPixel32( x1, y1, value );
			error += dx;
			if( error > 0 )
			{
				x1 += yi;
				error -= dy;
			}
		}
	}
	else
	{
		error = -( dx >> 1 );

		for( ; x0 < x1 ; x0++ )
		{
			output.setPixel32( x0, y0, value );
			error += dy;
			if( error > 0 )
			{
				y0 += yi;
				error -= dx;
			}
		}
	}
}

watch here Flash8.5Player required

11 thoughts on “AS3 Bresenhams line algorithm”

  1. “The fastest method of handling all cases is to write a custom routine for each of the 8 line types:

    1) x1 = deltay
    2) x1 y2, deltax &gt;= deltay
    4) x1 y2, deltax x2, y1 = deltay
    6) x1 &gt; x2, y1 x2, y1 &gt; y2, deltax &gt;= deltay
    8) x1 &gt; x2, y1 &gt; y2, deltax

  2. The fastest method of handling all cases is to write a custom routine for each of the 8 line types
    Yes, of course. You are right. Didn’t thought about this ugly solution :)

  3. Great example Andre – I saw an article about line drawign algorithms somewhere and it looked really good, covered many different types, can’t find it now tho :(

    So is there a reason this code wouldn’t work in AS2 as well (obviously some rewriting would be needed).

    Also how does thge speed get affected by multiple lines (in particular I’m thinking a 3D wireframe demo)

  4. Yes :)
    I use for the moment a simple algorithm. in AS2 to create an Array.

    static public function getLine(p1, p2):Array {

    var dx,dy,x,y,s1,s2,e,temp,swap:Number ;

    dy = Math.abs( p2.y - p1.y ) ;
    dx = Math.abs( p2.x - p1.x ) ;
    s1 = MathsUtil.sign( p2.x - p1.x ) ;
    s2 = MathsUtil.sign ( p2.y - p1.y ) ;
    x = p1.x ;
    y = p1.y ;
    if (dy&gt;dx) {
    temp = dx ;
    dx = dy ;
    dy = temp ;
    swap = 1 ;
    } else {
    swap = 0 ;
    }
    e = 2 * dy - dx ;
    var ar:Array = [] ;
    for ( var i:Number = 0 ; i=0) {
    if (swap==1) x+= s1 ;
    else y+=s2 ;
    e-=2*dx;
    }
    if (swap==1) y+=s2 ;
    else x += s1 ;
    e+=2*dy ;
    }
    return ar ;
    }

    But your code is really interesting ! Thanks :)

Comments are closed.