@mousepox/math
Version:
Math-related objects and utilities
35 lines (34 loc) • 1.06 kB
JavaScript
import { GoldenRatio } from "./core";
export class SpatialHash {
pairs = [];
size;
buckets = new Map();
constructor(size) {
this.size = size;
}
clear() {
this.buckets.clear();
}
insert(rect) {
const ox = Math.floor(rect.x / this.size);
const tx = Math.floor((rect.x + rect.width) / this.size);
for (let x = ox; x <= tx; ++x) {
const oy = Math.floor(rect.y / this.size);
const ty = Math.floor((rect.y + rect.height) / this.size);
for (let y = oy; y <= ty; ++y) {
const key = x + ((GoldenRatio * y) % 1);
let bucket = this.buckets.get(key);
if (bucket === undefined) {
bucket = [];
this.buckets.set(key, bucket);
}
else {
for (const other of bucket) {
this.pairs.push([other, rect]);
}
}
bucket.push(rect);
}
}
}
}