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.

1106 lines
32 KiB

++PCBNew * Removed Pcb_Frame argument from BOARD() constructor, since it precludes having a BOARD being edited by more than one editor, it was a bad design. And this meant removing m_PcbFrame from BOARD. * removed BOARD::SetWindowFrame(), and BOARD::m_PcbFrame * Removed the global BOARD_DESIGN_SETTINGS which was in class_board.cpp * added BOARD_DESIGN_SETTINGS to the BOARD class, a full instance * a couple dialogs now only change BOARD_DESIGN_SETTINGS when OK is pressed, such as dialog_mask_clearance, dialog_drc, etc. * Removed common/pcbcommon.cpp's int g_CurrentVersionPCB = 1 and replaced it with build_version.h's #define BOARD_FILE_VERSION, although there may be a better place for this constant. * Made the public functions in PARAM_CFG_ARRAY be type const. void SaveParam(..) const and void ReadParam(..) const * PARAM_CFG_BASE now has virtual destructor since we have various way of destroying the derived class and boost::ptr_vector must be told about this. * Pass const PARAM_CFG_ARRAY& instead of PARAM_CFG_ARRAY so that we can use an automatic PARAM_CFG_ARRAY which is on the stack.\ * PCB_EDIT_FRAME::GetProjectFileParameters() may no longer cache the array, since it has to access the current BOARD and the BOARD can change. Remember BOARD_DESIGN_SETTINGS are now in the BOARD. * Made the m_BoundingBox member private, this was a brutally hard task, and indicative of the lack of commitment to accessors and object oriented design on the part of KiCad developers. We must do better. Added BOARD::GetBoundingBox, SetBoundingBox(), ComputeBoundingBox(). * Added PCB_BASE_FRAME::GetBoardBoundingBox() which calls BOARD::ComputeBoundingBox()
14 years ago
  1. /*
  2. * This program source code file is part of KiCad, a free EDA CAD application.
  3. *
  4. * Copyright (C) 2012 Jean-Pierre Charras, jean-pierre.charras@ujf-grenoble.fr
  5. * Copyright (C) 2012 SoftPLC Corporation, Dick Hollenbeck <dick@softplc.com>
  6. * Copyright (C) 2011 Wayne Stambaugh <stambaughw@verizon.net>
  7. *
  8. * Copyright (C) 1992-2012 KiCad Developers, see change_log.txt for contributors.
  9. *
  10. * This program is free software; you can redistribute it and/or
  11. * modify it under the terms of the GNU General Public License
  12. * as published by the Free Software Foundation; either version 2
  13. * of the License, or (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with this program; if not, you may find one here:
  22. * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  23. * or you may search the http://www.gnu.org website for the version 2 license,
  24. * or you may write to the Free Software Foundation, Inc.,
  25. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
  26. */
  27. #include <fctsys.h>
  28. #include <confirm.h>
  29. #include <pcbnew.h>
  30. #include <pcb_edit_frame.h>
  31. #include <gr_basic.h>
  32. #include <msgpanel.h>
  33. #include <class_board.h>
  34. #include <class_module.h>
  35. #include <class_track.h>
  36. #include <class_drawsegment.h>
  37. #include <class_pad.h>
  38. #include <board_commit.h>
  39. #include <connectivity/connectivity_data.h>
  40. #include <widgets/progress_reporter.h>
  41. #include "ar_autoplacer.h"
  42. #include "ar_matrix.h"
  43. #include <memory>
  44. #include <ratsnest/ratsnest_data.h>
  45. #define AR_GAIN 16
  46. #define AR_KEEPOUT_MARGIN 500
  47. #define AR_ABORT_PLACEMENT -1
  48. #define STEP_AR_MM 1.0
  49. /* Bits characterizing cell */
  50. #define CELL_IS_EMPTY 0x00
  51. #define CELL_IS_HOLE 0x01 /* a conducting hole or obstacle */
  52. #define CELL_IS_MODULE 0x02 /* auto placement occupied by a module */
  53. #define CELL_IS_EDGE 0x20 /* Area and auto-placement: limiting cell contour (Board, Zone) */
  54. #define CELL_IS_FRIEND 0x40 /* Area and auto-placement: cell part of the net */
  55. #define CELL_IS_ZONE 0x80 /* Area and auto-placement: cell available */
  56. /* Penalty (cost) for CntRot90 and CntRot180:
  57. * CntRot90 and CntRot180 are from 0 (rotation allowed) to 10 (rotation not allowed)
  58. */
  59. static const double OrientationPenalty[11] =
  60. {
  61. 2.0, // CntRot = 0 rotation prohibited
  62. 1.9, // CntRot = 1
  63. 1.8, // CntRot = 2
  64. 1.7, // CntRot = 3
  65. 1.6, // CntRot = 4
  66. 1.5, // CntRot = 5
  67. 1.4, // CntRot = 5
  68. 1.3, // CntRot = 7
  69. 1.2, // CntRot = 8
  70. 1.1, // CntRot = 9
  71. 1.0 // CntRot = 10 rotation authorized, no penalty
  72. };
  73. AR_AUTOPLACER::AR_AUTOPLACER( BOARD* aBoard )
  74. {
  75. m_board = aBoard;
  76. m_connectivity = std::make_unique<CONNECTIVITY_DATA>( );
  77. for( auto mod : m_board->Modules() )
  78. m_connectivity->Add( mod );
  79. m_gridSize = Millimeter2iu( STEP_AR_MM );
  80. m_progressReporter = nullptr;
  81. m_refreshCallback = nullptr;
  82. m_minCost = 0.0;
  83. }
  84. void AR_AUTOPLACER::placeModule( MODULE* aModule, bool aDoNotRecreateRatsnest, const wxPoint& aPos )
  85. {
  86. if( !aModule )
  87. return;
  88. aModule->SetPosition( aPos );
  89. m_connectivity->Update( aModule );
  90. }
  91. int AR_AUTOPLACER::genPlacementRoutingMatrix()
  92. {
  93. m_matrix.UnInitRoutingMatrix();
  94. EDA_RECT bbox = m_board->GetBoardEdgesBoundingBox();
  95. if( bbox.GetWidth() == 0 || bbox.GetHeight() == 0 )
  96. return 0;
  97. // Build the board shape
  98. m_board->GetBoardPolygonOutlines( m_boardShape /*, aErrorText, aErrorLocation*/ );
  99. m_topFreeArea = m_boardShape;
  100. m_bottomFreeArea = m_boardShape;
  101. m_matrix.ComputeMatrixSize( bbox );
  102. int nbCells = m_matrix.m_Ncols * m_matrix.m_Nrows;
  103. // Choose the number of board sides.
  104. m_matrix.m_RoutingLayersCount = 2;
  105. m_matrix.InitRoutingMatrix();
  106. m_matrix.m_routeLayerBottom = B_Cu;
  107. m_matrix.m_routeLayerTop = F_Cu;
  108. // Fill (mark) the cells inside the board:
  109. fillMatrix();
  110. // Other obstacles can be added here:
  111. for( auto drawing : m_board->Drawings() )
  112. {
  113. switch( drawing->Type() )
  114. {
  115. case PCB_LINE_T:
  116. if( drawing->GetLayer() != Edge_Cuts )
  117. {
  118. m_matrix.TraceSegmentPcb( (DRAWSEGMENT*)drawing, CELL_IS_HOLE | CELL_IS_EDGE,
  119. m_matrix.m_GridRouting, AR_MATRIX::WRITE_CELL );
  120. }
  121. break;
  122. default:
  123. break;
  124. }
  125. }
  126. // Initialize top layer. to the same value as the bottom layer
  127. if( m_matrix.m_BoardSide[AR_SIDE_TOP] )
  128. memcpy( m_matrix.m_BoardSide[AR_SIDE_TOP], m_matrix.m_BoardSide[AR_SIDE_BOTTOM],
  129. nbCells * sizeof(AR_MATRIX::MATRIX_CELL) );
  130. return 1;
  131. }
  132. bool AR_AUTOPLACER::fillMatrix()
  133. {
  134. std::vector <int> x_coordinates;
  135. bool success = true;
  136. int step = m_matrix.m_GridRouting;
  137. wxPoint coord_orgin = m_matrix.GetBrdCoordOrigin(); // Board coordinate of matruix cell (0,0)
  138. // Create a single board outline:
  139. SHAPE_POLY_SET brd_shape = m_boardShape;
  140. brd_shape.Fracture( SHAPE_POLY_SET::PM_FAST );
  141. const SHAPE_LINE_CHAIN& outline = brd_shape.Outline(0);
  142. const BOX2I& rect = outline.BBox();
  143. // Creates the horizontal segments
  144. // Calculate the y limits of the area
  145. for( int refy = rect.GetY(), endy = rect.GetBottom(); refy < endy; refy += step )
  146. {
  147. // The row index (vertical position) of current line scan inside the placement matrix
  148. int idy = (refy - coord_orgin.y) / step;
  149. // Ensure we are still inside the placement matrix
  150. if( idy >= m_matrix.m_Nrows )
  151. break;
  152. // Ensure we are inside the placement matrix
  153. if( idy <= 0 )
  154. continue;
  155. // find all intersection points of an infinite line with polyline sides
  156. x_coordinates.clear();
  157. for( int v = 0; v < outline.PointCount(); v++ )
  158. {
  159. int seg_startX = outline.CPoint( v ).x;
  160. int seg_startY = outline.CPoint( v ).y;
  161. int seg_endX = outline.CPoint( v + 1 ).x;
  162. int seg_endY = outline.CPoint( v + 1 ).y;
  163. /* Trivial cases: skip if ref above or below the segment to test */
  164. if( ( seg_startY > refy ) && ( seg_endY > refy ) )
  165. continue;
  166. // segment below ref point, or its Y end pos on Y coordinate ref point: skip
  167. if( ( seg_startY <= refy ) && (seg_endY <= refy ) )
  168. continue;
  169. /* at this point refy is between seg_startY and seg_endY
  170. * see if an horizontal line at Y = refy is intersecting this segment
  171. */
  172. // calculate the x position of the intersection of this segment and the
  173. // infinite line this is more easier if we move the X,Y axis origin to
  174. // the segment start point:
  175. seg_endX -= seg_startX;
  176. seg_endY -= seg_startY;
  177. double newrefy = (double) ( refy - seg_startY );
  178. double intersec_x;
  179. if ( seg_endY == 0 ) // horizontal segment on the same line: skip
  180. continue;
  181. // Now calculate the x intersection coordinate of the horizontal line at
  182. // y = newrefy and the segment from (0,0) to (seg_endX,seg_endY) with the
  183. // horizontal line at the new refy position the line slope is:
  184. // slope = seg_endY/seg_endX; and inv_slope = seg_endX/seg_endY
  185. // and the x pos relative to the new origin is:
  186. // intersec_x = refy/slope = refy * inv_slope
  187. // Note: because horizontal segments are already tested and skipped, slope
  188. // exists (seg_end_y not O)
  189. double inv_slope = (double) seg_endX / seg_endY;
  190. intersec_x = newrefy * inv_slope;
  191. x_coordinates.push_back( (int) intersec_x + seg_startX );
  192. }
  193. // A line scan is finished: build list of segments
  194. // Sort intersection points by increasing x value:
  195. // So 2 consecutive points are the ends of a segment
  196. std::sort( x_coordinates.begin(), x_coordinates.end() );
  197. // An even number of coordinates is expected, because a segment has 2 ends.
  198. // An if this algorithm always works, it must always find an even count.
  199. if( ( x_coordinates.size() & 1 ) != 0 )
  200. {
  201. success = false;
  202. break;
  203. }
  204. // Fill cells having the same Y coordinate
  205. int iimax = x_coordinates.size() - 1;
  206. for( int ii = 0; ii < iimax; ii += 2 )
  207. {
  208. int seg_start_x = x_coordinates[ii] - coord_orgin.x;
  209. int seg_end_x = x_coordinates[ii + 1] - coord_orgin.x;
  210. // Fill cells at y coord = idy,
  211. // and at x cood >= seg_start_x and <= seg_end_x
  212. for( int idx = seg_start_x / step; idx < m_matrix.m_Ncols; idx++ )
  213. {
  214. if( idx * step > seg_end_x )
  215. break;
  216. if( idx * step >= seg_start_x )
  217. m_matrix.SetCell( idy, idx, AR_SIDE_BOTTOM, CELL_IS_ZONE );
  218. }
  219. }
  220. } // End examine segments in one area
  221. return success;
  222. }
  223. void AR_AUTOPLACER::rotateModule( MODULE* module, double angle, bool incremental )
  224. {
  225. if( module == NULL )
  226. return;
  227. if( incremental )
  228. module->SetOrientation( module->GetOrientation() + angle );
  229. else
  230. module->SetOrientation( angle );
  231. m_board->GetConnectivity()->Update( module );
  232. }
  233. void AR_AUTOPLACER::addFpBody( wxPoint aStart, wxPoint aEnd, LSET aLayerMask )
  234. {
  235. // Add a polygonal shape (rectangle) to m_fpAreaFront and/or m_fpAreaBack
  236. if( aLayerMask[ F_Cu ] )
  237. {
  238. m_fpAreaTop.NewOutline();
  239. m_fpAreaTop.Append( aStart.x, aStart.y );
  240. m_fpAreaTop.Append( aEnd.x, aStart.y );
  241. m_fpAreaTop.Append( aEnd.x, aEnd.y );
  242. m_fpAreaTop.Append( aStart.x, aEnd.y );
  243. }
  244. if( aLayerMask[ B_Cu ] )
  245. {
  246. m_fpAreaBottom.NewOutline();
  247. m_fpAreaBottom.Append( aStart.x, aStart.y );
  248. m_fpAreaBottom.Append( aEnd.x, aStart.y );
  249. m_fpAreaBottom.Append( aEnd.x, aEnd.y );
  250. m_fpAreaBottom.Append( aStart.x, aEnd.y );
  251. }
  252. }
  253. void AR_AUTOPLACER::addPad( D_PAD* aPad, int aClearance )
  254. {
  255. // Add a polygonal shape (rectangle) to m_fpAreaFront and/or m_fpAreaBack
  256. EDA_RECT bbox = aPad->GetBoundingBox();
  257. bbox.Inflate( aClearance );
  258. if( aPad->IsOnLayer( F_Cu ) )
  259. {
  260. m_fpAreaTop.NewOutline();
  261. m_fpAreaTop.Append( bbox.GetLeft(), bbox.GetTop() );
  262. m_fpAreaTop.Append( bbox.GetRight(), bbox.GetTop() );
  263. m_fpAreaTop.Append( bbox.GetRight(), bbox.GetBottom() );
  264. m_fpAreaTop.Append( bbox.GetLeft(), bbox.GetBottom() );
  265. }
  266. if( aPad->IsOnLayer( B_Cu ) )
  267. {
  268. m_fpAreaBottom.NewOutline();
  269. m_fpAreaBottom.Append( bbox.GetLeft(), bbox.GetTop() );
  270. m_fpAreaBottom.Append( bbox.GetRight(), bbox.GetTop() );
  271. m_fpAreaBottom.Append( bbox.GetRight(), bbox.GetBottom() );
  272. m_fpAreaBottom.Append( bbox.GetLeft(), bbox.GetBottom() );
  273. }
  274. }
  275. void AR_AUTOPLACER::buildFpAreas( MODULE* aFootprint, int aFpClearance )
  276. {
  277. m_fpAreaTop.RemoveAllContours();
  278. m_fpAreaBottom.RemoveAllContours();
  279. if( aFootprint->BuildPolyCourtyard() )
  280. {
  281. m_fpAreaTop = aFootprint->GetPolyCourtyardFront();
  282. m_fpAreaBottom = aFootprint->GetPolyCourtyardBack();
  283. }
  284. LSET layerMask;
  285. if( aFootprint->GetLayer() == F_Cu )
  286. layerMask.set( F_Cu );
  287. if( aFootprint->GetLayer() == B_Cu )
  288. layerMask.set( B_Cu );
  289. EDA_RECT fpBBox = aFootprint->GetBoundingBox();
  290. fpBBox.Inflate( ( m_matrix.m_GridRouting / 2 ) + aFpClearance );
  291. // Add a minimal area to the fp area:
  292. addFpBody( fpBBox.GetOrigin(), fpBBox.GetEnd(), layerMask );
  293. // Trace pads + clearance areas.
  294. for( D_PAD* pad : aFootprint->Pads() )
  295. {
  296. int margin = (m_matrix.m_GridRouting / 2) + pad->GetClearance( pad->GetLayer() );
  297. addPad( pad, margin );
  298. }
  299. }
  300. void AR_AUTOPLACER::genModuleOnRoutingMatrix( MODULE* Module )
  301. {
  302. int ox, oy, fx, fy;
  303. LSET layerMask;
  304. EDA_RECT fpBBox = Module->GetBoundingBox();
  305. fpBBox.Inflate( m_matrix.m_GridRouting / 2 );
  306. ox = fpBBox.GetX();
  307. fx = fpBBox.GetRight();
  308. oy = fpBBox.GetY();
  309. fy = fpBBox.GetBottom();
  310. if( ox < m_matrix.m_BrdBox.GetX() )
  311. ox = m_matrix.m_BrdBox.GetX();
  312. if( ox > m_matrix.m_BrdBox.GetRight() )
  313. ox = m_matrix.m_BrdBox.GetRight();
  314. if( fx < m_matrix.m_BrdBox.GetX() )
  315. fx = m_matrix.m_BrdBox.GetX();
  316. if( fx > m_matrix.m_BrdBox.GetRight() )
  317. fx = m_matrix.m_BrdBox.GetRight();
  318. if( oy < m_matrix.m_BrdBox.GetY() )
  319. oy = m_matrix.m_BrdBox.GetY();
  320. if( oy > m_matrix.m_BrdBox.GetBottom() )
  321. oy = m_matrix.m_BrdBox.GetBottom();
  322. if( fy < m_matrix.m_BrdBox.GetY() )
  323. fy = m_matrix.m_BrdBox.GetY();
  324. if( fy > m_matrix.m_BrdBox.GetBottom() )
  325. fy = m_matrix.m_BrdBox.GetBottom();
  326. if( Module->GetLayer() == F_Cu )
  327. layerMask.set( F_Cu );
  328. if( Module->GetLayer() == B_Cu )
  329. layerMask.set( B_Cu );
  330. m_matrix.TraceFilledRectangle( ox, oy, fx, fy, layerMask,
  331. CELL_IS_MODULE, AR_MATRIX::WRITE_OR_CELL );
  332. // Trace pads + clearance areas.
  333. for( D_PAD* pad : Module->Pads() )
  334. {
  335. int margin = (m_matrix.m_GridRouting / 2) + pad->GetClearance( pad->GetLayer() );
  336. m_matrix.PlacePad( pad, CELL_IS_MODULE, margin, AR_MATRIX::WRITE_OR_CELL );
  337. }
  338. // Trace clearance.
  339. int margin = ( m_matrix.m_GridRouting * Module->GetPadCount() ) / AR_GAIN;
  340. m_matrix.CreateKeepOutRectangle( ox, oy, fx, fy, margin, AR_KEEPOUT_MARGIN , layerMask );
  341. // Build the footprint courtyard
  342. buildFpAreas( Module, margin );
  343. // Substract the shape to free areas
  344. m_topFreeArea.BooleanSubtract( m_fpAreaTop, SHAPE_POLY_SET::PM_FAST );
  345. m_bottomFreeArea.BooleanSubtract( m_fpAreaBottom, SHAPE_POLY_SET::PM_FAST );
  346. }
  347. /* Test if the rectangular area (ux, ux .. y0, y1):
  348. * - is a free zone (except OCCUPED_By_MODULE returns)
  349. * - is on the working surface of the board (otherwise returns OUT_OF_BOARD)
  350. *
  351. * Returns OUT_OF_BOARD, or OCCUPED_By_MODULE or FREE_CELL if OK
  352. */
  353. int AR_AUTOPLACER::testRectangle( const EDA_RECT& aRect, int side )
  354. {
  355. EDA_RECT rect = aRect;
  356. rect.Inflate( m_matrix.m_GridRouting / 2 );
  357. wxPoint start = rect.GetOrigin();
  358. wxPoint end = rect.GetEnd();
  359. start -= m_matrix.m_BrdBox.GetOrigin();
  360. end -= m_matrix.m_BrdBox.GetOrigin();
  361. int row_min = start.y / m_matrix.m_GridRouting;
  362. int row_max = end.y / m_matrix.m_GridRouting;
  363. int col_min = start.x / m_matrix.m_GridRouting;
  364. int col_max = end.x / m_matrix.m_GridRouting;
  365. if( start.y > row_min * m_matrix.m_GridRouting )
  366. row_min++;
  367. if( start.x > col_min * m_matrix.m_GridRouting )
  368. col_min++;
  369. if( row_min < 0 )
  370. row_min = 0;
  371. if( row_max >= ( m_matrix.m_Nrows - 1 ) )
  372. row_max = m_matrix.m_Nrows - 1;
  373. if( col_min < 0 )
  374. col_min = 0;
  375. if( col_max >= ( m_matrix.m_Ncols - 1 ) )
  376. col_max = m_matrix.m_Ncols - 1;
  377. for( int row = row_min; row <= row_max; row++ )
  378. {
  379. for( int col = col_min; col <= col_max; col++ )
  380. {
  381. unsigned int data = m_matrix.GetCell( row, col, side );
  382. if( ( data & CELL_IS_ZONE ) == 0 )
  383. return AR_OUT_OF_BOARD;
  384. if( (data & CELL_IS_MODULE) )
  385. return AR_OCCUIPED_BY_MODULE;
  386. }
  387. }
  388. return AR_FREE_CELL;
  389. }
  390. /* Calculates and returns the clearance area of the rectangular surface
  391. * aRect):
  392. * (Sum of cells in terms of distance)
  393. */
  394. unsigned int AR_AUTOPLACER::calculateKeepOutArea( const EDA_RECT& aRect, int side )
  395. {
  396. wxPoint start = aRect.GetOrigin();
  397. wxPoint end = aRect.GetEnd();
  398. start -= m_matrix.m_BrdBox.GetOrigin();
  399. end -= m_matrix.m_BrdBox.GetOrigin();
  400. int row_min = start.y / m_matrix.m_GridRouting;
  401. int row_max = end.y / m_matrix.m_GridRouting;
  402. int col_min = start.x / m_matrix.m_GridRouting;
  403. int col_max = end.x / m_matrix.m_GridRouting;
  404. if( start.y > row_min * m_matrix.m_GridRouting )
  405. row_min++;
  406. if( start.x > col_min * m_matrix.m_GridRouting )
  407. col_min++;
  408. if( row_min < 0 )
  409. row_min = 0;
  410. if( row_max >= ( m_matrix.m_Nrows - 1 ) )
  411. row_max = m_matrix.m_Nrows - 1;
  412. if( col_min < 0 )
  413. col_min = 0;
  414. if( col_max >= ( m_matrix.m_Ncols - 1 ) )
  415. col_max = m_matrix.m_Ncols - 1;
  416. unsigned int keepOutCost = 0;
  417. for( int row = row_min; row <= row_max; row++ )
  418. {
  419. for( int col = col_min; col <= col_max; col++ )
  420. {
  421. // m_matrix.GetDist returns the "cost" of the cell
  422. // at position (row, col)
  423. // in autoplace this is the cost of the cell, if it is
  424. // inside aRect
  425. keepOutCost += m_matrix.GetDist( row, col, side );
  426. }
  427. }
  428. return keepOutCost;
  429. }
  430. /* Test if the module can be placed on the board.
  431. * Returns the value TstRectangle().
  432. * Module is known by its bounding box
  433. */
  434. int AR_AUTOPLACER::testModuleOnBoard( MODULE* aModule, bool TstOtherSide, const wxPoint& aOffset )
  435. {
  436. int side = AR_SIDE_TOP;
  437. int otherside = AR_SIDE_BOTTOM;
  438. if( aModule->GetLayer() == B_Cu )
  439. {
  440. side = AR_SIDE_BOTTOM; otherside = AR_SIDE_TOP;
  441. }
  442. EDA_RECT fpBBox = aModule->GetFootprintRect();
  443. fpBBox.Move( -aOffset );
  444. buildFpAreas( aModule, 0 );
  445. int diag = //testModuleByPolygon( aModule, side, aOffset );
  446. testRectangle( fpBBox, side );
  447. //printf("test %p diag %d\n", aModule, diag);fflush(0);
  448. if( diag != AR_FREE_CELL )
  449. return diag;
  450. if( TstOtherSide )
  451. {
  452. diag = //testModuleByPolygon( aModule, otherside, aOffset );
  453. testRectangle( fpBBox, otherside );
  454. if( diag != AR_FREE_CELL )
  455. return diag;
  456. }
  457. int marge = ( m_matrix.m_GridRouting * aModule->GetPadCount() ) / AR_GAIN;
  458. fpBBox.Inflate( marge );
  459. return calculateKeepOutArea( fpBBox, side );
  460. }
  461. int AR_AUTOPLACER::getOptimalModulePlacement(MODULE* aModule)
  462. {
  463. int error = 1;
  464. wxPoint LastPosOK;
  465. double min_cost, curr_cost, Score;
  466. bool TstOtherSide;
  467. aModule->CalculateBoundingBox();
  468. LastPosOK = m_matrix.m_BrdBox.GetOrigin();
  469. wxPoint mod_pos = aModule->GetPosition();
  470. EDA_RECT fpBBox = aModule->GetFootprintRect();
  471. // Move fpBBox to have the footprint position at (0,0)
  472. fpBBox.Move( -mod_pos );
  473. wxPoint fpBBoxOrg = fpBBox.GetOrigin();
  474. // Calculate the limit of the footprint position, relative
  475. // to the routing matrix area
  476. wxPoint xylimit = m_matrix.m_BrdBox.GetEnd() - fpBBox.GetEnd();
  477. wxPoint initialPos = m_matrix.m_BrdBox.GetOrigin() - fpBBoxOrg;
  478. // Stay on grid.
  479. initialPos.x -= initialPos.x % m_matrix.m_GridRouting;
  480. initialPos.y -= initialPos.y % m_matrix.m_GridRouting;
  481. m_curPosition = initialPos;
  482. auto moduleOffset = mod_pos - m_curPosition;
  483. /* Examine pads, and set TstOtherSide to true if a footprint
  484. * has at least 1 pad through.
  485. */
  486. TstOtherSide = false;
  487. if( m_matrix.m_RoutingLayersCount > 1 )
  488. {
  489. LSET other( aModule->GetLayer() == B_Cu ? F_Cu : B_Cu );
  490. for( auto pad : aModule->Pads() )
  491. {
  492. if( !( pad->GetLayerSet() & other ).any() )
  493. continue;
  494. TstOtherSide = true;
  495. break;
  496. }
  497. }
  498. fpBBox.SetOrigin( fpBBoxOrg + m_curPosition );
  499. min_cost = -1.0;
  500. // m_frame->SetStatusText( wxT( "Score ??, pos ??" ) );
  501. for( ; m_curPosition.x < xylimit.x; m_curPosition.x += m_matrix.m_GridRouting )
  502. {
  503. m_curPosition.y = initialPos.y;
  504. for( ; m_curPosition.y < xylimit.y; m_curPosition.y += m_matrix.m_GridRouting )
  505. {
  506. fpBBox.SetOrigin( fpBBoxOrg + m_curPosition );
  507. moduleOffset = mod_pos - m_curPosition;
  508. int keepOutCost = testModuleOnBoard( aModule, TstOtherSide, moduleOffset );
  509. if( keepOutCost >= 0 ) // i.e. if the module can be put here
  510. {
  511. error = 0;
  512. // m_frame->build_ratsnest_module( aModule ); // fixme
  513. curr_cost = computePlacementRatsnestCost( aModule, moduleOffset );
  514. Score = curr_cost + keepOutCost;
  515. if( (min_cost >= Score ) || (min_cost < 0 ) )
  516. {
  517. LastPosOK = m_curPosition;
  518. min_cost = Score;
  519. wxString msg;
  520. /* msg.Printf( wxT( "Score %g, pos %s, %s" ),
  521. min_cost,
  522. GetChars( ::CoordinateToString( LastPosOK.x ) ),
  523. GetChars( ::CoordinateToString( LastPosOK.y ) ) );
  524. m_frame->SetStatusText( msg );*/
  525. }
  526. }
  527. }
  528. }
  529. // Regeneration of the modified variable.
  530. m_curPosition = LastPosOK;
  531. m_minCost = min_cost;
  532. return error;
  533. }
  534. const D_PAD* AR_AUTOPLACER::nearestPad( MODULE *aRefModule, D_PAD* aRefPad, const wxPoint& aOffset)
  535. {
  536. const D_PAD* nearest = nullptr;
  537. int64_t nearestDist = INT64_MAX;
  538. for ( auto mod : m_board->Modules() )
  539. {
  540. if ( mod == aRefModule )
  541. continue;
  542. if( !m_matrix.m_BrdBox.Contains( mod->GetPosition() ) )
  543. continue;
  544. for ( auto pad: mod->Pads() )
  545. {
  546. if ( pad->GetNetCode() != aRefPad->GetNetCode() || pad->GetNetCode() <= 0 )
  547. continue;
  548. auto dist = (VECTOR2I( aRefPad->GetPosition() - aOffset ) - VECTOR2I( pad->GetPosition() ) ).EuclideanNorm();
  549. if ( dist < nearestDist )
  550. {
  551. nearestDist = dist;
  552. nearest = pad;
  553. }
  554. }
  555. }
  556. return nearest;
  557. }
  558. double AR_AUTOPLACER::computePlacementRatsnestCost( MODULE *aModule, const wxPoint& aOffset )
  559. {
  560. double curr_cost;
  561. VECTOR2I start; // start point of a ratsnest
  562. VECTOR2I end; // end point of a ratsnest
  563. int dx, dy;
  564. curr_cost = 0;
  565. for ( auto pad : aModule->Pads() )
  566. {
  567. auto nearest = nearestPad( aModule, pad, aOffset );
  568. if( !nearest )
  569. continue;
  570. //printf("pad %s nearest %s\n", (const char *)aModule->GetReference().c_str(), (const char *)nearest->GetParent()->GetReference().c_str());
  571. start = VECTOR2I( pad->GetPosition() ) - VECTOR2I(aOffset);
  572. end = VECTOR2I( nearest->GetPosition() );
  573. //m_overlay->SetIsStroke( true );
  574. //m_overlay->SetStrokeColor( COLOR4D(0.0, 1.0, 0.0, 1.0) );
  575. //m_overlay->Line( start, end );
  576. // Cost of the ratsnest.
  577. dx = end.x - start.x;
  578. dy = end.y - start.y;
  579. dx = abs( dx );
  580. dy = abs( dy );
  581. // ttry to have always dx >= dy to calculate the cost of the rastsnet
  582. if( dx < dy )
  583. std::swap( dx, dy );
  584. // Cost of the connection = length + penalty due to the slope
  585. // dx is the biggest length relative to the X or Y axis
  586. // the penalty is max for 45 degrees ratsnests,
  587. // and 0 for horizontal or vertical ratsnests.
  588. // For Horizontal and Vertical ratsnests, dy = 0;
  589. double conn_cost = hypot( dx, dy * 2.0 );
  590. curr_cost += conn_cost; // Total cost = sum of costs of each connection
  591. }
  592. return curr_cost;
  593. }
  594. // Sort routines
  595. static bool sortFootprintsByComplexity( MODULE* ref, MODULE* compare )
  596. {
  597. double ff1, ff2;
  598. ff1 = ref->GetArea() * ref->GetPadCount();
  599. ff2 = compare->GetArea() * compare->GetPadCount();
  600. return ff2 < ff1;
  601. }
  602. static bool sortFootprintsByRatsnestSize( MODULE* ref, MODULE* compare )
  603. {
  604. double ff1, ff2;
  605. ff1 = ref->GetArea() * ref->GetFlag();
  606. ff2 = compare->GetArea() * compare->GetFlag();
  607. return ff2 < ff1;
  608. }
  609. MODULE* AR_AUTOPLACER::pickModule( )
  610. {
  611. MODULE* module;
  612. std::vector <MODULE*> moduleList;
  613. for( auto m : m_board->Modules() )
  614. {
  615. m->CalculateBoundingBox();
  616. moduleList.push_back( m );
  617. }
  618. sort( moduleList.begin(), moduleList.end(), sortFootprintsByComplexity );
  619. for( unsigned kk = 0; kk < moduleList.size(); kk++ )
  620. {
  621. module = moduleList[kk];
  622. module->SetFlag( 0 );
  623. if( !module->NeedsPlaced() )
  624. continue;
  625. m_connectivity->Update( module );
  626. }
  627. m_connectivity->RecalculateRatsnest();
  628. for( unsigned kk = 0; kk < moduleList.size(); kk++ )
  629. {
  630. module = moduleList[kk];
  631. auto edges = m_connectivity->GetRatsnestForComponent( module, true );
  632. module->SetFlag( edges.size() ) ;
  633. }
  634. sort( moduleList.begin(), moduleList.end(), sortFootprintsByRatsnestSize );
  635. // Search for "best" module.
  636. MODULE* bestModule = nullptr;
  637. MODULE* altModule = nullptr;
  638. for( unsigned ii = 0; ii < moduleList.size(); ii++ )
  639. {
  640. module = moduleList[ii];
  641. if( !module->NeedsPlaced() )
  642. continue;
  643. altModule = module;
  644. if( module->GetFlag() == 0 )
  645. continue;
  646. bestModule = module;
  647. break;
  648. }
  649. if( bestModule )
  650. return bestModule;
  651. else
  652. return altModule;
  653. }
  654. void AR_AUTOPLACER::drawPlacementRoutingMatrix( )
  655. {
  656. // Draw the board free area
  657. m_overlay->Clear();
  658. m_overlay->SetIsFill( true );
  659. m_overlay->SetIsStroke( false );
  660. SHAPE_POLY_SET freeArea = m_topFreeArea;
  661. freeArea.Fracture( SHAPE_POLY_SET::PM_FAST );
  662. // Draw the free polygon areas, top side:
  663. if( freeArea.OutlineCount() > 0 )
  664. {
  665. m_overlay->SetIsFill( true );
  666. m_overlay->SetIsStroke( false );
  667. m_overlay->SetFillColor( COLOR4D(0.7, 0.0, 0.1, 0.2) );
  668. m_overlay->Polygon( freeArea );
  669. }
  670. freeArea = m_bottomFreeArea;
  671. freeArea.Fracture( SHAPE_POLY_SET::PM_FAST );
  672. // Draw the free polygon areas, bottom side:
  673. if( freeArea.OutlineCount() > 0 )
  674. {
  675. m_overlay->SetFillColor( COLOR4D(0.0, 0.7, 0.0, 0.2) );
  676. m_overlay->Polygon( freeArea );
  677. }
  678. }
  679. AR_RESULT AR_AUTOPLACER::AutoplaceModules( std::vector<MODULE*> aModules,
  680. BOARD_COMMIT* aCommit, bool aPlaceOffboardModules )
  681. {
  682. wxPoint PosOK;
  683. wxPoint memopos;
  684. int error;
  685. MODULE* module = nullptr;
  686. bool cancelled = false;
  687. memopos = m_curPosition;
  688. //printf("set grid: %d\n", m_gridSize);
  689. m_matrix.m_GridRouting = m_gridSize; //(int) m_frame->GetScreen()->GetGridSize().x;
  690. // Ensure Board.m_GridRouting has a reasonable value:
  691. if( m_matrix.m_GridRouting < Millimeter2iu( 0.25 ) )
  692. m_matrix.m_GridRouting = Millimeter2iu( 0.25 );
  693. // Compute module parameters used in auto place
  694. if( genPlacementRoutingMatrix( ) == 0 )
  695. return AR_FAILURE;
  696. int moduleCount = 0;
  697. for ( auto m : m_board->Modules() )
  698. {
  699. m->SetNeedsPlaced( false );
  700. }
  701. std::vector<MODULE *> offboardMods;
  702. if( aPlaceOffboardModules )
  703. {
  704. for ( auto m : m_board->Modules() )
  705. {
  706. if( !m_matrix.m_BrdBox.Contains( m->GetPosition() ) )
  707. {
  708. offboardMods.push_back( m );
  709. }
  710. }
  711. }
  712. for ( auto m : aModules )
  713. {
  714. m->SetNeedsPlaced( true );
  715. aCommit->Modify(m);
  716. }
  717. for ( auto m : offboardMods )
  718. {
  719. m->SetNeedsPlaced( true );
  720. aCommit->Modify(m);
  721. }
  722. for ( auto m : m_board->Modules() )
  723. {
  724. if( m->NeedsPlaced() ) // Erase from screen
  725. moduleCount++;
  726. else
  727. genModuleOnRoutingMatrix( m );
  728. }
  729. int cnt = 0;
  730. wxString msg;
  731. if( m_progressReporter )
  732. {
  733. m_progressReporter->Report( _( "Autoplacing components..." ) );
  734. m_progressReporter->SetMaxProgress( moduleCount );
  735. }
  736. drawPlacementRoutingMatrix();
  737. if( m_refreshCallback )
  738. m_refreshCallback( nullptr );
  739. while( ( module = pickModule( ) ) != nullptr )
  740. {
  741. // Display some info about activity, module placement can take a while:
  742. //m_frame->SetStatusText( msg );
  743. if( m_progressReporter )
  744. m_progressReporter->SetTitle( wxString::Format(
  745. _( "Autoplacing %s" ), module->GetReference() ) );
  746. double initialOrient = module->GetOrientation();
  747. error = getOptimalModulePlacement( module );
  748. double bestScore = m_minCost;
  749. double bestRotation = 0.0;
  750. int rotAllowed;
  751. PosOK = m_curPosition;
  752. if( error == AR_ABORT_PLACEMENT )
  753. goto end_of_tst;
  754. // Try orientations 90, 180, 270 degrees from initial orientation
  755. rotAllowed = module->GetPlacementCost180();
  756. //printf("rotAllowed %d\n", rotAllowed);
  757. if( rotAllowed != 0 )
  758. {
  759. rotateModule( module, 1800.0, true );
  760. error = getOptimalModulePlacement( module );
  761. m_minCost *= OrientationPenalty[rotAllowed];
  762. if( bestScore > m_minCost ) // This orientation is better.
  763. {
  764. PosOK = m_curPosition;
  765. bestScore = m_minCost;
  766. bestRotation = 1800.0;
  767. }
  768. else
  769. {
  770. rotateModule( module, initialOrient, false );
  771. }
  772. if( error == AR_ABORT_PLACEMENT )
  773. goto end_of_tst;
  774. }
  775. // Determine if the best orientation of a module is 90.
  776. rotAllowed = module->GetPlacementCost90();
  777. if( rotAllowed != 0 )
  778. {
  779. rotateModule( module, 900.0, true );
  780. error = getOptimalModulePlacement( module );
  781. m_minCost *= OrientationPenalty[rotAllowed];
  782. if( bestScore > m_minCost ) // This orientation is better.
  783. {
  784. PosOK = m_curPosition;
  785. bestScore = m_minCost;
  786. bestRotation = 900.0;
  787. }
  788. else
  789. {
  790. rotateModule( module, initialOrient, false );
  791. }
  792. if( error == AR_ABORT_PLACEMENT )
  793. goto end_of_tst;
  794. }
  795. // Determine if the best orientation of a module is -90.
  796. if( rotAllowed != 0 )
  797. {
  798. rotateModule( module, 2700.0, true );
  799. error = getOptimalModulePlacement( module );
  800. m_minCost *= OrientationPenalty[rotAllowed];
  801. if( bestScore > m_minCost ) // This orientation is better.
  802. {
  803. PosOK = m_curPosition;
  804. bestScore = m_minCost;
  805. bestRotation = 2700.0;
  806. }
  807. else
  808. {
  809. rotateModule( module, initialOrient, false );
  810. }
  811. if( error == AR_ABORT_PLACEMENT )
  812. goto end_of_tst;
  813. }
  814. end_of_tst:
  815. if( error == AR_ABORT_PLACEMENT )
  816. break;
  817. bestRotation += initialOrient;
  818. if( bestRotation != module->GetOrientation() )
  819. {
  820. //printf("best rotation %d\n", bestRotation );
  821. rotateModule( module, bestRotation, false );
  822. }
  823. // Place module.
  824. placeModule( module, true, m_curPosition );
  825. module->CalculateBoundingBox();
  826. genModuleOnRoutingMatrix( module );
  827. module->SetIsPlaced( true );
  828. module->SetNeedsPlaced( false );
  829. drawPlacementRoutingMatrix();
  830. if( m_refreshCallback )
  831. m_refreshCallback( module );
  832. if( m_progressReporter )
  833. {
  834. m_progressReporter->AdvanceProgress();
  835. if ( !m_progressReporter->KeepRefreshing( false ) )
  836. {
  837. cancelled = true;
  838. break;
  839. }
  840. }
  841. cnt++;
  842. }
  843. m_curPosition = memopos;
  844. m_matrix.UnInitRoutingMatrix();
  845. for ( auto m : m_board->Modules() )
  846. {
  847. m->CalculateBoundingBox();
  848. }
  849. return cancelled ? AR_CANCELLED : AR_COMPLETED;
  850. }