Skip to content

Commit

Permalink
Fix swarm crashing and optimize swarm group counting with wrap disabled
Browse files Browse the repository at this point in the history
  • Loading branch information
IgorYeremin committed Apr 4, 2017
1 parent 8426fd4 commit 1b4f2a1
Showing 1 changed file with 42 additions and 21 deletions.
63 changes: 42 additions & 21 deletions src/main/java/org/cobweb/cobweb2/core/Topology.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ public Location getRandomLocation() {
}

public boolean isValidLocation(Location l) {
return l.x >= 0 && l.x < width
return l != null
&& l.x >= 0 && l.x < width
&& l.y >= 0 && l.y < height;
}

Expand Down Expand Up @@ -123,31 +124,51 @@ private Location getClosestWrapLocation(Location zero, Location target) {
public Set<Location> getArea(Location zero, float radius) {
Set<Location> result = new HashSet<Location>();

result.add(zero);
LocationDirection l = new LocationDirection(zero, NORTH);
if (!wrap) {
int x0 = Math.min(zero.x - (int)Math.ceil(radius), 0);
int x1 = Math.max(zero.x + (int)Math.ceil(radius), width - 1);
int y0 = Math.min(zero.y - (int)Math.ceil(radius), 0);
int y1 = Math.max(zero.y + (int)Math.ceil(radius), height - 1);

// walk around the zero point in increasingly larger rectangles
for (int r = 1; r <= radius; r++) {
// North-center point
l = getAdjacent(l);
result.add(l);

// length of walks along each side of the rectangle
// North-center to NE to SE to SW to NW, back to North-center
int[] sides = {r, r*2, r*2, r*2, r-1};

for (int side : sides) {
l = getTurnRightPosition(l);
for (int i = 0; i < side; i++) {
l = getAdjacent(l);
if (getDistance(zero, l) <= radius)
for (int x = x0; x < x1; x++) {
for (int y = y0; y < y1; y++) {
Location l = new Location(x, y);
if (getDistance(zero, l) <= radius) {
result.add(l);
}
}
}

// finish back at top-center, facing up
l = getAdjacent(l);
l = getTurnLeftPosition(l);
} else {
if (radius > Math.max(width, height))
radius = Math.max(width, height);

result.add(zero);
LocationDirection l = new LocationDirection(zero, NORTH);

// walk around the zero point in increasingly larger rectangles
for (int r = 1; r <= radius; r++) {
// North-center point
l = getAdjacent(l);
result.add(l);

// length of walks along each side of the rectangle
// North-center to NE to SE to SW to NW, back to North-center
int[] sides = {r, r*2, r*2, r*2, r-1};

for (int side : sides) {
l = getTurnRightPosition(l);
for (int i = 0; i < side; i++) {
l = getAdjacent(l);
if (getDistance(zero, l) <= radius)
result.add(l);
}
}

// finish back at top-center, facing up
l = getAdjacent(l);
l = getTurnLeftPosition(l);
}
}

return result;
Expand Down

0 comments on commit 1b4f2a1

Please sign in to comment.