KiCad PCB EDA Suite
PolygonTriangulation Class Reference

#include <polygon_triangulation.h>

Classes

struct  Vertex
 

Public Member Functions

 PolygonTriangulation (SHAPE_POLY_SET::TRIANGULATED_POLYGON &aResult)
 
bool TesselatePolygon (const SHAPE_LINE_CHAIN &aPoly)
 

Private Member Functions

int32_t zOrder (const double aX, const double aY) const
 Calculate the Morton code of the Vertex http://www.graphics.stanford.edu/~seander/bithacks.html#InterleaveBMN. More...
 
VertexremoveNullTriangles (Vertex *aStart)
 Iterate through the list to remove NULL triangles if they exist. More...
 
VertexcreateList (const ClipperLib::Path &aPath)
 Take a Clipper path and converts it into a circular, doubly-linked list for triangulation. More...
 
VertexcreateList (const SHAPE_LINE_CHAIN &points)
 Take a SHAPE_LINE_CHAIN and links each point into a circular, doubly-linked list. More...
 
bool earcutList (Vertex *aPoint, int pass=0)
 Walk through a circular linked list starting at aPoint. More...
 
bool isEar (Vertex *aEar) const
 Check whether the given vertex is in the middle of an ear. More...
 
void splitPolygon (Vertex *start)
 If we cannot find an ear to slice in the current polygon list, we use this to split the polygon into two separate lists and slice them each independently. More...
 
bool goodSplit (const Vertex *a, const Vertex *b) const
 Check if a segment joining two vertices lies fully inside the polygon. More...
 
double area (const Vertex *p, const Vertex *q, const Vertex *r) const
 Return the twice the signed area of the triangle formed by vertices p, q, and r. More...
 
bool intersects (const Vertex *p1, const Vertex *q1, const Vertex *p2, const Vertex *q2) const
 Check for intersection between two segments, end points included. More...
 
bool intersectsPolygon (const Vertex *a, const Vertex *b) const
 Check whether the segment from vertex a -> vertex b crosses any of the segments of the polygon of which vertex a is a member. More...
 
bool locallyInside (const Vertex *a, const Vertex *b) const
 Check whether the segment from vertex a -> vertex b is inside the polygon around the immediate area of vertex a. More...
 
VertexinsertVertex (const VECTOR2I &pt, Vertex *last)
 Create an entry in the vertices lookup and optionally inserts the newly created vertex into an existing linked list. More...
 

Private Attributes

BOX2I m_bbox
 
std::deque< Vertexm_vertices
 
SHAPE_POLY_SET::TRIANGULATED_POLYGONm_result
 

Detailed Description

Definition at line 59 of file polygon_triangulation.h.

Constructor & Destructor Documentation

◆ PolygonTriangulation()

PolygonTriangulation::PolygonTriangulation ( SHAPE_POLY_SET::TRIANGULATED_POLYGON aResult)
inline

Definition at line 62 of file polygon_triangulation.h.

62 :
63 m_result( aResult )
64 {};
SHAPE_POLY_SET::TRIANGULATED_POLYGON & m_result

Member Function Documentation

◆ area()

double PolygonTriangulation::area ( const Vertex p,
const Vertex q,
const Vertex r 
) const
inlineprivate

Return the twice the signed area of the triangle formed by vertices p, q, and r.

Definition at line 609 of file polygon_triangulation.h.

610 {
611 return ( q->y - p->y ) * ( r->x - q->x ) - ( q->x - p->x ) * ( r->y - q->y );
612 }

References PolygonTriangulation::Vertex::x, and PolygonTriangulation::Vertex::y.

Referenced by earcutList(), intersects(), isEar(), locallyInside(), and removeNullTriangles().

◆ createList() [1/2]

Vertex * PolygonTriangulation::createList ( const ClipperLib::Path &  aPath)
inlineprivate

Take a Clipper path and converts it into a circular, doubly-linked list for triangulation.

Definition at line 330 of file polygon_triangulation.h.

331 {
332 Vertex* tail = nullptr;
333 double sum = 0.0;
334 auto len = aPath.size();
335
336 // Check for winding order
337 for( size_t i = 0; i < len; i++ )
338 {
339 auto p1 = aPath.at( i );
340 auto p2 = aPath.at( ( i + 1 ) < len ? i + 1 : 0 );
341
342 sum += ( ( p2.X - p1.X ) * ( p2.Y + p1.Y ) );
343 }
344
345 if( sum <= 0.0 )
346 {
347 for( auto point : aPath )
348 tail = insertVertex( VECTOR2I( point.X, point.Y ), tail );
349 }
350 else
351 {
352 for( size_t i = 0; i < len; i++ )
353 {
354 auto p = aPath.at( len - i - 1 );
355 tail = insertVertex( VECTOR2I( p.X, p.Y ), tail );
356 }
357 }
358
359 if( tail && ( *tail == *tail->next ) )
360 {
361 tail->next->remove();
362 }
363
364 return tail;
365
366 }
Vertex * insertVertex(const VECTOR2I &pt, Vertex *last)
Create an entry in the vertices lookup and optionally inserts the newly created vertex into an existi...
VECTOR2< int > VECTOR2I
Definition: vector2d.h:590

References insertVertex(), PolygonTriangulation::Vertex::next, and PolygonTriangulation::Vertex::remove().

Referenced by TesselatePolygon().

◆ createList() [2/2]

Vertex * PolygonTriangulation::createList ( const SHAPE_LINE_CHAIN points)
inlineprivate

Take a SHAPE_LINE_CHAIN and links each point into a circular, doubly-linked list.

Definition at line 371 of file polygon_triangulation.h.

372 {
373 Vertex* tail = nullptr;
374 double sum = 0.0;
375
376 // Check for winding order
377 for( int i = 0; i < points.PointCount(); i++ )
378 {
379 VECTOR2D p1 = points.CPoint( i );
380 VECTOR2D p2 = points.CPoint( i + 1 );
381
382 sum += ( ( p2.x - p1.x ) * ( p2.y + p1.y ) );
383 }
384
385 if( sum > 0.0 )
386 for( int i = points.PointCount() - 1; i >= 0; i--)
387 tail = insertVertex( points.CPoint( i ), tail );
388 else
389 for( int i = 0; i < points.PointCount(); i++ )
390 tail = insertVertex( points.CPoint( i ), tail );
391
392 if( tail && ( *tail == *tail->next ) )
393 {
394 tail->next->remove();
395 }
396
397 return tail;
398 }
int PointCount() const
Return the number of points (vertices) in this line chain.
const VECTOR2I & CPoint(int aIndex) const
Return a reference to a given point in the line chain.
void remove()
Remove the node from the linked list and z-ordered linked list.

References SHAPE_LINE_CHAIN::CPoint(), insertVertex(), PolygonTriangulation::Vertex::next, SHAPE_LINE_CHAIN::PointCount(), PolygonTriangulation::Vertex::remove(), VECTOR2< T >::x, and VECTOR2< T >::y.

◆ earcutList()

bool PolygonTriangulation::earcutList ( Vertex aPoint,
int  pass = 0 
)
inlineprivate

Walk through a circular linked list starting at aPoint.

For each point, test to see if the adjacent points form a triangle that is completely enclosed by the remaining polygon (an "ear" sticking off the polygon). If the three points form an ear, we log the ear's location and remove the center point from the linked list.

This function can be called recursively in the case of difficult polygons. In cases where there is an intersection (not technically allowed by KiCad, but could exist in an edited file), we create a single triangle and remove both vertices before attempting to.

Definition at line 413 of file polygon_triangulation.h.

414 {
415 if( !aPoint )
416 return true;
417
418 Vertex* stop = aPoint;
419 Vertex* prev;
420 Vertex* next;
421
422 while( aPoint->prev != aPoint->next )
423 {
424 prev = aPoint->prev;
425 next = aPoint->next;
426
427 if( isEar( aPoint ) )
428 {
429 m_result.AddTriangle( prev->i, aPoint->i, next->i );
430 aPoint->remove();
431
432 // Skip one vertex as the triangle will account for the prev node
433 aPoint = next->next;
434 stop = next->next;
435
436 continue;
437 }
438
439 Vertex* nextNext = next->next;
440
441 if( *prev != *nextNext && intersects( prev, aPoint, next, nextNext ) &&
442 locallyInside( prev, nextNext ) &&
443 locallyInside( nextNext, prev ) )
444 {
445 m_result.AddTriangle( prev->i, aPoint->i, nextNext->i );
446
447 // remove two nodes involved
448 next->remove();
449 aPoint->remove();
450
451 aPoint = nextNext;
452 stop = nextNext;
453
454 continue;
455 }
456
457 aPoint = next;
458
459 /*
460 * We've searched the entire polygon for available ears and there are still
461 * un-sliced nodes remaining.
462 */
463 if( aPoint == stop )
464 {
465 // First, try to remove the remaining steiner points
466 // If aPoint is a steiner, we need to re-assign both the start and stop points
467 if( auto newPoint = removeNullTriangles( aPoint ) )
468 {
469 aPoint = newPoint;
470 stop = newPoint;
471 continue;
472 }
473
474 // If we don't have any NULL triangles left, cut the polygon in two and try again
475 splitPolygon( aPoint );
476 break;
477 }
478 }
479
480 // Check to see if we are left with only three points in the polygon
481 if( aPoint->next && aPoint->prev == aPoint->next->next )
482 {
483 // Three concave points will never be able to be triangulated because they were
484 // created by an intersecting polygon, so just drop them.
485 if( area( aPoint->prev, aPoint, aPoint->next ) >= 0 )
486 return true;
487 }
488
489 /*
490 * At this point, our polygon should be fully tessellated.
491 */
492 return( aPoint->prev == aPoint->next );
493 }
Vertex * removeNullTriangles(Vertex *aStart)
Iterate through the list to remove NULL triangles if they exist.
bool isEar(Vertex *aEar) const
Check whether the given vertex is in the middle of an ear.
bool intersects(const Vertex *p1, const Vertex *q1, const Vertex *p2, const Vertex *q2) const
Check for intersection between two segments, end points included.
bool locallyInside(const Vertex *a, const Vertex *b) const
Check whether the segment from vertex a -> vertex b is inside the polygon around the immediate area o...
void splitPolygon(Vertex *start)
If we cannot find an ear to slice in the current polygon list, we use this to split the polygon into ...
double area(const Vertex *p, const Vertex *q, const Vertex *r) const
Return the twice the signed area of the triangle formed by vertices p, q, and r.
void AddTriangle(int a, int b, int c)
CITER next(CITER it)
Definition: ptree.cpp:126

References SHAPE_POLY_SET::TRIANGULATED_POLYGON::AddTriangle(), area(), PolygonTriangulation::Vertex::i, intersects(), isEar(), locallyInside(), m_result, next(), PolygonTriangulation::Vertex::next, PolygonTriangulation::Vertex::prev, PolygonTriangulation::Vertex::remove(), removeNullTriangles(), and splitPolygon().

Referenced by splitPolygon(), and TesselatePolygon().

◆ goodSplit()

bool PolygonTriangulation::goodSplit ( const Vertex a,
const Vertex b 
) const
inlineprivate

Check if a segment joining two vertices lies fully inside the polygon.

To do this, we first ensure that the line isn't along the polygon edge. Next, we know that if the line doesn't intersect the polygon, then it is either fully inside or fully outside the polygon. Finally, by checking whether the segment is enclosed by the local triangles, we distinguish between these two cases and no further checks are needed.

Definition at line 598 of file polygon_triangulation.h.

599 {
600 return a->next->i != b->i &&
601 a->prev->i != b->i &&
602 !intersectsPolygon( a, b ) &&
603 locallyInside( a, b );
604 }
bool intersectsPolygon(const Vertex *a, const Vertex *b) const
Check whether the segment from vertex a -> vertex b crosses any of the segments of the polygon of whi...

References PolygonTriangulation::Vertex::i, intersectsPolygon(), locallyInside(), PolygonTriangulation::Vertex::next, and PolygonTriangulation::Vertex::prev.

Referenced by splitPolygon().

◆ insertVertex()

Vertex * PolygonTriangulation::insertVertex ( const VECTOR2I pt,
Vertex last 
)
inlineprivate

Create an entry in the vertices lookup and optionally inserts the newly created vertex into an existing linked list.

Returns
a pointer to the newly created vertex.

Definition at line 675 of file polygon_triangulation.h.

676 {
677 m_result.AddVertex( pt );
678 m_vertices.emplace_back( m_result.GetVertexCount() - 1, pt.x, pt.y, this );
679
680 Vertex* p = &m_vertices.back();
681
682 if( !last )
683 {
684 p->prev = p;
685 p->next = p;
686 }
687 else
688 {
689 p->next = last->next;
690 p->prev = last;
691 last->next->prev = p;
692 last->next = p;
693 }
694 return p;
695 }
std::deque< Vertex > m_vertices
void AddVertex(const VECTOR2I &aP)

References SHAPE_POLY_SET::TRIANGULATED_POLYGON::AddVertex(), SHAPE_POLY_SET::TRIANGULATED_POLYGON::GetVertexCount(), m_result, m_vertices, PolygonTriangulation::Vertex::next, PolygonTriangulation::Vertex::prev, VECTOR2< T >::x, and VECTOR2< T >::y.

Referenced by createList().

◆ intersects()

bool PolygonTriangulation::intersects ( const Vertex p1,
const Vertex q1,
const Vertex p2,
const Vertex q2 
) const
inlineprivate

Check for intersection between two segments, end points included.

Returns
true if p1-p2 intersects q1-q2.

Definition at line 619 of file polygon_triangulation.h.

620 {
621 if( ( *p1 == *q1 && *p2 == *q2 ) || ( *p1 == *q2 && *p2 == *q1 ) )
622 return true;
623
624 return ( area( p1, q1, p2 ) > 0 ) != ( area( p1, q1, q2 ) > 0 )
625 && ( area( p2, q2, p1 ) > 0 ) != ( area( p2, q2, q1 ) > 0 );
626 }

References area().

Referenced by earcutList(), and intersectsPolygon().

◆ intersectsPolygon()

bool PolygonTriangulation::intersectsPolygon ( const Vertex a,
const Vertex b 
) const
inlineprivate

Check whether the segment from vertex a -> vertex b crosses any of the segments of the polygon of which vertex a is a member.

Returns
true if the segment intersects the edge of the polygon.

Definition at line 634 of file polygon_triangulation.h.

635 {
636 const Vertex* p = a->next;
637
638 do
639 {
640 if( p->i != a->i &&
641 p->next->i != a->i &&
642 p->i != b->i &&
643 p->next->i != b->i && intersects( p, p->next, a, b ) )
644 return true;
645
646 p = p->next;
647 } while( p != a );
648
649 return false;
650 }

References PolygonTriangulation::Vertex::i, intersects(), and PolygonTriangulation::Vertex::next.

Referenced by goodSplit().

◆ isEar()

bool PolygonTriangulation::isEar ( Vertex aEar) const
inlineprivate

Check whether the given vertex is in the middle of an ear.

This works by walking forward and backward in zOrder to the limits of the minimal bounding box formed around the triangle, checking whether any points are located inside the given triangle.

Returns
true if aEar is the apex point of a ear in the polygon.

Definition at line 504 of file polygon_triangulation.h.

505 {
506 const Vertex* a = aEar->prev;
507 const Vertex* b = aEar;
508 const Vertex* c = aEar->next;
509
510 // If the area >=0, then the three points for a concave sequence
511 // with b as the reflex point
512 if( area( a, b, c ) >= 0 )
513 return false;
514
515 // triangle bbox
516 const double minTX = std::min( a->x, std::min( b->x, c->x ) );
517 const double minTY = std::min( a->y, std::min( b->y, c->y ) );
518 const double maxTX = std::max( a->x, std::max( b->x, c->x ) );
519 const double maxTY = std::max( a->y, std::max( b->y, c->y ) );
520
521 // z-order range for the current triangle bounding box
522 const int32_t minZ = zOrder( minTX, minTY );
523 const int32_t maxZ = zOrder( maxTX, maxTY );
524
525 // first look for points inside the triangle in increasing z-order
526 Vertex* p = aEar->nextZ;
527
528 while( p && p->z <= maxZ )
529 {
530 if( p != a && p != c
531 && p->inTriangle( *a, *b, *c )
532 && area( p->prev, p, p->next ) >= 0 )
533 return false;
534
535 p = p->nextZ;
536 }
537
538 // then look for points in decreasing z-order
539 p = aEar->prevZ;
540
541 while( p && p->z >= minZ )
542 {
543 if( p != a && p != c
544 && p->inTriangle( *a, *b, *c )
545 && area( p->prev, p, p->next ) >= 0 )
546 return false;
547
548 p = p->prevZ;
549 }
550
551 return true;
552 }
int32_t zOrder(const double aX, const double aY) const
Calculate the Morton code of the Vertex http://www.graphics.stanford.edu/~seander/bithacks....

References area(), PolygonTriangulation::Vertex::inTriangle(), PolygonTriangulation::Vertex::next, PolygonTriangulation::Vertex::nextZ, PolygonTriangulation::Vertex::prev, PolygonTriangulation::Vertex::prevZ, PolygonTriangulation::Vertex::x, PolygonTriangulation::Vertex::y, PolygonTriangulation::Vertex::z, and zOrder().

Referenced by earcutList().

◆ locallyInside()

bool PolygonTriangulation::locallyInside ( const Vertex a,
const Vertex b 
) const
inlineprivate

Check whether the segment from vertex a -> vertex b is inside the polygon around the immediate area of vertex a.

We don't define the exact area over which the segment is inside but it is guaranteed to be inside the polygon immediately adjacent to vertex a.

Returns
true if the segment from a->b is inside a's polygon next to vertex a.

Definition at line 661 of file polygon_triangulation.h.

662 {
663 if( area( a->prev, a, a->next ) < 0 )
664 return area( a, b, a->next ) >= 0 && area( a, a->prev, b ) >= 0;
665 else
666 return area( a, b, a->prev ) < 0 || area( a, a->next, b ) < 0;
667 }

References area(), PolygonTriangulation::Vertex::next, and PolygonTriangulation::Vertex::prev.

Referenced by earcutList(), and goodSplit().

◆ removeNullTriangles()

Vertex * PolygonTriangulation::removeNullTriangles ( Vertex aStart)
inlineprivate

Iterate through the list to remove NULL triangles if they exist.

This should only be called as a last resort when tesselation fails as the NULL triangles are inserted as Steiner points to improve the triangulation regularity of polygons

Definition at line 297 of file polygon_triangulation.h.

298 {
299 Vertex* retval = nullptr;
300 Vertex* p = aStart->next;
301
302 while( p != aStart )
303 {
304 if( area( p->prev, p, p->next ) == 0.0 )
305 {
306 p = p->prev;
307 p->next->remove();
308 retval = aStart;
309
310 if( p == p->next )
311 break;
312 }
313 p = p->next;
314 };
315
316 // We needed an end point above that wouldn't be removed, so
317 // here we do the final check for this as a Steiner point
318 if( area( aStart->prev, aStart, aStart->next ) == 0.0 )
319 {
320 retval = p->next;
321 p->remove();
322 }
323
324 return retval;
325 }

References area(), PolygonTriangulation::Vertex::next, PolygonTriangulation::Vertex::prev, and PolygonTriangulation::Vertex::remove().

Referenced by earcutList().

◆ splitPolygon()

void PolygonTriangulation::splitPolygon ( Vertex start)
inlineprivate

If we cannot find an ear to slice in the current polygon list, we use this to split the polygon into two separate lists and slice them each independently.

This is assured to generate at least one new ear if the split is successful

Definition at line 560 of file polygon_triangulation.h.

561 {
562 Vertex* origPoly = start;
563
564 do
565 {
566 Vertex* marker = origPoly->next->next;
567
568 while( marker != origPoly->prev )
569 {
570 // Find a diagonal line that is wholly enclosed by the polygon interior
571 if( origPoly->i != marker->i && goodSplit( origPoly, marker ) )
572 {
573 Vertex* newPoly = origPoly->split( marker );
574
575 origPoly->updateList();
576 newPoly->updateList();
577
578 earcutList( origPoly );
579 earcutList( newPoly );
580 return;
581 }
582
583 marker = marker->next;
584 }
585
586 origPoly = origPoly->next;
587 } while( origPoly != start );
588 }
bool goodSplit(const Vertex *a, const Vertex *b) const
Check if a segment joining two vertices lies fully inside the polygon.
bool earcutList(Vertex *aPoint, int pass=0)
Walk through a circular linked list starting at aPoint.

References earcutList(), goodSplit(), PolygonTriangulation::Vertex::i, PolygonTriangulation::Vertex::next, PolygonTriangulation::Vertex::prev, PolygonTriangulation::Vertex::split(), and PolygonTriangulation::Vertex::updateList().

Referenced by earcutList().

◆ TesselatePolygon()

bool PolygonTriangulation::TesselatePolygon ( const SHAPE_LINE_CHAIN aPoly)
inline

Place the polygon Vertices into a circular linked list and check for lists that have only 0, 1 or 2 elements and therefore cannot be polygons

Definition at line 66 of file polygon_triangulation.h.

67 {
68 m_bbox = aPoly.BBox();
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 }
coord_type GetHeight() const
Definition: box2.h:188
coord_type GetWidth() const
Definition: box2.h:187
Vertex * createList(const ClipperLib::Path &aPath)
Take a Clipper path and converts it into a circular, doubly-linked list for triangulation.
const BOX2I BBox(int aClearance=0) const override
Compute a bounding box of the shape, with a margin of aClearance a collision.

References SHAPE_LINE_CHAIN::BBox(), SHAPE_POLY_SET::TRIANGULATED_POLYGON::Clear(), createList(), earcutList(), BOX2< Vec >::GetHeight(), BOX2< Vec >::GetWidth(), m_bbox, m_result, m_vertices, PolygonTriangulation::Vertex::next, PolygonTriangulation::Vertex::prev, and PolygonTriangulation::Vertex::updateList().

Referenced by SHAPE_POLY_SET::CacheTriangulation().

◆ zOrder()

int32_t PolygonTriangulation::zOrder ( const double  aX,
const double  aY 
) const
inlineprivate

Calculate the Morton code of the Vertex http://www.graphics.stanford.edu/~seander/bithacks.html#InterleaveBMN.

Definition at line 272 of file polygon_triangulation.h.

273 {
274 int32_t x = static_cast<int32_t>( 32767.0 * ( aX - m_bbox.GetX() ) / m_bbox.GetWidth() );
275 int32_t y = static_cast<int32_t>( 32767.0 * ( aY - m_bbox.GetY() ) / m_bbox.GetHeight() );
276
277 x = ( x | ( x << 8 ) ) & 0x00FF00FF;
278 x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
279 x = ( x | ( x << 2 ) ) & 0x33333333;
280 x = ( x | ( x << 1 ) ) & 0x55555555;
281
282 y = ( y | ( y << 8 ) ) & 0x00FF00FF;
283 y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
284 y = ( y | ( y << 2 ) ) & 0x33333333;
285 y = ( y | ( y << 1 ) ) & 0x55555555;
286
287 return x | ( y << 1 );
288 }
coord_type GetY() const
Definition: box2.h:181
coord_type GetX() const
Definition: box2.h:180

References BOX2< Vec >::GetHeight(), BOX2< Vec >::GetWidth(), BOX2< Vec >::GetX(), BOX2< Vec >::GetY(), and m_bbox.

Referenced by isEar(), and PolygonTriangulation::Vertex::updateOrder().

Member Data Documentation

◆ m_bbox

BOX2I PolygonTriangulation::m_bbox
private

Definition at line 698 of file polygon_triangulation.h.

Referenced by TesselatePolygon(), and zOrder().

◆ m_result

SHAPE_POLY_SET::TRIANGULATED_POLYGON& PolygonTriangulation::m_result
private

Definition at line 700 of file polygon_triangulation.h.

Referenced by earcutList(), insertVertex(), and TesselatePolygon().

◆ m_vertices

std::deque<Vertex> PolygonTriangulation::m_vertices
private

The documentation for this class was generated from the following file: