rbush.js 16 KB

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