index.js 15 KB

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