| 1 | import Quad from "./quad.js";
|
|---|
| 2 |
|
|---|
| 3 | export default function(x, y, radius) {
|
|---|
| 4 | var data,
|
|---|
| 5 | x0 = this._x0,
|
|---|
| 6 | y0 = this._y0,
|
|---|
| 7 | x1,
|
|---|
| 8 | y1,
|
|---|
| 9 | x2,
|
|---|
| 10 | y2,
|
|---|
| 11 | x3 = this._x1,
|
|---|
| 12 | y3 = this._y1,
|
|---|
| 13 | quads = [],
|
|---|
| 14 | node = this._root,
|
|---|
| 15 | q,
|
|---|
| 16 | i;
|
|---|
| 17 |
|
|---|
| 18 | if (node) quads.push(new Quad(node, x0, y0, x3, y3));
|
|---|
| 19 | if (radius == null) radius = Infinity;
|
|---|
| 20 | else {
|
|---|
| 21 | x0 = x - radius, y0 = y - radius;
|
|---|
| 22 | x3 = x + radius, y3 = y + radius;
|
|---|
| 23 | radius *= radius;
|
|---|
| 24 | }
|
|---|
| 25 |
|
|---|
| 26 | while (q = quads.pop()) {
|
|---|
| 27 |
|
|---|
| 28 | // Stop searching if this quadrant can’t contain a closer node.
|
|---|
| 29 | if (!(node = q.node)
|
|---|
| 30 | || (x1 = q.x0) > x3
|
|---|
| 31 | || (y1 = q.y0) > y3
|
|---|
| 32 | || (x2 = q.x1) < x0
|
|---|
| 33 | || (y2 = q.y1) < y0) continue;
|
|---|
| 34 |
|
|---|
| 35 | // Bisect the current quadrant.
|
|---|
| 36 | if (node.length) {
|
|---|
| 37 | var xm = (x1 + x2) / 2,
|
|---|
| 38 | ym = (y1 + y2) / 2;
|
|---|
| 39 |
|
|---|
| 40 | quads.push(
|
|---|
| 41 | new Quad(node[3], xm, ym, x2, y2),
|
|---|
| 42 | new Quad(node[2], x1, ym, xm, y2),
|
|---|
| 43 | new Quad(node[1], xm, y1, x2, ym),
|
|---|
| 44 | new Quad(node[0], x1, y1, xm, ym)
|
|---|
| 45 | );
|
|---|
| 46 |
|
|---|
| 47 | // Visit the closest quadrant first.
|
|---|
| 48 | if (i = (y >= ym) << 1 | (x >= xm)) {
|
|---|
| 49 | q = quads[quads.length - 1];
|
|---|
| 50 | quads[quads.length - 1] = quads[quads.length - 1 - i];
|
|---|
| 51 | quads[quads.length - 1 - i] = q;
|
|---|
| 52 | }
|
|---|
| 53 | }
|
|---|
| 54 |
|
|---|
| 55 | // Visit this point. (Visiting coincident points isn’t necessary!)
|
|---|
| 56 | else {
|
|---|
| 57 | var dx = x - +this._x.call(null, node.data),
|
|---|
| 58 | dy = y - +this._y.call(null, node.data),
|
|---|
| 59 | d2 = dx * dx + dy * dy;
|
|---|
| 60 | if (d2 < radius) {
|
|---|
| 61 | var d = Math.sqrt(radius = d2);
|
|---|
| 62 | x0 = x - d, y0 = y - d;
|
|---|
| 63 | x3 = x + d, y3 = y + d;
|
|---|
| 64 | data = node.data;
|
|---|
| 65 | }
|
|---|
| 66 | }
|
|---|
| 67 | }
|
|---|
| 68 |
|
|---|
| 69 | return data;
|
|---|
| 70 | }
|
|---|