Task

Using the data storage type defined on the Bitmap page for raster graphics images,

draw a line given two points with Bresenham's line algorithm.




-- demo\rosetta\Bresenham_line.exw (runnable version)
 
global function bresLine(sequence image, integer x0, y0, x1, y1, colour)
    -- The line algorithm
    integer dimx = length(image),
            dimy = length(image[1]),
            deltaX = abs(x1-x0),
            deltaY = abs(y1-y0),
            stepX = iff(x0<x1,1,-1),
            stepY = iff(y0<y1,1,-1),
            lineError = iff(deltaX>deltaY,deltaX,-deltaY),
            prevle
    lineError = round(lineError/2, 1)
    while true do
        if  x0>=1 and x0<=dimx
        and y0>=1 and y0<=dimy then
            image[x0][y0] = colour
        end if
        if x0=x1 and y0=y1 then exit end if
        prevle = lineError
        if prevle>-deltaX then
            lineError -= deltaY
            x0 += stepX
        end if
        if prevle<deltaY then
            lineError += deltaX
            y0 += stepY
        end if
    end while
    return image
end function
 
--include ppm.e   -- red, green, blue, white, new_image(), write_ppm(), bresLine()  (as distributed, instead of the above)
 
sequence screenData = new_image(400,300,black)
screenData = bresLine(screenData,100,1,50,300,red)
screenData = bresLine(screenData,1,180,400,240,green)
screenData = bresLine(screenData,200,1,400,150,white)
screenData = bresLine(screenData,195,1,205,300,blue)
write_ppm("bresenham.ppm",screenData)