-
-
Notifications
You must be signed in to change notification settings - Fork 643
/
grid_index.ts
414 lines (375 loc) · 14.9 KB
/
grid_index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
import type {OverlapMode} from '../style/style_layer/overlap_mode';
type QueryArgs = {
hitTest: boolean;
overlapMode?: OverlapMode;
circle?: {
x: number;
y: number;
radius: number;
};
seenUids: {
box: {
[_: number]: boolean;
};
circle: {
[_: number]: boolean;
};
};
};
type QueryResult<T> = {
key: T;
x1: number;
y1: number;
x2: number;
y2: number;
};
/**
* A key for the grid
*/
export type GridKey = {
overlapMode?: OverlapMode;
}
function overlapAllowed(overlapA: OverlapMode, overlapB: OverlapMode): boolean {
let allowed = true;
if (overlapA === 'always') {
// symbol A using 'always' overlap - allowed to overlap anything.
} else if (overlapA === 'never' || overlapB === 'never') {
// symbol A using 'never' overlap - can't overlap anything
// symbol A using 'cooperative' overlap - can overlap 'always' or 'cooperative' symbol; can't overlap 'never'
allowed = false;
}
return allowed;
}
/**
* @internal
* GridIndex is a data structure for testing the intersection of
* circles and rectangles in a 2d plane.
* It is optimized for rapid insertion and querying.
* GridIndex splits the plane into a set of "cells" and keeps track
* of which geometries intersect with each cell. At query time,
* full geometry comparisons are only done for items that share
* at least one cell. As long as the geometries are relatively
* uniformly distributed across the plane, this greatly reduces
* the number of comparisons necessary.
*/
export class GridIndex<T extends GridKey> {
circleKeys: Array<T>;
boxKeys: Array<T>;
boxCells: Array<Array<number>>;
circleCells: Array<Array<number>>;
bboxes: Array<number>;
circles: Array<number>;
xCellCount: number;
yCellCount: number;
width: number;
height: number;
xScale: number;
yScale: number;
boxUid: number;
circleUid: number;
constructor (width: number, height: number, cellSize: number) {
const boxCells = this.boxCells = [];
const circleCells = this.circleCells = [];
// More cells -> fewer geometries to check per cell, but items tend
// to be split across more cells.
// Sweet spot allows most small items to fit in one cell
this.xCellCount = Math.ceil(width / cellSize);
this.yCellCount = Math.ceil(height / cellSize);
for (let i = 0; i < this.xCellCount * this.yCellCount; i++) {
boxCells.push([]);
circleCells.push([]);
}
this.circleKeys = [];
this.boxKeys = [];
this.bboxes = [];
this.circles = [];
this.width = width;
this.height = height;
this.xScale = this.xCellCount / width;
this.yScale = this.yCellCount / height;
this.boxUid = 0;
this.circleUid = 0;
}
keysLength() {
return this.boxKeys.length + this.circleKeys.length;
}
insert(key: T, x1: number, y1: number, x2: number, y2: number) {
this._forEachCell(x1, y1, x2, y2, this._insertBoxCell, this.boxUid++);
this.boxKeys.push(key);
this.bboxes.push(x1);
this.bboxes.push(y1);
this.bboxes.push(x2);
this.bboxes.push(y2);
}
insertCircle(key: T, x: number, y: number, radius: number) {
// Insert circle into grid for all cells in the circumscribing square
// It's more than necessary (by a factor of 4/PI), but fast to insert
this._forEachCell(x - radius, y - radius, x + radius, y + radius, this._insertCircleCell, this.circleUid++);
this.circleKeys.push(key);
this.circles.push(x);
this.circles.push(y);
this.circles.push(radius);
}
private _insertBoxCell(x1: number, y1: number, x2: number, y2: number, cellIndex: number, uid: number) {
this.boxCells[cellIndex].push(uid);
}
private _insertCircleCell(x1: number, y1: number, x2: number, y2: number, cellIndex: number, uid: number) {
this.circleCells[cellIndex].push(uid);
}
private _query(x1: number, y1: number, x2: number, y2: number, hitTest: boolean, overlapMode: OverlapMode, predicate?: (key: T) => boolean): Array<QueryResult<T>> {
if (x2 < 0 || x1 > this.width || y2 < 0 || y1 > this.height) {
return [];
}
const result: Array<QueryResult<T>> = [];
if (x1 <= 0 && y1 <= 0 && this.width <= x2 && this.height <= y2) {
if (hitTest) {
// Covers the entire grid, so collides with everything
return [{
key: null,
x1,
y1,
x2,
y2
}];
}
for (let boxUid = 0; boxUid < this.boxKeys.length; boxUid++) {
result.push({
key: this.boxKeys[boxUid],
x1: this.bboxes[boxUid * 4],
y1: this.bboxes[boxUid * 4 + 1],
x2: this.bboxes[boxUid * 4 + 2],
y2: this.bboxes[boxUid * 4 + 3]
});
}
for (let circleUid = 0; circleUid < this.circleKeys.length; circleUid++) {
const x = this.circles[circleUid * 3];
const y = this.circles[circleUid * 3 + 1];
const radius = this.circles[circleUid * 3 + 2];
result.push({
key: this.circleKeys[circleUid],
x1: x - radius,
y1: y - radius,
x2: x + radius,
y2: y + radius
});
}
} else {
const queryArgs: QueryArgs = {
hitTest,
overlapMode,
seenUids: {box: {}, circle: {}}
};
this._forEachCell(x1, y1, x2, y2, this._queryCell, result, queryArgs, predicate);
}
return result;
}
query(x1: number, y1: number, x2: number, y2: number): Array<QueryResult<T>> {
return this._query(x1, y1, x2, y2, false, null);
}
hitTest(x1: number, y1: number, x2: number, y2: number, overlapMode: OverlapMode, predicate?: (key: T) => boolean): boolean {
return this._query(x1, y1, x2, y2, true, overlapMode, predicate).length > 0;
}
hitTestCircle(x: number, y: number, radius: number, overlapMode: OverlapMode, predicate?: (key: T) => boolean): boolean {
// Insert circle into grid for all cells in the circumscribing square
// It's more than necessary (by a factor of 4/PI), but fast to insert
const x1 = x - radius;
const x2 = x + radius;
const y1 = y - radius;
const y2 = y + radius;
if (x2 < 0 || x1 > this.width || y2 < 0 || y1 > this.height) {
return false;
}
// Box query early exits if the bounding box is larger than the grid, but we don't do
// the equivalent calculation for circle queries because early exit is less likely
// and the calculation is more expensive
const result: boolean[] = [];
const queryArgs: QueryArgs = {
hitTest: true,
overlapMode,
circle: {x, y, radius},
seenUids: {box: {}, circle: {}}
};
this._forEachCell(x1, y1, x2, y2, this._queryCellCircle, result, queryArgs, predicate);
return result.length > 0;
}
private _queryCell(x1: number, y1: number, x2: number, y2: number, cellIndex: number, result: Array<QueryResult<T>>, queryArgs: QueryArgs, predicate?: (key: T) => boolean): boolean {
const {seenUids, hitTest, overlapMode} = queryArgs;
const boxCell = this.boxCells[cellIndex];
if (boxCell !== null) {
const bboxes = this.bboxes;
for (const boxUid of boxCell) {
if (!seenUids.box[boxUid]) {
seenUids.box[boxUid] = true;
const offset = boxUid * 4;
const key = this.boxKeys[boxUid];
if ((x1 <= bboxes[offset + 2]) &&
(y1 <= bboxes[offset + 3]) &&
(x2 >= bboxes[offset + 0]) &&
(y2 >= bboxes[offset + 1]) &&
(!predicate || predicate(key))) {
if (!hitTest || !overlapAllowed(overlapMode, key.overlapMode)) {
result.push({
key,
x1: bboxes[offset],
y1: bboxes[offset + 1],
x2: bboxes[offset + 2],
y2: bboxes[offset + 3]
});
if (hitTest) {
// true return value stops the query after first match
return true;
}
}
}
}
}
}
const circleCell = this.circleCells[cellIndex];
if (circleCell !== null) {
const circles = this.circles;
for (const circleUid of circleCell) {
if (!seenUids.circle[circleUid]) {
seenUids.circle[circleUid] = true;
const offset = circleUid * 3;
const key = this.circleKeys[circleUid];
if (this._circleAndRectCollide(
circles[offset],
circles[offset + 1],
circles[offset + 2],
x1,
y1,
x2,
y2) &&
(!predicate || predicate(key))) {
if (!hitTest || !overlapAllowed(overlapMode, key.overlapMode)) {
const x = circles[offset];
const y = circles[offset + 1];
const radius = circles[offset + 2];
result.push({
key,
x1: x - radius,
y1: y - radius,
x2: x + radius,
y2: y + radius
});
if (hitTest) {
// true return value stops the query after first match
return true;
}
}
}
}
}
}
// false return to continue query
return false;
}
private _queryCellCircle(x1: number, y1: number, x2: number, y2: number, cellIndex: number, result: Array<boolean>, queryArgs: QueryArgs, predicate?: (key: T) => boolean): boolean {
const {circle, seenUids, overlapMode} = queryArgs;
const boxCell = this.boxCells[cellIndex];
if (boxCell !== null) {
const bboxes = this.bboxes;
for (const boxUid of boxCell) {
if (!seenUids.box[boxUid]) {
seenUids.box[boxUid] = true;
const offset = boxUid * 4;
const key = this.boxKeys[boxUid];
if (this._circleAndRectCollide(
circle.x,
circle.y,
circle.radius,
bboxes[offset + 0],
bboxes[offset + 1],
bboxes[offset + 2],
bboxes[offset + 3]) &&
(!predicate || predicate(key)) &&
!overlapAllowed(overlapMode, key.overlapMode)) {
result.push(true);
return true;
}
}
}
}
const circleCell = this.circleCells[cellIndex];
if (circleCell !== null) {
const circles = this.circles;
for (const circleUid of circleCell) {
if (!seenUids.circle[circleUid]) {
seenUids.circle[circleUid] = true;
const offset = circleUid * 3;
const key = this.circleKeys[circleUid];
if (this._circlesCollide(
circles[offset],
circles[offset + 1],
circles[offset + 2],
circle.x,
circle.y,
circle.radius) &&
(!predicate || predicate(key)) &&
!overlapAllowed(overlapMode, key.overlapMode)) {
result.push(true);
return true;
}
}
}
}
}
private _forEachCell<TArg>(
x1: number,
y1: number,
x2: number,
y2: number,
fn: (x1: number, y1: number, x2: number, y2: number, cellIndex: number, arg1: TArg, arg2?: QueryArgs, predicate?: (key: T) => boolean) => boolean | void,
arg1: TArg,
arg2?: QueryArgs,
predicate?: (key: T) => boolean) {
const cx1 = this._convertToXCellCoord(x1);
const cy1 = this._convertToYCellCoord(y1);
const cx2 = this._convertToXCellCoord(x2);
const cy2 = this._convertToYCellCoord(y2);
for (let x = cx1; x <= cx2; x++) {
for (let y = cy1; y <= cy2; y++) {
const cellIndex = this.xCellCount * y + x;
if (fn.call(this, x1, y1, x2, y2, cellIndex, arg1, arg2, predicate)) return;
}
}
}
private _convertToXCellCoord(x: number) {
return Math.max(0, Math.min(this.xCellCount - 1, Math.floor(x * this.xScale)));
}
private _convertToYCellCoord(y: number) {
return Math.max(0, Math.min(this.yCellCount - 1, Math.floor(y * this.yScale)));
}
private _circlesCollide(x1: number, y1: number, r1: number, x2: number, y2: number, r2: number): boolean {
const dx = x2 - x1;
const dy = y2 - y1;
const bothRadii = r1 + r2;
return (bothRadii * bothRadii) > (dx * dx + dy * dy);
}
private _circleAndRectCollide(
circleX: number,
circleY: number,
radius: number,
x1: number,
y1: number,
x2: number,
y2: number
): boolean {
const halfRectWidth = (x2 - x1) / 2;
const distX = Math.abs(circleX - (x1 + halfRectWidth));
if (distX > (halfRectWidth + radius)) {
return false;
}
const halfRectHeight = (y2 - y1) / 2;
const distY = Math.abs(circleY - (y1 + halfRectHeight));
if (distY > (halfRectHeight + radius)) {
return false;
}
if (distX <= halfRectWidth || distY <= halfRectHeight) {
return true;
}
const dx = distX - halfRectWidth;
const dy = distY - halfRectHeight;
return (dx * dx + dy * dy <= (radius * radius));
}
}