rbush.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. function quickselect(arr, k, left, right, compare) {
  2. quickselectStep(arr, k, left || 0, right || (arr.length - 1), compare || defaultCompare);
  3. }
  4. function quickselectStep(arr, k, left, right, compare) {
  5. while (right > left) {
  6. if (right - left > 600) {
  7. var n = right - left + 1;
  8. var m = k - left + 1;
  9. var z = Math.log(n);
  10. var s = 0.5 * Math.exp(2 * z / 3);
  11. var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
  12. var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
  13. var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
  14. quickselectStep(arr, k, newLeft, newRight, compare);
  15. }
  16. var t = arr[k];
  17. var i = left;
  18. var j = right;
  19. swap(arr, left, k);
  20. if (compare(arr[right], t) > 0) { swap(arr, left, right); }
  21. while (i < j) {
  22. swap(arr, i, j);
  23. i++;
  24. j--;
  25. while (compare(arr[i], t) < 0) { i++; }
  26. while (compare(arr[j], t) > 0) { j--; }
  27. }
  28. if (compare(arr[left], t) === 0) { swap(arr, left, j); }
  29. else {
  30. j++;
  31. swap(arr, j, right);
  32. }
  33. if (j <= k) { left = j + 1; }
  34. if (k <= j) { right = j - 1; }
  35. }
  36. }
  37. function swap(arr, i, j) {
  38. var tmp = arr[i];
  39. arr[i] = arr[j];
  40. arr[j] = tmp;
  41. }
  42. function defaultCompare(a, b) {
  43. return a < b ? -1 : a > b ? 1 : 0;
  44. }
  45. function RBush(maxEntries) {
  46. if ( maxEntries === void 0 ) maxEntries = 9;
  47. // max entries in a node is 9 by default; min node fill is 40% for best performance
  48. this._maxEntries = Math.max(4, maxEntries);
  49. this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));
  50. this.clear();
  51. };
  52. RBush.prototype.all = function all () {
  53. return this._all(this.data, []);
  54. };
  55. RBush.prototype.search = function search (bbox) {
  56. var node = this.data;
  57. var result = [];
  58. if (!intersects(bbox, node)) { return result; }
  59. var toBBox = this.toBBox;
  60. var nodesToSearch = [];
  61. while (node) {
  62. for (var i = 0; i < node.children.length; i++) {
  63. var child = node.children[i];
  64. var childBBox = node.leaf ? toBBox(child) : child;
  65. if (intersects(bbox, childBBox)) {
  66. if (node.leaf) { result.push(child); }
  67. else if (contains(bbox, childBBox)) { this._all(child, result); }
  68. else { nodesToSearch.push(child); }
  69. }
  70. }
  71. node = nodesToSearch.pop();
  72. }
  73. return result;
  74. };
  75. RBush.prototype.collides = function collides (bbox) {
  76. var node = this.data;
  77. if (!intersects(bbox, node)) { return false; }
  78. var nodesToSearch = [];
  79. while (node) {
  80. for (var i = 0; i < node.children.length; i++) {
  81. var child = node.children[i];
  82. var childBBox = node.leaf ? this.toBBox(child) : child;
  83. if (intersects(bbox, childBBox)) {
  84. if (node.leaf || contains(bbox, childBBox)) { return true; }
  85. nodesToSearch.push(child);
  86. }
  87. }
  88. node = nodesToSearch.pop();
  89. }
  90. return false;
  91. };
  92. RBush.prototype.load = function load (data) {
  93. if (!(data && data.length)) { return this; }
  94. if (data.length < this._minEntries) {
  95. for (var i = 0; i < data.length; i++) {
  96. this.insert(data[i]);
  97. }
  98. return this;
  99. }
  100. // recursively build the tree with the given data from scratch using OMT algorithm
  101. var node = this._build(data.slice(), 0, data.length - 1, 0);
  102. if (!this.data.children.length) {
  103. // save as is if tree is empty
  104. this.data = node;
  105. } else if (this.data.height === node.height) {
  106. // split root if trees have the same height
  107. this._splitRoot(this.data, node);
  108. } else {
  109. if (this.data.height < node.height) {
  110. // swap trees if inserted one is bigger
  111. var tmpNode = this.data;
  112. this.data = node;
  113. node = tmpNode;
  114. }
  115. // insert the small tree into the large tree at appropriate level
  116. this._insert(node, this.data.height - node.height - 1, true);
  117. }
  118. return this;
  119. };
  120. RBush.prototype.insert = function insert (item) {
  121. if (item) { this._insert(item, this.data.height - 1); }
  122. return this;
  123. };
  124. RBush.prototype.clear = function clear () {
  125. this.data = createNode([]);
  126. return this;
  127. };
  128. RBush.prototype.remove = function remove (item, equalsFn) {
  129. if (!item) { return this; }
  130. var node = this.data;
  131. var bbox = this.toBBox(item);
  132. var path = [];
  133. var indexes = [];
  134. var i, parent, goingUp;
  135. // depth-first iterative tree traversal
  136. while (node || path.length) {
  137. if (!node) { // go up
  138. node = path.pop();
  139. parent = path[path.length - 1];
  140. i = indexes.pop();
  141. goingUp = true;
  142. }
  143. if (node.leaf) { // check current node
  144. var index = findItem(item, node.children, equalsFn);
  145. if (index !== -1) {
  146. // item found, remove the item and condense tree upwards
  147. node.children.splice(index, 1);
  148. path.push(node);
  149. this._condense(path);
  150. return this;
  151. }
  152. }
  153. if (!goingUp && !node.leaf && contains(node, bbox)) { // go down
  154. path.push(node);
  155. indexes.push(i);
  156. i = 0;
  157. parent = node;
  158. node = node.children[0];
  159. } else if (parent) { // go right
  160. i++;
  161. node = parent.children[i];
  162. goingUp = false;
  163. } else { node = null; } // nothing found
  164. }
  165. return this;
  166. };
  167. RBush.prototype.toBBox = function toBBox (item) { return item; };
  168. RBush.prototype.compareMinX = function compareMinX (a, b) { return a.minX - b.minX; };
  169. RBush.prototype.compareMinY = function compareMinY (a, b) { return a.minY - b.minY; };
  170. RBush.prototype.toJSON = function toJSON () { return this.data; };
  171. RBush.prototype.fromJSON = function fromJSON (data) {
  172. this.data = data;
  173. return this;
  174. };
  175. RBush.prototype._all = function _all (node, result) {
  176. var nodesToSearch = [];
  177. while (node) {
  178. if (node.leaf) { result.push.apply(result, node.children); }
  179. else { nodesToSearch.push.apply(nodesToSearch, node.children); }
  180. node = nodesToSearch.pop();
  181. }
  182. return result;
  183. };
  184. RBush.prototype._build = function _build (items, left, right, height) {
  185. var N = right - left + 1;
  186. var M = this._maxEntries;
  187. var node;
  188. if (N <= M) {
  189. // reached leaf level; return leaf
  190. node = createNode(items.slice(left, right + 1));
  191. calcBBox(node, this.toBBox);
  192. return node;
  193. }
  194. if (!height) {
  195. // target height of the bulk-loaded tree
  196. height = Math.ceil(Math.log(N) / Math.log(M));
  197. // target number of root entries to maximize storage utilization
  198. M = Math.ceil(N / Math.pow(M, height - 1));
  199. }
  200. node = createNode([]);
  201. node.leaf = false;
  202. node.height = height;
  203. // split the items into M mostly square tiles
  204. var N2 = Math.ceil(N / M);
  205. var N1 = N2 * Math.ceil(Math.sqrt(M));
  206. multiSelect(items, left, right, N1, this.compareMinX);
  207. for (var i = left; i <= right; i += N1) {
  208. var right2 = Math.min(i + N1 - 1, right);
  209. multiSelect(items, i, right2, N2, this.compareMinY);
  210. for (var j = i; j <= right2; j += N2) {
  211. var right3 = Math.min(j + N2 - 1, right2);
  212. // pack each entry recursively
  213. node.children.push(this._build(items, j, right3, height - 1));
  214. }
  215. }
  216. calcBBox(node, this.toBBox);
  217. return node;
  218. };
  219. RBush.prototype._chooseSubtree = function _chooseSubtree (bbox, node, level, path) {
  220. while (true) {
  221. path.push(node);
  222. if (node.leaf || path.length - 1 === level) { break; }
  223. var minArea = Infinity;
  224. var minEnlargement = Infinity;
  225. var targetNode = (void 0);
  226. for (var i = 0; i < node.children.length; i++) {
  227. var child = node.children[i];
  228. var area = bboxArea(child);
  229. var enlargement = enlargedArea(bbox, child) - area;
  230. // choose entry with the least area enlargement
  231. if (enlargement < minEnlargement) {
  232. minEnlargement = enlargement;
  233. minArea = area < minArea ? area : minArea;
  234. targetNode = child;
  235. } else if (enlargement === minEnlargement) {
  236. // otherwise choose one with the smallest area
  237. if (area < minArea) {
  238. minArea = area;
  239. targetNode = child;
  240. }
  241. }
  242. }
  243. node = targetNode || node.children[0];
  244. }
  245. return node;
  246. };
  247. RBush.prototype._insert = function _insert (item, level, isNode) {
  248. var bbox = isNode ? item : this.toBBox(item);
  249. var insertPath = [];
  250. // find the best node for accommodating the item, saving all nodes along the path too
  251. var node = this._chooseSubtree(bbox, this.data, level, insertPath);
  252. // put the item into the node
  253. node.children.push(item);
  254. extend(node, bbox);
  255. // split on node overflow; propagate upwards if necessary
  256. while (level >= 0) {
  257. if (insertPath[level].children.length > this._maxEntries) {
  258. this._split(insertPath, level);
  259. level--;
  260. } else { break; }
  261. }
  262. // adjust bboxes along the insertion path
  263. this._adjustParentBBoxes(bbox, insertPath, level);
  264. };
  265. // split overflowed node into two
  266. RBush.prototype._split = function _split (insertPath, level) {
  267. var node = insertPath[level];
  268. var M = node.children.length;
  269. var m = this._minEntries;
  270. this._chooseSplitAxis(node, m, M);
  271. var splitIndex = this._chooseSplitIndex(node, m, M);
  272. var newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex));
  273. newNode.height = node.height;
  274. newNode.leaf = node.leaf;
  275. calcBBox(node, this.toBBox);
  276. calcBBox(newNode, this.toBBox);
  277. if (level) { insertPath[level - 1].children.push(newNode); }
  278. else { this._splitRoot(node, newNode); }
  279. };
  280. RBush.prototype._splitRoot = function _splitRoot (node, newNode) {
  281. // split root node
  282. this.data = createNode([node, newNode]);
  283. this.data.height = node.height + 1;
  284. this.data.leaf = false;
  285. calcBBox(this.data, this.toBBox);
  286. };
  287. RBush.prototype._chooseSplitIndex = function _chooseSplitIndex (node, m, M) {
  288. var index;
  289. var minOverlap = Infinity;
  290. var minArea = Infinity;
  291. for (var i = m; i <= M - m; i++) {
  292. var bbox1 = distBBox(node, 0, i, this.toBBox);
  293. var bbox2 = distBBox(node, i, M, this.toBBox);
  294. var overlap = intersectionArea(bbox1, bbox2);
  295. var area = bboxArea(bbox1) + bboxArea(bbox2);
  296. // choose distribution with minimum overlap
  297. if (overlap < minOverlap) {
  298. minOverlap = overlap;
  299. index = i;
  300. minArea = area < minArea ? area : minArea;
  301. } else if (overlap === minOverlap) {
  302. // otherwise choose distribution with minimum area
  303. if (area < minArea) {
  304. minArea = area;
  305. index = i;
  306. }
  307. }
  308. }
  309. return index || M - m;
  310. };
  311. // sorts node children by the best axis for split
  312. RBush.prototype._chooseSplitAxis = function _chooseSplitAxis (node, m, M) {
  313. var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX;
  314. var compareMinY = node.leaf ? this.compareMinY : compareNodeMinY;
  315. var xMargin = this._allDistMargin(node, m, M, compareMinX);
  316. var yMargin = this._allDistMargin(node, m, M, compareMinY);
  317. // if total distributions margin value is minimal for x, sort by minX,
  318. // otherwise it's already sorted by minY
  319. if (xMargin < yMargin) { node.children.sort(compareMinX); }
  320. };
  321. // total margin of all possible split distributions where each node is at least m full
  322. RBush.prototype._allDistMargin = function _allDistMargin (node, m, M, compare) {
  323. node.children.sort(compare);
  324. var toBBox = this.toBBox;
  325. var leftBBox = distBBox(node, 0, m, toBBox);
  326. var rightBBox = distBBox(node, M - m, M, toBBox);
  327. var margin = bboxMargin(leftBBox) + bboxMargin(rightBBox);
  328. for (var i = m; i < M - m; i++) {
  329. var child = node.children[i];
  330. extend(leftBBox, node.leaf ? toBBox(child) : child);
  331. margin += bboxMargin(leftBBox);
  332. }
  333. for (var i$1 = M - m - 1; i$1 >= m; i$1--) {
  334. var child$1 = node.children[i$1];
  335. extend(rightBBox, node.leaf ? toBBox(child$1) : child$1);
  336. margin += bboxMargin(rightBBox);
  337. }
  338. return margin;
  339. };
  340. RBush.prototype._adjustParentBBoxes = function _adjustParentBBoxes (bbox, path, level) {
  341. // adjust bboxes along the given tree path
  342. for (var i = level; i >= 0; i--) {
  343. extend(path[i], bbox);
  344. }
  345. };
  346. RBush.prototype._condense = function _condense (path) {
  347. // go through the path, removing empty nodes and updating bboxes
  348. for (var i = path.length - 1, siblings = (void 0); i >= 0; i--) {
  349. if (path[i].children.length === 0) {
  350. if (i > 0) {
  351. siblings = path[i - 1].children;
  352. siblings.splice(siblings.indexOf(path[i]), 1);
  353. } else { this.clear(); }
  354. } else { calcBBox(path[i], this.toBBox); }
  355. }
  356. };
  357. function findItem(item, items, equalsFn) {
  358. if (!equalsFn) { return items.indexOf(item); }
  359. for (var i = 0; i < items.length; i++) {
  360. if (equalsFn(item, items[i])) { return i; }
  361. }
  362. return -1;
  363. }
  364. // calculate node's bbox from bboxes of its children
  365. function calcBBox(node, toBBox) {
  366. distBBox(node, 0, node.children.length, toBBox, node);
  367. }
  368. // min bounding rectangle of node children from k to p-1
  369. function distBBox(node, k, p, toBBox, destNode) {
  370. if (!destNode) { destNode = createNode(null); }
  371. destNode.minX = Infinity;
  372. destNode.minY = Infinity;
  373. destNode.maxX = -Infinity;
  374. destNode.maxY = -Infinity;
  375. for (var i = k; i < p; i++) {
  376. var child = node.children[i];
  377. extend(destNode, node.leaf ? toBBox(child) : child);
  378. }
  379. return destNode;
  380. }
  381. function extend(a, b) {
  382. a.minX = Math.min(a.minX, b.minX);
  383. a.minY = Math.min(a.minY, b.minY);
  384. a.maxX = Math.max(a.maxX, b.maxX);
  385. a.maxY = Math.max(a.maxY, b.maxY);
  386. return a;
  387. }
  388. function compareNodeMinX(a, b) { return a.minX - b.minX; }
  389. function compareNodeMinY(a, b) { return a.minY - b.minY; }
  390. function bboxArea(a) { return (a.maxX - a.minX) * (a.maxY - a.minY); }
  391. function bboxMargin(a) { return (a.maxX - a.minX) + (a.maxY - a.minY); }
  392. function enlargedArea(a, b) {
  393. return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) *
  394. (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY));
  395. }
  396. function intersectionArea(a, b) {
  397. var minX = Math.max(a.minX, b.minX);
  398. var minY = Math.max(a.minY, b.minY);
  399. var maxX = Math.min(a.maxX, b.maxX);
  400. var maxY = Math.min(a.maxY, b.maxY);
  401. return Math.max(0, maxX - minX) *
  402. Math.max(0, maxY - minY);
  403. }
  404. function contains(a, b) {
  405. return a.minX <= b.minX &&
  406. a.minY <= b.minY &&
  407. b.maxX <= a.maxX &&
  408. b.maxY <= a.maxY;
  409. }
  410. function intersects(a, b) {
  411. return b.minX <= a.maxX &&
  412. b.minY <= a.maxY &&
  413. b.maxX >= a.minX &&
  414. b.maxY >= a.minY;
  415. }
  416. function createNode(children) {
  417. return {
  418. children: children,
  419. height: 1,
  420. leaf: true,
  421. minX: Infinity,
  422. minY: Infinity,
  423. maxX: -Infinity,
  424. maxY: -Infinity
  425. };
  426. }
  427. // sort an array so that items come in groups of n unsorted items, with groups sorted between each other;
  428. // combines selection algorithm with binary divide & conquer approach
  429. function multiSelect(arr, left, right, n, compare) {
  430. var stack = [left, right];
  431. while (stack.length) {
  432. right = stack.pop();
  433. left = stack.pop();
  434. if (right - left <= n) { continue; }
  435. var mid = left + Math.ceil((right - left) / n / 2) * n;
  436. quickselect(arr, mid, left, right, compare);
  437. stack.push(left, mid, mid, right);
  438. }
  439. }
  440. export default RBush;