index.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. const EPSILON = Math.pow(2, -52);
  2. const EDGE_STACK = new Uint32Array(512);
  3. export default class Delaunator {
  4. static from(points, getX = defaultGetX, getY = defaultGetY) {
  5. const n = points.length;
  6. const coords = new Float64Array(n * 2);
  7. for (let i = 0; i < n; i++) {
  8. const p = points[i];
  9. coords[2 * i] = getX(p);
  10. coords[2 * i + 1] = getY(p);
  11. }
  12. return new Delaunator(coords);
  13. }
  14. constructor(coords) {
  15. const n = coords.length >> 1;
  16. if (n > 0 && typeof coords[0] !== 'number') throw new Error('Expected coords to contain numbers.');
  17. this.coords = coords;
  18. // arrays that will store the triangulation graph
  19. const maxTriangles = Math.max(2 * n - 5, 0);
  20. this._triangles = new Uint32Array(maxTriangles * 3);
  21. this._halfedges = new Int32Array(maxTriangles * 3);
  22. // temporary arrays for tracking the edges of the advancing convex hull
  23. this._hashSize = Math.ceil(Math.sqrt(n));
  24. this._hullPrev = new Uint32Array(n); // edge to prev edge
  25. this._hullNext = new Uint32Array(n); // edge to next edge
  26. this._hullTri = new Uint32Array(n); // edge to adjacent triangle
  27. this._hullHash = new Int32Array(this._hashSize).fill(-1); // angular edge hash
  28. // temporary arrays for sorting points
  29. this._ids = new Uint32Array(n);
  30. this._dists = new Float64Array(n);
  31. this.update();
  32. }
  33. update() {
  34. const {coords, _hullPrev: hullPrev, _hullNext: hullNext, _hullTri: hullTri, _hullHash: hullHash} = this;
  35. const n = coords.length >> 1;
  36. // populate an array of point indices; calculate input data bbox
  37. let minX = Infinity;
  38. let minY = Infinity;
  39. let maxX = -Infinity;
  40. let maxY = -Infinity;
  41. for (let i = 0; i < n; i++) {
  42. const x = coords[2 * i];
  43. const y = coords[2 * i + 1];
  44. if (x < minX) minX = x;
  45. if (y < minY) minY = y;
  46. if (x > maxX) maxX = x;
  47. if (y > maxY) maxY = y;
  48. this._ids[i] = i;
  49. }
  50. const cx = (minX + maxX) / 2;
  51. const cy = (minY + maxY) / 2;
  52. let minDist = Infinity;
  53. let i0, i1, i2;
  54. // pick a seed point close to the center
  55. for (let i = 0; i < n; i++) {
  56. const d = dist(cx, cy, coords[2 * i], coords[2 * i + 1]);
  57. if (d < minDist) {
  58. i0 = i;
  59. minDist = d;
  60. }
  61. }
  62. const i0x = coords[2 * i0];
  63. const i0y = coords[2 * i0 + 1];
  64. minDist = Infinity;
  65. // find the point closest to the seed
  66. for (let i = 0; i < n; i++) {
  67. if (i === i0) continue;
  68. const d = dist(i0x, i0y, coords[2 * i], coords[2 * i + 1]);
  69. if (d < minDist && d > 0) {
  70. i1 = i;
  71. minDist = d;
  72. }
  73. }
  74. let i1x = coords[2 * i1];
  75. let i1y = coords[2 * i1 + 1];
  76. let minRadius = Infinity;
  77. // find the third point which forms the smallest circumcircle with the first two
  78. for (let i = 0; i < n; i++) {
  79. if (i === i0 || i === i1) continue;
  80. const r = circumradius(i0x, i0y, i1x, i1y, coords[2 * i], coords[2 * i + 1]);
  81. if (r < minRadius) {
  82. i2 = i;
  83. minRadius = r;
  84. }
  85. }
  86. let i2x = coords[2 * i2];
  87. let i2y = coords[2 * i2 + 1];
  88. if (minRadius === Infinity) {
  89. // order collinear points by dx (or dy if all x are identical)
  90. // and return the list as a hull
  91. for (let i = 0; i < n; i++) {
  92. this._dists[i] = (coords[2 * i] - coords[0]) || (coords[2 * i + 1] - coords[1]);
  93. }
  94. quicksort(this._ids, this._dists, 0, n - 1);
  95. const hull = new Uint32Array(n);
  96. let j = 0;
  97. for (let i = 0, d0 = -Infinity; i < n; i++) {
  98. const id = this._ids[i];
  99. if (this._dists[id] > d0) {
  100. hull[j++] = id;
  101. d0 = this._dists[id];
  102. }
  103. }
  104. this.hull = hull.subarray(0, j);
  105. this.triangles = new Uint32Array(0);
  106. this.halfedges = new Uint32Array(0);
  107. return;
  108. }
  109. // swap the order of the seed points for counter-clockwise orientation
  110. if (orient(i0x, i0y, i1x, i1y, i2x, i2y)) {
  111. const i = i1;
  112. const x = i1x;
  113. const y = i1y;
  114. i1 = i2;
  115. i1x = i2x;
  116. i1y = i2y;
  117. i2 = i;
  118. i2x = x;
  119. i2y = y;
  120. }
  121. const center = circumcenter(i0x, i0y, i1x, i1y, i2x, i2y);
  122. this._cx = center.x;
  123. this._cy = center.y;
  124. for (let i = 0; i < n; i++) {
  125. this._dists[i] = dist(coords[2 * i], coords[2 * i + 1], center.x, center.y);
  126. }
  127. // sort the points by distance from the seed triangle circumcenter
  128. quicksort(this._ids, this._dists, 0, n - 1);
  129. // set up the seed triangle as the starting hull
  130. this._hullStart = i0;
  131. let hullSize = 3;
  132. hullNext[i0] = hullPrev[i2] = i1;
  133. hullNext[i1] = hullPrev[i0] = i2;
  134. hullNext[i2] = hullPrev[i1] = i0;
  135. hullTri[i0] = 0;
  136. hullTri[i1] = 1;
  137. hullTri[i2] = 2;
  138. hullHash.fill(-1);
  139. hullHash[this._hashKey(i0x, i0y)] = i0;
  140. hullHash[this._hashKey(i1x, i1y)] = i1;
  141. hullHash[this._hashKey(i2x, i2y)] = i2;
  142. this.trianglesLen = 0;
  143. this._addTriangle(i0, i1, i2, -1, -1, -1);
  144. for (let k = 0, xp, yp; k < this._ids.length; k++) {
  145. const i = this._ids[k];
  146. const x = coords[2 * i];
  147. const y = coords[2 * i + 1];
  148. // skip near-duplicate points
  149. if (k > 0 && Math.abs(x - xp) <= EPSILON && Math.abs(y - yp) <= EPSILON) continue;
  150. xp = x;
  151. yp = y;
  152. // skip seed triangle points
  153. if (i === i0 || i === i1 || i === i2) continue;
  154. // find a visible edge on the convex hull using edge hash
  155. let start = 0;
  156. for (let j = 0, key = this._hashKey(x, y); j < this._hashSize; j++) {
  157. start = hullHash[(key + j) % this._hashSize];
  158. if (start !== -1 && start !== hullNext[start]) break;
  159. }
  160. start = hullPrev[start];
  161. let e = start, q;
  162. while (q = hullNext[e], !orient(x, y, coords[2 * e], coords[2 * e + 1], coords[2 * q], coords[2 * q + 1])) {
  163. e = q;
  164. if (e === start) {
  165. e = -1;
  166. break;
  167. }
  168. }
  169. if (e === -1) continue; // likely a near-duplicate point; skip it
  170. // add the first triangle from the point
  171. let t = this._addTriangle(e, i, hullNext[e], -1, -1, hullTri[e]);
  172. // recursively flip triangles from the point until they satisfy the Delaunay condition
  173. hullTri[i] = this._legalize(t + 2);
  174. hullTri[e] = t; // keep track of boundary triangles on the hull
  175. hullSize++;
  176. // walk forward through the hull, adding more triangles and flipping recursively
  177. let n = hullNext[e];
  178. while (q = hullNext[n], orient(x, y, coords[2 * n], coords[2 * n + 1], coords[2 * q], coords[2 * q + 1])) {
  179. t = this._addTriangle(n, i, q, hullTri[i], -1, hullTri[n]);
  180. hullTri[i] = this._legalize(t + 2);
  181. hullNext[n] = n; // mark as removed
  182. hullSize--;
  183. n = q;
  184. }
  185. // walk backward from the other side, adding more triangles and flipping
  186. if (e === start) {
  187. while (q = hullPrev[e], orient(x, y, coords[2 * q], coords[2 * q + 1], coords[2 * e], coords[2 * e + 1])) {
  188. t = this._addTriangle(q, i, e, -1, hullTri[e], hullTri[q]);
  189. this._legalize(t + 2);
  190. hullTri[q] = t;
  191. hullNext[e] = e; // mark as removed
  192. hullSize--;
  193. e = q;
  194. }
  195. }
  196. // update the hull indices
  197. this._hullStart = hullPrev[i] = e;
  198. hullNext[e] = hullPrev[n] = i;
  199. hullNext[i] = n;
  200. // save the two new edges in the hash table
  201. hullHash[this._hashKey(x, y)] = i;
  202. hullHash[this._hashKey(coords[2 * e], coords[2 * e + 1])] = e;
  203. }
  204. this.hull = new Uint32Array(hullSize);
  205. for (let i = 0, e = this._hullStart; i < hullSize; i++) {
  206. this.hull[i] = e;
  207. e = hullNext[e];
  208. }
  209. // trim typed triangle mesh arrays
  210. this.triangles = this._triangles.subarray(0, this.trianglesLen);
  211. this.halfedges = this._halfedges.subarray(0, this.trianglesLen);
  212. }
  213. _hashKey(x, y) {
  214. return Math.floor(pseudoAngle(x - this._cx, y - this._cy) * this._hashSize) % this._hashSize;
  215. }
  216. _legalize(a) {
  217. const {_triangles: triangles, _halfedges: halfedges, coords} = this;
  218. let i = 0;
  219. let ar = 0;
  220. // recursion eliminated with a fixed-size stack
  221. while (true) {
  222. const b = halfedges[a];
  223. /* if the pair of triangles doesn't satisfy the Delaunay condition
  224. * (p1 is inside the circumcircle of [p0, pl, pr]), flip them,
  225. * then do the same check/flip recursively for the new pair of triangles
  226. *
  227. * pl pl
  228. * /||\ / \
  229. * al/ || \bl al/ \a
  230. * / || \ / \
  231. * / a||b \ flip /___ar___\
  232. * p0\ || /p1 => p0\---bl---/p1
  233. * \ || / \ /
  234. * ar\ || /br b\ /br
  235. * \||/ \ /
  236. * pr pr
  237. */
  238. const a0 = a - a % 3;
  239. ar = a0 + (a + 2) % 3;
  240. if (b === -1) { // convex hull edge
  241. if (i === 0) break;
  242. a = EDGE_STACK[--i];
  243. continue;
  244. }
  245. const b0 = b - b % 3;
  246. const al = a0 + (a + 1) % 3;
  247. const bl = b0 + (b + 2) % 3;
  248. const p0 = triangles[ar];
  249. const pr = triangles[a];
  250. const pl = triangles[al];
  251. const p1 = triangles[bl];
  252. const illegal = inCircle(
  253. coords[2 * p0], coords[2 * p0 + 1],
  254. coords[2 * pr], coords[2 * pr + 1],
  255. coords[2 * pl], coords[2 * pl + 1],
  256. coords[2 * p1], coords[2 * p1 + 1]);
  257. if (illegal) {
  258. triangles[a] = p1;
  259. triangles[b] = p0;
  260. const hbl = halfedges[bl];
  261. // edge swapped on the other side of the hull (rare); fix the halfedge reference
  262. if (hbl === -1) {
  263. let e = this._hullStart;
  264. do {
  265. if (this._hullTri[e] === bl) {
  266. this._hullTri[e] = a;
  267. break;
  268. }
  269. e = this._hullPrev[e];
  270. } while (e !== this._hullStart);
  271. }
  272. this._link(a, hbl);
  273. this._link(b, halfedges[ar]);
  274. this._link(ar, bl);
  275. const br = b0 + (b + 1) % 3;
  276. // don't worry about hitting the cap: it can only happen on extremely degenerate input
  277. if (i < EDGE_STACK.length) {
  278. EDGE_STACK[i++] = br;
  279. }
  280. } else {
  281. if (i === 0) break;
  282. a = EDGE_STACK[--i];
  283. }
  284. }
  285. return ar;
  286. }
  287. _link(a, b) {
  288. this._halfedges[a] = b;
  289. if (b !== -1) this._halfedges[b] = a;
  290. }
  291. // add a new triangle given vertex indices and adjacent half-edge ids
  292. _addTriangle(i0, i1, i2, a, b, c) {
  293. const t = this.trianglesLen;
  294. this._triangles[t] = i0;
  295. this._triangles[t + 1] = i1;
  296. this._triangles[t + 2] = i2;
  297. this._link(t, a);
  298. this._link(t + 1, b);
  299. this._link(t + 2, c);
  300. this.trianglesLen += 3;
  301. return t;
  302. }
  303. }
  304. // monotonically increases with real angle, but doesn't need expensive trigonometry
  305. function pseudoAngle(dx, dy) {
  306. const p = dx / (Math.abs(dx) + Math.abs(dy));
  307. return (dy > 0 ? 3 - p : 1 + p) / 4; // [0..1]
  308. }
  309. function dist(ax, ay, bx, by) {
  310. const dx = ax - bx;
  311. const dy = ay - by;
  312. return dx * dx + dy * dy;
  313. }
  314. // return 2d orientation sign if we're confident in it through J. Shewchuk's error bound check
  315. function orientIfSure(px, py, rx, ry, qx, qy) {
  316. const l = (ry - py) * (qx - px);
  317. const r = (rx - px) * (qy - py);
  318. return Math.abs(l - r) >= 3.3306690738754716e-16 * Math.abs(l + r) ? l - r : 0;
  319. }
  320. // a more robust orientation test that's stable in a given triangle (to fix robustness issues)
  321. function orient(rx, ry, qx, qy, px, py) {
  322. const sign = orientIfSure(px, py, rx, ry, qx, qy) ||
  323. orientIfSure(rx, ry, qx, qy, px, py) ||
  324. orientIfSure(qx, qy, px, py, rx, ry);
  325. return sign < 0;
  326. }
  327. function inCircle(ax, ay, bx, by, cx, cy, px, py) {
  328. const dx = ax - px;
  329. const dy = ay - py;
  330. const ex = bx - px;
  331. const ey = by - py;
  332. const fx = cx - px;
  333. const fy = cy - py;
  334. const ap = dx * dx + dy * dy;
  335. const bp = ex * ex + ey * ey;
  336. const cp = fx * fx + fy * fy;
  337. return dx * (ey * cp - bp * fy) -
  338. dy * (ex * cp - bp * fx) +
  339. ap * (ex * fy - ey * fx) < 0;
  340. }
  341. function circumradius(ax, ay, bx, by, cx, cy) {
  342. const dx = bx - ax;
  343. const dy = by - ay;
  344. const ex = cx - ax;
  345. const ey = cy - ay;
  346. const bl = dx * dx + dy * dy;
  347. const cl = ex * ex + ey * ey;
  348. const d = 0.5 / (dx * ey - dy * ex);
  349. const x = (ey * bl - dy * cl) * d;
  350. const y = (dx * cl - ex * bl) * d;
  351. return x * x + y * y;
  352. }
  353. function circumcenter(ax, ay, bx, by, cx, cy) {
  354. const dx = bx - ax;
  355. const dy = by - ay;
  356. const ex = cx - ax;
  357. const ey = cy - ay;
  358. const bl = dx * dx + dy * dy;
  359. const cl = ex * ex + ey * ey;
  360. const d = 0.5 / (dx * ey - dy * ex);
  361. const x = ax + (ey * bl - dy * cl) * d;
  362. const y = ay + (dx * cl - ex * bl) * d;
  363. return {x, y};
  364. }
  365. function quicksort(ids, dists, left, right) {
  366. if (right - left <= 20) {
  367. for (let i = left + 1; i <= right; i++) {
  368. const temp = ids[i];
  369. const tempDist = dists[temp];
  370. let j = i - 1;
  371. while (j >= left && dists[ids[j]] > tempDist) ids[j + 1] = ids[j--];
  372. ids[j + 1] = temp;
  373. }
  374. } else {
  375. const median = (left + right) >> 1;
  376. let i = left + 1;
  377. let j = right;
  378. swap(ids, median, i);
  379. if (dists[ids[left]] > dists[ids[right]]) swap(ids, left, right);
  380. if (dists[ids[i]] > dists[ids[right]]) swap(ids, i, right);
  381. if (dists[ids[left]] > dists[ids[i]]) swap(ids, left, i);
  382. const temp = ids[i];
  383. const tempDist = dists[temp];
  384. while (true) {
  385. do i++; while (dists[ids[i]] < tempDist);
  386. do j--; while (dists[ids[j]] > tempDist);
  387. if (j < i) break;
  388. swap(ids, i, j);
  389. }
  390. ids[left + 1] = ids[j];
  391. ids[j] = temp;
  392. if (right - i + 1 >= j - left) {
  393. quicksort(ids, dists, i, right);
  394. quicksort(ids, dists, left, j - 1);
  395. } else {
  396. quicksort(ids, dists, left, j - 1);
  397. quicksort(ids, dists, i, right);
  398. }
  399. }
  400. }
  401. function swap(arr, i, j) {
  402. const tmp = arr[i];
  403. arr[i] = arr[j];
  404. arr[j] = tmp;
  405. }
  406. function defaultGetX(p) {
  407. return p[0];
  408. }
  409. function defaultGetY(p) {
  410. return p[1];
  411. }