KiCad PCB EDA Suite
pad_custom_shape_functions.cpp
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  * Copyright (C) 2018 Jean-Pierre Charras, jp.charras at wanadoo.fr
5  * Copyright (C) 1992-2019 KiCad Developers, see AUTHORS.txt for contributors.
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, you may find one here:
19  * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
20  * or you may search the http://www.gnu.org website for the version 2 license,
21  * or you may write to the Free Software Foundation, Inc.,
22  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24 
30 #include <fctsys.h>
31 #include <trigo.h>
32 
33 #include <pcbnew.h>
34 
35 #include <bezier_curves.h>
36 #include <class_board.h>
37 #include <class_board_item.h>
38 #include <class_drawsegment.h>
39 #include <class_edge_mod.h>
40 #include <class_pad.h>
42 #include <geometry/convex_hull.h>
44 #include <geometry/shape_rect.h>
45 
46 
48 {
49  aTarget->SetShape( m_Shape );
50  aTarget->SetWidth( m_Thickness );
51  aTarget->SetStart( m_Start );
52  aTarget->SetEnd( m_End );
53  aTarget->SetBezControl1( m_Ctrl1 );
54  aTarget->SetBezControl2( m_Ctrl2 );
55 
56  // in a DRAWSEGMENT the radius of a circle is calculated from the
57  // center and one point on the circle outline (stored in m_End)
58  if( m_Shape == S_CIRCLE )
59  {
60  wxPoint end = m_Start;
61  end.x += m_Radius;
62  aTarget->SetEnd( end );
63  }
64 
65  aTarget->SetAngle( m_ArcAngle );
66  aTarget->SetPolyPoints( m_Poly );
67 }
68 
69 
71 {
72  ExportTo( static_cast<DRAWSEGMENT*>( aTarget ) );
73  // Initialize coordinates specific to the EDGE_MODULE (m_Start0 and m_End0)
74  aTarget->SetLocalCoord();
75 }
76 
77 
78 void PAD_CS_PRIMITIVE::Move( wxPoint aMoveVector )
79 {
80  m_Start += aMoveVector;
81  m_End += aMoveVector;
82  m_Ctrl1 += aMoveVector;
83  m_Ctrl2 += aMoveVector;
84 
85  for( auto& corner : m_Poly )
86  {
87  corner += aMoveVector;
88  }
89 }
90 
91 
92 void PAD_CS_PRIMITIVE::Rotate( const wxPoint& aRotCentre, double aAngle )
93 {
94  switch( m_Shape )
95  {
96  case S_ARC:
97  case S_SEGMENT:
98  case S_CIRCLE:
99  // these can all be done by just rotating the start and end points
100  RotatePoint( &m_Start, aRotCentre, aAngle );
101  RotatePoint( &m_End, aRotCentre, aAngle );
102  break;
103 
104  case S_POLYGON:
105  for( auto& pt : m_Poly )
106  RotatePoint( &pt, aRotCentre, aAngle );
107 
108  break;
109 
110  case S_CURVE:
111  RotatePoint( &m_Start, aRotCentre, aAngle );
112  RotatePoint( &m_End, aRotCentre, aAngle );
113  RotatePoint( &m_Ctrl1, aRotCentre, aAngle );
114  RotatePoint( &m_Ctrl2, aRotCentre, aAngle );
115 
116  break;
117 
118  case S_RECT:
119  default:
120  // un-handled edge transform
121  wxASSERT_MSG( false, wxT( "PAD_CS_PRIMITIVE::Rotate not implemented for "
123  break;
124  }
125 }
126 
127 
128 /*
129  * Has meaning only for free shape pads.
130  * add a free shape to the shape list.
131  * the shape is a polygon (can be with thick outline), segment, circle or arc
132  */
133 
134 void D_PAD::AddPrimitive( const SHAPE_POLY_SET& aPoly, int aThickness )
135 {
136  std::vector<wxPoint> points;
137 
138  // If aPoly has holes, convert it to a polygon with no holes.
139  SHAPE_POLY_SET poly_no_hole;
140  poly_no_hole.Append( aPoly );
142 
143  for( auto iter = poly_no_hole.CIterate(); iter; iter++ )
144  points.push_back( wxPoint( iter->x, iter->y ) );
145 
146  AddPrimitive( points, aThickness );
147 }
148 
149 void D_PAD::AddPrimitive( const std::vector<wxPoint>& aPoly, int aThickness )
150 {
151  PAD_CS_PRIMITIVE shape( S_POLYGON );
152  shape.m_Poly = aPoly;
153  shape.m_Thickness = aThickness;
154  m_basicShapes.push_back( shape );
155 
157 }
158 
159 
160 void D_PAD::AddPrimitive( wxPoint aStart, wxPoint aEnd, int aThickness )
161 {
162  PAD_CS_PRIMITIVE shape( S_SEGMENT );
163  shape.m_Start = aStart;
164  shape.m_End = aEnd;
165  shape.m_Thickness = aThickness;
166  m_basicShapes.push_back( shape );
167 
169 }
170 
171 
172 void D_PAD::AddPrimitive( wxPoint aCenter, wxPoint aStart, int aArcAngle, int aThickness )
173 {
174  PAD_CS_PRIMITIVE shape( S_ARC );
175  shape.m_Start = aCenter;
176  shape.m_End = aStart;
177  shape.m_ArcAngle = aArcAngle;
178  shape.m_Thickness = aThickness;
179  m_basicShapes.push_back( shape );
180 
182 }
183 
184 
185 void D_PAD::AddPrimitive( wxPoint aStart, wxPoint aEnd, wxPoint aCtrl1, wxPoint aCtrl2, int aThickness )
186 {
187  PAD_CS_PRIMITIVE shape( S_CURVE );
188  shape.m_Start = aStart;
189  shape.m_End = aEnd;
190  shape.m_Ctrl1 = aCtrl1;
191  shape.m_Ctrl2 = aCtrl2;
192  shape.m_Thickness = aThickness;
193  m_basicShapes.push_back( shape );
194 
196 }
197 
198 
199 void D_PAD::AddPrimitive( wxPoint aCenter, int aRadius, int aThickness )
200 {
201  PAD_CS_PRIMITIVE shape( S_CIRCLE );
202  shape.m_Start = aCenter;
203  shape.m_Radius = aRadius;
204  shape.m_Thickness = aThickness;
205  m_basicShapes.push_back( shape );
206 
208 }
209 
210 
211 bool D_PAD::SetPrimitives( const std::vector<PAD_CS_PRIMITIVE>& aPrimitivesList )
212 {
213  // clear old list
214  m_basicShapes.clear();
215 
216  // Import to the basic shape list
217  if( aPrimitivesList.size() )
218  m_basicShapes = aPrimitivesList;
219 
220  // Only one polygon is expected (pad area = only one copper area)
221  return MergePrimitivesAsPolygon();
222 }
223 
224 bool D_PAD::AddPrimitives( const std::vector<PAD_CS_PRIMITIVE>& aPrimitivesList )
225 {
226  for( const auto& prim : aPrimitivesList )
227  m_basicShapes.push_back( prim );
228 
229  return MergePrimitivesAsPolygon();
230 }
231 
232 
233 // clear the basic shapes list and associated data
235 {
236  m_basicShapes.clear();
238 }
239 
240 
241 bool D_PAD::buildCustomPadPolygon( SHAPE_POLY_SET* aMergedPolygon, int aError )
242 
243 {
244  SHAPE_POLY_SET aux_polyset;
245 
246  for( unsigned cnt = 0; cnt < m_basicShapes.size(); ++cnt )
247  {
248  const PAD_CS_PRIMITIVE& bshape = m_basicShapes[cnt];
249 
250  switch( bshape.m_Shape )
251  {
252  case S_CURVE:
253  {
254  std::vector<wxPoint> ctrlPoints = { bshape.m_Start, bshape.m_Ctrl1, bshape.m_Ctrl2, bshape.m_End };
255  BEZIER_POLY converter( ctrlPoints );
256  std::vector< wxPoint> poly;
257  converter.GetPoly( poly, bshape.m_Thickness );
258 
259  for( unsigned ii = 1; ii < poly.size(); ii++ )
260  {
262  aux_polyset, poly[ ii - 1 ], poly[ ii ], aError, bshape.m_Thickness );
263  }
264  break;
265  }
266 
267  case S_SEGMENT: // usual segment : line with rounded ends
268  {
270  aux_polyset, bshape.m_Start, bshape.m_End, aError, bshape.m_Thickness );
271  break;
272  }
273 
274  case S_ARC: // Arc with rounded ends
275  {
276  TransformArcToPolygon( aux_polyset, bshape.m_Start, bshape.m_End, bshape.m_ArcAngle,
277  aError, bshape.m_Thickness );
278  break;
279  }
280 
281  case S_CIRCLE: // ring or circle
282  {
283  if( bshape.m_Thickness ) // ring
285  aux_polyset, bshape.m_Start, bshape.m_Radius, aError, bshape.m_Thickness );
286  else // Filled circle
287  TransformCircleToPolygon( aux_polyset, bshape.m_Start, bshape.m_Radius, aError );
288  break;
289  }
290 
291  case S_POLYGON: // polygon
292  if( bshape.m_Poly.size() < 2 )
293  break; // Malformed polygon.
294  {
295  // Insert the polygon:
296  const std::vector< wxPoint>& poly = bshape.m_Poly;
297  aux_polyset.NewOutline();
298 
299  if( bshape.m_Thickness )
300  {
301  SHAPE_POLY_SET polyset;
302  polyset.NewOutline();
303 
304  for( unsigned ii = 0; ii < poly.size(); ii++ )
305  {
306  polyset.Append( poly[ii].x, poly[ii].y );
307  }
308 
309  int numSegs = std::max(
310  GetArcToSegmentCount( bshape.m_Thickness / 2, aError, 360.0 ), 6 );
311  polyset.Inflate( bshape.m_Thickness / 2, numSegs );
312 
313  aux_polyset.Append( polyset );
314  }
315  else
316  for( unsigned ii = 0; ii < poly.size(); ii++ )
317  aux_polyset.Append( poly[ii].x, poly[ii].y );
318  }
319  break;
320 
321  default:
322  break;
323  }
324  }
325 
326  aux_polyset.Simplify( SHAPE_POLY_SET::PM_FAST );
327 
328  // Merge all polygons with the initial pad anchor shape
329  if( aux_polyset.OutlineCount() )
330  {
331  aMergedPolygon->BooleanAdd( aux_polyset, SHAPE_POLY_SET::PM_STRICTLY_SIMPLE );
332  aMergedPolygon->Fracture( SHAPE_POLY_SET::PM_STRICTLY_SIMPLE );
333  }
334 
335  return aMergedPolygon->OutlineCount() <= 1;
336 }
337 
338 /* Merge all basic shapes, converted to a polygon in one polygon,
339  * return true if OK, false in there is more than one polygon
340  * in aMergedPolygon
341  */
343 {
344  auto board = GetBoard();
345  int maxError = ARC_HIGH_DEF;
346 
347  if( board )
348  maxError = board->GetDesignSettings().m_MaxError;
349 
350  // if aMergedPolygon == NULL, use m_customShapeAsPolygon as target
351 
352  if( !aMergedPolygon )
353  aMergedPolygon = &m_customShapeAsPolygon;
354 
355  aMergedPolygon->RemoveAllContours();
356 
357  // Add the anchor pad shape in aMergedPolygon, others in aux_polyset:
358  // The anchor pad is always at 0,0
359  switch( GetAnchorPadShape() )
360  {
361  default:
362  case PAD_SHAPE_CIRCLE:
363  TransformCircleToPolygon( *aMergedPolygon, wxPoint( 0, 0 ), GetSize().x / 2, maxError );
364  break;
365 
366  case PAD_SHAPE_RECT:
367  {
368  SHAPE_RECT rect( -GetSize().x / 2, -GetSize().y / 2, GetSize().x, GetSize().y );
369  aMergedPolygon->AddOutline( rect.Outline() );
370 
371  break;
372  }
373  }
374 
375  if( !buildCustomPadPolygon( aMergedPolygon, maxError ) )
376  return false;
377 
378  m_boundingRadius = -1; // The current bounding radius is no longer valid.
379 
380  return aMergedPolygon->OutlineCount() <= 1;
381 }
382 
384  wxPoint aPosition, double aRotation ) const
385 {
386  if( aMergedPolygon->OutlineCount() == 0 )
387  return;
388 
389  // Move, rotate, ... coordinates in aMergedPolygon according to the
390  // pad position and orientation
391  for( int cnt = 0; cnt < aMergedPolygon->OutlineCount(); ++cnt )
392  {
393  SHAPE_LINE_CHAIN& poly = aMergedPolygon->Outline( cnt );
394 
395  for( int ii = 0; ii < poly.PointCount(); ++ii )
396  {
397  wxPoint corner( poly.Point( ii ).x, poly.Point( ii ).y );
398  RotatePoint( &corner, aRotation );
399  corner += aPosition;
400 
401  poly.Point( ii ).x = corner.x;
402  poly.Point( ii ).y = corner.y;
403  }
404  }
405 }
406 
408 {
409  SHAPE_POLY_SET poly;
410 
411  if( !buildCustomPadPolygon( &poly, ARC_LOW_DEF ) )
412  return false;
413 
414  const int minSteps = 10;
415  const int maxSteps = 50;
416 
417  int stepsX, stepsY;
418 
419  auto bbox = poly.BBox();
420 
421  if( bbox.GetWidth() < bbox.GetHeight() )
422  {
423  stepsX = minSteps;
424  stepsY = minSteps * (double) bbox.GetHeight() / (double )(bbox.GetWidth() + 1);
425  }
426  else
427  {
428  stepsY = minSteps;
429  stepsX = minSteps * (double) bbox.GetWidth() / (double )(bbox.GetHeight() + 1);
430  }
431 
432  stepsX = std::max(minSteps, std::min( maxSteps, stepsX ) );
433  stepsY = std::max(minSteps, std::min( maxSteps, stepsY ) );
434 
435  auto center = bbox.Centre();
436 
437  auto minDist = std::numeric_limits<int64_t>::max();
438  int64_t minDistEdge;
439 
441  {
442  minDistEdge = GetSize().x;
443  }
444  else
445  {
446  minDistEdge = std::max( GetSize().x, GetSize().y );
447  }
448 
449  OPT<VECTOR2I> bestAnchor( []()->OPT<VECTOR2I> { return NULLOPT; }() );
450 
451  for ( int y = 0; y < stepsY ; y++ )
452  {
453  for ( int x = 0; x < stepsX; x++ )
454  {
455  VECTOR2I p = bbox.GetPosition();
456  p.x += rescale( x, bbox.GetWidth(), (stepsX - 1) );
457  p.y += rescale( y, bbox.GetHeight(), (stepsY - 1) );
458 
459  if ( poly.Contains(p) )
460  {
461 
462  auto dist = (center - p).EuclideanNorm();
463  auto distEdge = poly.COutline(0).Distance( p, true );
464  if ( distEdge >= minDistEdge )
465  {
466  if ( dist < minDist )
467  {
468  bestAnchor = p;
469  minDist = dist;
470  }
471  }
472  }
473  }
474  }
475 
476  if ( bestAnchor )
477  {
478  aPos = *bestAnchor;
479  return true;
480  }
481 
482  return false;
483 }
double EuclideanNorm(const wxPoint &vector)
Euclidean norm of a 2D vector.
Definition: trigo.h:123
static wxString ShowShape(STROKE_T aShape)
Function ShowShape converts the enum STROKE_T integer value to a wxString.
int m_boundingRadius
radius of the circle containing the pad shape
Definition: class_pad.h:821
std::vector< PAD_CS_PRIMITIVE > m_basicShapes
for free shape pads: a list of basic shapes, in local coordinates, orient 0, coordinates relative to ...
Definition: class_pad.h:836
void TransformArcToPolygon(SHAPE_POLY_SET &aCornerBuffer, wxPoint aCentre, wxPoint aStart, double aArcAngle, int aError, int aWidth)
Function TransformArcToPolygon Creates a polygon from an Arc Convert arcs to multiple straight segmen...
void SetShape(STROKE_T aShape)
int OutlineCount() const
Returns the number of outlines in the set
void TransformCircleToPolygon(SHAPE_LINE_CHAIN &aBuffer, wxPoint aCenter, int aRadius, int aError)
const SHAPE_LINE_CHAIN Outline() const
Definition: shape_rect.h:145
int GetArcToSegmentCount(int aRadius, int aErrorMax, double aArcAngleDegree)
static const int dist[10][10]
Definition: ar_matrix.cpp:320
void BooleanAdd(const SHAPE_POLY_SET &b, POLYGON_MODE aFastMode)
Performs boolean polyset union For aFastMode meaning, see function booleanOp
PAD_SHAPE_T GetAnchorPadShape() const
Function GetAnchorPadShape.
Definition: class_pad.h:231
Classes BOARD_ITEM and BOARD_CONNECTED_ITEM.
void GetPoly(std::vector< wxPoint > &aOutput, int aMinSegLen=0)
Converts Bezier curve to a polygon.
bool GetBestAnchorPosition(VECTOR2I &aPos)
bool AddPrimitives(const std::vector< PAD_CS_PRIMITIVE > &aPrimitivesList)
Add to the basic shape list.
void ExportTo(DRAWSEGMENT *aTarget)
Export the PAD_CS_PRIMITIVE parameters to a DRAWSEGMENT useful to draw a primitive shape.
wxPoint m_Start
angle of an arc, from its starting point, in 0.1 deg
Definition: class_pad.h:98
polygon (not yet used for tracks, but could be in microwave apps)
void TransformRingToPolygon(SHAPE_POLY_SET &aCornerBuffer, wxPoint aCentre, int aRadius, int aError, int aWidth)
Function TransformRingToPolygon Creates a polygon from a ring Convert arcs to multiple straight segme...
int Distance(const VECTOR2I &aP, bool aOutlineOnly=false) const
Function Distance()
usual segment : line with rounded ends
void Move(wxPoint aMoveVector)
returns the start point of an arc
bool Contains(const VECTOR2I &aP, int aSubpolyIndex=-1, int aAccuracy=0, bool aUseBBoxCaches=false) const
Returns true if a given subpolygon contains the point aP.
void RotatePoint(int *pX, int *pY, double angle)
Definition: trigo.cpp:206
void Inflate(int aAmount, int aCircleSegmentsCount, CORNER_STRATEGY aCornerStrategy=ROUND_ALL_CORNERS)
Performs outline inflation/deflation.
int PointCount() const
Function PointCount()
void SetBezControl2(const wxPoint &aPoint)
wxPoint m_Ctrl1
is also the start point of the arc
Definition: class_pad.h:100
segment with non rounded ends
int m_Radius
thickness of segment or outline For filled S_CIRCLE shape, thickness = 0.
Definition: class_pad.h:96
const auto NULLOPT
Definition: optional.h:9
std::vector< wxPoint > m_Poly
Bezier Control point 2.
Definition: class_pad.h:102
bool MergePrimitivesAsPolygon(SHAPE_POLY_SET *aMergedPolygon=NULL)
Merge all basic shapes, converted to a polygon in one polygon, in m_customShapeAsPolygon.
Class SHAPE_POLY_SET.
SHAPE_LINE_CHAIN & Outline(int aIndex)
Returns the reference to aIndex-th outline in the set
Arcs (with rounded ends)
Helper class to handle a primitive (basic shape: polygon, segment, circle or arc) to build a custom p...
Definition: class_pad.h:89
virtual BOARD * GetBoard() const
Function GetBoard returns the BOARD in which this BOARD_ITEM resides, or NULL if none.
a few functions useful in geometry calculations.
void Simplify(POLYGON_MODE aFastMode)
Simplifies the polyset (merges overlapping polys, eliminates degeneracy/self-intersections) For aFast...
SHAPE_POLY_SET m_customShapeAsPolygon
for free shape pads: the set of basic shapes, merged as one polygon, in local coordinates,...
Definition: class_pad.h:841
Bezier Curve.
wxPoint m_End
is also the center of the circle and arc
Definition: class_pad.h:99
int NewOutline()
Creates a new empty polygon in the set and returns its index
CONST_ITERATOR CIterate(int aFirst, int aLast, bool aIterateHoles=false) const
STROKE_T m_Shape
Definition: class_pad.h:92
void Fracture(POLYGON_MODE aFastMode)
Converts a set of polygons with holes to a singe outline with "slits"/"fractures" connecting the oute...
Pad object description.
wxPoint m_Ctrl2
Bezier Control point 1.
Definition: class_pad.h:101
void SetStart(const wxPoint &aStart)
bool buildCustomPadPolygon(SHAPE_POLY_SET *aMergedPolygon, int aError)
void SetPolyPoints(const std::vector< wxPoint > &aPoints)
int m_Thickness
S_SEGMENT, S_ARC, S_CIRCLE, S_POLYGON only (same as DRAWSEGMENT)
Definition: class_pad.h:93
int AddOutline(const SHAPE_LINE_CHAIN &aOutline)
Adds a new outline to the set and returns its index
void SetLocalCoord()
Set relative coordinates from draw coordinates.
Bezier curves to polygon converter.
Definition: bezier_curves.h:35
Class to handle a graphic segment.
#define max(a, b)
Definition: auxiliary.h:86
T rescale(T aNumerator, T aValue, T aDenominator)
Function rescale()
Class SHAPE_LINE_CHAIN.
void CustomShapeAsPolygonToBoardPosition(SHAPE_POLY_SET *aMergedPolygon, wxPoint aPosition, double aRotation) const
When created, the corners coordinates are relative to the pad position, orientation 0,...
const SHAPE_LINE_CHAIN & COutline(int aIndex) const
void TransformSegmentToPolygon(SHAPE_POLY_SET &aCornerBuffer, wxPoint aStart, wxPoint aEnd, int aError, int aWidth)
Function TransformRoundedEndsSegmentToPolygon convert a segment with rounded ends to a polygon Conver...
void RemoveAllContours()
Removes all outlines & holes (clears) the polygon set.
void AddPrimitive(const SHAPE_POLY_SET &aPoly, int aThickness)
Has meaning only for free shape pads.
coord_type GetHeight() const
Definition: box2.h:196
boost::optional< T > OPT
Definition: optional.h:7
void SetEnd(const wxPoint &aEnd)
void SetAngle(double aAngle)
Function SetAngle sets the angle for arcs, and normalizes it within the range 0 - 360 degrees.
VECTOR2I & Point(int aIndex)
Function Point()
const wxSize & GetSize() const
Definition: class_pad.h:284
EDGE_MODULE class definition.
void Rotate(const wxPoint &aRotCentre, double aAngle)
Rotates the primitive about a point.
const BOX2I BBox(int aClearance=0) const override
Function BBox()
bool SetPrimitives(const std::vector< PAD_CS_PRIMITIVE > &aPrimitivesList)
Import to the basic shape list.
void DeletePrimitivesList()
clear the basic shapes list
double m_ArcAngle
radius of a circle
Definition: class_pad.h:97
#define min(a, b)
Definition: auxiliary.h:85
void SetBezControl1(const wxPoint &aPoint)
int Append(int x, int y, int aOutline=-1, int aHole=-1, bool aAllowDuplication=false)
Appends a vertex at the end of the given outline/hole (default: the last outline)
void SetWidth(int aWidth)