1 /**
2  * Drawing functions.
3  *
4  * License:
5  *   This Source Code Form is subject to the terms of
6  *   the Mozilla Public License, v. 2.0. If a copy of
7  *   the MPL was not distributed with this file, You
8  *   can obtain one at http://mozilla.org/MPL/2.0/.
9  *
10  * Authors:
11  *   Vladimir Panteleev <vladimir@thecybershadow.net>
12  */
13 
14 module ae.utils.graphics.draw;
15 
16 import std.algorithm : sort;
17 import std.traits;
18 
19 import ae.utils.geometry : TAU;
20 import ae.utils.graphics.view;
21 import ae.utils.math;
22 import ae.utils.meta : structFields, SignedBitsType, UnsignedBitsType;
23 
24 version(unittest) import ae.utils.graphics.image;
25 
26 // Constraints could be simpler if this was fixed:
27 // https://d.puremagic.com/issues/show_bug.cgi?id=12386
28 
29 /// Get the pixel color at the specified coordinates,
30 /// or fall back to the specified default value if
31 /// the coordinates are out of bounds.
32 COLOR safeGet(V, COLOR)(auto ref V v, int x, int y, COLOR def)
33 	if (isView!V && is(COLOR : ViewColor!V))
34 {
35 	if (x>=0 && y>=0 && x<v.w && y<v.h)
36 		return v[x, y];
37 	else
38 		return def;
39 }
40 
41 unittest
42 {
43 	auto v = onePixel(7);
44 	assert(v.safeGet(0, 0, 0) == 7);
45 	assert(v.safeGet(0, 1, 0) == 0);
46 }
47 
48 /// Set the pixel color at the specified coordinates
49 /// if the coordinates are not out of bounds.
50 void safePut(V, COLOR)(auto ref V v, int x, int y, COLOR value)
51 	if (isWritableView!V && is(COLOR : ViewColor!V))
52 {
53 	if (x>=0 && y>=0 && x<v.w && y<v.h)
54 		v[x, y] = value;
55 }
56 
57 unittest
58 {
59 	auto v = Image!int(1, 1);
60 	v.safePut(0, 0, 7);
61 	v.safePut(0, 1, 9);
62 	assert(v[0, 0] == 7);
63 }
64 
65 /// Forwards to safePut or opIndex, depending on the
66 /// CHECKED parameter. Allows propagation of a
67 /// CHECKED parameter from other callers.
68 void putPixel(bool CHECKED, V, COLOR)(auto ref V v, int x, int y, COLOR value)
69 	if (isWritableView!V && is(COLOR : ViewColor!V))
70 {
71 	static if (CHECKED)
72 		v.safePut(x, y, value);
73 	else
74 		v[x, y] = value;
75 }
76 
77 unittest
78 {
79 	auto v = Image!int(1, 1);
80 	v.putPixel!false(0, 0, 7);
81 	v.putPixel!true(0, 1, 9);
82 	assert(v[0, 0] == 7);
83 }
84 
85 /// Gets a pixel's address from a direct view.
86 ViewColor!V* pixelPtr(V)(auto ref V v, int x, int y)
87 	if (isDirectView!V)
88 {
89 	return &v.scanline(y)[x];
90 }
91 
92 unittest
93 {
94 	auto v = Image!int(1, 1);
95 	v[0, 0] = 7;
96 	auto p = v.pixelPtr(0, 0);
97 	assert(*p == 7);
98 }
99 
100 /// Fills a writable view with a solid color.
101 void fill(V, COLOR)(auto ref V v, COLOR c)
102 	if (isWritableView!V
103 	 && is(COLOR : ViewColor!V))
104 {
105 	foreach (y; 0..v.h)
106 	{
107 		static if (isDirectView!V)
108 			v.scanline(y)[] = c;
109 		else
110 			foreach (x; 0..v.w)
111 				v[x, y] = c;
112 	}
113 }
114 deprecated alias clear = fill;
115 
116 unittest
117 {
118 	auto i = onePixel(0).copy();
119 	i.fill(1);
120 	assert(i[0, 0] == 1);
121 	auto t = i.tile(10, 10);
122 	t.fill(2);
123 	assert(i[0, 0] == 2);
124 }
125 
126 // ***************************************************************************
127 
128 enum CheckHLine =
129 q{
130 	static if (CHECKED)
131 	{
132 		if (x1 >= v.w || x2 <= 0 || y < 0 || y >= v.h || x1 >= x2) return;
133 		if (x1 <    0) x1 =   0;
134 		if (x2 >= v.w) x2 = v.w;
135 	}
136 	assert(x1 <= x2);
137 };
138 
139 enum CheckVLine =
140 q{
141 	static if (CHECKED)
142 	{
143 		if (x < 0 || x >= v.w || y1 >= v.h || y2 <= 0 || y1 >= y2) return;
144 		if (y1 <    0) y1 =   0;
145 		if (y2 >= v.h) y2 = v.h;
146 	}
147 	assert(y1 <= y2);
148 };
149 
150 void hline(bool CHECKED=true, V, COLOR)(auto ref V v, int x1, int x2, int y, COLOR c)
151 	if (isWritableView!V && is(COLOR : ViewColor!V))
152 {
153 	mixin(CheckHLine);
154 	v.scanline(y)[x1..x2] = c;
155 }
156 
157 void vline(bool CHECKED=true, V, COLOR)(auto ref V v, int x, int y1, int y2, COLOR c)
158 	if (isWritableView!V && is(COLOR : ViewColor!V))
159 {
160 	mixin(CheckVLine);
161 	foreach (y; y1..y2) // TODO: optimize
162 		v[x, y] = c;
163 }
164 
165 void line(bool CHECKED=true, V, COLOR)(auto ref V v, int x1, int y1, int x2, int y2, COLOR c)
166 	if (isWritableView!V && is(COLOR : ViewColor!V))
167 {
168 	mixin FixMath;
169 
170 	enum DrawLine = q{
171 		// Axis-independent part. Mixin context:
172 		// a0 .. a1  - longer side
173 		// b0 .. b1  - shorter side
174 		// DrawPixel - mixin to draw a pixel at coordinates (a, b)
175 
176 		if (a0 == a1)
177 			return;
178 
179 		if (a0 > a1)
180 		{
181 			 swap(a0, a1);
182 			 swap(b0, b1);
183 		}
184 
185 		// Use fixed-point for b position and offset per 1 pixel along "a" axis
186 		assert(b0 < (1L<<coordinateBits) && b1 < (1L<<coordinateBits));
187 		SignedBitsType!(coordinateBits*2) bPos = b0 << coordinateBits;
188 		SignedBitsType!(coordinateBits*2) bOff = ((b1-b0) << coordinateBits) / (a1-a0);
189 
190 		foreach (a; a0..a1+1)
191 		{
192 			int b = (bPos += bOff) >> coordinateBits;
193 			mixin(DrawPixel);
194 		}
195 	};
196 
197 	if (abs(x2-x1) > abs(y2-y1))
198 	{
199 		alias x1 a0;
200 		alias x2 a1;
201 		alias y1 b0;
202 		alias y2 b1;
203 		enum DrawPixel = q{ v.putPixel!CHECKED(a, b, c); };
204 		mixin(DrawLine);
205 	}
206 	else
207 	{
208 		alias y1 a0;
209 		alias y2 a1;
210 		alias x1 b0;
211 		alias x2 b1;
212 		enum DrawPixel = q{ v.putPixel!CHECKED(b, a, c); };
213 		mixin(DrawLine);
214 	}
215 }
216 
217 /// Draws a rectangle with a solid line.
218 /// The coordinates represent bounds (open on the right) for the outside of the rectangle.
219 void rect(bool CHECKED=true, V, COLOR)(auto ref V v, int x1, int y1, int x2, int y2, COLOR c)
220 	if (isWritableView!V && is(COLOR : ViewColor!V))
221 {
222 	sort2(x1, x2);
223 	sort2(y1, y2);
224 	v.hline!CHECKED(x1, x2, y1  , c);
225 	v.hline!CHECKED(x1, x2, y2-1, c);
226 	v.vline!CHECKED(x1  , y1, y2, c);
227 	v.vline!CHECKED(x2-1, y1, y2, c);
228 }
229 
230 void fillRect(bool CHECKED=true, V, COLOR)(auto ref V v, int x1, int y1, int x2, int y2, COLOR b) // [)
231 	if (isWritableView!V && is(COLOR : ViewColor!V))
232 {
233 	sort2(x1, x2);
234 	sort2(y1, y2);
235 	static if (CHECKED)
236 	{
237 		if (x1 >= v.w || y1 >= v.h || x2 <= 0 || y2 <= 0 || x1==x2 || y1==y2) return;
238 		if (x1 <    0) x1 =   0;
239 		if (y1 <    0) y1 =   0;
240 		if (x2 >= v.w) x2 = v.w;
241 		if (y2 >= v.h) y2 = v.h;
242 	}
243 	foreach (y; y1..y2)
244 		v.scanline(y)[x1..x2] = b;
245 }
246 
247 void fillRect(bool CHECKED=true, V, COLOR)(auto ref V v, int x1, int y1, int x2, int y2, COLOR c, COLOR b) // [)
248 	if (isWritableView!V && is(COLOR : ViewColor!V))
249 {
250 	v.rect!CHECKED(x1, y1, x2, y2, c);
251 	if (x2-x1>2 && y2-y1>2)
252 		v.fillRect!CHECKED(x1+1, y1+1, x2-1, y2-1, b);
253 }
254 
255 /// Unchecked! Make sure area is bounded.
256 void uncheckedFloodFill(V, COLOR)(auto ref V v, int x, int y, COLOR c)
257 	if (isDirectView!V && is(COLOR : ViewColor!V))
258 {
259 	v.floodFillPtr(&v[x, y], c, v[x, y]);
260 }
261 
262 private void floodFillPtr(V, COLOR)(auto ref V v, COLOR* pp, COLOR c, COLOR f)
263 	if (isDirectView!V && is(COLOR : ViewColor!V))
264 {
265 	COLOR* p0 = pp; while (*p0==f) p0--; p0++;
266 	COLOR* p1 = pp; while (*p1==f) p1++; p1--;
267 	auto stride = v.scanline(1).ptr-v.scanline(0).ptr;
268 	for (auto p=p0; p<=p1; p++)
269 		*p = c;
270 	p0 -= stride; p1 -= stride;
271 	for (auto p=p0; p<=p1; p++)
272 		if (*p == f)
273 			v.floodFillPtr(p, c, f);
274 	p0 += stride*2; p1 += stride*2;
275 	for (auto p=p0; p<=p1; p++)
276 		if (*p == f)
277 			v.floodFillPtr(p, c, f);
278 }
279 
280 void fillCircle(V, COLOR)(auto ref V v, int x, int y, int r, COLOR c)
281 	if (isWritableView!V && is(COLOR : ViewColor!V))
282 {
283 	int x0 = x>r?x-r:0;
284 	int y0 = y>r?y-r:0;
285 	int x1 = min(x+r, v.w-1);
286 	int y1 = min(y+r, v.h-1);
287 	int rs = sqr(r);
288 	// TODO: optimize
289 	foreach (py; y0..y1+1)
290 		foreach (px; x0..x1+1)
291 			if (sqr(x-px) + sqr(y-py) < rs)
292 				v[px, py] = c;
293 }
294 
295 void fillSector(V, COLOR)(auto ref V v, int x, int y, int r0, int r1, real a0, real a1, COLOR c)
296 	if (isWritableView!V && is(COLOR : ViewColor!V))
297 {
298 	int x0 = x>r1?x-r1:0;
299 	int y0 = y>r1?y-r1:0;
300 	int x1 = min(x+r1, v.w-1);
301 	int y1 = min(y+r1, v.h-1);
302 	int r0s = sqr(r0);
303 	int r1s = sqr(r1);
304 	if (a0 > a1)
305 		a1 += TAU;
306 	foreach (py; y0..y1+1)
307 		foreach (px; x0..x1+1)
308 		{
309 			int dx = px-x;
310 			int dy = py-y;
311 			int rs = sqr(dx) + sqr(dy);
312 			if (r0s <= rs && rs < r1s)
313 			{
314 				real a = atan2(cast(real)dy, cast(real)dx);
315 				if ((a0 <= a && a <= a1) ||
316 				    (a += TAU,
317 				    (a0 <= a && a <= a1)))
318 					v[px, py] = c;
319 			}
320 		}
321 }
322 
323 struct Coord { int x, y; string toString() { import std.string; return format("%s", [this.tupleof]); } }
324 
325 void fillPoly(V, COLOR)(auto ref V v, Coord[] coords, COLOR f)
326 	if (isWritableView!V && is(COLOR : ViewColor!V))
327 {
328 	int minY, maxY;
329 	minY = maxY = coords[0].y;
330 	foreach (c; coords[1..$])
331 		minY = min(minY, c.y),
332 		maxY = max(maxY, c.y);
333 
334 	foreach (y; minY..maxY+1)
335 	{
336 		int[] intersections;
337 		for (uint i=0; i<coords.length; i++)
338 		{
339 			auto c0=coords[i], c1=coords[i==$-1?0:i+1];
340 			if (y==c0.y)
341 			{
342 				assert(y == coords[i%$].y);
343 				int pi = i-1; int py;
344 				while ((py=coords[(pi+$)%$].y)==y)
345 					pi--;
346 				int ni = i+1; int ny;
347 				while ((ny=coords[ni%$].y)==y)
348 					ni++;
349 				if (ni > coords.length)
350 					continue;
351 				if ((py>y) == (y>ny))
352 					intersections ~= coords[i%$].x;
353 				i = ni-1;
354 			}
355 			else
356 			if (c0.y<y && y<c1.y)
357 				intersections ~= itpl(c0.x, c1.x, y, c0.y, c1.y);
358 			else
359 			if (c1.y<y && y<c0.y)
360 				intersections ~= itpl(c1.x, c0.x, y, c1.y, c0.y);
361 		}
362 
363 		assert(intersections.length % 2==0);
364 		intersections.sort();
365 		for (uint i=0; i<intersections.length; i+=2)
366 			v.hline!true(intersections[i], intersections[i+1], y, f);
367 	}
368 }
369 
370 // No caps
371 void thickLine(V, COLOR)(auto ref V v, int x1, int y1, int x2, int y2, int r, COLOR c)
372 	if (isWritableView!V && is(COLOR : ViewColor!V))
373 {
374 	int dx = x2-x1;
375 	int dy = y2-y1;
376 	int d  = cast(int)sqrt(cast(float)(sqr(dx)+sqr(dy)));
377 	if (d==0) return;
378 
379 	int nx = dx*r/d;
380 	int ny = dy*r/d;
381 
382 	fillPoly([
383 		Coord(x1-ny, y1+nx),
384 		Coord(x1+ny, y1-nx),
385 		Coord(x2+ny, y2-nx),
386 		Coord(x2-ny, y2+nx),
387 	], c);
388 }
389 
390 // No caps
391 void thickLinePoly(V, COLOR)(auto ref V v, Coord[] coords, int r, COLOR c)
392 	if (isWritableView!V && is(COLOR : ViewColor!V))
393 {
394 	foreach (i; 0..coords.length)
395 		thickLine(coords[i].tupleof, coords[(i+1)%$].tupleof, r, c);
396 }
397 
398 // ************************************************************************************************************************************
399 
400 mixin template FixMath(ubyte coordinateBitsParam = 16)
401 {
402 	enum coordinateBits = coordinateBitsParam;
403 
404 	static assert(COLOR.homogenous, "Asymmetric color types not supported, fix me!");
405 	/// Fixed-point type, big enough to hold a coordinate, with fractionary precision corresponding to channel precision.
406 	alias fix  = SignedBitsType!(COLOR.channelBits   + coordinateBits);
407 	/// Type to hold temporary values for multiplication and division
408 	alias fix2 = SignedBitsType!(COLOR.channelBits*2 + coordinateBits);
409 
410 	static assert(COLOR.channelBits < 32, "Shift operators are broken for shifts over 32 bits, fix me!");
411 	fix tofix(T:int  )(T x) { return cast(fix) (x<<COLOR.channelBits); }
412 	fix tofix(T:float)(T x) { return cast(fix) (x*(1<<COLOR.channelBits)); }
413 	T fixto(T:int)(fix x) { return cast(T)(x>>COLOR.channelBits); }
414 
415 	fix fixsqr(fix x)        { return cast(fix)((cast(fix2)x*x) >> COLOR.channelBits); }
416 	fix fixmul(fix x, fix y) { return cast(fix)((cast(fix2)x*y) >> COLOR.channelBits); }
417 	fix fixdiv(fix x, fix y) { return cast(fix)((cast(fix2)x << COLOR.channelBits)/y); }
418 
419 	static assert(COLOR.ChannelType.sizeof*8 == COLOR.channelBits, "COLORs with ChannelType not corresponding to native type not currently supported, fix me!");
420 	/// Type only large enough to hold a fractionary part of a "fix" (i.e. color channel precision). Used for alpha values, etc.
421 	alias COLOR.ChannelType frac;
422 	/// Type to hold temporary values for multiplication and division
423 	alias UnsignedBitsType!(COLOR.channelBits*2) frac2;
424 
425 	frac tofrac(T:float)(T x) { return cast(frac) (x*(1<<COLOR.channelBits)); }
426 	frac fixfpart(fix x) { return cast(frac)x; }
427 	frac fracsqr(frac x        ) { return cast(frac)((cast(frac2)x*x) >> COLOR.channelBits); }
428 	frac fracmul(frac x, frac y) { return cast(frac)((cast(frac2)x*y) >> COLOR.channelBits); }
429 
430 	frac tofracBounded(T:float)(T x) { return cast(frac) bound(tofix(x), 0, frac.max); }
431 }
432 
433 // ************************************************************************************************************************************
434 
435 void whiteNoise(V)(V v)
436 	if (isWritableView!V)
437 {
438 	import std.random;
439 	alias COLOR = ViewColor!V;
440 
441 	for (int y=0;y<v.h/2;y++)
442 		for (int x=0;x<v.w/2;x++)
443 			v[x*2, y*2] = COLOR.monochrome(uniform!(COLOR.ChannelType)());
444 
445 	// interpolate
446 	enum AVERAGE = q{(a+b)/2};
447 
448 	for (int y=0;y<v.h/2;y++)
449 		for (int x=0;x<v.w/2-1;x++)
450 			v[x*2+1, y*2  ] = COLOR.op!AVERAGE(v[x*2  , y*2], v[x*2+2, y*2  ]);
451 	for (int y=0;y<v.h/2-1;y++)
452 		for (int x=0;x<v.w/2;x++)
453 			v[x*2  , y*2+1] = COLOR.op!AVERAGE(v[x*2  , y*2], v[x*2  , y*2+2]);
454 	for (int y=0;y<v.h/2-1;y++)
455 		for (int x=0;x<v.w/2-1;x++)
456 			v[x*2+1, y*2+1] = COLOR.op!AVERAGE(v[x*2+1, y*2], v[x*2+2, y*2+2]);
457 }
458 
459 private template softRoundShape(bool RING)
460 {
461 	void softRoundShape(T, V, COLOR)(auto ref V v, T x, T y, T r0, T r1, T r2, COLOR color)
462 		if (isWritableView!V && isNumeric!T && is(COLOR : ViewColor!V))
463 	{
464 		mixin FixMath;
465 
466 		assert(r0 <= r1);
467 		assert(r1 <= r2);
468 		assert(r2 < 256); // precision constraint - see SqrType
469 		//int ix = cast(int)x;
470 		//int iy = cast(int)y;
471 		//int ir1 = cast(int)sqr(r1-1);
472 		//int ir2 = cast(int)sqr(r2+1);
473 		int x1 = cast(int)(x-r2-1); if (x1<0) x1=0;
474 		int y1 = cast(int)(y-r2-1); if (y1<0) y1=0;
475 		int x2 = cast(int)(x+r2+1); if (x2>v.w) x2 = v.w;
476 		int y2 = cast(int)(y+r2+1); if (y2>v.h) y2 = v.h;
477 
478 		static if (RING)
479 		auto r0s = r0*r0;
480 		auto r1s = r1*r1;
481 		auto r2s = r2*r2;
482 		//float rds = r2s - r1s;
483 
484 		fix fx = tofix(x);
485 		fix fy = tofix(y);
486 
487 		static if (RING)
488 		fix fr0s = tofix(r0s);
489 		fix fr1s = tofix(r1s);
490 		fix fr2s = tofix(r2s);
491 
492 		static if (RING)
493 		fix fr10 = fr1s - fr0s;
494 		fix fr21 = fr2s - fr1s;
495 
496 		for (int cy=y1;cy<y2;cy++)
497 		{
498 			auto row = v.scanline(cy);
499 			for (int cx=x1;cx<x2;cx++)
500 			{
501 				alias SignedBitsType!(2*(8 + COLOR.channelBits)) SqrType; // fit the square of radius expressed as fixed-point
502 				fix frs = cast(fix)((sqr(cast(SqrType)fx-tofix(cx)) + sqr(cast(SqrType)fy-tofix(cy))) >> COLOR.channelBits); // shift-right only once instead of once-per-sqr
503 
504 				//static frac alphafunc(frac x) { return fracsqr(x); }
505 				static frac alphafunc(frac x) { return x; }
506 
507 				static if (RING)
508 				{
509 					if (frs<fr0s)
510 						{}
511 					else
512 					if (frs<fr2s)
513 					{
514 						frac alpha;
515 						if (frs<fr1s)
516 							alpha =  alphafunc(cast(frac)fixdiv(frs-fr0s, fr10));
517 						else
518 							alpha = ~alphafunc(cast(frac)fixdiv(frs-fr1s, fr21));
519 						row[cx] = COLOR.op!q{.blend(a, b, c)}(color, row[cx], alpha);
520 					}
521 				}
522 				else
523 				{
524 					if (frs<fr1s)
525 						row[cx] = color;
526 					else
527 					if (frs<fr2s)
528 					{
529 						frac alpha = ~alphafunc(cast(frac)fixdiv(frs-fr1s, fr21));
530 						row[cx] = COLOR.op!q{.blend(a, b, c)}(color, row[cx], alpha);
531 					}
532 				}
533 			}
534 		}
535 	}
536 }
537 
538 void softRing(T, V, COLOR)(auto ref V v, T x, T y, T r0, T r1, T r2, COLOR color)
539 	if (isWritableView!V && isNumeric!T && is(COLOR : ViewColor!V))
540 {
541 	v.softRoundShape!true(x, y, r0, r1, r2, color);
542 }
543 
544 void softCircle(T, V, COLOR)(auto ref V v, T x, T y, T r1, T r2, COLOR color)
545 	if (isWritableView!V && isNumeric!T && is(COLOR : ViewColor!V))
546 {
547 	v.softRoundShape!false(x, y, cast(T)0, r1, r2, color);
548 }
549 
550 template aaPutPixel(bool CHECKED=true, bool USE_ALPHA=true)
551 {
552 	void aaPutPixel(F:float, V, COLOR, frac)(auto ref V v, F x, F y, COLOR color, frac alpha)
553 		if (isWritableView!V && is(COLOR : ViewColor!V))
554 	{
555 		mixin FixMath;
556 
557 		void plot(bool CHECKED2)(int x, int y, frac f)
558 		{
559 			static if (CHECKED2)
560 				if (x<0 || x>=v.w || y<0 || y>=v.h)
561 					return;
562 
563 			COLOR* p = v.pixelPtr(x, y);
564 			static if (USE_ALPHA) f = fracmul(f, cast(frac)alpha);
565 			*p = COLOR.op!q{.blend(a, b, c)}(color, *p, f);
566 		}
567 
568 		fix fx = tofix(x);
569 		fix fy = tofix(y);
570 		int ix = fixto!int(fx);
571 		int iy = fixto!int(fy);
572 		static if (CHECKED)
573 			if (ix>=0 && iy>=0 && ix+1<v.w && iy+1<v.h)
574 			{
575 				plot!false(ix  , iy  , fracmul(~fixfpart(fx), ~fixfpart(fy)));
576 				plot!false(ix  , iy+1, fracmul(~fixfpart(fx),  fixfpart(fy)));
577 				plot!false(ix+1, iy  , fracmul( fixfpart(fx), ~fixfpart(fy)));
578 				plot!false(ix+1, iy+1, fracmul( fixfpart(fx),  fixfpart(fy)));
579 				return;
580 			}
581 		plot!CHECKED(ix  , iy  , fracmul(~fixfpart(fx), ~fixfpart(fy)));
582 		plot!CHECKED(ix  , iy+1, fracmul(~fixfpart(fx),  fixfpart(fy)));
583 		plot!CHECKED(ix+1, iy  , fracmul( fixfpart(fx), ~fixfpart(fy)));
584 		plot!CHECKED(ix+1, iy+1, fracmul( fixfpart(fx),  fixfpart(fy)));
585 	}
586 }
587 
588 void aaPutPixel(bool CHECKED=true, F:float, V, COLOR)(auto ref V v, F x, F y, COLOR color)
589 	if (isWritableView!V && is(COLOR : ViewColor!V))
590 {
591 	//aaPutPixel!(false, F)(x, y, color, 0); // doesn't work, wtf
592 	alias aaPutPixel!(CHECKED, false) f;
593 	f(v, x, y, color, 0);
594 }
595 
596 void hline(bool CHECKED=true, V, COLOR, frac)(auto ref V v, int x1, int x2, int y, COLOR color, frac alpha)
597 	if (isWritableView!V && is(COLOR : ViewColor!V))
598 {
599 	mixin(CheckHLine);
600 
601 	if (alpha==0)
602 		return;
603 	else
604 	if (alpha==frac.max)
605 		v.scanline(y)[x1..x2] = color;
606 	else
607 		foreach (ref p; v.scanline(y)[x1..x2])
608 			p = COLOR.op!q{.blend(a, b, c)}(color, p, alpha);
609 }
610 
611 void vline(bool CHECKED=true, V, COLOR, frac)(auto ref V v, int x, int y1, int y2, COLOR color, frac alpha)
612 	if (isWritableView!V && is(COLOR : ViewColor!V))
613 {
614 	mixin(CheckVLine);
615 
616 	if (alpha==0)
617 		return;
618 	else
619 	if (alpha==frac.max)
620 		foreach (y; y1..y2)
621 			v[x, y] = color;
622 	else
623 		foreach (y; y1..y2)
624 		{
625 			auto p = v.pixelPtr(x, y);
626 			*p = COLOR.op!q{.blend(a, b, c)}(color, *p, alpha);
627 		}
628 }
629 
630 void aaFillRect(bool CHECKED=true, F:float, V, COLOR)(auto ref V v, F x1, F y1, F x2, F y2, COLOR color)
631 	if (isWritableView!V && is(COLOR : ViewColor!V))
632 {
633 	mixin FixMath;
634 
635 	sort2(x1, x2);
636 	sort2(y1, y2);
637 	fix x1f = tofix(x1); int x1i = fixto!int(x1f);
638 	fix y1f = tofix(y1); int y1i = fixto!int(y1f);
639 	fix x2f = tofix(x2); int x2i = fixto!int(x2f);
640 	fix y2f = tofix(y2); int y2i = fixto!int(y2f);
641 
642 	v.vline!CHECKED(x1i, y1i+1, y2i, color, ~fixfpart(x1f));
643 	v.vline!CHECKED(x2i, y1i+1, y2i, color,  fixfpart(x2f));
644 	v.hline!CHECKED(x1i+1, x2i, y1i, color, ~fixfpart(y1f));
645 	v.hline!CHECKED(x1i+1, x2i, y2i, color,  fixfpart(y2f));
646 	v.aaPutPixel!CHECKED(x1i, y1i, color, fracmul(~fixfpart(x1f), ~fixfpart(y1f)));
647 	v.aaPutPixel!CHECKED(x1i, y2i, color, fracmul(~fixfpart(x1f),  fixfpart(y2f)));
648 	v.aaPutPixel!CHECKED(x2i, y1i, color, fracmul( fixfpart(x2f), ~fixfpart(y1f)));
649 	v.aaPutPixel!CHECKED(x2i, y2i, color, fracmul( fixfpart(x2f),  fixfpart(y2f)));
650 
651 	v.fillRect!CHECKED(x1i+1, y1i+1, x2i, y2i, color);
652 }
653 
654 void aaLine(bool CHECKED=true, V, COLOR)(auto ref V v, float x1, float y1, float x2, float y2, COLOR color)
655 	if (isWritableView!V && is(COLOR : ViewColor!V))
656 {
657 	// Simplistic straight-forward implementation. TODO: optimize
658 	if (abs(x1-x2) > abs(y1-y2))
659 		for (auto x=x1; sign(x1-x2)!=sign(x2-x); x += sign(x2-x1))
660 			v.aaPutPixel!CHECKED(x, itpl(y1, y2, x, x1, x2), color);
661 	else
662 		for (auto y=y1; sign(y1-y2)!=sign(y2-y); y += sign(y2-y1))
663 			v.aaPutPixel!CHECKED(itpl(x1, x2, y, y1, y2), y, color);
664 }
665 
666 void aaLine(bool CHECKED=true, V, COLOR, frac)(auto ref V v, float x1, float y1, float x2, float y2, COLOR color, frac alpha)
667 	if (isWritableView!V && is(COLOR : ViewColor!V))
668 {
669 	// ditto
670 	if (abs(x1-x2) > abs(y1-y2))
671 		for (auto x=x1; sign(x1-x2)!=sign(x2-x); x += sign(x2-x1))
672 			v.aaPutPixel!CHECKED(x, itpl(y1, y2, x, x1, x2), color, alpha);
673 	else
674 		for (auto y=y1; sign(y1-y2)!=sign(y2-y); y += sign(y2-y1))
675 			v.aaPutPixel!CHECKED(itpl(x1, x2, y, y1, y2), y, color, alpha);
676 }
677 
678 unittest
679 {
680 	// Test instantiation
681 	import ae.utils.graphics.color;
682 	auto i = Image!RGB(100, 100);
683 	auto c = RGB(1, 2, 3);
684 	i.whiteNoise();
685 	i.aaLine(10, 10, 20, 20, c);
686 	i.aaLine(10f, 10f, 20f, 20f, c, 100);
687 	i.rect(10, 10, 20, 20, c);
688 	i.fillRect(10, 10, 20, 20, c);
689 	i.aaFillRect(10, 10, 20, 20, c);
690 	i.vline(10, 10, 20, c);
691 	i.vline(10, 10, 20, c);
692 	i.line(10, 10, 20, 20, c);
693 	i.fillCircle(10, 10, 10, c);
694 	i.fillSector(10, 10, 10, 10, 0.0, TAU, c);
695 	i.softRing(50, 50, 10, 15, 20, c);
696 	i.softCircle(50, 50, 10, 15, c);
697 	i.fillPoly([Coord(10, 10), Coord(10, 20), Coord(20, 20)], c);
698 	i.uncheckedFloodFill(15, 15, RGB(4, 5, 6));
699 }
700 
701 // ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
702 
703 // Outdated code from before the overhaul.
704 // TODO: fix and update
705 
706 version(none):
707 
708 /// Draws an image. Returns this.
709 typeof(this) draw(bool CHECKED=true, SRCCANVAS)(int x, int y, SRCCANVAS v)
710 	if (IsCanvas!SRCCANVAS && is(COLOR == SRCCANVAS.COLOR))
711 {
712 	static if (CHECKED)
713 	{
714 		if (v.w == 0 || v.h == 0 ||
715 			x+v.w <= 0 || y+v.h <= 0 || x >= w || y >= h)
716 			return this;
717 
718 		auto r = v.window(0, 0, v.w, v.h);
719 		if (x < 0)
720 			r = r.window(-x, 0, r.w, r.h),
721 			x = 0;
722 		if (y < 0)
723 			r = r.window(0, -y, r.w, r.h),
724 			y = 0;
725 		if (x+r.w > w)
726 			r = r.window(0, 0, w-x, r.h);
727 		if (y+r.h > h)
728 			r = r.window(0, 0, r.w, h-y);
729 
730 		draw!false(x, y, r);
731 	}
732 	else
733 	{
734 		assert(v.w > 0 && v.h > 0);
735 		assert(x >= 0 && x+v.w <= w && y >= 0 && y+v.h <= h);
736 
737 		// TODO: alpha blending
738 		size_t dstStart = y*stride+x, srcStart = 0;
739 		foreach (j; 0..v.h)
740 			pixels[dstStart..dstStart+v.w] = v.pixels[srcStart..srcStart+v.w],
741 			dstStart += stride,
742 			srcStart += v.stride;
743 	}
744 
745 	return this;
746 }
747 
748 void subpixelDownscale()()
749 	if (structFields!COLOR == ["r","g","b"] || structFields!COLOR == ["b","g","r"])
750 {
751 	Image!COLOR i;
752 	i.size(HRX + hr.w*3 + HRX, hr.h);
753 	i.draw(0, 0, hr.window(0, 0, HRX, hr.h));
754 	i.window(HRX, 0, HRX+hr.w*3, hr.h).upscaleDraw!(3, 1)(hr);
755 	i.draw(HRX + hr.w*3, 0, hr.window(hr.w-HRX, 0, hr.w, hr.h));
756 	alias Color!(COLOR.BaseType, "g") BASE;
757 	Image!BASE[3] channels;
758 	Image!BASE scratch;
759 	scratch.size(hr.w*3, hr.h);
760 
761 	foreach (int cx, char c; ValueTuple!('r', 'g', 'b'))
762 	{
763 		auto w = i.window(cx*HRX, 0, cx*HRX+hr.w*3, hr.h);
764 		scratch.transformDraw!(`COLOR(c.`~c~`)`)(0, 0, w);
765 		channels[cx].size(lr.w, lr.h);
766 		channels[cx].downscaleDraw!(3*HRX, HRY)(scratch);
767 	}
768 
769 	foreach (y; 0..lr.h)
770 		foreach (x; 0..lr.w)
771 		{
772 			COLOR c;
773 			c.r = channels[0][x, y].g;
774 			c.g = channels[1][x, y].g;
775 			c.b = channels[2][x, y].g;
776 			lr[x, y] = c;
777 		}
778 }