earcut-2.1.1.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. function earcut(data, holeIndices, dim) {
  2. dim = dim || 2;
  3. var hasHoles = holeIndices && holeIndices.length,
  4. outerLen = hasHoles ? holeIndices[0] * dim : data.length,
  5. outerNode = linkedList(data, 0, outerLen, dim, true),
  6. triangles = [];
  7. if (!outerNode) return triangles;
  8. var minX, minY, maxX, maxY, x, y, size;
  9. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  10. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  11. if (data.length > 80 * dim) {
  12. minX = maxX = data[0];
  13. minY = maxY = data[1];
  14. for (var i = dim; i < outerLen; i += dim) {
  15. x = data[i];
  16. y = data[i + 1];
  17. if (x < minX) minX = x;
  18. if (y < minY) minY = y;
  19. if (x > maxX) maxX = x;
  20. if (y > maxY) maxY = y;
  21. }
  22. // minX, minY and size are later used to transform coords into integers for z-order calculation
  23. size = Math.max(maxX - minX, maxY - minY);
  24. }
  25. earcutLinked(outerNode, triangles, dim, minX, minY, size);
  26. return triangles;
  27. }
  28. // create a circular doubly linked list from polygon points in the specified winding order
  29. function linkedList(data, start, end, dim, clockwise) {
  30. var i, last;
  31. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  32. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  33. } else {
  34. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  35. }
  36. if (last && equals(last, last.next)) {
  37. removeNode(last);
  38. last = last.next;
  39. }
  40. return last;
  41. }
  42. // eliminate colinear or duplicate points
  43. function filterPoints(start, end) {
  44. if (!start) return start;
  45. if (!end) end = start;
  46. var p = start,
  47. again;
  48. do {
  49. again = false;
  50. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  51. removeNode(p);
  52. p = end = p.prev;
  53. if (p === p.next) return null;
  54. again = true;
  55. } else {
  56. p = p.next;
  57. }
  58. } while (again || p !== end);
  59. return end;
  60. }
  61. // main ear slicing loop which triangulates a polygon (given as a linked list)
  62. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  63. if (!ear) return;
  64. // interlink polygon nodes in z-order
  65. if (!pass && size) indexCurve(ear, minX, minY, size);
  66. var stop = ear,
  67. prev, next;
  68. // iterate through ears, slicing them one by one
  69. while (ear.prev !== ear.next) {
  70. prev = ear.prev;
  71. next = ear.next;
  72. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  73. // cut off the triangle
  74. triangles.push(prev.i / dim);
  75. triangles.push(ear.i / dim);
  76. triangles.push(next.i / dim);
  77. removeNode(ear);
  78. // skipping the next vertice leads to less sliver triangles
  79. ear = next.next;
  80. stop = next.next;
  81. continue;
  82. }
  83. ear = next;
  84. // if we looped through the whole remaining polygon and can't find any more ears
  85. if (ear === stop) {
  86. // try filtering points and slicing again
  87. if (!pass) {
  88. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1);
  89. // if this didn't work, try curing all small self-intersections locally
  90. } else if (pass === 1) {
  91. ear = cureLocalIntersections(ear, triangles, dim);
  92. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  93. // as a last resort, try splitting the remaining polygon into two
  94. } else if (pass === 2) {
  95. splitEarcut(ear, triangles, dim, minX, minY, size);
  96. }
  97. break;
  98. }
  99. }
  100. }
  101. // check whether a polygon node forms a valid ear with adjacent nodes
  102. function isEar(ear) {
  103. var a = ear.prev,
  104. b = ear,
  105. c = ear.next;
  106. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  107. // now make sure we don't have other points inside the potential ear
  108. var p = ear.next.next;
  109. while (p !== ear.prev) {
  110. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  111. area(p.prev, p, p.next) >= 0) return false;
  112. p = p.next;
  113. }
  114. return true;
  115. }
  116. function isEarHashed(ear, minX, minY, size) {
  117. var a = ear.prev,
  118. b = ear,
  119. c = ear.next;
  120. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  121. // triangle bbox; min & max are calculated like this for speed
  122. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),
  123. minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),
  124. maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),
  125. maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  126. // z-order range for the current triangle bbox;
  127. var minZ = zOrder(minTX, minTY, minX, minY, size),
  128. maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  129. // first look for points inside the triangle in increasing z-order
  130. var p = ear.nextZ;
  131. while (p && p.z <= maxZ) {
  132. if (p !== ear.prev && p !== ear.next &&
  133. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  134. area(p.prev, p, p.next) >= 0) return false;
  135. p = p.nextZ;
  136. }
  137. // then look for points in decreasing z-order
  138. p = ear.prevZ;
  139. while (p && p.z >= minZ) {
  140. if (p !== ear.prev && p !== ear.next &&
  141. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  142. area(p.prev, p, p.next) >= 0) return false;
  143. p = p.prevZ;
  144. }
  145. return true;
  146. }
  147. // go through all polygon nodes and cure small local self-intersections
  148. function cureLocalIntersections(start, triangles, dim) {
  149. var p = start;
  150. do {
  151. var a = p.prev,
  152. b = p.next.next;
  153. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  154. triangles.push(a.i / dim);
  155. triangles.push(p.i / dim);
  156. triangles.push(b.i / dim);
  157. // remove two nodes involved
  158. removeNode(p);
  159. removeNode(p.next);
  160. p = start = b;
  161. }
  162. p = p.next;
  163. } while (p !== start);
  164. return p;
  165. }
  166. // try splitting polygon into two and triangulate them independently
  167. function splitEarcut(start, triangles, dim, minX, minY, size) {
  168. // look for a valid diagonal that divides the polygon into two
  169. var a = start;
  170. do {
  171. var b = a.next.next;
  172. while (b !== a.prev) {
  173. if (a.i !== b.i && isValidDiagonal(a, b)) {
  174. // split the polygon in two by the diagonal
  175. var c = splitPolygon(a, b);
  176. // filter colinear points around the cuts
  177. a = filterPoints(a, a.next);
  178. c = filterPoints(c, c.next);
  179. // run earcut on each half
  180. earcutLinked(a, triangles, dim, minX, minY, size);
  181. earcutLinked(c, triangles, dim, minX, minY, size);
  182. return;
  183. }
  184. b = b.next;
  185. }
  186. a = a.next;
  187. } while (a !== start);
  188. }
  189. // link every hole into the outer loop, producing a single-ring polygon without holes
  190. function eliminateHoles(data, holeIndices, outerNode, dim) {
  191. var queue = [],
  192. i, len, start, end, list;
  193. for (i = 0, len = holeIndices.length; i < len; i++) {
  194. start = holeIndices[i] * dim;
  195. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  196. list = linkedList(data, start, end, dim, false);
  197. if (list === list.next) list.steiner = true;
  198. queue.push(getLeftmost(list));
  199. }
  200. queue.sort(compareX);
  201. // process holes from left to right
  202. for (i = 0; i < queue.length; i++) {
  203. eliminateHole(queue[i], outerNode);
  204. outerNode = filterPoints(outerNode, outerNode.next);
  205. }
  206. return outerNode;
  207. }
  208. function compareX(a, b) {
  209. return a.x - b.x;
  210. }
  211. // find a bridge between vertices that connects hole with an outer ring and and link it
  212. function eliminateHole(hole, outerNode) {
  213. outerNode = findHoleBridge(hole, outerNode);
  214. if (outerNode) {
  215. var b = splitPolygon(outerNode, hole);
  216. filterPoints(b, b.next);
  217. }
  218. }
  219. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  220. function findHoleBridge(hole, outerNode) {
  221. var p = outerNode,
  222. hx = hole.x,
  223. hy = hole.y,
  224. qx = -Infinity,
  225. m;
  226. // find a segment intersected by a ray from the hole's leftmost point to the left;
  227. // segment's endpoint with lesser x will be potential connection point
  228. do {
  229. if (hy <= p.y && hy >= p.next.y) {
  230. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  231. if (x <= hx && x > qx) {
  232. qx = x;
  233. if (x === hx) {
  234. if (hy === p.y) return p;
  235. if (hy === p.next.y) return p.next;
  236. }
  237. m = p.x < p.next.x ? p : p.next;
  238. }
  239. }
  240. p = p.next;
  241. } while (p !== outerNode);
  242. if (!m) return null;
  243. if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
  244. // look for points inside the triangle of hole point, segment intersection and endpoint;
  245. // if there are no points found, we have a valid connection;
  246. // otherwise choose the point of the minimum angle with the ray as connection point
  247. var stop = m,
  248. mx = m.x,
  249. my = m.y,
  250. tanMin = Infinity,
  251. tan;
  252. p = m.next;
  253. while (p !== stop) {
  254. if (hx >= p.x && p.x >= mx &&
  255. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  256. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  257. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  258. m = p;
  259. tanMin = tan;
  260. }
  261. }
  262. p = p.next;
  263. }
  264. return m;
  265. }
  266. // interlink polygon nodes in z-order
  267. function indexCurve(start, minX, minY, size) {
  268. var p = start;
  269. do {
  270. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size);
  271. p.prevZ = p.prev;
  272. p.nextZ = p.next;
  273. p = p.next;
  274. } while (p !== start);
  275. p.prevZ.nextZ = null;
  276. p.prevZ = null;
  277. sortLinked(p);
  278. }
  279. // Simon Tatham's linked list merge sort algorithm
  280. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  281. function sortLinked(list) {
  282. var i, p, q, e, tail, numMerges, pSize, qSize,
  283. inSize = 1;
  284. do {
  285. p = list;
  286. list = null;
  287. tail = null;
  288. numMerges = 0;
  289. while (p) {
  290. numMerges++;
  291. q = p;
  292. pSize = 0;
  293. for (i = 0; i < inSize; i++) {
  294. pSize++;
  295. q = q.nextZ;
  296. if (!q) break;
  297. }
  298. qSize = inSize;
  299. while (pSize > 0 || (qSize > 0 && q)) {
  300. if (pSize === 0) {
  301. e = q;
  302. q = q.nextZ;
  303. qSize--;
  304. } else if (qSize === 0 || !q) {
  305. e = p;
  306. p = p.nextZ;
  307. pSize--;
  308. } else if (p.z <= q.z) {
  309. e = p;
  310. p = p.nextZ;
  311. pSize--;
  312. } else {
  313. e = q;
  314. q = q.nextZ;
  315. qSize--;
  316. }
  317. if (tail) tail.nextZ = e;
  318. else list = e;
  319. e.prevZ = tail;
  320. tail = e;
  321. }
  322. p = q;
  323. }
  324. tail.nextZ = null;
  325. inSize *= 2;
  326. } while (numMerges > 1);
  327. return list;
  328. }
  329. // z-order of a point given coords and size of the data bounding box
  330. function zOrder(x, y, minX, minY, size) {
  331. // coords are transformed into non-negative 15-bit integer range
  332. x = 32767 * (x - minX) / size;
  333. y = 32767 * (y - minY) / size;
  334. x = (x | (x << 8)) & 0x00FF00FF;
  335. x = (x | (x << 4)) & 0x0F0F0F0F;
  336. x = (x | (x << 2)) & 0x33333333;
  337. x = (x | (x << 1)) & 0x55555555;
  338. y = (y | (y << 8)) & 0x00FF00FF;
  339. y = (y | (y << 4)) & 0x0F0F0F0F;
  340. y = (y | (y << 2)) & 0x33333333;
  341. y = (y | (y << 1)) & 0x55555555;
  342. return x | (y << 1);
  343. }
  344. // find the leftmost node of a polygon ring
  345. function getLeftmost(start) {
  346. var p = start,
  347. leftmost = start;
  348. do {
  349. if (p.x < leftmost.x) leftmost = p;
  350. p = p.next;
  351. } while (p !== start);
  352. return leftmost;
  353. }
  354. // check if a point lies within a convex triangle
  355. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  356. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  357. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  358. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  359. }
  360. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  361. function isValidDiagonal(a, b) {
  362. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) &&
  363. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
  364. }
  365. // signed area of a triangle
  366. function area(p, q, r) {
  367. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  368. }
  369. // check if two points are equal
  370. function equals(p1, p2) {
  371. return p1.x === p2.x && p1.y === p2.y;
  372. }
  373. // check if two segments intersect
  374. function intersects(p1, q1, p2, q2) {
  375. if ((equals(p1, q1) && equals(p2, q2)) ||
  376. (equals(p1, q2) && equals(p2, q1))) return true;
  377. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  378. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  379. }
  380. // check if a polygon diagonal intersects any polygon segments
  381. function intersectsPolygon(a, b) {
  382. var p = a;
  383. do {
  384. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  385. intersects(p, p.next, a, b)) return true;
  386. p = p.next;
  387. } while (p !== a);
  388. return false;
  389. }
  390. // check if a polygon diagonal is locally inside the polygon
  391. function locallyInside(a, b) {
  392. return area(a.prev, a, a.next) < 0 ?
  393. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  394. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  395. }
  396. // check if the middle point of a polygon diagonal is inside the polygon
  397. function middleInside(a, b) {
  398. var p = a,
  399. inside = false,
  400. px = (a.x + b.x) / 2,
  401. py = (a.y + b.y) / 2;
  402. do {
  403. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  404. inside = !inside;
  405. p = p.next;
  406. } while (p !== a);
  407. return inside;
  408. }
  409. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  410. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  411. function splitPolygon(a, b) {
  412. var a2 = new Node(a.i, a.x, a.y),
  413. b2 = new Node(b.i, b.x, b.y),
  414. an = a.next,
  415. bp = b.prev;
  416. a.next = b;
  417. b.prev = a;
  418. a2.next = an;
  419. an.prev = a2;
  420. b2.next = a2;
  421. a2.prev = b2;
  422. bp.next = b2;
  423. b2.prev = bp;
  424. return b2;
  425. }
  426. // create a node and optionally link it with previous one (in a circular doubly linked list)
  427. function insertNode(i, x, y, last) {
  428. var p = new Node(i, x, y);
  429. if (!last) {
  430. p.prev = p;
  431. p.next = p;
  432. } else {
  433. p.next = last.next;
  434. p.prev = last;
  435. last.next.prev = p;
  436. last.next = p;
  437. }
  438. return p;
  439. }
  440. function removeNode(p) {
  441. p.next.prev = p.prev;
  442. p.prev.next = p.next;
  443. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  444. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  445. }
  446. function Node(i, x, y) {
  447. // vertice index in coordinates array
  448. this.i = i;
  449. // vertex coordinates
  450. this.x = x;
  451. this.y = y;
  452. // previous and next vertice nodes in a polygon ring
  453. this.prev = null;
  454. this.next = null;
  455. // z-order curve value
  456. this.z = null;
  457. // previous and next nodes in z-order
  458. this.prevZ = null;
  459. this.nextZ = null;
  460. // indicates whether this is a steiner point
  461. this.steiner = false;
  462. }
  463. // return a percentage difference between the polygon area and its triangulation area;
  464. // used to verify correctness of triangulation
  465. earcut.deviation = function (data, holeIndices, dim, triangles) {
  466. var hasHoles = holeIndices && holeIndices.length;
  467. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  468. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  469. if (hasHoles) {
  470. for (var i = 0, len = holeIndices.length; i < len; i++) {
  471. var start = holeIndices[i] * dim;
  472. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  473. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  474. }
  475. }
  476. var trianglesArea = 0;
  477. for (i = 0; i < triangles.length; i += 3) {
  478. var a = triangles[i] * dim;
  479. var b = triangles[i + 1] * dim;
  480. var c = triangles[i + 2] * dim;
  481. trianglesArea += Math.abs(
  482. (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  483. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  484. }
  485. return polygonArea === 0 && trianglesArea === 0 ? 0 :
  486. Math.abs((trianglesArea - polygonArea) / polygonArea);
  487. };
  488. function signedArea(data, start, end, dim) {
  489. var sum = 0;
  490. for (var i = start, j = end - dim; i < end; i += dim) {
  491. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  492. j = i;
  493. }
  494. return sum;
  495. }
  496. // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  497. earcut.flatten = function (data) {
  498. var dim = data[0][0].length,
  499. result = {vertices: [], holes: [], dimensions: dim},
  500. holeIndex = 0;
  501. for (var i = 0; i < data.length; i++) {
  502. for (var j = 0; j < data[i].length; j++) {
  503. for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
  504. }
  505. if (i > 0) {
  506. holeIndex += data[i - 1].length;
  507. result.holes.push(holeIndex);
  508. }
  509. }
  510. return result;
  511. };
  512. export default earcut;