// both the outer outline and the outline of a hole are called a "trace" // should return outer outline first and then outline of holes srecord noeq RegionBorder_innerPoints(BWImage_FastRegions regions, int iRegion) extends AbstractSteppable { event newTrace(bool isHole); event foundPoint(Pt p); event traceDone; int w, x, y, dir; BWImage_FastRegions.RegionIterator it; BitSet seen; bool tracing; gettable bool tracingHole; // directions (0 = right, 1 = down, 2 = left, 3 = up) static Pt[] directions = { pt(1, 0), pt(0, 1), pt(-1, 0), pt(0, -1) // r, d, l, u }; void init { w = regions.w; seen = new BitSet; it = regions.regionIterator(iRegion); } public bool step() { if (seen == null) init(); if (tracing) { int pos = y*w+x; if (seen.get(pos)) { traceDone(); tracing = false; true; } seen.set(pos); foundPoint(x, y); for (int turn = 3; turn <= 6; turn++) { // try left, straight, right, back int newDir = (dir+turn) & 3; Pt d = directions[newDir]; int x2 = x+d.x, y2 = y+d.y; bool b = regions.inRegion(iRegion, x2, y2); ifdef RegionBorder_innerPoints_debug printVars(+x, +y, +dir, +turn, +newDir, +x2, +y2, +b); endifdef if (b) { x = x2; y = y2; dir = newDir; true; } } true; // i think this ends the trace in next iteration } else { // search for border pixel if (!it.next()) false; // done x = it.x(); y = it.y(); if (seen.get(y*w+x)) true; // seen pixel before // if pixel above is empty, walk to the right if (!regions.inRegion(iRegion, x, y-1)) ret true with startTrace(0); // if pixel on the left is empty, walk upwards if (!regions.inRegion(iRegion, x-1, y)) ret true with startTrace(3); // if pixel on the right is empty, walk downwards if (!regions.inRegion(iRegion, x+1, y)) ret true with startTrace(1); // if pixel below is empty, walk left if (!regions.inRegion(iRegion, x, y+1)) ret true with startTrace(2); // not a border pixel, continue search true; } } void startTrace(int dir) { this.dir = dir; set tracing; newTrace(tracingHole); set tracingHole; } void foundPoint(int x, int y) { foundPoint(pt(x, y)); } void runAndPrint { onNewTrace(hole -> print(!hole ? "new outline" : "new hole")); onTraceDone(-> print("traceDone")); onFoundPoint(p -> print("foundPoint " + p)); stepMaxWithStats(this, 10000); } }