Initial floodSearch impl

This commit is contained in:
Tangent Wantwight 2024-01-12 22:19:54 -05:00
parent 92917be9f7
commit 6bf157bd32

View file

@ -35,6 +35,38 @@ class IslandGrid {
this.data[this.xy(x, y)] = tile;
console.log(x, y, this.xy(x, y), this.data[this.xy(x, y)]);
}
public floodSearch(
startPos: number,
shouldExpand: (tile: number) => boolean
): number[] {
const len = this.data.length;
const width = this.width;
const seen = new Uint8Array(len);
const hitPositions: number[] = [];
function enqueue(pos: number) {
if (!seen[pos]) {
hitPositions.push(pos);
seen[pos] = 1;
}
}
enqueue(startPos);
for (let i = 0; i < hitPositions.length; i++) {
const pos = hitPositions[i];
if (shouldExpand(this.data[pos])) {
enqueue((pos - width) % len);
enqueue((pos - 1) % len);
enqueue((pos + 1) % len);
enqueue((pos + width) % len);
}
}
return hitPositions;
}
}
function renderIslands(islands: IslandGrid, cx: CanvasRenderingContext2D) {
@ -75,6 +107,9 @@ export function IslandApplet() {
const y = islands.rng();
islands.set(x, y, 1);
islands
.floodSearch(islands.xy(x, y), (tile) => tile > 0)
.forEach((pos) => islands.data[pos]++);
renderIslands(islands, cx);