KiCad PCB EDA Suite
polygon_triangulation.h
Go to the documentation of this file.
1 /*
2  * This program source code file is part of KiCad, a free EDA CAD application.
3  *
4  * Modifications Copyright (C) 2018-2019 KiCad Developers
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, you may find one here:
18  * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
19  * or you may search the http://www.gnu.org website for the version 2 license,
20  * or you may write to the Free Software Foundation, Inc.,
21  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
22  *
23  * Based on Uniform Plane Subdivision algorithm from Lamot, Marko, and Borut ┼Żalik.
24  * "A fast polygon triangulation algorithm based on uniform plane subdivision."
25  * Computers & graphics 27, no. 2 (2003): 239-253.
26  *
27  * Code derived from:
28  * K-3D which is Copyright (c) 2005-2006, Romain Behar, GPL-2, license above
29  * earcut which is Copyright (c) 2016, Mapbox, ISC
30  *
31  * ISC License:
32  * Permission to use, copy, modify, and/or distribute this software for any purpose
33  * with or without fee is hereby granted, provided that the above copyright notice
34  * and this permission notice appear in all copies.
35  *
36  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
37  * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
38  * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
39  * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
40  * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
41  * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
42  * THIS SOFTWARE.
43  *
44  */
45 
46 #ifndef __POLYGON_TRIANGULATION_H
47 #define __POLYGON_TRIANGULATION_H
48 
49 #include <algorithm>
50 #include <deque>
51 #include <cmath>
52 
53 #include <clipper.hpp>
56 #include <math/box2.h>
57 #include <math/vector2d.h>
58 
60 {
61 public:
63  m_result( aResult )
64  {};
65 
66  bool TesselatePolygon( const SHAPE_LINE_CHAIN& aPoly )
67  {
68  m_bbox = aPoly.BBox();
69  m_result.Clear();
70 
71  if( !m_bbox.GetWidth() || !m_bbox.GetHeight() )
72  return false;
73 
77  Vertex* firstVertex = createList( aPoly );
78  if( !firstVertex || firstVertex->prev == firstVertex->next )
79  return false;
80 
81  firstVertex->updateList();
82 
83  auto retval = earcutList( firstVertex );
84  m_vertices.clear();
85  return retval;
86  }
87 
88 private:
89  struct Vertex
90  {
91  Vertex( size_t aIndex, double aX, double aY, PolygonTriangulation* aParent ) :
92  i( aIndex ),
93  x( aX ),
94  y( aY ),
95  parent( aParent )
96  {
97  }
98  Vertex& operator=( const Vertex& ) = delete;
99  Vertex& operator=( Vertex&& ) = delete;
100 
101  bool operator==( const Vertex& rhs ) const
102  {
103  return this->x == rhs.x && this->y == rhs.y;
104  }
105  bool operator!=( const Vertex& rhs ) const { return !( *this == rhs ); }
106 
107 
120  {
121  parent->m_vertices.emplace_back( i, x, y, parent );
122  Vertex* a2 = &parent->m_vertices.back();
123  parent->m_vertices.emplace_back( b->i, b->x, b->y, parent );
124  Vertex* b2 = &parent->m_vertices.back();
125  Vertex* an = next;
126  Vertex* bp = b->prev;
127 
128  next = b;
129  b->prev = this;
130 
131  a2->next = an;
132  an->prev = a2;
133 
134  b2->next = a2;
135  a2->prev = b2;
136 
137  bp->next = b2;
138  b2->prev = bp;
139 
140  return b2;
141  }
142 
147  void remove()
148  {
149  next->prev = prev;
150  prev->next = next;
151 
152  if( prevZ )
153  prevZ->nextZ = nextZ;
154  if( nextZ )
155  nextZ->prevZ = prevZ;
156  next = NULL;
157  prev = NULL;
158  nextZ = NULL;
159  prevZ = NULL;
160  }
161 
162  void updateOrder()
163  {
164  if( !z )
165  z = parent->zOrder( x, y );
166  }
167 
173  void updateList()
174  {
175  Vertex* p = next;
176 
177  while( p != this )
178  {
182  if( *p == *p->next )
183  {
184  p = p->prev;
185  p->next->remove();
186 
187  if( p == p->next )
188  break;
189  }
190 
191  p->updateOrder();
192  p = p->next;
193  };
194 
195  updateOrder();
196  zSort();
197  }
198 
202  void zSort()
203  {
204  std::deque<Vertex*> queue;
205 
206  queue.push_back( this );
207 
208  for( auto p = next; p && p != this; p = p->next )
209  queue.push_back( p );
210 
211  std::sort( queue.begin(), queue.end(), []( const Vertex* a, const Vertex* b)
212  {
213  return a->z < b->z;
214  } );
215 
216  Vertex* prev_elem = nullptr;
217  for( auto elem : queue )
218  {
219  if( prev_elem )
220  prev_elem->nextZ = elem;
221 
222  elem->prevZ = prev_elem;
223  prev_elem = elem;
224  }
225 
226  prev_elem->nextZ = nullptr;
227  }
228 
229 
233  bool inTriangle( const Vertex& a, const Vertex& b, const Vertex& c )
234  {
235  return ( c.x - x ) * ( a.y - y ) - ( a.x - x ) * ( c.y - y ) >= 0
236  && ( a.x - x ) * ( b.y - y ) - ( b.x - x ) * ( a.y - y ) >= 0
237  && ( b.x - x ) * ( c.y - y ) - ( c.x - x ) * ( b.y - y ) >= 0;
238  }
239 
240  const size_t i;
241  const double x;
242  const double y;
244 
245  // previous and next vertices nodes in a polygon ring
246  Vertex* prev = nullptr;
247  Vertex* next = nullptr;
248 
249  // z-order curve value
250  int32_t z = 0;
251 
252  // previous and next nodes in z-order
253  Vertex* prevZ = nullptr;
254  Vertex* nextZ = nullptr;
255  };
256 
262  int32_t zOrder( const double aX, const double aY ) const
263  {
264  int32_t x = static_cast<int32_t>( 32767.0 * ( aX - m_bbox.GetX() ) / m_bbox.GetWidth() );
265  int32_t y = static_cast<int32_t>( 32767.0 * ( aY - m_bbox.GetY() ) / m_bbox.GetHeight() );
266 
267  x = ( x | ( x << 8 ) ) & 0x00FF00FF;
268  x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
269  x = ( x | ( x << 2 ) ) & 0x33333333;
270  x = ( x | ( x << 1 ) ) & 0x55555555;
271 
272  y = ( y | ( y << 8 ) ) & 0x00FF00FF;
273  y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
274  y = ( y | ( y << 2 ) ) & 0x33333333;
275  y = ( y | ( y << 1 ) ) & 0x55555555;
276 
277  return x | ( y << 1 );
278  }
279 
288  {
289  Vertex* retval = nullptr;
290  Vertex* p = aStart->next;
291 
292  while( p != aStart )
293  {
294  if( area( p->prev, p, p->next ) == 0.0 )
295  {
296  p = p->prev;
297  p->next->remove();
298  retval = aStart;
299 
300  if( p == p->next )
301  break;
302  }
303  p = p->next;
304  };
305 
306  // We needed an end point above that wouldn't be removed, so
307  // here we do the final check for this as a Steiner point
308  if( area( aStart->prev, aStart, aStart->next ) == 0.0 )
309  {
310  retval = p->next;
311  p->remove();
312  }
313 
314  return retval;
315  }
316 
322  Vertex* createList( const ClipperLib::Path& aPath )
323  {
324  Vertex* tail = nullptr;
325  double sum = 0.0;
326  auto len = aPath.size();
327 
328  // Check for winding order
329  for( size_t i = 0; i < len; i++ )
330  {
331  auto p1 = aPath.at( i );
332  auto p2 = aPath.at( ( i + 1 ) < len ? i + 1 : 0 );
333 
334  sum += ( ( p2.X - p1.X ) * ( p2.Y + p1.Y ) );
335  }
336 
337  if( sum <= 0.0 )
338  {
339  for( auto point : aPath )
340  tail = insertVertex( VECTOR2I( point.X, point.Y ), tail );
341  }
342  else
343  {
344  for( size_t i = 0; i < len; i++ )
345  {
346  auto p = aPath.at( len - i - 1 );
347  tail = insertVertex( VECTOR2I( p.X, p.Y ), tail );
348  }
349  }
350 
351  if( tail && ( *tail == *tail->next ) )
352  {
353  tail->next->remove();
354  }
355 
356  return tail;
357 
358  }
359 
366  {
367  Vertex* tail = nullptr;
368  double sum = 0.0;
369 
370  // Check for winding order
371  for( int i = 0; i < points.PointCount(); i++ )
372  {
373  VECTOR2D p1 = points.CPoint( i );
374  VECTOR2D p2 = points.CPoint( i + 1 );
375 
376  sum += ( ( p2.x - p1.x ) * ( p2.y + p1.y ) );
377  }
378 
379  if( sum > 0.0 )
380  for( int i = points.PointCount() - 1; i >= 0; i--)
381  tail = insertVertex( points.CPoint( i ), tail );
382  else
383  for( int i = 0; i < points.PointCount(); i++ )
384  tail = insertVertex( points.CPoint( i ), tail );
385 
386  if( tail && ( *tail == *tail->next ) )
387  {
388  tail->next->remove();
389  }
390 
391  return tail;
392  }
393 
405  bool earcutList( Vertex* aPoint, int pass = 0 )
406  {
407  if( !aPoint )
408  return true;
409 
410  Vertex* stop = aPoint;
411  Vertex* prev;
412  Vertex* next;
413 
414  while( aPoint->prev != aPoint->next )
415  {
416  prev = aPoint->prev;
417  next = aPoint->next;
418 
419  if( isEar( aPoint ) )
420  {
421  m_result.AddTriangle( prev->i, aPoint->i, next->i );
422  aPoint->remove();
423 
424  // Skip one vertex as the triangle will account for the prev node
425  aPoint = next->next;
426  stop = next->next;
427 
428  continue;
429  }
430 
431  Vertex* nextNext = next->next;
432 
433  if( *prev != *nextNext && intersects( prev, aPoint, next, nextNext ) &&
434  locallyInside( prev, nextNext ) &&
435  locallyInside( nextNext, prev ) )
436  {
437  m_result.AddTriangle( prev->i, aPoint->i, nextNext->i );
438 
439  // remove two nodes involved
440  next->remove();
441  aPoint->remove();
442 
443  aPoint = nextNext;
444  stop = nextNext;
445 
446  continue;
447  }
448 
449  aPoint = next;
450 
455  if( aPoint == stop )
456  {
457  // First, try to remove the remaining steiner points
458  // If aPoint is a steiner, we need to re-assign both the start and stop points
459  if( auto newPoint = removeNullTriangles( aPoint ) )
460  {
461  aPoint = newPoint;
462  stop = newPoint;
463  continue;
464  }
465 
466  // If we don't have any NULL triangles left, cut the polygon in two and try again
467  splitPolygon( aPoint );
468  break;
469  }
470  }
471 
475  return( aPoint->prev == aPoint->next );
476  }
477 
487  bool isEar( Vertex* aEar ) const
488  {
489  const Vertex* a = aEar->prev;
490  const Vertex* b = aEar;
491  const Vertex* c = aEar->next;
492 
493  // If the area >=0, then the three points for a concave sequence
494  // with b as the reflex point
495  if( area( a, b, c ) >= 0 )
496  return false;
497 
498  // triangle bbox
499  const double minTX = std::min( a->x, std::min( b->x, c->x ) );
500  const double minTY = std::min( a->y, std::min( b->y, c->y ) );
501  const double maxTX = std::max( a->x, std::max( b->x, c->x ) );
502  const double maxTY = std::max( a->y, std::max( b->y, c->y ) );
503 
504  // z-order range for the current triangle bounding box
505  const int32_t minZ = zOrder( minTX, minTY );
506  const int32_t maxZ = zOrder( maxTX, maxTY );
507 
508  // first look for points inside the triangle in increasing z-order
509  Vertex* p = aEar->nextZ;
510 
511  while( p && p->z <= maxZ )
512  {
513  if( p != a && p != c
514  && p->inTriangle( *a, *b, *c )
515  && area( p->prev, p, p->next ) >= 0 )
516  return false;
517  p = p->nextZ;
518  }
519 
520  // then look for points in decreasing z-order
521  p = aEar->prevZ;
522 
523  while( p && p->z >= minZ )
524  {
525  if( p != a && p != c
526  && p->inTriangle( *a, *b, *c )
527  && area( p->prev, p, p->next ) >= 0 )
528  return false;
529  p = p->prevZ;
530  }
531 
532  return true;
533  }
534 
542  void splitPolygon( Vertex* start )
543  {
544  Vertex* origPoly = start;
545  do
546  {
547  Vertex* marker = origPoly->next->next;
548  while( marker != origPoly->prev )
549  {
550  // Find a diagonal line that is wholly enclosed by the polygon interior
551  if( origPoly->i != marker->i && goodSplit( origPoly, marker ) )
552  {
553  Vertex* newPoly = origPoly->split( marker );
554 
555  origPoly->updateList();
556  newPoly->updateList();
557 
558  earcutList( origPoly );
559  earcutList( newPoly );
560  return;
561  }
562  marker = marker->next;
563  }
564  origPoly = origPoly->next;
565  } while( origPoly != start );
566  }
567 
576  bool goodSplit( const Vertex* a, const Vertex* b ) const
577  {
578  return a->next->i != b->i &&
579  a->prev->i != b->i &&
580  !intersectsPolygon( a, b ) &&
581  locallyInside( a, b );
582  }
583 
589  double area( const Vertex* p, const Vertex* q, const Vertex* r ) const
590  {
591  return ( q->y - p->y ) * ( r->x - q->x ) - ( q->x - p->x ) * ( r->y - q->y );
592  }
593 
599  bool intersects( const Vertex* p1, const Vertex* q1, const Vertex* p2, const Vertex* q2 ) const
600  {
601  if( ( *p1 == *q1 && *p2 == *q2 ) || ( *p1 == *q2 && *p2 == *q1 ) )
602  return true;
603 
604  return ( area( p1, q1, p2 ) > 0 ) != ( area( p1, q1, q2 ) > 0 )
605  && ( area( p2, q2, p1 ) > 0 ) != ( area( p2, q2, q1 ) > 0 );
606  }
607 
614  bool intersectsPolygon( const Vertex* a, const Vertex* b ) const
615  {
616  const Vertex* p = a->next;
617  do
618  {
619  if( p->i != a->i &&
620  p->next->i != a->i &&
621  p->i != b->i &&
622  p->next->i != b->i && intersects( p, p->next, a, b ) )
623  return true;
624 
625  p = p->next;
626  } while( p != a );
627 
628  return false;
629  }
630 
639  bool locallyInside( const Vertex* a, const Vertex* b ) const
640  {
641  if( area( a->prev, a, a->next ) < 0 )
642  return area( a, b, a->next ) >= 0 && area( a, a->prev, b ) >= 0;
643  else
644  return area( a, b, a->prev ) < 0 || area( a, a->next, b ) < 0;
645  }
646 
653  Vertex* insertVertex( const VECTOR2I& pt, Vertex* last )
654  {
655  m_result.AddVertex( pt );
656  m_vertices.emplace_back( m_result.GetVertexCount() - 1, pt.x, pt.y, this );
657 
658  Vertex* p = &m_vertices.back();
659  if( !last )
660  {
661  p->prev = p;
662  p->next = p;
663  }
664  else
665  {
666  p->next = last->next;
667  p->prev = last;
668  last->next->prev = p;
669  last->next = p;
670  }
671  return p;
672  }
673 
674 private:
676  std::deque<Vertex> m_vertices;
678 };
679 
680 #endif //__POLYGON_TRIANGULATION_H
CITER next(CITER it)
Definition: ptree.cpp:126
bool TesselatePolygon(const SHAPE_LINE_CHAIN &aPoly)
Vertex * createList(const ClipperLib::Path &aPath)
Function createList Takes a Clipper path and converts it into a circular, doubly-linked list for tria...
coord_type GetX() const
Definition: box2.h:190
bool operator!=(const Vertex &rhs) const
Vertex * split(Vertex *b)
Function split Splits the referenced polygon between the reference point and vertex b,...
bool intersects(const Vertex *p1, const Vertex *q1, const Vertex *p2, const Vertex *q2) const
Function intersects Checks for intersection between two segments, end points included.
void remove()
Function remove Removes the node from the linked list and z-ordered linked list.
bool intersectsPolygon(const Vertex *a, const Vertex *b) const
Function intersectsPolygon Checks whether the segment from vertex a -> vertex b crosses any of the se...
VECTOR2< int > VECTOR2I
Definition: vector2d.h:623
int PointCount() const
Function PointCount()
PolygonTriangulation(SHAPE_POLY_SET::TRIANGULATED_POLYGON &aResult)
Vertex * createList(const SHAPE_LINE_CHAIN &points)
Function createList Takes the SHAPE_LINE_CHAIN and links each point into a circular,...
bool earcutList(Vertex *aPoint, int pass=0)
Function: earcutList Walks through a circular linked list starting at aPoint.
const VECTOR2I & CPoint(int aIndex) const
Function Point()
Vertex * removeNullTriangles(Vertex *aStart)
Function removeNullTriangles Iterates through the list to remove NULL triangles if they exist.
int32_t zOrder(const double aX, const double aY) const
Calculate the Morton code of the Vertex http://www.graphics.stanford.edu/~seander/bithacks....
bool goodSplit(const Vertex *a, const Vertex *b) const
Check if a segment joining two vertices lies fully inside the polygon.
bool operator==(const Vertex &rhs) const
const BOX2I BBox(int aClearance=0) const override
Compute a bounding box of the shape, with a margin of aClearance a collision.
#define NULL
void zSort()
Sort all vertices in this vertex's list by their Morton code.
coord_type GetWidth() const
Definition: box2.h:197
SHAPE_POLY_SET::TRIANGULATED_POLYGON & m_result
coord_type GetY() const
Definition: box2.h:191
void updateList()
Function updateList After inserting or changing nodes, this function should be called to remove dupli...
bool locallyInside(const Vertex *a, const Vertex *b) const
Function locallyInside Checks whether the segment from vertex a -> vertex b is inside the polygon aro...
void AddVertex(const VECTOR2I &aP)
void AddTriangle(int a, int b, int c)
SHAPE_LINE_CHAIN.
coord_type GetHeight() const
Definition: box2.h:198
Vertex(size_t aIndex, double aX, double aY, PolygonTriangulation *aParent)
bool inTriangle(const Vertex &a, const Vertex &b, const Vertex &c)
Check to see if triangle surrounds our current vertex.
Vertex & operator=(const Vertex &)=delete
bool isEar(Vertex *aEar) const
Function isEar Checks whether the given vertex is in the middle of an ear.
double area(const Vertex *p, const Vertex *q, const Vertex *r) const
Function area Returns the twice the signed area of the triangle formed by vertices p,...
std::deque< Vertex > m_vertices
Vertex * insertVertex(const VECTOR2I &pt, Vertex *last)
Function insertVertex Creates an entry in the vertices lookup and optionally inserts the newly create...
void splitPolygon(Vertex *start)
Function splitPolygon If we cannot find an ear to slice in the current polygon list,...