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