1

How to get the co-ordinates of the outline shape formed using smaller grid blocks.

For example, If I used 32x32 unit blocks for construct a shape (any shape). Then how can I get overall co-ordinates of the shape, including the negative spaces.

For example: One could arrange the blocks like this: (each block is 32x32 and coordinates refer to bottom left corner of the block)

Block 1 - (0,0)
BLock 2 - (32,0)
Block 3 - 64,0)
Block 4 - (64,32)
Block 5 - (64, 64)
BLock 6 - (32, 64)
BLock 6 - (0 64)
Block 7 - (0, 32)

Now you can see this will create an empty space in the middle.

So what I would like to know is, how to get the coordinates of the above shape such that I get:

Main Block = (0,0), (96,0), (0,96)
Empty space = (32,32), (64,32), (64,64), (32,64)

Is there any mathematical solution to this?

Eventually I will be doing complex shapes.

thanks

******** edit **** Hi,

How to deal with this condition?

<------------------^<----^
|                  ||    |
V------------------>|    |
<------^          /^|    |
|      |<------^ / ||    |
|      ||      |/  ||    |
V------>V------>V-->V---->

i would like the result to be like this

<-------------------<----^
|                        |
V      ^----------->     |
|      |          /      |
|      <-------^ /       |
|              |/        |
V------>------->--->----->
brainjam
  • 18,863
  • 8
  • 57
  • 82
ssdesign
  • 2,743
  • 6
  • 37
  • 53

3 Answers3

4

Think of each square as an outline comprised of four vectors going in a counter-clockwise chain.

<-----^
|     |
|     |
V----->

So for all the squares in your shape, take the union of their outline vectors. If two outline vectors in the union are identical but go in opposite directions, they cancel each other out and are removed from the union.

For example, for two squares that are side by side the union is 8 vectors

<-----^<-----^
|     ||     |
|     ||     |
V----->V----->

which reduces to 6 vectors because the two vertical vectors in the middle cancel:

<-----<-----^
|           |
|           |
V----->----->

For the example you gave, the result of this will be (after cancellations):

<-----<-----<-----^
|                 |
|                 |
V     ^----->     ^
|     |     |     |
|     |     |     |
V     <-----V     ^
|                 |
|                 |
V----->----->----->

You just have to connect up the vectors in the final reduced union to read off the outline paths. Note that the inner outline ("the hole") runs clockwise.

brainjam
  • 18,863
  • 8
  • 57
  • 82
  • Hi, That sound very promising. Basically I am trying to do this with PHP Arrays. I have not been able to find a good Vector class for PHP yet. btw. Any idea how to identify closed loops which are clockwise in direction and segregate them from anticlockwise loops? – ssdesign Aug 18 '10 at 02:57
  • WIll this logic work even if the spahes are odd shaped? For example. What if the second shape was a rectangle (half the height of first square). – ssdesign Aug 18 '10 at 07:08
  • @ssdesign, you don't really need a Vector class, just something that indicates start and end points, or start point+direction+length. You can search StackOverflow for tests that distinguish clockwise vs. counterclockwise. As for odd shapes, I guess you can have vectors partially cancelling one another - so 1.0up + 0.5down = 0.5up. – brainjam Aug 18 '10 at 14:59
  • Hi, I am not a Math person atall :) Its just that I have to deal with this situation while making a web application. So is it possible to give me some more hints on a couple of things? I tried searching StackOverflow about clockwise vs counterclockwise but didnt get anything useful. Anything i missed? Also I would like to know how to cancel vectors partially. --- thanks – ssdesign Aug 19 '10 at 04:32
  • @ssdesign, for CW and CCW, see http://stackoverflow.com/questions/1046542/how-to-represent-a-polygon-with-holes, http://stackoverflow.com/questions/1199428/determine-ordering-of-polygon-3d, http://stackoverflow.com/questions/1165647/how-to-determine-if-a-list-of-polygon-points-are-in-clockwise-order/1165943#1165943 – brainjam Aug 19 '10 at 14:50
  • @ssdesign, re partial vector cancellation, what part of "1.0 up + 0.5 down = 0.5 up" don't you understand? – brainjam Aug 19 '10 at 14:52
  • that part i understand. what i didnt understand was, just before the loops have been closed, end condition before the hole is created, how can i know this is the end? and after that, how to I extract the two separate polygons? – ssdesign Aug 19 '10 at 15:19
  • as an afterthought, would it help if I first get the outer shape using 'convex hull' and then would there be a way to find if there are holes inside the hull? edit**** Maybe not. – ssdesign Aug 19 '10 at 15:31
  • 1
    @ssdesign: You know that a loop is closing when the last vertex is the same as the starting vertex. Two outlines are separate if they don't have any vertices in common. – brainjam Aug 19 '10 at 16:40
  • Not really helpful (for me) since it doesn't provide any insight on how to implement this. It's obvious how to do this "graphically", not so, when all you have is just a number of points representing simple polygons and you want to unify/intersect/substract them. – Dan M. Jul 31 '16 at 21:52
  • @Dan: agreed. But the problem here is about finding the union of grid aligned squares. Union/intersection/difference of simple polygons is a larger topic. See the other answer here (http://stackoverflow.com/a/3501778/242848) for a link. – brainjam Aug 01 '16 at 16:31
2

You would probably need to focus on Boolean Polygon Operations, unions in your case. There are plenty of papers covering the 2D boolean polygon operations and constructive planar geometry, see the Wikipedia: http://en.wikipedia.org/wiki/Boolean_operations_on_polygons.

mbaitoff
  • 8,831
  • 4
  • 24
  • 32
0

I know this is very late to the discussion, but I recently had to deal with the same problem, and came up with the following algorithm, described in a somewhat high level here.

First, some terminology. As seen in the picture, we label the top left cell "r0c0" (i.e. row 0 column 0), and the one to the right "r0c1" and so on. We say that the edge to the left of rxcy starts at x,y and goes to x,(y+1) and so on.

enter image description here

The idea is to first find the points at which the outline should change direction. That is the corners of the shape. I did this by first making a 2d array of numbers where the number was 1 if there was a cell in that place, and 0 otherwise.

Then I looped over the 2d array, and found that the top left point of a cell should be included if either the cell above and the cell to the right were both not there, or if they were both there and the cell above and to the left was not there. Similarly for the three other corners of the cell. We also remember to label the points according to what intercardinal direction they are in their cell (north west, north east and so on)

After this we have a list of points. We then start by finding the top left point of those and traversing. We know to start going right after the top left point. Using the image, we go right from a north west point. We then find the point that has the same y coordinate, but an x-coordinate larger, but the least largest of the points to the right. We also know that the next corner we hit should have an intercardinal direction of north west or north east, as we can't go from north to west by going right.

In the picture we would hit the north east point at r3c6. We then know to go down after that, because going to a north east point from the right means going down afterwards. We continue like this until we can find no more points.

There might still be points left after all this. This means we have disjoint cells, or that there is a hole. So just do the whole thing again.

I get that this wall of text is quite difficult to follow along with, so here is some typescript code, that will hopefully make it a bit simpler (sorry, don't know php). If you have any questions, please reach out. Also, this code can probably be optimized.

The main function is the createOutlines function

type Position = {row: number; column: number};
type Dimensions = { rows: number; columns: number };

type Point = {
    x: number;
    y: number;
};

type Direction = 'up' | 'left' | 'right' | 'down';
type InterCardinal = 'nw' | 'ne' | 'sw' | 'se';

type OutlinePoint = {
    point: Point;
    interCardinal: InterCardinal;
};

function findOutlinePoints(
    positions: Position[],
    dimensions: Dimensions
): OutlinePoint[] {
    // Essentially a grid of 1 and undefined where it is 1 if there is a cell in that position
    // The JSON.parse(JSON.stringify()) part is just a deep copy, as javascript is quite weird
    const matrixOfPoints: (number | undefined)[][] = JSON.parse(JSON.stringify(Array(dimensions.rows).fill([])));

    positions.forEach(({ row, column }) => {
        matrixOfPoints[row][column] = 1;
    });

    const points: OutlinePoint[] = [];

    for (let rowIndex = 0; rowIndex < dimensions.rows; rowIndex++) {
        const row = matrixOfPoints[rowIndex];
        if (row.length === 0) {
            continue;
        }
        for (let columnIndex = 0; columnIndex < dimensions.columns; columnIndex++) {
            const cell = row[columnIndex];
            if (!cell) {
                continue;
            }

            // Find the values of cells around the center cell
            const nw = matrixOfPoints[rowIndex - 1]?.[columnIndex - 1];
            const n = matrixOfPoints[rowIndex - 1]?.[columnIndex];
            const ne = matrixOfPoints[rowIndex - 1]?.[columnIndex + 1];
            const w = matrixOfPoints[rowIndex]?.[columnIndex - 1];
            const e = matrixOfPoints[rowIndex]?.[columnIndex + 1];
            const sw = matrixOfPoints[rowIndex + 1]?.[columnIndex - 1];
            const s = matrixOfPoints[rowIndex + 1]?.[columnIndex];
            const se = matrixOfPoints[rowIndex + 1]?.[columnIndex + 1];

            // Add the points
            // Top left point
            if ((n == null && w == null) || (n != null && nw == null && w != null)) {
                // The north west point of this cell is a corner point, so add this point and specify that it is a north west (nw) point
                points.push({
                    point: { x: columnIndex, y: rowIndex },
                    interCardinal: 'nw'
                });
            }
            // Top right point
            if ((n == null && e == null) || (n != null && ne == null && e != null)) {
                points.push({
                    point: { x: columnIndex + 1, y: rowIndex },
                    interCardinal: 'ne'
                });
            }
            // Bottom left
            if ((w == null && s == null) || (w != null && sw == null && s != null)) {
                points.push({
                    point: { x: columnIndex, y: rowIndex + 1 },
                    interCardinal: 'sw'
                });
            }
            // Bottom right
            if ((e == null && s == null) || (e != null && se == null && s != null)) {
                points.push({
                    point: { x: columnIndex + 1, y: rowIndex + 1 },
                    interCardinal: 'se'
                });
            }
        }
    }

    return points;
}

// Finds the point that is left most, and of the left most points, the one that is highest. Also finds the index of that point in the list
function findTopLeftOutlinePoint(
    outlinePoints: OutlinePoint[]
): [OutlinePoint | undefined, number] {
    let topLeftPoint: OutlinePoint | undefined = undefined;
    let index = -1;
    outlinePoints.forEach((p, i) => {
        if (topLeftPoint == null) {
            topLeftPoint = p;
            index = i;
            return;
        }
        if (
            p.point.x < topLeftPoint.point.x ||
            (p.point.x <= topLeftPoint.point.x &&
                p.point.y < topLeftPoint.point.y)
        ) {
            index = i;
            topLeftPoint = p;
        }
    });
    return [topLeftPoint, index];
}

/** E.g. going, "up", coming to "nw", one has to go "right" */
const NextDirection: Record<Direction, Record<InterCardinal, Direction>> = {
    up: {
        nw: 'right',
        ne: 'left',
        sw: 'left',
        se: 'right'
    },
    down: {
        nw: 'left',
        ne: 'right',
        sw: 'right',
        se: 'left'
    },
    right: {
        nw: 'up',
        ne: 'down',
        sw: 'down',
        se: 'up'
    },
    left: {
        nw: 'down',
        ne: 'up',
        sw: 'up',
        se: 'down'
    }
};

// Given the previous point, and the direction, find the next point from the list of points
function findNextPoint(
    previousPointInPath: OutlinePoint,
    points: OutlinePoint[],
    direction: Direction
): [OutlinePoint, number] | undefined {
    // e.g. if coming from nw going right, we should find a point that has the same y coordinates, and has an interCardinal of ne or se
    let nextPointIndex: number | undefined;
    let nextPoint: OutlinePoint | undefined;
    switch (direction) {
        case 'right':
            // We are going "right"
            points.forEach((p, i) => {
                if (
                    // The next point should have the same y coordinate
                    p.point.y === previousPointInPath.point.y &&
                    // The next point should have a larger x coordinate
                    p.point.x > previousPointInPath.point.x &&
                    // If the previous point is north, then the next point should be north as well. Similar for south
                    p.interCardinal[0] === previousPointInPath.interCardinal[0]
                ) {
                    if (nextPoint == null) {
                        nextPoint = p;
                        nextPointIndex = i;
                        return;
                    } else if (p.point.x < nextPoint.point.x) {
                        // This is closer to the previous point than the one we already found
                        nextPoint = p;
                        nextPointIndex = i;
                        return;
                    }
                }
            });
            break;
        case 'left':
            points.forEach((p, i) => {
                if (
                    p.point.y === previousPointInPath.point.y &&
                    p.point.x < previousPointInPath.point.x &&
                    p.interCardinal[0] === previousPointInPath.interCardinal[0]
                ) {
                    if (nextPoint == null) {
                        nextPoint = p;
                        nextPointIndex = i;
                        return;
                    } else if (p.point.x > nextPoint.point.x) {
                        nextPoint = p;
                        nextPointIndex = i;
                        return;
                    }
                }
            });
            break;
        case 'up':
            points.forEach((p, i) => {
                if (
                    p.point.x === previousPointInPath.point.x &&
                    p.point.y < previousPointInPath.point.y &&
                    p.interCardinal[1] === previousPointInPath.interCardinal[1]
                ) {
                    if (nextPoint == null) {
                        nextPoint = p;
                        nextPointIndex = i;
                        return;
                    } else if (p.point.y > nextPoint.point.y) {
                        nextPoint = p;
                        nextPointIndex = i;
                        return;
                    }
                }
            });
            break;
        case 'down':
            points.forEach((p, i) => {
                if (
                    p.point.x === previousPointInPath.point.x &&
                    p.point.y > previousPointInPath.point.y &&
                    p.interCardinal[1] === previousPointInPath.interCardinal[1]
                ) {
                    if (nextPoint == null) {
                        nextPoint = p;
                        nextPointIndex = i;
                        return;
                    } else if (p.point.y < nextPoint.point.y) {
                        nextPoint = p;
                        nextPointIndex = i;
                        return;
                    }
                }
            });
            break;
    }
    // If we didn't find anything, we should close the loop
    if (nextPoint == null || nextPointIndex == null) return undefined;
    return [nextPoint, nextPointIndex];
}

// Find the oultine of cells in a grid.
function createOutlines(
    positions: Position[],
    dimensions: Dimensions
): OutlinePoint[][] {
    const points = findOutlinePoints(positions, dimensions);
    const paths: OutlinePoint[][] = [];

    while (points.length > 0) {
        // This loop creates new outlines until there are no points left
        const pathPoints: OutlinePoint[] = [];
        const [topLeftPoint, index] = findTopLeftOutlinePoint(points);
        if (topLeftPoint == null) return [];
        // Remove the top left point
        points.splice(index, 1);
        // And add it to the path
        pathPoints.push(topLeftPoint);

        let direction: Direction = 'up';

        while (true) {
            const previousPointInPath = pathPoints[pathPoints.length - 1];

            direction = NextDirection[direction][previousPointInPath.interCardinal];

            const nextPointInfo = findNextPoint(previousPointInPath, points, direction);
            if (nextPointInfo == null) {
                // We have reached the end
                pathPoints.push(topLeftPoint); // Add the first point to the end to make a loop
                paths.push(pathPoints);
                break;
            }
            const [nextPoint, nextPointIndex] = nextPointInfo;
            points.splice(nextPointIndex, 1);
            pathPoints.push(nextPoint);
        }
    }

    return paths;
}
Norse
  • 628
  • 8
  • 26