rbush.js 18 KB

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