]> gitweb.factorcode.org Git - factor.git/blob - extra/rosetta-code/bitmap-line/bitmap-line.factor
factor: trim using lists
[factor.git] / extra / rosetta-code / bitmap-line / bitmap-line.factor
1 ! Copyright (c) 2012 Anonymous
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: arrays kernel math ranges rosetta-code.bitmap sequences ;
4 IN: rosetta-code.bitmap-line
5
6 ! http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
7
8 ! Using the data storage type defined on this page for raster
9 ! graphics images, draw a line given 2 points with the Bresenham's
10 ! algorithm.
11
12 :: line-points ( pt1 pt2 -- points )
13     pt1 first2 :> y0! :> x0!
14     pt2 first2 :> y1! :> x1!
15     y1 y0 - abs x1 x0 - abs > :> steep
16     steep [
17         y0 x0 y0! x0!
18         y1 x1 y1! x1!
19     ] when
20     x0 x1 > [
21         x0 x1 x0! x1!
22         y0 y1 y0! y1!
23     ] when
24     x1 x0 - :> deltax
25     y1 y0 - abs :> deltay
26     0 :> current-error!
27     deltay deltax / abs :> deltaerr
28     0 :> ystep!
29     y0 :> y!
30     y0 y1 < [ 1 ystep! ] [ -1 ystep! ] if
31     x0 x1 1 <range> [
32         y steep [ swap ] when 2array
33         current-error deltaerr + current-error!
34         current-error 0.5 >= [
35             ystep y + y!
36             current-error 1 - current-error!
37         ] when
38     ] { } map-as ;
39
40 ! Needs rosetta-code.bitmap for the set-pixel function and to create the image
41 : draw-line ( {R,G,B} pt1 pt2 image -- )
42     [ line-points ] dip
43     [ set-pixel ] curry with each ;