智慧水务管理系统 - 精河县供水工程综合管理平台

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. const ARRAY_TYPES = [
  2. Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array,
  3. Int32Array, Uint32Array, Float32Array, Float64Array
  4. ];
  5. /** @typedef {Int8ArrayConstructor | Uint8ArrayConstructor | Uint8ClampedArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor} TypedArrayConstructor */
  6. /** @typedef {Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array} TypedArray */
  7. const VERSION = 1; // serialized format version
  8. const HEADER_SIZE = 8;
  9. // Shared scratch stack for iterative DFS in range/within. Sized for the worst case:
  10. // 3 ints per frame * (treeHeight + 1), with treeHeight ≤ ceil(log2(2^32 / 3)) ≈ 31.
  11. const STACK = new Uint32Array(96);
  12. export default class KDBush {
  13. /**
  14. * Creates an index from raw `ArrayBuffer` data.
  15. * @param {ArrayBufferLike} data
  16. */
  17. static from(data) {
  18. // @ts-expect-error duck typing array buffers
  19. if (!data || data.byteLength === undefined || data.buffer) {
  20. throw new Error('Data must be an instance of ArrayBuffer or SharedArrayBuffer.');
  21. }
  22. const [magic, versionAndType] = new Uint8Array(data, 0, 2);
  23. if (magic !== 0xdb) {
  24. throw new Error('Data does not appear to be in a KDBush format.');
  25. }
  26. const version = versionAndType >> 4;
  27. if (version !== VERSION) {
  28. throw new Error(`Got v${version} data when expected v${VERSION}.`);
  29. }
  30. const ArrayType = ARRAY_TYPES[versionAndType & 0x0f];
  31. if (!ArrayType) {
  32. throw new Error('Unrecognized array type.');
  33. }
  34. const [nodeSize] = new Uint16Array(data, 2, 1);
  35. const [numItems] = new Uint32Array(data, 4, 1);
  36. return new KDBush(numItems, nodeSize, ArrayType, undefined, data);
  37. }
  38. /**
  39. * Creates an index that will hold a given number of items.
  40. * @param {number} numItems
  41. * @param {number} [nodeSize=64] Size of the KD-tree node (64 by default).
  42. * @param {TypedArrayConstructor} [ArrayType=Float64Array] The array type used for coordinates storage (`Float64Array` by default).
  43. * @param {ArrayBufferConstructor | SharedArrayBufferConstructor} [ArrayBufferType=ArrayBuffer] The array buffer type used for storage (`ArrayBuffer` by default).
  44. * @param {ArrayBufferLike} [data] (For internal use only)
  45. */
  46. constructor(numItems, nodeSize = 64, ArrayType = Float64Array, ArrayBufferType = ArrayBuffer, data) {
  47. if (isNaN(numItems) || numItems < 0) throw new Error(`Unexpected numItems value: ${numItems}.`);
  48. this.numItems = +numItems;
  49. this.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535);
  50. this.ArrayType = ArrayType;
  51. this.IndexArrayType = numItems < 65536 ? Uint16Array : Uint32Array;
  52. const arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType);
  53. const coordsByteSize = numItems * 2 * this.ArrayType.BYTES_PER_ELEMENT;
  54. const idsByteSize = numItems * this.IndexArrayType.BYTES_PER_ELEMENT;
  55. const padCoords = (8 - idsByteSize % 8) % 8;
  56. if (arrayTypeIndex < 0) {
  57. throw new Error(`Unexpected typed array class: ${ArrayType}.`);
  58. }
  59. if (data) { // reconstruct an index from a buffer
  60. this.data = data;
  61. // @ts-expect-error TS can't handle SharedArrayBuffer overloads
  62. this.ids = new this.IndexArrayType(data, HEADER_SIZE, numItems);
  63. // @ts-expect-error TS can't handle SharedArrayBuffer overloads
  64. this.coords = new ArrayType(data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);
  65. this._pos = numItems * 2;
  66. this._finished = true;
  67. } else { // initialize a new index
  68. const data = this.data = new ArrayBufferType(HEADER_SIZE + coordsByteSize + idsByteSize + padCoords);
  69. // @ts-expect-error TS can't handle SharedArrayBuffer overloads
  70. this.ids = new this.IndexArrayType(data, HEADER_SIZE, numItems);
  71. // @ts-expect-error TS can't handle SharedArrayBuffer overloads
  72. this.coords = new ArrayType(data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);
  73. this._pos = 0;
  74. this._finished = false;
  75. // set header
  76. new Uint8Array(data, 0, 2).set([0xdb, (VERSION << 4) + arrayTypeIndex]);
  77. new Uint16Array(data, 2, 1)[0] = nodeSize;
  78. new Uint32Array(data, 4, 1)[0] = numItems;
  79. }
  80. }
  81. /**
  82. * Add a point to the index.
  83. * @param {number} x
  84. * @param {number} y
  85. * @returns {number} An incremental index associated with the added item (starting from `0`).
  86. */
  87. add(x, y) {
  88. const index = this._pos >> 1;
  89. this.ids[index] = index;
  90. this.coords[this._pos++] = x;
  91. this.coords[this._pos++] = y;
  92. return index;
  93. }
  94. /**
  95. * Perform indexing of the added points.
  96. */
  97. finish() {
  98. const numAdded = this._pos >> 1;
  99. if (numAdded !== this.numItems) {
  100. throw new Error(`Added ${numAdded} items when expected ${this.numItems}.`);
  101. }
  102. // kd-sort both arrays for efficient search
  103. sort(this.ids, this.coords, this.nodeSize, 0, this.numItems - 1, 0);
  104. this._finished = true;
  105. return this;
  106. }
  107. /**
  108. * Search the index for items within a given bounding box.
  109. * @param {number} minX
  110. * @param {number} minY
  111. * @param {number} maxX
  112. * @param {number} maxY
  113. * @returns {number[]} An array of indices correponding to the found items.
  114. */
  115. range(minX, minY, maxX, maxY) {
  116. if (!this._finished) throw new Error('Data not yet indexed - call index.finish().');
  117. const {ids, coords, nodeSize} = this;
  118. STACK[0] = 0;
  119. STACK[1] = ids.length - 1;
  120. STACK[2] = 0;
  121. let sp = 3;
  122. const result = [];
  123. // recursively search for items in range in the kd-sorted arrays
  124. while (sp > 0) {
  125. const axis = STACK[--sp];
  126. const right = STACK[--sp];
  127. const left = STACK[--sp];
  128. // if we reached "tree node", search linearly
  129. if (right - left <= nodeSize) {
  130. for (let i = left; i <= right; i++) {
  131. const x = coords[2 * i];
  132. const y = coords[2 * i + 1];
  133. if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[i]);
  134. }
  135. continue;
  136. }
  137. // otherwise find the middle index
  138. const m = (left + right) >> 1;
  139. // include the middle item if it's in range
  140. const x = coords[2 * m];
  141. const y = coords[2 * m + 1];
  142. if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]);
  143. // queue search in halves that intersect the query
  144. if (axis === 0 ? minX <= x : minY <= y) {
  145. STACK[sp++] = left;
  146. STACK[sp++] = m - 1;
  147. STACK[sp++] = 1 - axis;
  148. }
  149. if (axis === 0 ? maxX >= x : maxY >= y) {
  150. STACK[sp++] = m + 1;
  151. STACK[sp++] = right;
  152. STACK[sp++] = 1 - axis;
  153. }
  154. }
  155. return result;
  156. }
  157. /**
  158. * Search the index for items within a given radius.
  159. * @param {number} qx
  160. * @param {number} qy
  161. * @param {number} r Query radius.
  162. * @returns {number[]} An array of indices correponding to the found items.
  163. */
  164. within(qx, qy, r) {
  165. const result = /** @type {number[]} */ ([]);
  166. this.withinInto(qx, qy, r, result);
  167. return result;
  168. }
  169. /**
  170. * Search the index for items within a given radius, writing matching ids into `out`
  171. * via indexed assignment (`out[i] = id`). Accepts any indexed-writable container —
  172. * a typed array sized to the expected upper bound (allocation-free, fast) or a plain
  173. * `Array` (which will grow as needed). Returns the number of matches written.
  174. * @param {number} qx
  175. * @param {number} qy
  176. * @param {number} r Query radius.
  177. * @param {number[] | TypedArray} out Container to write matching ids into.
  178. * @returns {number} The number of matches written to `out`.
  179. */
  180. withinInto(qx, qy, r, out) {
  181. if (!this._finished) throw new Error('Data not yet indexed - call index.finish().');
  182. const {ids, coords, nodeSize} = this;
  183. STACK[0] = 0;
  184. STACK[1] = ids.length - 1;
  185. STACK[2] = 0;
  186. let sp = 3;
  187. let count = 0;
  188. const r2 = r * r;
  189. // recursively search for items within radius in the kd-sorted arrays
  190. while (sp > 0) {
  191. const axis = STACK[--sp];
  192. const right = STACK[--sp];
  193. const left = STACK[--sp];
  194. // if we reached "tree node", search linearly
  195. if (right - left <= nodeSize) {
  196. for (let i = left; i <= right; i++) {
  197. if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) out[count++] = ids[i];
  198. }
  199. continue;
  200. }
  201. // otherwise find the middle index
  202. const m = (left + right) >> 1;
  203. // include the middle item if it's in range
  204. const x = coords[2 * m];
  205. const y = coords[2 * m + 1];
  206. if (sqDist(x, y, qx, qy) <= r2) out[count++] = ids[m];
  207. // queue search in halves that intersect the query
  208. if (axis === 0 ? qx - r <= x : qy - r <= y) {
  209. STACK[sp++] = left;
  210. STACK[sp++] = m - 1;
  211. STACK[sp++] = 1 - axis;
  212. }
  213. if (axis === 0 ? qx + r >= x : qy + r >= y) {
  214. STACK[sp++] = m + 1;
  215. STACK[sp++] = right;
  216. STACK[sp++] = 1 - axis;
  217. }
  218. }
  219. return count;
  220. }
  221. }
  222. /**
  223. * @param {Uint16Array | Uint32Array} ids
  224. * @param {TypedArray} coords
  225. * @param {number} nodeSize
  226. * @param {number} left
  227. * @param {number} right
  228. * @param {number} axis
  229. */
  230. function sort(ids, coords, nodeSize, left, right, axis) {
  231. if (right - left <= nodeSize) return;
  232. const m = (left + right) >> 1; // middle index
  233. // sort ids and coords around the middle index so that the halves lie
  234. // either left/right or top/bottom correspondingly (taking turns)
  235. select(ids, coords, m, left, right, axis);
  236. // recursively kd-sort first half and second half on the opposite axis
  237. sort(ids, coords, nodeSize, left, m - 1, 1 - axis);
  238. sort(ids, coords, nodeSize, m + 1, right, 1 - axis);
  239. }
  240. /**
  241. * Custom Floyd-Rivest selection algorithm: sort ids and coords so that
  242. * [left..k-1] items are smaller than k-th item (on either x or y axis)
  243. * @param {Uint16Array | Uint32Array} ids
  244. * @param {TypedArray} coords
  245. * @param {number} k
  246. * @param {number} left
  247. * @param {number} right
  248. * @param {number} axis
  249. */
  250. function select(ids, coords, k, left, right, axis) {
  251. while (right > left) {
  252. if (right - left > 600) {
  253. const n = right - left + 1;
  254. const m = k - left + 1;
  255. const z = Math.log(n);
  256. const s = 0.5 * Math.exp(2 * z / 3);
  257. const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
  258. const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
  259. const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
  260. select(ids, coords, k, newLeft, newRight, axis);
  261. }
  262. const t = coords[2 * k + axis];
  263. let i = left;
  264. let j = right;
  265. swapItem(ids, coords, left, k);
  266. if (coords[2 * right + axis] > t) swapItem(ids, coords, left, right);
  267. while (i < j) {
  268. swapItem(ids, coords, i, j);
  269. i++;
  270. j--;
  271. while (coords[2 * i + axis] < t) i++;
  272. while (coords[2 * j + axis] > t) j--;
  273. }
  274. if (coords[2 * left + axis] === t) swapItem(ids, coords, left, j);
  275. else {
  276. j++;
  277. swapItem(ids, coords, j, right);
  278. }
  279. if (j <= k) left = j + 1;
  280. if (k <= j) right = j - 1;
  281. }
  282. }
  283. /**
  284. * @param {Uint16Array | Uint32Array} ids
  285. * @param {TypedArray} coords
  286. * @param {number} i
  287. * @param {number} j
  288. */
  289. function swapItem(ids, coords, i, j) {
  290. swap(ids, i, j);
  291. swap(coords, 2 * i, 2 * j);
  292. swap(coords, 2 * i + 1, 2 * j + 1);
  293. }
  294. /**
  295. * @param {TypedArray} arr
  296. * @param {number} i
  297. * @param {number} j
  298. */
  299. function swap(arr, i, j) {
  300. const tmp = arr[i];
  301. arr[i] = arr[j];
  302. arr[j] = tmp;
  303. }
  304. /**
  305. * @param {number} ax
  306. * @param {number} ay
  307. * @param {number} bx
  308. * @param {number} by
  309. */
  310. function sqDist(ax, ay, bx, by) {
  311. const dx = ax - bx;
  312. const dy = ay - by;
  313. return dx * dx + dy * dy;
  314. }