You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

631 lines
22 KiB

  1. /*
  2. * This program source code file is part of KiCad, a free EDA CAD application.
  3. *
  4. * Copyright (C) 2017 Jean-Pierre Charras, jp.charras at wanadoo.fr
  5. * Copyright (C) 2015 SoftPLC Corporation, Dick Hollenbeck <dick@softplc.com>
  6. * Copyright (C) 1992-2017 KiCad Developers, see AUTHORS.txt for contributors.
  7. *
  8. * This program is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU General Public License
  10. * as published by the Free Software Foundation; either version 2
  11. * of the License, or (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program; if not, you may find one here:
  20. * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  21. * or you may search the http://www.gnu.org website for the version 2 license,
  22. * or you may write to the Free Software Foundation, Inc.,
  23. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
  24. */
  25. /**
  26. * @file convert_drawsegment_list_to_polygon.cpp
  27. * @brief functions to convert a shape built with DRAWSEGMENTS to a polygon.
  28. * expecting the shape describes shape similar to a polygon
  29. */
  30. #include <trigo.h>
  31. #include <macros.h>
  32. #include <class_drawsegment.h>
  33. #include <base_units.h>
  34. #include <convert_basic_shapes_to_polygon.h>
  35. #include <geometry/geometry_utils.h>
  36. /**
  37. * Function close_ness
  38. * is a non-exact distance (also called Manhattan distance) used to approximate
  39. * the distance between two points.
  40. * The distance is very in-exact, but can be helpful when used
  41. * to pick between alternative neighboring points.
  42. * @param aLeft is the first point
  43. * @param aRight is the second point
  44. * @return unsigned - a measure of proximity that the caller knows about, in BIU,
  45. * but remember it is only an approximation.
  46. */
  47. static unsigned close_ness( const wxPoint& aLeft, const wxPoint& aRight )
  48. {
  49. // Don't need an accurate distance calculation, just something
  50. // approximating it, for relative ordering.
  51. return unsigned( std::abs( aLeft.x - aRight.x ) + abs( aLeft.y - aRight.y ) );
  52. }
  53. /**
  54. * Function close_enough
  55. * is a local and tunable method of qualifying the proximity of two points.
  56. *
  57. * @param aLeft is the first point
  58. * @param aRight is the second point
  59. * @param aLimit is a measure of proximity that the caller knows about.
  60. * @return bool - true if the two points are close enough, else false.
  61. */
  62. inline bool close_enough( const wxPoint& aLeft, const wxPoint& aRight, unsigned aLimit )
  63. {
  64. // We don't use an accurate distance calculation, just something
  65. // approximating it, since aLimit is non-exact anyway except when zero.
  66. return close_ness( aLeft, aRight ) <= aLimit;
  67. }
  68. /**
  69. * Function close_st
  70. * is a local method of qualifying if either the start of end point of a segment is closest to a point.
  71. *
  72. * @param aReference is the reference point
  73. * @param aFirst is the first point
  74. * @param aSecond is the second point
  75. * @return bool - true if the the first point is closest to the reference, otherwise false.
  76. */
  77. inline bool close_st( const wxPoint& aReference, const wxPoint& aFirst, const wxPoint& aSecond )
  78. {
  79. // We don't use an accurate distance calculation, just something
  80. // approximating to find the closest to the reference.
  81. return close_ness( aReference, aFirst ) <= close_ness( aReference, aSecond );
  82. }
  83. /**
  84. * Searches for a DRAWSEGMENT matching a given end point or start point in a list, and
  85. * if found, removes it from the TYPE_COLLECTOR and returns it, else returns NULL.
  86. * @param aPoint The starting or ending point to search for.
  87. * @param aList The list to remove from.
  88. * @param aLimit is the distance from \a aPoint that still constitutes a valid find.
  89. * @return DRAWSEGMENT* - The first DRAWSEGMENT that has a start or end point matching
  90. * aPoint, otherwise NULL if none.
  91. */
  92. static DRAWSEGMENT* findPoint( const wxPoint& aPoint, std::vector< DRAWSEGMENT* >& aList, unsigned aLimit )
  93. {
  94. unsigned min_d = INT_MAX;
  95. int ndx_min = 0;
  96. // find the point closest to aPoint and perhaps exactly matching aPoint.
  97. for( size_t i = 0; i < aList.size(); ++i )
  98. {
  99. DRAWSEGMENT* graphic = aList[i];
  100. unsigned d;
  101. switch( graphic->GetShape() )
  102. {
  103. case S_ARC:
  104. if( aPoint == graphic->GetArcStart() || aPoint == graphic->GetArcEnd() )
  105. {
  106. aList.erase( aList.begin() + i );
  107. return graphic;
  108. }
  109. d = close_ness( aPoint, graphic->GetArcStart() );
  110. if( d < min_d )
  111. {
  112. min_d = d;
  113. ndx_min = i;
  114. }
  115. d = close_ness( aPoint, graphic->GetArcEnd() );
  116. if( d < min_d )
  117. {
  118. min_d = d;
  119. ndx_min = i;
  120. }
  121. break;
  122. default:
  123. if( aPoint == graphic->GetStart() || aPoint == graphic->GetEnd() )
  124. {
  125. aList.erase( aList.begin() + i );
  126. return graphic;
  127. }
  128. d = close_ness( aPoint, graphic->GetStart() );
  129. if( d < min_d )
  130. {
  131. min_d = d;
  132. ndx_min = i;
  133. }
  134. d = close_ness( aPoint, graphic->GetEnd() );
  135. if( d < min_d )
  136. {
  137. min_d = d;
  138. ndx_min = i;
  139. }
  140. }
  141. }
  142. if( min_d <= aLimit )
  143. {
  144. DRAWSEGMENT* graphic = aList[ndx_min];
  145. aList.erase( aList.begin() + ndx_min );
  146. return graphic;
  147. }
  148. return NULL;
  149. }
  150. /**
  151. * Function ConvertOutlineToPolygon
  152. * build a polygon (with holes) from a DRAWSEGMENT list, which is expected to be
  153. * a outline, therefore a closed main outline with perhaps closed inner outlines.
  154. * These closed inner outlines are considered as holes in the main outline
  155. * @param aSegList the initial list of drawsegments (only lines, circles and arcs).
  156. * @param aPolygons will contain the complex polygon.
  157. * @param aErrorText is a wxString to return error message.
  158. */
  159. bool ConvertOutlineToPolygon( std::vector< DRAWSEGMENT* >& aSegList,
  160. SHAPE_POLY_SET& aPolygons, wxString* aErrorText )
  161. {
  162. if( aSegList.size() == 0 )
  163. return true;
  164. wxString msg;
  165. // Make a working copy of aSegList, because the list is modified during calculations
  166. std::vector< DRAWSEGMENT* > segList = aSegList;
  167. unsigned prox; // a proximity BIU metric, not an accurate distance
  168. DRAWSEGMENT* graphic;
  169. wxPoint prevPt;
  170. // Find edge point with minimum x, this should be in the outer polygon
  171. // which will define the perimeter Edge.Cuts polygon.
  172. wxPoint xmin = wxPoint( INT_MAX, 0 );
  173. int xmini = 0;
  174. for( size_t i = 0; i < segList.size(); i++ )
  175. {
  176. graphic = (DRAWSEGMENT*) segList[i];
  177. switch( graphic->GetShape() )
  178. {
  179. case S_SEGMENT:
  180. {
  181. if( graphic->GetStart().x < xmin.x )
  182. {
  183. xmin = graphic->GetStart();
  184. xmini = i;
  185. }
  186. if( graphic->GetEnd().x < xmin.x )
  187. {
  188. xmin = graphic->GetEnd();
  189. xmini = i;
  190. }
  191. }
  192. break;
  193. case S_ARC:
  194. // Freerouter does not yet understand arcs, so approximate
  195. // an arc with a series of short lines and put those
  196. // line segments into the !same! PATH.
  197. {
  198. wxPoint pstart = graphic->GetArcStart();
  199. wxPoint center = graphic->GetCenter();
  200. double angle = -graphic->GetAngle();
  201. double radius = graphic->GetRadius();
  202. int steps = GetArcToSegmentCount( radius, ARC_LOW_DEF, angle / 10.0 );
  203. wxPoint pt;
  204. for( int step = 1; step<=steps; ++step )
  205. {
  206. double rotation = ( angle * step ) / steps;
  207. pt = pstart;
  208. RotatePoint( &pt, center, rotation );
  209. if( pt.x < xmin.x )
  210. {
  211. xmin = pt;
  212. xmini = i;
  213. }
  214. }
  215. }
  216. break;
  217. case S_CIRCLE:
  218. {
  219. wxPoint pt = graphic->GetCenter();
  220. // pt has minimum x point
  221. pt.x -= graphic->GetRadius();
  222. // when the radius <= 0, this is a mal-formed circle. Skip it
  223. if( graphic->GetRadius() > 0 && pt.x < xmin.x )
  224. {
  225. xmin = pt;
  226. xmini = i;
  227. }
  228. }
  229. break;
  230. default:
  231. break;
  232. }
  233. }
  234. // Grab the left most point, assume its on the board's perimeter, and see if we
  235. // can put enough graphics together by matching endpoints to formulate a cohesive
  236. // polygon.
  237. graphic = (DRAWSEGMENT*) segList[xmini];
  238. // The first DRAWSEGMENT is in 'graphic', ok to remove it from 'items'
  239. segList.erase( segList.begin() + xmini );
  240. // Set maximum proximity threshold for point to point nearness metric for
  241. // board perimeter only, not interior keepouts yet.
  242. prox = Millimeter2iu( 0.01 ); // should be enough to fix rounding issues
  243. // is arc start and end point calculations
  244. // Output the Edge.Cuts perimeter as circle or polygon.
  245. if( graphic->GetShape() == S_CIRCLE )
  246. {
  247. int steps = GetArcToSegmentCount( graphic->GetRadius(), ARC_LOW_DEF, 360.0 );
  248. TransformCircleToPolygon( aPolygons, graphic->GetCenter(), graphic->GetRadius(), steps );
  249. }
  250. else
  251. {
  252. // Polygon start point. Arbitrarily chosen end of the
  253. // segment and build the poly from here.
  254. wxPoint startPt = wxPoint( graphic->GetEnd() );
  255. prevPt = graphic->GetEnd();
  256. aPolygons.NewOutline();
  257. aPolygons.Append( prevPt );
  258. // Do not append the other end point yet of this 'graphic', this first
  259. // 'graphic' might be an arc.
  260. for(;;)
  261. {
  262. switch( graphic->GetShape() )
  263. {
  264. case S_SEGMENT:
  265. {
  266. wxPoint nextPt;
  267. // Use the line segment end point furthest away from
  268. // prevPt as we assume the other end to be ON prevPt or
  269. // very close to it.
  270. if( close_st( prevPt, graphic->GetStart(), graphic->GetEnd() ) )
  271. nextPt = graphic->GetEnd();
  272. else
  273. nextPt = graphic->GetStart();
  274. aPolygons.Append( nextPt );
  275. prevPt = nextPt;
  276. }
  277. break;
  278. case S_ARC:
  279. // We do not support arcs in polygons, so approximate
  280. // an arc with a series of short lines and put those
  281. // line segments into the !same! PATH.
  282. {
  283. wxPoint pstart = graphic->GetArcStart();
  284. wxPoint pend = graphic->GetArcEnd();
  285. wxPoint pcenter = graphic->GetCenter();
  286. double angle = -graphic->GetAngle();
  287. double radius = graphic->GetRadius();
  288. int steps = GetArcToSegmentCount( radius, ARC_LOW_DEF, angle / 10.0 );
  289. if( !close_enough( prevPt, pstart, prox ) )
  290. {
  291. wxASSERT( close_enough( prevPt, graphic->GetArcEnd(), prox ) );
  292. angle = -angle;
  293. std::swap( pstart, pend );
  294. }
  295. wxPoint nextPt;
  296. for( int step = 1; step<=steps; ++step )
  297. {
  298. double rotation = ( angle * step ) / steps;
  299. nextPt = pstart;
  300. RotatePoint( &nextPt, pcenter, rotation );
  301. aPolygons.Append( nextPt );
  302. }
  303. prevPt = nextPt;
  304. }
  305. break;
  306. default:
  307. if( aErrorText )
  308. {
  309. msg.Printf( _( "Unsupported DRAWSEGMENT type %s" ),
  310. GetChars( BOARD_ITEM::ShowShape( graphic->GetShape() ) ) );
  311. *aErrorText << msg << "\n";
  312. }
  313. return false;
  314. }
  315. // Get next closest segment.
  316. graphic = findPoint( prevPt, segList, prox );
  317. // If there are no more close segments, check if the board
  318. // outline polygon can be closed.
  319. if( !graphic )
  320. {
  321. if( close_enough( startPt, prevPt, prox ) )
  322. {
  323. // Close the polygon back to start point
  324. // aPolygons.Append( startPt ); // not needed
  325. }
  326. else
  327. {
  328. if( aErrorText )
  329. {
  330. msg.Printf(
  331. _( "Unable to find the next boundary segment with an endpoint of (%s mm, %s mm). "
  332. "graphic outline must form a contiguous, closed polygon." ),
  333. GetChars( FROM_UTF8( BOARD_ITEM::FormatInternalUnits( prevPt.x ).c_str() ) ),
  334. GetChars( FROM_UTF8( BOARD_ITEM::FormatInternalUnits( prevPt.y ).c_str() ) )
  335. );
  336. *aErrorText << msg << "\n";
  337. }
  338. return false;
  339. }
  340. break;
  341. }
  342. }
  343. }
  344. // Output the interior Edge.Cuts graphics as keepouts, using same nearness
  345. // metric as the board edge as otherwise we have trouble completing complex
  346. // polygons.
  347. prox = Millimeter2iu( 0.05 );
  348. while( segList.size() )
  349. {
  350. // emit a signal layers keepout for every interior polygon left...
  351. int hole = aPolygons.NewHole();
  352. graphic = (DRAWSEGMENT*) segList[0];
  353. segList.erase( segList.begin() );
  354. if( graphic->GetShape() == S_CIRCLE )
  355. {
  356. // make a circle by segments;
  357. wxPoint center = graphic->GetCenter();
  358. double angle = 3600.0;
  359. wxPoint start = center;
  360. int radius = graphic->GetRadius();
  361. int steps = GetArcToSegmentCount( radius, ARC_LOW_DEF, 360.0 );
  362. wxPoint nextPt;
  363. start.x += radius;
  364. for( int step = 0; step < steps; ++step )
  365. {
  366. double rotation = ( angle * step ) / steps;
  367. nextPt = start;
  368. RotatePoint( &nextPt.x, &nextPt.y, center.x, center.y, rotation );
  369. aPolygons.Append( nextPt, -1, hole );
  370. }
  371. }
  372. else
  373. {
  374. // Polygon start point. Arbitrarily chosen end of the
  375. // segment and build the poly from here.
  376. wxPoint startPt( graphic->GetEnd() );
  377. prevPt = graphic->GetEnd();
  378. aPolygons.Append( prevPt, -1, hole );
  379. // do not append the other end point yet, this first 'graphic' might be an arc
  380. for(;;)
  381. {
  382. switch( graphic->GetShape() )
  383. {
  384. case S_SEGMENT:
  385. {
  386. wxPoint nextPt;
  387. // Use the line segment end point furthest away from
  388. // prevPt as we assume the other end to be ON prevPt or
  389. // very close to it.
  390. if( close_st( prevPt, graphic->GetStart(), graphic->GetEnd() ) )
  391. {
  392. nextPt = graphic->GetEnd();
  393. }
  394. else
  395. {
  396. nextPt = graphic->GetStart();
  397. }
  398. prevPt = nextPt;
  399. aPolygons.Append( prevPt, -1, hole );
  400. }
  401. break;
  402. case S_ARC:
  403. // Freerouter does not yet understand arcs, so approximate
  404. // an arc with a series of short lines and put those
  405. // line segments into the !same! PATH.
  406. {
  407. wxPoint pstart = graphic->GetArcStart();
  408. wxPoint pend = graphic->GetArcEnd();
  409. wxPoint pcenter = graphic->GetCenter();
  410. double angle = -graphic->GetAngle();
  411. int radius = graphic->GetRadius();
  412. int steps = GetArcToSegmentCount( radius, ARC_LOW_DEF, angle / 10.0 );
  413. if( !close_enough( prevPt, pstart, prox ) )
  414. {
  415. wxASSERT( close_enough( prevPt, graphic->GetArcEnd(), prox ) );
  416. angle = -angle;
  417. std::swap( pstart, pend );
  418. }
  419. wxPoint nextPt;
  420. for( int step = 1; step <= steps; ++step )
  421. {
  422. double rotation = ( angle * step ) / steps;
  423. nextPt = pstart;
  424. RotatePoint( &nextPt, pcenter, rotation );
  425. aPolygons.Append( nextPt, -1, hole );
  426. }
  427. prevPt = nextPt;
  428. }
  429. break;
  430. default:
  431. if( aErrorText )
  432. {
  433. msg.Printf( _( "Unsupported DRAWSEGMENT type %s" ),
  434. GetChars( BOARD_ITEM::ShowShape( graphic->GetShape() ) ) );
  435. *aErrorText << msg << "\n";
  436. }
  437. return false;
  438. }
  439. // Get next closest segment.
  440. graphic = findPoint( prevPt, segList, prox );
  441. // If there are no more close segments, check if polygon
  442. // can be closed.
  443. if( !graphic )
  444. {
  445. if( close_enough( startPt, prevPt, prox ) )
  446. {
  447. // Close the polygon back to start point
  448. // aPolygons.Append( startPt, -1, hole ); // not needed
  449. }
  450. else
  451. {
  452. if( aErrorText )
  453. {
  454. msg.Printf(
  455. _( "Unable to find the next graphic segment with an endpoint of (%s mm, %s mm).\n"
  456. "Edit graphics, making them contiguous polygons each." ),
  457. GetChars( FROM_UTF8( BOARD_ITEM::FormatInternalUnits( prevPt.x ).c_str() ) ),
  458. GetChars( FROM_UTF8( BOARD_ITEM::FormatInternalUnits( prevPt.y ).c_str() ) )
  459. );
  460. *aErrorText << msg << "\n";
  461. }
  462. return false;
  463. }
  464. break;
  465. }
  466. }
  467. }
  468. }
  469. return true;
  470. }
  471. #include <class_board.h>
  472. #include <collectors.h>
  473. /* This function is used to extract a board outlines (3D view, automatic zones build ...)
  474. * Any closed outline inside the main outline is a hole
  475. * All contours should be closed, i.e. valid closed polygon vertices
  476. */
  477. bool BuildBoardPolygonOutlines( BOARD* aBoard,
  478. SHAPE_POLY_SET& aOutlines,
  479. wxString* aErrorText )
  480. {
  481. PCB_TYPE_COLLECTOR items;
  482. // Get all the DRAWSEGMENTS and module graphics into 'items',
  483. // then keep only those on layer == Edge_Cuts.
  484. static const KICAD_T scan_graphics[] = { PCB_LINE_T, PCB_MODULE_EDGE_T, EOT };
  485. items.Collect( aBoard, scan_graphics );
  486. // Make a working copy of aSegList, because the list is modified during calculations
  487. std::vector< DRAWSEGMENT* > segList;
  488. for( int ii = 0; ii < items.GetCount(); ii++ )
  489. {
  490. if( items[ii]->GetLayer() == Edge_Cuts )
  491. segList.push_back( static_cast< DRAWSEGMENT* >( items[ii] ) );
  492. }
  493. bool success = ConvertOutlineToPolygon( segList, aOutlines, aErrorText );
  494. if( !success || !aOutlines.OutlineCount() )
  495. {
  496. // Creates a valid polygon outline is not possible.
  497. // So uses the board edge cuts bounding box to create a
  498. // rectangular outline
  499. // When no edge cuts items, build a contour
  500. // from global bounding box
  501. EDA_RECT bbbox = aBoard->GetBoardEdgesBoundingBox();
  502. // If null area, uses the global bounding box.
  503. if( ( bbbox.GetWidth() ) == 0 || ( bbbox.GetHeight() == 0 ) )
  504. bbbox = aBoard->ComputeBoundingBox();
  505. // Ensure non null area. If happen, gives a minimal size.
  506. if( ( bbbox.GetWidth() ) == 0 || ( bbbox.GetHeight() == 0 ) )
  507. bbbox.Inflate( Millimeter2iu( 1.0 ) );
  508. aOutlines.RemoveAllContours();
  509. aOutlines.NewOutline();
  510. wxPoint corner;
  511. aOutlines.Append( bbbox.GetOrigin() );
  512. corner.x = bbbox.GetOrigin().x;
  513. corner.y = bbbox.GetEnd().y;
  514. aOutlines.Append( corner );
  515. aOutlines.Append( bbbox.GetEnd() );
  516. corner.x = bbbox.GetEnd().x;
  517. corner.y = bbbox.GetOrigin().y;
  518. aOutlines.Append( corner );
  519. }
  520. return success;
  521. }