iv.nanovega: fontconfig is too aggressive
[iv.d.git] / region.d
blob0a74bb013b73f091f796fe20e555f3ec3ce4b1b0
1 /*
2 * Pixel Region Operations
3 * coded by Ketmar // Invisible Vector <ketmar@ketmar.no-ip.org>
4 * Understanding is not required. Only obedience.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 module iv.region /*is aliced*/;
20 import iv.alice;
23 // ////////////////////////////////////////////////////////////////////////// //
24 /// regions are copy-on-write shared, yay
25 struct Region {
26 alias SpanType = ushort; /// you probably will never need this, but...
28 /// combine operation for region combiner %-)
29 enum CombineOp {
30 Or, /// logic or
31 And, /// logic and
32 Xor, /// logic exclusive or
33 Cut, /// cut solid parts
34 NCut, /// cut empty parts
37 @property pure const nothrow @safe @nogc {
38 int width () { pragma(inline, true); return (rdatap ? rdata.rwdt : 0); } ///
39 int height () { pragma(inline, true); return (rdatap ? rdata.rhgt : 0); } ///
40 bool solid () { pragma(inline, true); return (rdatap ? rdata.simple && rdata.rwdt > 0 && rdata.rhgt > 0 && rdata.simpleSolid : false); } ///
41 bool empty () { pragma(inline, true); return (rdatap ? rdata.rwdt < 1 || rdata.rhgt < 1 || (rdata.simple && !rdata.simpleSolid) : true); } ///
44 /// can be used to save region data
45 @property uint[] getData () const nothrow @safe {
46 uint[] res;
47 if (rdata.simple) {
48 res ~= 1|(rdata.simpleSolid ? 2 : 0);
49 } else {
50 res ~= 0;
52 res[0] |= cast(int)(SpanType.sizeof<<4);
53 res ~= rdata.rwdt;
54 res ~= rdata.rhgt;
55 if (!rdata.simple) {
56 res ~= rdata.lineofs;
57 foreach (SpanType d; rdata.data) res ~= d;
59 return res;
62 /// can be used to restore region data
63 void setData (const(int)[] data) nothrow @safe {
64 cow!false();
65 if (data.length < 3 || (data[0]>>4) != SpanType.sizeof) assert(0, "invalid region data");
66 rdata.rwdt = data[1];
67 rdata.rhgt = data[2];
68 rdata.simple = ((data[0]&0x01) != 0);
69 rdata.lineofs = null;
70 rdata.data = null;
71 if (rdata.simple) {
72 rdata.simpleSolid = ((data[0]&0x02) != 0);
73 } else {
74 foreach (int d; data[3..3+rdata.rhgt]) rdata.lineofs ~= d;
75 foreach (int d; data[3+rdata.rhgt..$]) rdata.data ~= cast(SpanType)d;
79 /// this creates solid region (by default)
80 this (int awidth, int aheight, bool solid=true) nothrow @safe @nogc { setSize(awidth, aheight, solid); }
81 ~this () nothrow @safe @nogc { decRC(); } /// release this region data
82 this (this) nothrow @safe @nogc { if (rdatap) ++rdata.rc; } /// share this region data
84 ///
85 void setSize (int awidth, int aheight, bool solid=true) nothrow @safe @nogc {
86 if (awidth <= 0 || aheight <= 0) awidth = aheight = 0;
87 if (awidth > SpanType.max-1 || aheight > SpanType.max-1) assert(0, "Region internal error: region dimensions are too big");
88 cow!false();
89 rdata.rwdt = awidth;
90 rdata.rhgt = aheight;
91 rdata.simpleSolid = solid;
92 rdata.lineofs = null;
93 rdata.data = null;
96 /// is given point visible?
97 bool visible (int x, int y) const pure nothrow @safe @nogc {
98 // easiest cases
99 if (!rdatap) return false;
100 if (rdata.rwdt < 1 || rdata.rhgt < 1) return false;
101 if (x < 0 || y < 0 || x >= rdata.rwdt || y >= rdata.rhgt) return false;
102 if (rdata.simple) return true; // ok, easy case here
103 // now the hard one
104 immutable ldofs = rdata.lineofs[y];
105 immutable len = rdata.data[ldofs];
106 debug assert(len > 1);
107 auto line = rdata.data[ldofs+1..ldofs+len];
108 int idx = void; // will be initied in mixin
109 mixin(FindSpanMixinStr!"idx");
110 debug assert(idx < line.length); // too far (the thing that should not be)
111 return ((idx+(line[idx] == x))%2 == 0);
114 /// punch a hole
115 void punch (int x, int y, int w=1, int h=1) nothrow @trusted { pragma(inline, true); doPunchPatch!"punch"(x, y, w, h); }
117 /// patch a hole
118 void patch (int x, int y, int w=1, int h=1) nothrow @trusted { pragma(inline, true); doPunchPatch!"patch"(x, y, w, h); }
120 // ////////////////////////////////////////////////////////////////////////// //
121 enum State { Mixed = -1, Empty, Solid } /// WARNING! don't change the order!
123 /// return span state %-)
124 State spanState (int y, int x0, int x1) const pure nothrow @safe @nogc {
125 if (rdata is null) return State.Empty;
126 if (y < 0 || y >= rdata.rhgt || x1 < 0 || x0 >= rdata.rwdt || x1 < x0) return State.Empty;
127 if (rdata.simple) {
128 // if our span is not fully inside, it can be either Empty or Mixed
129 if (rdata.simpleSolid) {
130 return (x0 >= 0 && x1 < rdata.rwdt ? State.Solid : State.Mixed);
131 } else {
132 return State.Empty;
135 immutable ldofs = rdata.lineofs[y];
136 immutable len = rdata.data[ldofs];
137 debug assert(len > 1);
138 auto line = rdata.data[ldofs+1..ldofs+len];
139 int idx = void; // will be initied in mixin
140 immutable x = (x0 >= 0 ? x0 : 0);
141 mixin(FindSpanMixinStr!"idx");
142 debug assert(idx < line.length); // too far (the thing that should not be)
143 // move to "real" span
144 if (line[idx] == x) ++idx;
145 // now, sx is line[idx-1], ex is line[idx]
146 if (x1 >= (idx < line.length ? line[idx] : rdata.rwdt)) return State.Mixed;
147 idx = (idx^1)&1; // we are interested only in last bit, and we converted it to State here
148 // if our span is not fully inside, it can be either Empty or Mixed
149 if (idx == State.Solid && x0 < 0) return State.Mixed;
150 return cast(State)idx;
153 static private template IsGoodSDG(T) {
154 private import std.traits;
155 static private template IsGoodRT(T) { enum IsGoodRT = is(T == void) || is(T == bool) || is(T : int); }
156 static private template IsGoodAT(T) { enum IsGoodAT = is(T == int) || is(T == long) || is(T == uint) || is(T == ulong); }
157 enum IsGoodSDG = isCallable!T && IsGoodRT!(ReturnType!T) && (variadicFunctionStyle!T == Variadic.no) &&
158 Parameters!T.length == 2 && IsGoodAT!(Parameters!T[0]) && IsGoodAT!(Parameters!T[1]);
161 /// call delegate for each solid or empty span
162 /// for non-void returning delegates, return !0 to exit
163 auto spans(bool solids=true, DG) (int y, int x0, int x1, scope DG dg) const if (IsGoodSDG!DG) { return spansEnumerator!(DG, solids)(y, 0, x0, x1, dg); }
165 /// call delegate for each solid or empty span
166 /// for non-void returning delegates, return !0 to exit
167 /// `ofsx` will be automatically subtracted from `x0` and `x1` args, and added to `x0` and `x1` delegate args
168 auto spans(bool solids=true, DG) (int y, int ofsx, int x0, int x1, scope DG dg) const if (IsGoodSDG!DG) { return spansEnumerator!(DG, solids)(y, ofsx, x0, x1, dg); }
170 /// element of span range
171 static struct XPair { int x0, x1; }
173 /// get range of spans
174 auto spanRange(bool solids=true) (int y, int x0, int x1) nothrow @safe @nogc { return spanRange!solids(y, 0, x0, x1); }
176 /// ditto
177 auto spanRange(bool solids=true) (int y, int ofsx, int x0, int x1) nothrow @safe @nogc {
178 static struct SpanRange(bool solids) {
179 int ofsx, x0, x1, rwdt, idx;
180 ubyte eosNM; // empty(bit0), nomore(bit1) ;-)
181 XPair fpair; // front
182 const(SpanType)[] line;
184 nothrow @trusted @nogc:
185 this (ref Region reg, int y, int aofsx, int ax0, int ax1) {
186 ofsx = aofsx;
187 x0 = ax0;
188 x1 = ax1;
189 if (x0 > x1) { eosNM = 0x01; return; }
190 if (reg.rdata is null) {
191 static if (!solids) {
192 fpair.x0 = x0;
193 fpair.x1 = x1;
194 eosNM = 0x02;
195 } else {
196 eosNM = 0x01;
198 return;
200 rwdt = reg.rdata.rwdt;
201 x0 -= ofsx;
202 x1 -= ofsx;
203 if (y < 0 || y >= reg.rdata.rhgt || x1 < 0 || x0 >= rwdt || x1 < x0) {
204 static if (!solids) {
205 fpair.x0 = x0+ofsx;
206 fpair.x1 = x1+ofsx;
207 eosNM = 0x02;
208 } else {
209 eosNM = 0x01;
211 return;
213 if (reg.rdata.simple) {
214 if (reg.rdata.simpleSolid) {
215 static if (solids) {
216 if (x0 < 0) x0 = 0;
217 if (x1 >= rwdt) x1 = rwdt-1;
218 if (x0 <= x1) {
219 fpair.x0 = x0+ofsx;
220 fpair.x1 = x1+ofsx;
221 eosNM = 0x02;
222 } else {
223 eosNM = 0x01;
225 } else {
226 if (x0 < 0) {
227 fpair.x0 = x0+ofsx;
228 fpair.x1 = -1+ofsx;
229 eosNM = (x1 < rwdt ? 0x02 : 0x04);
230 } else {
231 if (x1 >= rwdt) {
232 fpair.x0 = rwdt+ofsx;
233 fpair.x1 = x1+ofsx;
234 eosNM = 0x02;
235 } else {
236 eosNM = 0x01;
240 } else {
241 static if (!solids) {
242 fpair.x0 = x0+ofsx;
243 fpair.x1 = x1+ofsx;
244 eosNM = 0x02;
245 } else {
246 eosNM = 0x01;
249 return;
251 // edge cases are checked
252 immutable ldofs = reg.rdata.lineofs[y];
253 immutable len = reg.rdata.data[ldofs];
254 debug assert(len > 1);
255 line = reg.rdata.data[ldofs+1..ldofs+len];
256 // beyond left border? move to first solid span
257 bool hasOne = false;
258 if (x0 < 0) {
259 int ex = (line[0] == 0 ? line[1]-1 : -1);
260 // is first span empty too?
261 if (ex >= x1) {
262 static if (!solids) {
263 fpair.x0 = x0+ofsx;
264 fpair.x1 = x1+ofsx;
265 eosNM = 0x02;
266 } else {
267 eosNM = 0x01;
269 return;
271 static if (!solids) {
272 fpair.x0 = x0+ofsx;
273 fpair.x1 = ex+ofsx;
274 hasOne = true;
275 if (x0 == -9) {
276 //import iv.writer; writeln("*");
279 x0 = ex+1;
281 static if (solids) { if (x1 >= rwdt) x1 = rwdt-1; }
282 //int idx = void; // will be initied in mixin
283 alias x = x0; // for mixin
284 mixin(FindSpanMixinStr!"idx");
285 debug assert(idx < line.length); // too far (the thing that should not be)
286 // move to "real" span, so sx is line[idx-1], ex+1 is line[idx]
287 if (line[idx] == x) ++idx;
288 if (!hasOne) popFront();
291 @property auto save () pure {
292 SpanRange!solids res;
293 res.ofsx = ofsx;
294 res.x0 = x0;
295 res.x1 = x1;
296 res.rwdt = rwdt;
297 res.idx = idx;
298 res.eosNM = eosNM;
299 res.fpair = fpair;
300 res.line = line;
301 return res;
304 @property bool empty () const pure { return ((eosNM&0x01) != 0); }
305 @property XPair front () const pure { return XPair(fpair.x0, fpair.x1); }
307 void popFront () {
308 if (eosNM&0x02) eosNM = 0x01;
309 if (eosNM&0x01) return;
310 // edge case
311 if (eosNM&0x04) {
312 if (x1 >= rwdt) {
313 static if (!solids) {
314 fpair.x0 = rwdt+ofsx;
315 fpair.x1 = x1+ofsx;
316 eosNM = 0x02;
317 } else {
318 eosNM = 0x01;
320 } else {
321 eosNM = 0x01;
323 return;
325 bool hasOne = false;
326 // process spans
327 while (x0 <= x1) {
328 int ex = line[idx]-1;
329 int cex = (ex < x1 ? ex : x1); // clipped ex
330 // emit part from x0 to ex if necessary
331 static if (solids) {
332 // current span is solid?
333 if (idx%2 == 0) {
334 fpair.x0 = x0+ofsx;
335 fpair.x1 = cex+ofsx;
336 hasOne = true;
338 } else {
339 // current span is empty?
340 if (idx%2 == 1) {
341 fpair.x0 = x0+ofsx;
342 fpair.x1 = (ex < rwdt-1 ? cex : x1)+ofsx;
343 hasOne = true;
344 if (ex == rwdt-1) { eosNM = 0x02; return; }
345 } else {
346 if (ex == rwdt-1) { x0 = rwdt; break; }
349 x0 = ex+1;
350 ++idx;
351 if (hasOne) return;
353 if (hasOne) return;
354 static if (!solids) {
355 if (x0 <= x1) {
356 fpair.x0 = x0+ofsx;
357 fpair.x1 = x1+ofsx;
358 eosNM = 0x02;
359 return;
362 eosNM = 0x01;
366 return SpanRange!solids(this, y, ofsx, x0, x1);
369 private:
370 // ////////////////////////////////////////////////////////////////////////// //
371 auto spansEnumerator(DG, bool solids) (int y, int ofsx, int x0, int x1, scope DG dg) const {
372 import std.traits : ReturnType;
373 static if (is(ReturnType!DG == void)) {
374 enum ReturnFail = "return;";
375 enum DgCall(string args) = "dg("~args~");";
376 } else {
377 static if (is(ReturnType!DG == bool)) enum ReturnFail = "return false;"; else enum ReturnFail = "return 0;";
378 enum DgCall(string args) = "if (auto xres = dg("~args~")) return xres;";
380 if (x0 > x1 || dg is null) mixin(ReturnFail);
381 if (rdata is null) {
382 static if (!solids) dg(x0, x1);
383 mixin(ReturnFail);
385 x0 -= ofsx;
386 x1 -= ofsx;
387 if (y < 0 || y >= rdata.rhgt || x1 < 0 || x0 >= rdata.rwdt || x1 < x0) {
388 static if (!solids) { mixin(DgCall!"x0+ofsx, x1+ofsx"); }
389 mixin(ReturnFail);
391 if (rdata.simple) {
392 if (rdata.simpleSolid) {
393 static if (solids) {
394 if (x0 < 0) x0 = 0;
395 if (x1 >= rdata.rwdt) x1 = rdata.rwdt-1;
396 if (x0 <= x1) { mixin(DgCall!"x0+ofsx, x1+ofsx"); }
397 } else {
398 if (x0 < 0) { mixin(DgCall!"x0+ofsx, -1+ofsx"); }
399 if (x1 >= rdata.rwdt) { mixin(DgCall!"rdata.rwdt+ofsx, x1+ofsx"); }
401 } else {
402 static if (!solids) { mixin(DgCall!"x0+ofsx, x1+ofsx"); }
404 mixin(ReturnFail);
406 immutable ldofs = rdata.lineofs[y];
407 immutable len = rdata.data[ldofs];
408 debug assert(len > 1);
409 auto line = rdata.data[ldofs+1..ldofs+len];
410 // beyond left border? move to first solid span
411 if (x0 < 0) {
412 int ex = (rdata.data[ldofs+1] == 0 ? rdata.data[ldofs+2]-1 : -1);
413 // is first span empty too?
414 if (ex >= x1) { static if (!solids) { mixin(DgCall!"x0+ofsx, x1+ofsx"); } mixin(ReturnFail); }
415 static if (!solids) { mixin(DgCall!"x0+ofsx, ex+ofsx"); }
416 x0 = ex+1;
418 static if (solids) { if (x1 >= rdata.rwdt) x1 = rdata.rwdt-1; }
419 int idx = void; // will be initied in mixin
420 alias x = x0; // for mixin
421 mixin(FindSpanMixinStr!"idx");
422 debug assert(idx < line.length); // too far (the thing that should not be)
423 // move to "real" span, so sx is line[idx-1], ex+1 is line[idx]
424 if (line[idx] == x) ++idx;
425 // process spans
426 while (x0 <= x1) {
427 int ex = line[idx]-1;
428 int cex = (ex < x1 ? ex : x1); // clipped ex
429 // emit part from x0 to ex if necessary
430 static if (solids) {
431 // current span is solid?
432 if (idx%2 == 0) { mixin(DgCall!"x0+ofsx, cex+ofsx"); }
433 } else {
434 // current span is empty?
435 if (idx%2 == 1) {
436 { mixin(DgCall!"x0+ofsx, (ex < rdata.rwdt-1 ? cex : x1)+ofsx"); }
437 if (ex == rdata.rwdt-1) mixin(ReturnFail);
438 } else {
439 if (ex == rdata.rwdt-1) { x0 = rdata.rwdt; break; }
442 x0 = ex+1;
443 ++idx;
444 //static if (!solids) { if (x0 == rdata.rwdt) break; }
446 static if (!solids) { if (x0 <= x1) { mixin(DgCall!"x0+ofsx, x1+ofsx"); } }
447 mixin(ReturnFail);
450 // ////////////////////////////////////////////////////////////////////////// //
451 // find element index
452 // always returns index of key which is >= `x`
453 private enum FindSpanMixinStr(string minAndRes) = "{
454 ("~minAndRes~") = 0;
455 int max = cast(int)line.length;
456 while (("~minAndRes~") < max) {
457 int mid = (("~minAndRes~")+max)/2; // ignore possible overflow, it can't happen here
458 debug assert(mid < max);
459 if (line[mid] < x) ("~minAndRes~") = mid+1; else max = mid;
461 //return ("~minAndRes~"); // actually, key is found if (max == min/*always*/ && min < line.length && line[min] == x)
464 // ////////////////////////////////////////////////////////////////////////// //
465 // punch a hole, patch a hole
466 // mode: "punch", "patch"
467 //FIXME: overflows
468 void doPunchPatch(string mode) (int x, int y, int w=1, int h=1) nothrow @trusted {
469 static assert(mode == "punch" || mode == "patch", "Region: invalid mode: "~mode);
470 if (rdata is null) return;
471 static if (mode == "punch") {
472 if (empty) return;
473 } else {
474 if (solid) return;
476 if (w < 1 || h < 1) return;
477 if (x >= rdata.rwdt || y >= rdata.rhgt) return;
478 //TODO: overflow check
479 if (x < 0) {
480 if (x+w <= 0) return;
481 w += x;
482 x = 0;
484 if (y < 0) {
485 if (y+h <= 0) return;
486 h += y;
487 y = 0;
489 int x1 = x+w-1;
490 if (x1 >= rdata.rwdt) x1 = rdata.rwdt-1;
491 debug assert(x <= x1);
492 int y1 = y+h-1;
493 if (y1 >= rdata.rhgt) y1 = rdata.rhgt-1;
494 debug assert(y <= y1);
495 foreach (int cy; y..y1+1) doPunchPatchLine!mode(cy, x, x1);
499 // ////////////////////////////////////////////////////////////////////////// //
500 void makeRoom (usize ofs, ssize count) nothrow @trusted {
501 import core.stdc.string : memmove;
502 debug assert(ofs <= rdata.data.length);
503 if (count > 0) {
504 // make room
505 // `assumeSafeAppend` was already called in caller
506 //rdata.data.assumeSafeAppend.length += count;
507 rdata.data.length += count;
508 if (ofs+count < rdata.data.length) memmove(rdata.data.ptr+ofs+count, rdata.data.ptr+ofs, SpanType.sizeof*(rdata.data.length-ofs-count));
509 } else if (count < 0) {
510 // remove rdata.data
511 count = -count;
512 debug assert(ofs+count <= rdata.data.length);
513 if (ofs+count == rdata.data.length) {
514 rdata.data.length = ofs;
515 } else {
516 immutable auto left = rdata.data.length-ofs-count;
517 memmove(rdata.data.ptr+ofs, rdata.data.ptr+ofs+count, SpanType.sizeof*(rdata.data.length-ofs-count));
518 rdata.data.length -= count;
520 //rdata.data.assumeSafeAppend; // in case we will want to grow later
524 // replace span data at plofs with another data from spofs, return # of bytes added (or removed, if negative)
525 ssize replaceSpanData (usize plofs, usize spofs) nothrow @trusted {
526 //import core.stdc.string : memcpy;
527 debug assert(spofs < rdata.data.length && spofs+rdata.data[spofs] == rdata.data.length);
528 debug assert(plofs <= spofs && plofs+rdata.data[plofs] <= spofs);
529 if (plofs == spofs) return 0; // nothing to do; just in case
530 auto oldlen = rdata.data[plofs];
531 auto newlen = rdata.data[spofs];
532 // same length?
533 ssize ins = cast(ssize)newlen-cast(ssize)oldlen;
534 if (ins) {
535 makeRoom(plofs, ins);
536 spofs += ins;
538 if (newlen > 0) rdata.data[plofs..plofs+newlen] = rdata.data[spofs..spofs+newlen]; //memcpy(rdata.data.ptr+plofs, rdata.data.ptr+spofs, SpanType.sizeof*newlen);
539 return ins;
542 // insert span data from spofs at plofs
543 void insertSpanData (usize plofs, usize spofs) nothrow @trusted {
544 //import core.stdc.string : memcpy;
545 debug assert(spofs < rdata.data.length && spofs+rdata.data[spofs] == rdata.data.length);
546 debug assert(plofs <= spofs);
547 if (plofs == spofs) return; // nothing to do; just in case
548 auto newlen = rdata.data[spofs];
549 makeRoom(plofs, newlen);
550 spofs += newlen;
551 rdata.data[plofs..plofs+newlen] = rdata.data[spofs..spofs+newlen];
552 //memcpy(rdata.data.ptr+plofs, rdata.data.ptr+spofs, SpanType.sizeof*newlen);
555 bool isEqualLines (int y0, int y1) nothrow @trusted @nogc {
556 import core.stdc.string : memcmp;
557 if (y0 < 0 || y1 < 0 || y0 >= rdata.rhgt || y1 >= rdata.rhgt) return false;
558 auto ofs0 = rdata.lineofs[y0];
559 auto ofs1 = rdata.lineofs[y1];
560 if (rdata.data[ofs0] != rdata.data[ofs1]) return false;
561 return (memcmp(rdata.data.ptr+ofs0, rdata.data.ptr+ofs1, SpanType.sizeof*rdata.data[ofs0]) == 0);
564 // all args must be valid
565 // [x0..x1]
566 void doPunchPatchLine(string mode) (int y, int x0, int x1) nothrow @trusted {
567 static if (mode == "patch") {
568 if (rdata.simple && rdata.simpleSolid) return; // no need to patch completely solid region
569 } else {
570 if (rdata.simple && !rdata.simpleSolid) return; // no need to patch completely empty region
573 // check if we really have to do anything here
574 static if (mode == "patch") {
575 if (spanState(y, x0, x1) == State.Solid) return;
576 //enum psmode = true;
577 enum op = CombineOp.Or;
578 } else {
579 if (spanState(y, x0, x1) == State.Empty) return;
580 //enum psmode = false;
581 enum op = CombineOp.Cut;
584 doCombine(y, (uint lofs, ref SpanType[] dptr) nothrow @trusted {
585 // note that after `assumeSafeAppend` we can increase length without further `assumeSafeAppend` calls
586 debug(region_more_prints) { import core.stdc.stdio : printf; printf("op=%d; x0=%d; x1=%d; rwdt=%d\n", cast(int)op, x0, x1, rdata.rwdt); }
587 SpanType dsp = cast(SpanType)(x1-x0+1);
588 debug(region_more_prints) {
589 import core.stdc.stdio : printf;
590 auto cspd = CSPD(op, &dsp, x1-x0+1, x0);
591 while (!cspd.empty) {
592 printf(" (%d,%d,%d)", cspd.sx, cspd.ex, (cspd.solid ? 1 : 0));
593 cspd.popFront();
595 printf("\n");
597 combineSpans(
598 (int x) nothrow @trusted { dptr ~= cast(SpanType)x; },
599 CSPD(CombineOp.Or, rdata.data.ptr+lofs+1, rdata.rwdt), // base span
600 CSPD(op, &dsp, x1-x0+1, x0),
605 // `combine`: `lofs` is starting index in `rdata.data` for base line (i.e. length element)
606 // it should build a new valid line data, starting from `rdata.data.length`, not including line length tho
607 // all args must be valid
608 void doCombine() (int y, scope void delegate (uint lofs, ref SpanType[] dptr) nothrow @trusted combine) nothrow @trusted {
609 // bad luck, build new line
610 cow!true();
611 if (rdata.simple) {
612 // build complex region rdata.data
613 if (rdata.lineofs is null) {
614 rdata.lineofs.length = rdata.rhgt; // allocate and clear
615 } else {
616 if (rdata.lineofs.length < rdata.rhgt) rdata.lineofs.assumeSafeAppend;
617 rdata.lineofs.length = rdata.rhgt;
618 rdata.lineofs[] = 0; // clear
620 rdata.data.length = 0;
621 if (rdata.simpleSolid) {
622 rdata.data.assumeSafeAppend ~= 2; // length
623 } else {
624 rdata.data.assumeSafeAppend ~= 3; // length
625 rdata.data ~= 0; // dummy solid
627 rdata.data ~= cast(SpanType)rdata.rwdt; // the only span
628 rdata.simple = false;
631 auto lofs = rdata.lineofs[y]; // current line offset
632 int lsize = rdata.data.ptr[lofs]; // current line size
633 auto tmppos = cast(uint)rdata.data.length; // starting position of the new line data
635 //patchSpan!psmode(lofs+1, x0, x1);
636 rdata.data.assumeSafeAppend ~= 0; // length
637 combine(lofs, rdata.data);
638 debug(region_more_prints) { import core.stdc.stdio : printf; printf("LEN=%d\n", cast(int)(rdata.data.length-tmppos)); }
639 if (rdata.data.length-tmppos > SpanType.max) assert(0, "region internal error: line data too big");
640 rdata.data.ptr[tmppos] = cast(SpanType)(rdata.data.length-tmppos);
642 debug(region_more_prints) {
643 import core.stdc.stdio : printf;
644 foreach (SpanType t; rdata.data[tmppos..$]) printf(" %u", cast(uint)t);
645 printf("\n");
648 int newsize = rdata.data[tmppos]; // size of the new line
650 // was this line first in slab?
651 auto prevofs = (y > 0 ? rdata.lineofs[y-1] : -1);
652 auto nextofs = (y+1 < rdata.rhgt ? rdata.lineofs[y+1] : -2);
654 // place new line data, breaking span if necessary
655 if (prevofs != lofs && nextofs != lofs) {
656 // we were a slab on our own?
657 // replace line
658 auto delta = replaceSpanData(lofs, tmppos);
659 tmppos += delta;
660 if (delta) foreach (ref ofs; rdata.lineofs[y+1..$]) ofs += delta;
661 } else if (prevofs != lofs && nextofs == lofs) {
662 // we were a slab start
663 // insert at lofs
664 insertSpanData(lofs, tmppos);
665 tmppos += newsize;
666 foreach (ref ofs; rdata.lineofs[y+1..$]) ofs += newsize;
667 } else if (prevofs == lofs && nextofs != lofs) {
668 // we were a slab end
669 // insert after lofs
670 lofs += lsize;
671 insertSpanData(lofs, tmppos);
672 tmppos += newsize;
673 rdata.lineofs[y] = lofs;
674 foreach (ref ofs; rdata.lineofs[y+1..$]) ofs += newsize;
675 } else {
676 //import core.stdc.string : memcpy;
677 // we were a slab brick
678 debug assert(prevofs == lofs && nextofs == lofs);
679 // the most complex case
680 // insert us after lofs, insert slab start after us, fix slab and offsets
681 // insert us
682 lofs += lsize;
683 insertSpanData(lofs, tmppos);
684 tmppos += newsize;
685 rdata.lineofs[y] = lofs;
686 // insert old slab start
687 lofs += newsize;
688 lsize = rdata.data[prevofs];
689 makeRoom(lofs, lsize);
690 //memcpy(rdata.data.ptr+lofs, rdata.data.ptr+prevofs, SpanType.sizeof*lsize);
691 rdata.data[lofs..lofs+lsize] = rdata.data[prevofs..prevofs+lsize];
692 // fix current slab
693 int ny = y+1;
694 while (ny < rdata.rhgt && rdata.lineofs[ny] == prevofs) rdata.lineofs[ny++] = lofs;
695 // fix offsets
696 newsize += lsize; // simple optimization
697 while (ny < rdata.rhgt) rdata.lineofs[ny++] += newsize;
698 newsize -= lsize;
701 // remove extra data
702 lofs = rdata.lineofs[$-1];
703 rdata.data.length = lofs+rdata.data[lofs];
705 // now check if we can join slabs
706 // of course, this is somewhat wasteful, but if we'll combine this
707 // check with previous code, the whole thing will explode to an
708 // unmaintainable mess; anyway, we aren't on ZX Spectrum
710 bool upequ = isEqualLines(y-1, y);
711 bool dnequ = isEqualLines(y+1, y);
712 if (upequ || dnequ) {
713 rdata.data.assumeSafeAppend; // we have to call it after shrinking
714 lofs = rdata.lineofs[y];
715 debug assert(rdata.data[lofs] == newsize);
716 makeRoom(lofs, -newsize); // drop us
717 if (upequ && dnequ) {
718 // join prev and next slabs by removing two lines...
719 auto pofs = rdata.lineofs[y-1];
720 makeRoom(lofs, -newsize); // drop next line
721 newsize *= 2;
722 // and fixing offsets
723 rdata.lineofs[y++] = pofs;
724 auto sofs = rdata.lineofs[y];
725 while (y < rdata.rhgt && rdata.lineofs[y] == sofs) rdata.lineofs[y++] = pofs;
726 } else if (upequ) {
727 // join prev slab
728 rdata.lineofs[y] = rdata.lineofs[y-1];
729 ++y;
730 } else if (dnequ) {
731 // lead next slab
732 auto sofs = rdata.lineofs[++y];
733 while (y < rdata.rhgt && rdata.lineofs[y] == sofs) rdata.lineofs[y++] = lofs;
735 // fix offsets
736 foreach (ref ofs; rdata.lineofs[y..$]) ofs -= newsize;
740 // check if we can collapse this region
741 if (rdata.data.length == 2) {
742 if (rdata.data.ptr[0] != 2 || rdata.data.ptr[1] != rdata.rwdt) return;
743 } else if (rdata.data.length == 3) {
744 if (rdata.data.ptr[0] != 3 || rdata.data.ptr[1] != 0 || rdata.data.ptr[2] != rdata.rwdt) return;
745 } else {
746 return;
748 foreach (immutable ofs; rdata.lineofs[1..$]) if (ofs != 0) return;
750 rdata.simple = true;
751 //static if (mode == "patch") rdata.simpleSolid = true; else rdata.simpleSolid = false;
752 rdata.simpleSolid = (rdata.data.length == 2);
753 rdata.lineofs.length = 0; // we may need it later, so keep it
756 static struct CSPD {
757 nothrow @trusted @nogc:
758 const(SpanType)* data;
759 int width; // to detect span end
760 int xofs;
761 CombineOp op; // operation
762 bool dsolid; // current span
763 int csx;
765 this (CombineOp aop, const(SpanType)* adata, int awdt, int axofs=0) {
766 // if first span is zero-sized, this region starts with empty span
767 op = aop;
768 width = awdt;
769 xofs = axofs;
770 if (*adata == 0) {
771 dsolid = false;
772 ++adata;
773 } else {
774 dsolid = true;
776 data = adata;
779 this() (CombineOp aop, auto ref Region rg, int axofs=0) {
780 this(aop, rg.ldata.ptr, rg.width, axofs);
783 @disable this (this); // no copies
785 @property bool empty () const pure { pragma(inline, true); return (data is null); }
786 @property bool solid () const pure { pragma(inline, true); return dsolid; }
787 @property int sx () const pure { pragma(inline, true); return xofs+csx; }
788 @property int ex () const pure { pragma(inline, true); return xofs+(*data)-1; }
789 void popFront () {
790 pragma(inline, true);
791 csx = *data++;
792 if (csx >= width) data = null;
793 dsolid = !dsolid;
797 // spans[0] should have `int .width`, `empty`, `popFront`, `sx`, `ex`, `solid`
798 // others sould have: `empty`, `popFront`, `sx`, `ex`, `solid`, `op`
799 // spans[0] should always start at 0 (i.e. it is alpha and omega)
800 static void combineSpans(SPR...) (scope void delegate (int x) nothrow @safe putX, auto ref SPR spans) if (SPR.length > 1) {
801 bool lastsolid = true; // it's ok
802 int lastsx = 0; // it's ok
804 void pushSpan() (int ex, bool solid) {
805 debug(region_more_prints) {} else pragma(inline, true);
806 //debug(region_more_prints) { import core.stdc.stdio : printf; printf(" ex=%d; solid=%d; lastsx=%d; lastsolid=%d\n", ex, (solid ? 1 : 0), lastsx, (lastsolid ? 1 : 0)); }
807 //debug if (ex <= lastsx) { import core.stdc.stdio : printf; printf("ex=%d; lastsx=%d\n", ex, lastsx); }
808 debug assert(ex >= lastsx);
809 if (solid != lastsolid) {
810 lastsolid = solid;
811 putX(lastsx); // new span starts here
812 debug(region_more_prints) { import core.stdc.stdio : printf; printf(" EMIT: %d\n", lastsx); }
814 lastsx = ex+1;
817 debug assert(!spans[0].empty);
818 debug assert(spans[0].sx == 0);
819 immutable sp0w = spans[0].width;
820 int cursx = 0;
821 while (!spans[0].empty) {
822 // process other spans
823 bool seenAliveSpan = false;
824 bool nsolid = spans[0].solid;
825 int nex = spans[0].ex;
826 foreach (ref sp; spans[1..$]) {
827 while (!sp.empty && sp.ex < cursx) sp.popFront();
828 if (sp.empty) continue;
829 seenAliveSpan = true;
830 debug(region_more_prints) { import core.stdc.stdio : printf; printf(" cursx=%d; nex=%d; nsolid=%d; sp.sx=%d; sp.ex=%d; sp.solid=%d\n", cursx, nex, (nsolid ? 1 : 0), sp.sx, sp.ex, (sp.solid ? 1 : 0)); }
831 //debug if (sp.sx > cursx) { import core.stdc.stdio : printf; printf("cursx=%d; sp.sx=%d; sp.ex=%d; sp.solid=%d\n", cursx, sp.sx, sp.ex, (sp.solid ? 1 : 0)); }
832 //debug assert(sp.sx <= cursx);
833 if (sp.sx > nex) continue; // too far
834 if (sp.sx > cursx) { nex = sp.sx-1; continue; } // partial
835 // do logic op
836 final switch (sp.op) {
837 case CombineOp.Or: nsolid = nsolid || sp.solid; break;
838 case CombineOp.And: nsolid = nsolid && sp.solid; break;
839 case CombineOp.Xor: if (sp.solid) nsolid = !nsolid; break;
840 case CombineOp.Cut: if (sp.solid) nsolid = false; break;
841 case CombineOp.NCut: if (!sp.solid) nsolid = false; break;
843 if (sp.ex < nex) nex = sp.ex;
845 pushSpan(nex, nsolid);
846 if (!seenAliveSpan) {
847 // no more alive spans, process span0 till the end
848 debug(region_more_prints) { import core.stdc.stdio : printf; printf(" NM!\n"); }
849 if (nex < spans[0].ex) pushSpan(spans[0].ex, spans[0].solid); // finish current span
850 for (;;) {
851 spans[0].popFront();
852 if (spans[0].empty) break;
853 pushSpan(spans[0].ex, spans[0].solid);
855 // put sentinel
856 debug assert(lastsx <= sp0w);
857 putX(sp0w);
858 return;
860 if (nex < spans[0].ex) {
861 // something was done, and first slab of span0 is not completely eaten
862 cursx = nex+1;
863 } else {
864 // either no alive spans, or first slab of span0 is completely eaten
865 spans[0].popFront();
866 if (spans[0].empty) { putX(sp0w); return; } // done
867 cursx = spans[0].sx;
870 // put sentinel
871 debug assert(lastsx <= sp0w);
872 putX(sp0w);
875 private:
876 usize rdatap = 0; // hide from GC
878 @property inout(RData)* rdata () inout pure const nothrow @trusted @nogc { static if (__VERSION__ > 2067) pragma(inline, true); return cast(RData*)rdatap; }
880 void decRC () nothrow @trusted @nogc {
881 if (rdatap != 0) {
882 if (--rdata.rc == 0) {
883 import core.memory : GC;
884 import core.stdc.stdlib : free;
885 GC.removeRange(rdata);
886 free(rdata);
888 rdatap = 0; // just in case
892 // copy-on-write mechanics
893 void cow(bool doCopyData) () nothrow @trusted {
894 auto srcd = rdata;
895 if (srcd is null || srcd.rc != 1) {
896 import core.memory : GC;
897 import core.stdc.stdlib : malloc, free;
898 import core.stdc.string : memcpy;
899 auto dstd = cast(RData*)malloc(RData.sizeof);
900 if (dstd is null) assert(0, "Region: out of memory"); // this is unlikely, and hey, just crash
901 // init with default values
902 //*dstd = RData.init;
903 static immutable RData initr = RData.init;
904 memcpy(dstd, &initr, RData.sizeof);
905 //(*dstd).__ctor();
906 if (srcd !is null) {
907 // copy
908 dstd.rwdt = srcd.rwdt;
909 dstd.rhgt = srcd.rhgt;
910 dstd.simple = srcd.simple;
911 dstd.simpleSolid = srcd.simpleSolid;
912 dstd.lineofs = null;
913 dstd.data = null;
914 dstd.rc = 1;
915 static if (doCopyData) {
916 if (!dstd.simple) {
917 // copy complex region
918 if (srcd.lineofs.length) dstd.lineofs = srcd.lineofs.dup;
919 if (srcd.data.length) dstd.data = srcd.data.dup;
922 --srcd.rc;
923 assert(srcd.rc > 0);
925 rdatap = cast(usize)dstd;
926 GC.addRange(rdata, RData.sizeof, typeid(RData));
930 // region data
931 // all data is here, so passing region struct around is painless
932 static struct RData {
933 int rwdt, rhgt; // width and height
934 bool simple = true; // is this region a simple one (i.e. rectangular, without holes)?
935 bool simpleSolid = true; // if it is simple, is it solid or empty?
936 //WARNING! the following arrays should NEVER be shared!
937 uint[] lineofs; // line data offset in data[]
938 SpanType[] data;
939 // data format for each line:
940 // len, data[len-1]
941 // line items: list of increasing x coords; each coord marks start of next region
942 // all even regions are solid, i.e.
943 // 0..line[0]-1: solid region
944 // line[0]..line[1]-1: transparent (empty) region
945 // etc.
946 // note that line[$-1] is always rwdt; it's used as sentinel too
947 // `line[0] == 0` means that first span is transparent (empty)
948 // (i.e. region starts from transparent span)
949 int rc = 1; // refcount
954 // ////////////////////////////////////////////////////////////////////////// //
955 version(sdpy_region_test) {
956 //static assert(0);
957 import iv.writer;
960 void dumpData (ref Region reg) {
961 import iv.writer;
962 if (reg.rdata.simple) { writeln("simple ", (reg.rdata.simpleSolid ? "solid" : "empty"), " region"); return; }
963 foreach (immutable y, uint ofs; reg.rdata.lineofs) {
964 if (y > 0 && reg.rdata.lineofs[y-1] == ofs) {
965 writefln!"%5s:%3s: ditto"(ofs, y);
966 } else {
967 writef!"%5s:%3s: len="(ofs, y);
968 write(reg.rdata.data[ofs]);
969 auto end = ofs+reg.rdata.data[ofs];
970 ++ofs;
971 while (ofs < end) write("; ", reg.rdata.data[ofs++]);
972 writeln;
978 void checkLineOffsets (ref Region reg) {
979 if (reg.rdata.simple) return;
980 foreach (immutable idx; 1..reg.rdata.lineofs.length) {
981 if (reg.rdata.lineofs[idx-1] > reg.rdata.lineofs[idx]) assert(0, "invalid line offset data");
982 // check for two equal, but unmerged lines
983 if (reg.rdata.lineofs[idx-1] != reg.rdata.lineofs[idx]) {
984 import core.stdc.string : memcmp;
985 if (reg.rdata.data[reg.rdata.lineofs[idx-1]] == reg.rdata.data[reg.rdata.lineofs[idx]] &&
986 memcmp(reg.rdata.data.ptr+reg.rdata.lineofs[idx-1], reg.rdata.data.ptr+reg.rdata.lineofs[idx], reg.SpanType.sizeof*reg.rdata.data[reg.rdata.lineofs[idx]]) == 0)
988 dumpData(reg);
989 assert(0, "found two identical, but not merged lines");
991 if (reg.rdata.data[reg.rdata.lineofs[idx-1]] < 2) assert(0, "bad data (0)");
992 if (reg.rdata.data[reg.rdata.lineofs[idx]] < 2) assert(0, "bad data (1)");
998 void buildBitmap (ref Region reg, int[] bmp) {
999 if (reg.rdata.simple) {
1000 bmp[0..reg.width*reg.height] = (reg.rdata.simpleSolid ? 1 : 0);
1001 return;
1003 bmp[0..reg.width*reg.height] = 42;
1004 foreach (immutable y, uint ofs; reg.rdata.lineofs) {
1005 usize a = y*reg.width;
1006 usize len = reg.rdata.data[ofs++];
1007 if (len < 1) assert(0, "invalid span");
1008 int sx = 0;
1009 bool solid = true;
1010 if (reg.rdata.data[ofs] == 0) { solid = false; ++ofs; }
1011 while (sx != reg.width) {
1012 // we should not have two consecutive zero-width spans
1013 if (reg.rdata.data[ofs] == 0 || reg.rdata.data[ofs] <= sx) {
1014 //foreach (immutable idx; 0..reg.rdata.data.length) if (reg.rdata.data[idx] >= 0) writeln(idx, ": ", reg.rdata.data[idx]); else break;
1015 //assert(reg.rdata.data[ofs+1] != 0);
1016 assert(0, "invalid span");
1018 int ex = reg.rdata.data[ofs++];
1019 bmp[a+sx..a+ex] = (solid ? 1 : 0);
1020 solid = !solid;
1021 sx = ex;
1023 debug assert(sx == reg.width);
1025 foreach (immutable v; bmp[0..reg.width*reg.height]) if (v == 42) assert(0, "invalid region data");
1029 int[] buildCoords (int[] bmp, int type, int x0, int x1) {
1030 bool isSolid (int x) { return (x >= 0 && x < bmp.length && bmp[x] != 0); }
1031 int[] res;
1032 while (x0 <= x1) {
1033 while (x0 <= x1 && type != isSolid(x0)) ++x0;
1034 if (x0 > x1) break;
1035 res ~= x0; // start
1036 while (x0 <= x1 && type == isSolid(x0)) ++x0;
1037 res ~= x0-1;
1039 return res;
1043 void fuzzyEnumerator () {
1044 import std.random;
1045 auto reg = Region(uniform!"[]"(1, 128), 1);
1046 int[] bmp, ebmp;
1047 bmp.length = reg.width*reg.height;
1048 ebmp.length = reg.width*reg.height;
1049 if (uniform!"[]"(0, 1)) {
1050 reg.rdata.simpleSolid = false;
1051 ebmp[] = 0; // default is empty
1052 } else {
1053 ebmp[] = 1; // default is solid
1055 foreach (immutable tx0; 0..1000) {
1056 checkLineOffsets(reg);
1057 buildBitmap(reg, bmp[]);
1058 version(sdpy_aggressive_gc) { import core.memory : GC; GC.collect(); }
1059 debug(region_more_prints) {
1060 if (1/*bmp[] != ebmp[]*/) {
1061 assert(bmp.length == ebmp.length);
1062 writeln;
1063 foreach (immutable idx; 0..bmp.length) write(bmp[idx]); writeln;
1064 foreach (immutable idx; 0..ebmp.length) write(ebmp[idx]); writeln;
1067 assert(bmp[] == ebmp[]);
1068 foreach (immutable trx; 0..200) {
1069 //writeln("*");
1070 int x0 = uniform!"[)"(-10, reg.width+10);
1071 int x1 = uniform!"[)"(-10, reg.width+10);
1072 if (x0 > x1) { auto t = x0; x0 = x1; x1 = t; }
1073 int[] coords;
1074 int type = uniform!"[]"(0, 1);
1075 if (type == 0) {
1076 reg.spans!false(0, x0, x1, (int x0, int x1) { coords ~= x0; coords ~= x1; });
1077 } else {
1078 reg.spans!true(0, x0, x1, (int x0, int x1) { coords ~= x0; coords ~= x1; return 0; });
1080 auto ecr = buildCoords(bmp[], type, x0, x1);
1081 assert(ecr[] == coords[]);
1082 // now check enumerator range
1083 coords.length = 0;
1084 if (type == 0) {
1085 foreach (ref pair; reg.spanRange!false(0, x0, x1)) { coords ~= pair.x0; coords ~= pair.x1; }
1086 } else {
1087 foreach (ref pair; reg.spanRange!true(0, x0, x1)) { coords ~= pair.x0; coords ~= pair.x1; }
1089 if (ecr[] != coords[]) {
1090 import std.stdio : writeln;
1091 writeln("\ntype=", type);
1092 writeln("ecr=", ecr);
1093 writeln("crd=", coords);
1095 assert(ecr[] == coords[]);
1096 version(sdpy_aggressive_gc) { import core.memory : GC; GC.collect(); }
1098 // now do random punch/patch
1100 int x = uniform!"[)"(0, reg.width);
1101 int y = uniform!"[)"(0, reg.height);
1102 int w = uniform!"[]"(0, reg.width);
1103 int h = uniform!"[]"(0, reg.height);
1104 int patch = uniform!"[]"(0, 1);
1105 debug(region_more_prints) { import core.stdc.stdio : printf; printf(":x0=%d; x1=%d; w=%d; solid=%d\n", x, x+w-1, w, patch); }
1106 if (patch) reg.patch(x, y, w, h); else reg.punch(x, y, w, h);
1107 version(sdpy_aggressive_gc) { import core.memory : GC; GC.collect(); }
1108 // fix ebmp
1109 foreach (int dy; y..y+h) {
1110 if (dy < 0) continue;
1111 if (dy >= reg.height) break;
1112 foreach (int dx; x..x+w) {
1113 if (dx < 0) continue;
1114 if (dx >= reg.width) break;
1115 ebmp[dy*reg.width+dx] = patch;
1123 //enum OneSeed = 1586553857;
1125 void main () {
1126 import iv.writer;
1127 import std.random;
1128 foreach (immutable trycount; 0..1000) {
1130 auto seed = unpredictableSeed;
1131 static if (is(typeof(OneSeed))) seed = OneSeed;
1132 rndGen.seed(seed);
1133 write("try: ", trycount, "; seed = ", seed, " ... ");
1135 fuzzyEnumerator();
1136 writeln("OK");
1137 static if (is(typeof(OneSeed))) break;