Clipper.Offset.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  1. 
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Runtime.CompilerServices;
  5. namespace Clipper2Lib
  6. {
  7. public enum JoinType
  8. {
  9. Square,
  10. Round,
  11. Miter
  12. };
  13. public enum EndType
  14. {
  15. Polygon,
  16. Joined,
  17. Butt,
  18. Square,
  19. Round
  20. };
  21. public class ClipperOffset
  22. {
  23. private class Group
  24. {
  25. internal Paths64 _inPaths;
  26. internal Path64 _outPath;
  27. internal Paths64 _outPaths;
  28. internal JoinType _joinType;
  29. internal EndType _endType;
  30. internal bool _pathsReversed;
  31. public Group(Paths64 paths, JoinType joinType, EndType endType = EndType.Polygon)
  32. {
  33. _inPaths = new Paths64(paths);
  34. _joinType = joinType;
  35. _endType = endType;
  36. _outPath = new Path64();
  37. _outPaths = new Paths64();
  38. _pathsReversed = false;
  39. }
  40. }
  41. private readonly List<Group> _pathGroups = new List<Group>();
  42. private readonly PathD _normals = new PathD();
  43. private readonly Paths64 solution = new Paths64();
  44. private double _group_delta, _abs_group_delta, _tmpLimit, _stepsPerRad;
  45. private JoinType _joinType;
  46. public double ArcTolerance { get; set; }
  47. public bool MergeGroups { get; set; }
  48. public double MiterLimit { get; set; }
  49. public bool PreserveCollinear { get; set; }
  50. public bool ReverseSolution { get; set; }
  51. private const double TwoPi = Math.PI * 2;
  52. public ClipperOffset(double miterLimit = 2.0,
  53. double arcTolerance = 0.0, bool
  54. preserveCollinear = false, bool reverseSolution = false)
  55. {
  56. MiterLimit = miterLimit;
  57. ArcTolerance = arcTolerance;
  58. MergeGroups = true;
  59. PreserveCollinear = preserveCollinear;
  60. ReverseSolution = reverseSolution;
  61. }
  62. public void Clear()
  63. {
  64. _pathGroups.Clear();
  65. }
  66. public void AddPath(Path64 path, JoinType joinType, EndType endType)
  67. {
  68. int cnt = path.Count;
  69. if (cnt == 0)
  70. {
  71. return;
  72. }
  73. Paths64 pp = new Paths64(1) { path };
  74. AddPaths(pp, joinType, endType);
  75. }
  76. public void AddPaths(Paths64 paths, JoinType joinType, EndType endType)
  77. {
  78. int cnt = paths.Count;
  79. if (cnt == 0)
  80. {
  81. return;
  82. }
  83. _pathGroups.Add(new Group(paths, joinType, endType));
  84. }
  85. public Paths64 Execute(double delta)
  86. {
  87. solution.Clear();
  88. if (Math.Abs(delta) < 0.5)
  89. {
  90. foreach (Group group in _pathGroups)
  91. {
  92. foreach (Path64 path in group._inPaths)
  93. {
  94. solution.Add(path);
  95. }
  96. }
  97. return solution;
  98. }
  99. _tmpLimit = (MiterLimit <= 1 ? 2.0 : 2.0 / Clipper.Sqr(MiterLimit));
  100. foreach (Group group in _pathGroups)
  101. {
  102. DoGroupOffset(group, delta);
  103. }
  104. if (MergeGroups && _pathGroups.Count > 0)
  105. {
  106. // clean up self-intersections ...
  107. Clipper64 c = new Clipper64()
  108. {
  109. PreserveCollinear = PreserveCollinear,
  110. // the solution should retain the orientation of the input
  111. ReverseSolution = ReverseSolution != _pathGroups[0]._pathsReversed
  112. };
  113. c.AddSubject(solution);
  114. if (_pathGroups[0]._pathsReversed)
  115. {
  116. c.Execute(ClipType.Union, FillRule.Negative, solution);
  117. }
  118. else
  119. {
  120. c.Execute(ClipType.Union, FillRule.Positive, solution);
  121. }
  122. }
  123. return solution;
  124. }
  125. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  126. internal static PointD GetUnitNormal(Point64 pt1, Point64 pt2)
  127. {
  128. double dx = (pt2.X - pt1.X);
  129. double dy = (pt2.Y - pt1.Y);
  130. if ((dx == 0) && (dy == 0))
  131. {
  132. return new PointD();
  133. }
  134. double f = 1.0 / Math.Sqrt(dx * dx + dy * dy);
  135. dx *= f;
  136. dy *= f;
  137. return new PointD(dy, -dx);
  138. }
  139. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  140. private static int GetLowestPolygonIdx(Paths64 paths)
  141. {
  142. Point64 lp = new Point64(0, long.MinValue);
  143. int result = -1;
  144. for (int i = 0; i < paths.Count; i++)
  145. {
  146. foreach (Point64 pt in paths[i])
  147. {
  148. if (pt.Y < lp.Y || (pt.Y == lp.Y && pt.X >= lp.X))
  149. {
  150. continue;
  151. }
  152. result = i;
  153. lp = pt;
  154. }
  155. }
  156. return result;
  157. }
  158. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  159. private static PointD TranslatePoint(PointD pt, double dx, double dy)
  160. {
  161. return new PointD(pt.x + dx, pt.y + dy);
  162. }
  163. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  164. private static PointD ReflectPoint(PointD pt, PointD pivot)
  165. {
  166. return new PointD(pivot.x + (pivot.x - pt.x), pivot.y + (pivot.y - pt.y));
  167. }
  168. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  169. private static bool AlmostZero(double value, double epsilon = 0.001)
  170. {
  171. return Math.Abs(value) < epsilon;
  172. }
  173. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  174. private static double Hypotenuse(double x, double y)
  175. {
  176. return Math.Sqrt(Math.Pow(x, 2) + Math.Pow(y, 2));
  177. }
  178. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  179. private static PointD NormalizeVector(PointD vec)
  180. {
  181. double h = Hypotenuse(vec.x, vec.y);
  182. if (AlmostZero(h))
  183. {
  184. return new PointD(0, 0);
  185. }
  186. double inverseHypot = 1 / h;
  187. return new PointD(vec.x * inverseHypot, vec.y * inverseHypot);
  188. }
  189. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  190. private static PointD GetAvgUnitVector(PointD vec1, PointD vec2)
  191. {
  192. return NormalizeVector(new PointD(vec1.x + vec2.x, vec1.y + vec2.y));
  193. }
  194. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  195. private static PointD IntersectPoint(PointD pt1a, PointD pt1b, PointD pt2a, PointD pt2b)
  196. {
  197. if (InternalClipper.IsAlmostZero(pt1a.x - pt1b.x)) //vertical
  198. {
  199. if (InternalClipper.IsAlmostZero(pt2a.x - pt2b.x))
  200. {
  201. return new PointD(0, 0);
  202. }
  203. double m2 = (pt2b.y - pt2a.y) / (pt2b.x - pt2a.x);
  204. double b2 = pt2a.y - m2 * pt2a.x;
  205. return new PointD(pt1a.x, m2 * pt1a.x + b2);
  206. }
  207. if (InternalClipper.IsAlmostZero(pt2a.x - pt2b.x)) //vertical
  208. {
  209. double m1 = (pt1b.y - pt1a.y) / (pt1b.x - pt1a.x);
  210. double b1 = pt1a.y - m1 * pt1a.x;
  211. return new PointD(pt2a.x, m1 * pt2a.x + b1);
  212. }
  213. else
  214. {
  215. double m1 = (pt1b.y - pt1a.y) / (pt1b.x - pt1a.x);
  216. double b1 = pt1a.y - m1 * pt1a.x;
  217. double m2 = (pt2b.y - pt2a.y) / (pt2b.x - pt2a.x);
  218. double b2 = pt2a.y - (m2 * pt2a.x);
  219. if (InternalClipper.IsAlmostZero(m1 - m2))
  220. {
  221. return new PointD(0, 0);
  222. }
  223. double x = (b2 - b1) / (m1 - m2);
  224. return new PointD(x, m1 * x + b1);
  225. }
  226. }
  227. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  228. private Point64 GetPerpendic(Point64 pt, PointD norm)
  229. {
  230. return new Point64(pt.X + norm.x * _group_delta,
  231. pt.Y + norm.y * _group_delta);
  232. }
  233. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  234. private PointD GetPerpendicD(Point64 pt, PointD norm)
  235. {
  236. return new PointD(pt.X + norm.x * _group_delta,
  237. pt.Y + norm.y * _group_delta);
  238. }
  239. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  240. private void DoSquare(Group group, Path64 path, int j, int k)
  241. {
  242. PointD vec;
  243. if (j == k)
  244. {
  245. vec = new PointD(_normals[0].y, -_normals[0].x);
  246. }
  247. else
  248. {
  249. vec = GetAvgUnitVector(
  250. new PointD(-_normals[k].y, _normals[k].x),
  251. new PointD(_normals[j].y, -_normals[j].x));
  252. }
  253. // now offset the original vertex delta units along unit vector
  254. PointD ptQ = new PointD(path[j]);
  255. ptQ = TranslatePoint(ptQ, _abs_group_delta * vec.x, _abs_group_delta * vec.y);
  256. // get perpendicular vertices
  257. PointD pt1 = TranslatePoint(ptQ, _group_delta * vec.y, _group_delta * -vec.x);
  258. PointD pt2 = TranslatePoint(ptQ, _group_delta * -vec.y, _group_delta * vec.x);
  259. // get 2 vertices along one edge offset
  260. PointD pt3 = GetPerpendicD(path[k], _normals[k]);
  261. if (j == k)
  262. {
  263. PointD pt4 = new PointD(
  264. pt3.x + vec.x * _group_delta,
  265. pt3.y + vec.y * _group_delta);
  266. PointD pt = IntersectPoint(pt1, pt2, pt3, pt4);
  267. //get the second intersect point through reflecion
  268. group._outPath.Add(new Point64(ReflectPoint(pt, ptQ)));
  269. group._outPath.Add(new Point64(pt));
  270. }
  271. else
  272. {
  273. PointD pt4 = GetPerpendicD(path[j], _normals[k]);
  274. PointD pt = IntersectPoint(pt1, pt2, pt3, pt4);
  275. group._outPath.Add(new Point64(pt));
  276. //get the second intersect point through reflecion
  277. group._outPath.Add(new Point64(ReflectPoint(pt, ptQ)));
  278. }
  279. }
  280. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  281. private void DoMiter(Group group, Path64 path, int j, int k, double cosA)
  282. {
  283. double q = _group_delta / (cosA + 1);
  284. group._outPath.Add(new Point64(
  285. path[j].X + (_normals[k].x + _normals[j].x) * q,
  286. path[j].Y + (_normals[k].y + _normals[j].y) * q));
  287. }
  288. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  289. private void DoRound(Group group, Path64 path, int j, int k, double angle)
  290. {
  291. // even though angle may be negative this is a convex join
  292. Point64 pt = path[j];
  293. PointD pt2 = new PointD(_normals[k].x * _group_delta, _normals[k].y * _group_delta);
  294. if (j == k)
  295. {
  296. pt2.Negate();
  297. }
  298. int steps = (int)Math.Ceiling(_stepsPerRad * Math.Abs(angle));
  299. double stepSin = Math.Sin(angle / steps);
  300. double stepCos = Math.Cos(angle / steps);
  301. group._outPath.Add(new Point64(pt.X + pt2.x, pt.Y + pt2.y));
  302. for (int i = 0; i < steps; i++)
  303. {
  304. pt2 = new PointD(pt2.x * stepCos - stepSin * pt2.y,
  305. pt2.x * stepSin + pt2.y * stepCos);
  306. group._outPath.Add(new Point64(pt.X + pt2.x, pt.Y + pt2.y));
  307. }
  308. group._outPath.Add(GetPerpendic(pt, _normals[j]));
  309. }
  310. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  311. private void BuildNormals(Path64 path)
  312. {
  313. int cnt = path.Count;
  314. _normals.Clear();
  315. _normals.Capacity = cnt;
  316. for (int i = 0; i < cnt - 1; i++)
  317. {
  318. _normals.Add(GetUnitNormal(path[i], path[i + 1]));
  319. }
  320. _normals.Add(GetUnitNormal(path[cnt - 1], path[0]));
  321. }
  322. private void OffsetPoint(Group group, Path64 path, int j, ref int k)
  323. {
  324. // Let A = change in angle where edges join
  325. // A == 0: ie no change in angle (flat join)
  326. // A == PI: edges 'spike'
  327. // sin(A) < 0: right turning
  328. // cos(A) < 0: change in angle is more than 90 degree
  329. double sinA = InternalClipper.CrossProduct(_normals[j], _normals[k]);
  330. double cosA = InternalClipper.DotProduct(_normals[j], _normals[k]);
  331. if (sinA > 1.0)
  332. {
  333. sinA = 1.0;
  334. }
  335. else if (sinA < -1.0)
  336. {
  337. sinA = -1.0;
  338. }
  339. bool almostNoAngle = (AlmostZero(sinA) && cosA > 0);
  340. if (almostNoAngle || (sinA * _group_delta < 0))
  341. {
  342. group._outPath.Add(GetPerpendic(path[j], _normals[k]));
  343. if (!almostNoAngle)
  344. {
  345. group._outPath.Add(path[j]);
  346. }
  347. group._outPath.Add(GetPerpendic(path[j], _normals[j]));
  348. }
  349. else //convex
  350. {
  351. if (_joinType == JoinType.Round)
  352. {
  353. DoRound(group, path, j, k, Math.Atan2(sinA, cosA));
  354. }
  355. else if (_joinType == JoinType.Miter)
  356. {
  357. // miter unless the angle is so acute the miter would exceeds ML
  358. if (cosA > _tmpLimit - 1)
  359. {
  360. DoMiter(group, path, j, k, cosA);
  361. }
  362. else
  363. {
  364. DoSquare(group, path, j, k);
  365. }
  366. }
  367. // don't bother squaring angles that deviate < ~20 degrees because
  368. // squaring will be indistinguishable from mitering and just be a lot slower
  369. else if (cosA > 0.9)
  370. {
  371. DoMiter(group, path, j, k, cosA);
  372. }
  373. else
  374. {
  375. DoSquare(group, path, j, k);
  376. }
  377. }
  378. k = j;
  379. }
  380. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  381. private void OffsetPolygon(Group group, Path64 path)
  382. {
  383. group._outPath = new Path64();
  384. int cnt = path.Count, prev = cnt - 1;
  385. for (int i = 0; i < cnt; i++)
  386. {
  387. OffsetPoint(group, path, i, ref prev);
  388. }
  389. group._outPaths.Add(group._outPath);
  390. }
  391. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  392. private void OffsetOpenJoined(Group group, Path64 path)
  393. {
  394. OffsetPolygon(group, path);
  395. path = Clipper.ReversePath(path);
  396. BuildNormals(path);
  397. OffsetPolygon(group, path);
  398. }
  399. private void OffsetOpenPath(Group group, Path64 path, EndType endType)
  400. {
  401. group._outPath = new Path64();
  402. int highI = path.Count - 1;
  403. // do the line start cap
  404. switch (endType)
  405. {
  406. case EndType.Butt:
  407. group._outPath.Add(new Point64(
  408. path[0].X - _normals[0].x * _group_delta,
  409. path[0].Y - _normals[0].y * _group_delta));
  410. group._outPath.Add(GetPerpendic(path[0], _normals[0]));
  411. break;
  412. case EndType.Round:
  413. DoRound(group, path, 0, 0, Math.PI);
  414. break;
  415. default:
  416. DoSquare(group, path, 0, 0);
  417. break;
  418. }
  419. // offset the left side going forward
  420. for (int i = 1, k = 0; i < highI; i++)
  421. {
  422. OffsetPoint(group, path, i, ref k);
  423. }
  424. // reverse normals ...
  425. for (int i = highI; i > 0; i--)
  426. {
  427. _normals[i] = new PointD(-_normals[i - 1].x, -_normals[i - 1].y);
  428. }
  429. _normals[0] = _normals[highI];
  430. // do the line end cap
  431. switch (endType)
  432. {
  433. case EndType.Butt:
  434. group._outPath.Add(new Point64(
  435. path[highI].X - _normals[highI].x * _group_delta,
  436. path[highI].Y - _normals[highI].y * _group_delta));
  437. group._outPath.Add(GetPerpendic(path[highI], _normals[highI]));
  438. break;
  439. case EndType.Round:
  440. DoRound(group, path, highI, highI, Math.PI);
  441. break;
  442. default:
  443. DoSquare(group, path, highI, highI);
  444. break;
  445. }
  446. // offset the left side going back
  447. for (int i = highI, k = 0; i > 0; i--)
  448. {
  449. OffsetPoint(group, path, i, ref k);
  450. }
  451. group._outPaths.Add(group._outPath);
  452. }
  453. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  454. private static bool IsFullyOpenEndType(EndType et)
  455. {
  456. return (et != EndType.Polygon) && (et != EndType.Joined);
  457. }
  458. private void DoGroupOffset(Group group, double delta)
  459. {
  460. if (group._endType != EndType.Polygon)
  461. {
  462. delta = Math.Abs(delta) / 2;
  463. }
  464. bool isClosedPaths = !IsFullyOpenEndType(group._endType);
  465. if (isClosedPaths)
  466. {
  467. // the lowermost polygon must be an outer polygon. So we can use that as the
  468. // designated orientation for outer polygons (needed for tidy-up clipping)
  469. int lowestIdx = GetLowestPolygonIdx(group._inPaths);
  470. if (lowestIdx < 0)
  471. {
  472. return;
  473. }
  474. // nb: don't use the default orientation here ...
  475. double area = Clipper.Area(group._inPaths[lowestIdx]);
  476. if (area == 0)
  477. {
  478. return;
  479. }
  480. group._pathsReversed = (area < 0);
  481. if (group._pathsReversed)
  482. {
  483. delta = -delta;
  484. }
  485. }
  486. else
  487. {
  488. group._pathsReversed = false;
  489. }
  490. _group_delta = delta;
  491. _abs_group_delta = Math.Abs(_group_delta);
  492. _joinType = group._joinType;
  493. // calculate a sensible number of steps (for 360 deg for the given offset
  494. if (group._joinType == JoinType.Round || group._endType == EndType.Round)
  495. {
  496. double arcTol = ArcTolerance > 0.01 ?
  497. ArcTolerance :
  498. Math.Log10(2 + _abs_group_delta) * 0.25; // empirically derived
  499. // get steps per 180 degrees (see offset_triginometry2.svg)
  500. _stepsPerRad = Math.PI / Math.Acos(1 - arcTol / _abs_group_delta) / TwoPi;
  501. }
  502. foreach (Path64 p in group._inPaths)
  503. {
  504. Path64 path = Clipper.StripDuplicates(p, isClosedPaths);
  505. int cnt = path.Count;
  506. if (cnt == 0 || (cnt < 3 && !IsFullyOpenEndType(group._endType)))
  507. {
  508. continue;
  509. }
  510. if (cnt == 1)
  511. {
  512. group._outPath = new Path64();
  513. // single vertex so build a circle or square ...
  514. if (group._endType == EndType.Round)
  515. {
  516. double r = _abs_group_delta;
  517. if (group._endType == EndType.Polygon)
  518. {
  519. r *= 0.5;
  520. }
  521. group._outPath = Clipper.Ellipse(path[0], r, r);
  522. }
  523. else
  524. {
  525. int d = (int)Math.Ceiling(_group_delta);
  526. Rect64 r = new Rect64(path[0].X - d, path[0].Y - d,
  527. path[0].X - d, path[0].Y - d);
  528. group._outPath = r.AsPath();
  529. }
  530. group._outPaths.Add(group._outPath);
  531. }
  532. else
  533. {
  534. BuildNormals(path);
  535. if (group._endType == EndType.Polygon)
  536. {
  537. OffsetPolygon(group, path);
  538. }
  539. else if (group._endType == EndType.Joined)
  540. {
  541. OffsetOpenJoined(group, path);
  542. }
  543. else
  544. {
  545. OffsetOpenPath(group, path, group._endType);
  546. }
  547. }
  548. }
  549. if (!MergeGroups)
  550. {
  551. // clean up self-intersections
  552. Clipper64 c = new Clipper64()
  553. {
  554. PreserveCollinear = PreserveCollinear,
  555. // the solution should retain the orientation of the input
  556. ReverseSolution = ReverseSolution != group._pathsReversed
  557. };
  558. c.AddSubject(group._outPaths);
  559. if (group._pathsReversed)
  560. {
  561. c.Execute(ClipType.Union, FillRule.Negative, group._outPaths);
  562. }
  563. else
  564. {
  565. c.Execute(ClipType.Union, FillRule.Positive, group._outPaths);
  566. }
  567. }
  568. solution.AddRange(group._outPaths);
  569. group._outPaths.Clear();
  570. }
  571. }
  572. } // namespace