Bitmap/Bézier curves/Cubic: Difference between revisions

Added 11l
m (→‎{{header|Phix}}: minor tidy)
(Added 11l)
Line 3:
Using the data storage type defined [[Basic_bitmap_storage|on this page]] for raster images, and the <tt>draw_line</tt> function defined in [[Bresenham's_line_algorithm|this other one]], draw a '''cubic bezier curve'''
([[wp:Bezier_curves#Cubic_B.C3.A9zier_curves|definition on Wikipedia]]).
 
=={{header|11l}}==
{{trans|Python}}
 
<lang 11l>T Colour
Byte r, g, b
 
F ==(other)
R .r == other.r & .g == other.g & .b == other.b
 
F (r, g, b)
.r = r
.g = g
.b = b
 
V black = Colour(0, 0, 0)
V white = Colour(255, 255, 255)
 
T Bitmap
Int width, height
Colour background
[[Colour]] map
 
F (width = 40, height = 40, background = white)
assert(width > 0 & height > 0)
.width = width
.height = height
.background = background
.map = (0 .< height).map(h -> (0 .< @width).map(w -> @@background))
 
F fillrect(x, y, width, height, colour = black)
assert(x >= 0 & y >= 0 & width > 0 & height > 0)
L(h) 0 .< height
L(w) 0 .< width
.map[y + h][x + w] = colour
 
F chardisplay()
V txt = .map.map(row -> row.map(bit -> (I bit == @@.background {‘ ’} E ‘@’)).join(‘’))
txt = txt.map(row -> ‘|’row‘|’)
txt.insert(0, ‘+’(‘-’ * .width)‘+’)
txt.append(‘+’(‘-’ * .width)‘+’)
print(reversed(txt).join("\n"))
 
F set(x, y, colour = black)
.map[y][x] = colour
 
F get(x, y)
R .map[y][x]
 
F line(x0, y0, x1, y1)
‘Bresenham's line algorithm’
V dx = abs(x1 - x0)
V dy = abs(y1 - y0)
V (x, y) = (x0, y0)
V sx = I x0 > x1 {-1} E 1
V sy = I y0 > y1 {-1} E 1
I dx > dy
V err = dx / 2.0
L x != x1
.set(x, y)
err -= dy
I err < 0
y += sy
err += dx
x += sx
E
V err = dy / 2.0
L y != y1
.set(x, y)
err -= dx
I err < 0
x += sx
err += dy
y += sy
.set(x, y)
 
F cubicbezier(x0, y0, x1, y1, x2, y2, x3, y3, n = 20)
[(Int, Int)] pts
L(i) 0 .. n
V t = Float(i) / n
V a = (1. - t) ^ 3
V b = 3. * t * (1. - t) ^ 2
V c = 3.0 * t ^ 2 * (1.0 - t)
V d = t ^ 3
 
V x = Int(a * x0 + b * x1 + c * x2 + d * x3)
V y = Int(a * y0 + b * y1 + c * y2 + d * y3)
pts.append((x, y))
L(i) 0 .< n
.line(pts[i][0], pts[i][1], pts[i + 1][0], pts[i + 1][1])
 
V bitmap = Bitmap(17, 17)
bitmap.cubicbezier(16, 1, 1, 4, 3, 16, 15, 11)
bitmap.chardisplay()</lang>
 
{{out}}
<pre>
+-----------------+
| |
| |
| |
| |
| @@@@ |
| @@@ @@@ |
| @ |
| @ |
| @ |
| @ |
| @ |
| @ |
| @ |
| @ |
| @@@@ |
| @@@@|
| |
+-----------------+
</pre>
 
=={{header|Ada}}==
1,481

edits