KiCad PCB EDA Suite
Loading...
Searching...
No Matches
ar_autoplacer.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) 2012 Jean-Pierre Charras, [email protected]
5 * Copyright (C) 2012 SoftPLC Corporation, Dick Hollenbeck <[email protected]>
6 * Copyright (C) 2011 Wayne Stambaugh <[email protected]>
7 *
8 * Copyright The KiCad Developers, see AUTHORS.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, see <https://www.gnu.org/licenses/>.
22 */
23
24#include <confirm.h>
25#include <pcb_edit_frame.h>
26#include <widgets/msgpanel.h>
27#include <board.h>
28#include <footprint.h>
29#include <lset.h>
30#include <pcb_shape.h>
31#include <pad.h>
32#include <board_commit.h>
34#include <progress_reporter.h>
35
36#include "ar_autoplacer.h"
37#include "ar_matrix.h"
38#include <memory>
40
41#define AR_GAIN 16
42#define AR_KEEPOUT_MARGIN 500
43#define AR_ABORT_PLACEMENT -1
44
45#define STEP_AR_MM 1.0
46
47/* Bits characterizing cell */
48#define CELL_IS_EMPTY 0x00
49#define CELL_IS_HOLE 0x01 /* a conducting hole or obstacle */
50#define CELL_IS_MODULE 0x02 /* auto placement occupied by a footprint */
51#define CELL_IS_EDGE 0x20 /* Area and auto-placement: limiting cell contour (Board, Zone) */
52#define CELL_IS_FRIEND 0x40 /* Area and auto-placement: cell part of the net */
53#define CELL_IS_ZONE 0x80 /* Area and auto-placement: cell available */
54
55
57{
58 m_board = aBoard;
59 m_connectivity = std::make_unique<CONNECTIVITY_DATA>( );
60
61 for( FOOTPRINT* footprint : m_board->Footprints() )
62 m_connectivity->Add( footprint );
63
65 m_progressReporter = nullptr;
66 m_refreshCallback = nullptr;
67 m_minCost = 0.0;
68}
69
70
71void AR_AUTOPLACER::placeFootprint( FOOTPRINT* aFootprint, bool aDoNotRecreateRatsnest, const VECTOR2I& aPos )
72{
73 if( !aFootprint )
74 return;
75
76 aFootprint->SetPosition( aPos );
77 m_connectivity->Update( aFootprint );
78}
79
80
82{
83 m_matrix.UnInitRoutingMatrix();
84
85 BOX2I bbox = m_board->GetBoardEdgesBoundingBox();
86
87 if( bbox.GetWidth() == 0 || bbox.GetHeight() == 0 )
88 return 0;
89
90 // Build the board shape
91 m_board->GetBoardPolygonOutlines( m_boardShape, true );
94
95 m_matrix.ComputeMatrixSize( bbox );
96 int nbCells = m_matrix.m_Ncols * m_matrix.m_Nrows;
97
98 // Choose the number of board sides.
99 m_matrix.m_RoutingLayersCount = 2;
100 m_matrix.InitRoutingMatrix();
101
102 // Fill (mark) the cells inside the board:
103 fillMatrix();
104
105 // Other obstacles can be added here:
106 for( auto drawing : m_board->Drawings() )
107 {
108 switch( drawing->Type() )
109 {
110 case PCB_SHAPE_T:
111 if( drawing->GetLayer() != Edge_Cuts )
112 {
113 m_matrix.TracePcbShape( (PCB_SHAPE*) drawing, CELL_IS_HOLE | CELL_IS_EDGE, m_matrix.m_GridRouting,
115 }
116
117 break;
118
119 default:
120 break;
121 }
122 }
123
124 // Initialize top layer. to the same value as the bottom layer
125 if( m_matrix.m_BoardSide[AR_SIDE_TOP] )
126 {
127 memcpy( m_matrix.m_BoardSide[AR_SIDE_TOP], m_matrix.m_BoardSide[AR_SIDE_BOTTOM],
128 nbCells * sizeof(AR_MATRIX::MATRIX_CELL) );
129 }
130
131 return 1;
132}
133
134
136{
137 std::vector<int> x_coordinates;
138 bool success = true;
139 int step = m_matrix.m_GridRouting;
140 VECTOR2I coord_orgin = m_matrix.GetBrdCoordOrigin(); // Board coordinate of matruix cell (0,0)
141
142 // Create a single board outline:
143 SHAPE_POLY_SET brd_shape = m_boardShape.CloneDropTriangulation();
144 brd_shape.Fracture();
145 const SHAPE_LINE_CHAIN& outline = brd_shape.Outline(0);
146 const BOX2I& rect = outline.BBox();
147
148 // Creates the horizontal segments
149 // Calculate the y limits of the area
150 for( int refy = rect.GetY(), endy = rect.GetBottom(); refy < endy; refy += step )
151 {
152 // The row index (vertical position) of current line scan inside the placement matrix
153 int idy = (refy - coord_orgin.y) / step;
154
155 // Ensure we are still inside the placement matrix
156 if( idy >= m_matrix.m_Nrows )
157 break;
158
159 // Ensure we are inside the placement matrix
160 if( idy <= 0 )
161 continue;
162
163 // find all intersection points of an infinite line with polyline sides
164 x_coordinates.clear();
165
166 for( int v = 0; v < outline.PointCount(); v++ )
167 {
168 int seg_startX = outline.CPoint( v ).x;
169 int seg_startY = outline.CPoint( v ).y;
170 int seg_endX = outline.CPoint( v + 1 ).x;
171 int seg_endY = outline.CPoint( v + 1 ).y;
172
173 /* Trivial cases: skip if ref above or below the segment to test */
174 if( ( seg_startY > refy ) && ( seg_endY > refy ) )
175 continue;
176
177 // segment below ref point, or its Y end pos on Y coordinate ref point: skip
178 if( ( seg_startY <= refy ) && (seg_endY <= refy ) )
179 continue;
180
181 /* at this point refy is between seg_startY and seg_endY
182 * see if an horizontal line at Y = refy is intersecting this segment
183 */
184 // calculate the x position of the intersection of this segment and the
185 // infinite line this is more easier if we move the X,Y axis origin to
186 // the segment start point:
187
188 seg_endX -= seg_startX;
189 seg_endY -= seg_startY;
190 double newrefy = refy - seg_startY;
191 double intersec_x;
192
193 if ( seg_endY == 0 ) // horizontal segment on the same line: skip
194 continue;
195
196 // Now calculate the x intersection coordinate of the horizontal line at
197 // y = newrefy and the segment from (0,0) to (seg_endX,seg_endY) with the
198 // horizontal line at the new refy position the line slope is:
199 // slope = seg_endY/seg_endX; and inv_slope = seg_endX/seg_endY
200 // and the x pos relative to the new origin is:
201 // intersec_x = refy/slope = refy * inv_slope
202 // Note: because horizontal segments are already tested and skipped, slope
203 // exists (seg_end_y not O)
204 double inv_slope = (double) seg_endX / seg_endY;
205 intersec_x = newrefy * inv_slope;
206 x_coordinates.push_back( (int) intersec_x + seg_startX );
207 }
208
209 // A line scan is finished: build list of segments
210
211 // Sort intersection points by increasing x value:
212 // So 2 consecutive points are the ends of a segment
213 std::sort( x_coordinates.begin(), x_coordinates.end() );
214
215 // An even number of coordinates is expected, because a segment has 2 ends.
216 // An if this algorithm always works, it must always find an even count.
217 if( ( x_coordinates.size() & 1 ) != 0 )
218 {
219 success = false;
220 break;
221 }
222
223 // Fill cells having the same Y coordinate
224 int iimax = x_coordinates.size() - 1;
225
226 for( int ii = 0; ii < iimax; ii += 2 )
227 {
228 int seg_start_x = x_coordinates[ii] - coord_orgin.x;
229 int seg_end_x = x_coordinates[ii + 1] - coord_orgin.x;
230
231 // Fill cells at y coord = idy,
232 // and at x cood >= seg_start_x and <= seg_end_x
233
234 for( int idx = seg_start_x / step; idx < m_matrix.m_Ncols; idx++ )
235 {
236 if( idx * step > seg_end_x )
237 break;
238
239 if( idx * step >= seg_start_x )
240 m_matrix.SetCell( idy, idx, AR_SIDE_BOTTOM, CELL_IS_ZONE );
241 }
242 }
243 } // End examine segments in one area
244
245 return success;
246}
247
248
249void AR_AUTOPLACER::addFpBody( const VECTOR2I& aStart, const VECTOR2I& aEnd, const LSET& aLayerMask )
250{
251 // Add a polygonal shape (rectangle) to m_fpAreaFront and/or m_fpAreaBack
252 if( aLayerMask[ F_Cu ] )
253 {
254 m_fpAreaTop.NewOutline();
255 m_fpAreaTop.Append( aStart.x, aStart.y );
256 m_fpAreaTop.Append( aEnd.x, aStart.y );
257 m_fpAreaTop.Append( aEnd.x, aEnd.y );
258 m_fpAreaTop.Append( aStart.x, aEnd.y );
259 }
260
261 if( aLayerMask[ B_Cu ] )
262 {
263 m_fpAreaBottom.NewOutline();
264 m_fpAreaBottom.Append( aStart.x, aStart.y );
265 m_fpAreaBottom.Append( aEnd.x, aStart.y );
266 m_fpAreaBottom.Append( aEnd.x, aEnd.y );
267 m_fpAreaBottom.Append( aStart.x, aEnd.y );
268 }
269}
270
271
272void AR_AUTOPLACER::addPad( PAD* aPad, int aClearance )
273{
274 // Add a polygonal shape (rectangle) to m_fpAreaFront and/or m_fpAreaBack
275 BOX2I bbox = aPad->GetBoundingBox();
276 bbox.Inflate( aClearance );
277
278 if( aPad->IsOnLayer( F_Cu ) )
279 {
280 m_fpAreaTop.NewOutline();
281 m_fpAreaTop.Append( bbox.GetLeft(), bbox.GetTop() );
282 m_fpAreaTop.Append( bbox.GetRight(), bbox.GetTop() );
283 m_fpAreaTop.Append( bbox.GetRight(), bbox.GetBottom() );
284 m_fpAreaTop.Append( bbox.GetLeft(), bbox.GetBottom() );
285 }
286
287 if( aPad->IsOnLayer( B_Cu ) )
288 {
289 m_fpAreaBottom.NewOutline();
290 m_fpAreaBottom.Append( bbox.GetLeft(), bbox.GetTop() );
291 m_fpAreaBottom.Append( bbox.GetRight(), bbox.GetTop() );
292 m_fpAreaBottom.Append( bbox.GetRight(), bbox.GetBottom() );
293 m_fpAreaBottom.Append( bbox.GetLeft(), bbox.GetBottom() );
294 }
295}
296
297
298void AR_AUTOPLACER::buildFpAreas( FOOTPRINT* aFootprint, int aFpClearance )
299{
300 m_fpAreaTop.RemoveAllContours();
301 m_fpAreaBottom.RemoveAllContours();
302
303 aFootprint->BuildCourtyardCaches();
304 m_fpAreaTop = aFootprint->GetCourtyard( F_CrtYd );
305 m_fpAreaBottom = aFootprint->GetCourtyard( B_CrtYd );
306
307 LSET layerMask;
308
309 if( aFootprint->GetLayer() == F_Cu )
310 layerMask.set( F_Cu );
311
312 if( aFootprint->GetLayer() == B_Cu )
313 layerMask.set( B_Cu );
314
315 BOX2I fpBBox = aFootprint->GetBoundingBox( false );
316
317 fpBBox.Inflate( ( m_matrix.m_GridRouting / 2 ) + aFpClearance );
318
319 // Add a minimal area to the fp area:
320 addFpBody( fpBBox.GetOrigin(), fpBBox.GetEnd(), layerMask );
321
322 // Trace pads + clearance areas.
323 for( PAD* pad : aFootprint->Pads() )
324 {
325 int margin = (m_matrix.m_GridRouting / 2) + pad->GetOwnClearance( pad->GetLayer() );
326 addPad( pad, margin );
327 }
328}
329
330
332{
333 BOX2I fpBBox = aFootprint->GetBoundingBox( false );
334 fpBBox.Inflate( m_matrix.m_GridRouting / 2 );
335
336 int ox = fpBBox.GetX();
337 int fx = fpBBox.GetRight();
338 int oy = fpBBox.GetY();
339 int fy = fpBBox.GetBottom();
340
341 ox = std::max( m_matrix.m_BrdBox.GetX(), std::min( ox, m_matrix.m_BrdBox.GetRight() ) );
342 fx = std::max( m_matrix.m_BrdBox.GetX(), std::min( fx, m_matrix.m_BrdBox.GetRight() ) );
343 oy = std::max( m_matrix.m_BrdBox.GetY(), std::min( oy, m_matrix.m_BrdBox.GetBottom() ) );
344 fy = std::max( m_matrix.m_BrdBox.GetY(), std::min( fy, m_matrix.m_BrdBox.GetBottom() ) );
345
346 LSET layerMask;
347
348 if( aFootprint->GetLayer() == F_Cu )
349 layerMask.set( F_Cu );
350
351 if( aFootprint->GetLayer() == B_Cu )
352 layerMask.set( B_Cu );
353
354 m_matrix.TraceFilledRectangle( ox, oy, fx, fy, layerMask, CELL_IS_MODULE, AR_MATRIX::WRITE_OR_CELL );
355
356 // Trace pads + clearance areas.
357 for( PAD* pad : aFootprint->Pads() )
358 {
359 int margin = (m_matrix.m_GridRouting / 2) + pad->GetOwnClearance( pad->GetLayer() );
361 }
362
363 // Trace clearance.
364 int margin = KiROUND( ( m_matrix.m_GridRouting * aFootprint->GetPadCount() ) / AR_GAIN );
365 m_matrix.CreateKeepOutRectangle( ox, oy, fx, fy, margin, AR_KEEPOUT_MARGIN , layerMask );
366
367 // Build the footprint courtyard
368 buildFpAreas( aFootprint, margin );
369
370 // Substract the shape to free areas
371 m_topFreeArea.BooleanSubtract( m_fpAreaTop );
372 m_bottomFreeArea.BooleanSubtract( m_fpAreaBottom );
373}
374
375
376int AR_AUTOPLACER::testRectangle( const BOX2I& aRect, int side )
377{
378 BOX2I rect = aRect;
379 rect.Inflate( m_matrix.m_GridRouting / 2 );
380
381 VECTOR2I start = rect.GetOrigin() - m_matrix.m_BrdBox.GetOrigin();
382 VECTOR2I end = rect.GetEnd() - m_matrix.m_BrdBox.GetOrigin();
383
384 int row_min = start.y / m_matrix.m_GridRouting;
385 int row_max = end.y / m_matrix.m_GridRouting;
386 int col_min = start.x / m_matrix.m_GridRouting;
387 int col_max = end.x / m_matrix.m_GridRouting;
388
389 if( start.y > row_min * m_matrix.m_GridRouting )
390 row_min++;
391
392 if( start.x > col_min * m_matrix.m_GridRouting )
393 col_min++;
394
395 row_min = std::max( 0, row_min );
396 row_max = std::min( row_max, m_matrix.m_Nrows - 1 );
397 col_min = std::max( 0, col_min );
398 col_max = std::min( col_max, m_matrix.m_Ncols - 1 );
399
400 for( int row = row_min; row <= row_max; row++ )
401 {
402 for( int col = col_min; col <= col_max; col++ )
403 {
404 unsigned int data = m_matrix.GetCell( row, col, side );
405
406 if( ( data & CELL_IS_ZONE ) == 0 )
407 return AR_OUT_OF_BOARD;
408
409 if( (data & CELL_IS_MODULE) )
411 }
412 }
413
414 return AR_FREE_CELL;
415}
416
417
418unsigned int AR_AUTOPLACER::calculateKeepOutArea( const BOX2I& aRect, int side )
419{
420 VECTOR2I start = aRect.GetOrigin() - m_matrix.m_BrdBox.GetOrigin();
421 VECTOR2I end = aRect.GetEnd() - m_matrix.m_BrdBox.GetOrigin();
422
423 int row_min = start.y / m_matrix.m_GridRouting;
424 int row_max = end.y / m_matrix.m_GridRouting;
425 int col_min = start.x / m_matrix.m_GridRouting;
426 int col_max = end.x / m_matrix.m_GridRouting;
427
428 if( start.y > row_min * m_matrix.m_GridRouting )
429 row_min++;
430
431 if( start.x > col_min * m_matrix.m_GridRouting )
432 col_min++;
433
434 row_min = std::max( 0, row_min );
435 row_max = std::min( row_max, m_matrix.m_Nrows - 1 );
436 col_min = std::max( 0, col_min );
437 col_max = std::min( col_max, m_matrix.m_Ncols - 1 );
438
439 unsigned int keepOutCost = 0;
440
441 for( int row = row_min; row <= row_max; row++ )
442 {
443 for( int col = col_min; col <= col_max; col++ )
444 {
445 // m_matrix.GetDist returns the "cost" of the cell
446 // at position (row, col)
447 // in autoplace this is the cost of the cell, if it is
448 // inside aRect
449 keepOutCost += m_matrix.GetDist( row, col, side );
450 }
451 }
452
453 return keepOutCost;
454}
455
456
457int AR_AUTOPLACER::testFootprintOnBoard( FOOTPRINT* aFootprint, bool TstOtherSide, const VECTOR2I& aOffset )
458{
459 int side = AR_SIDE_TOP;
460 int otherside = AR_SIDE_BOTTOM;
461
462 if( aFootprint->GetLayer() == B_Cu )
463 {
464 side = AR_SIDE_BOTTOM;
465 otherside = AR_SIDE_TOP;
466 }
467
468 BOX2I fpBBox = aFootprint->GetBoundingBox( false );
469 fpBBox.Move( -1*aOffset );
470
471 int diag = testRectangle( fpBBox, side );
472
473 if( diag != AR_FREE_CELL )
474 return diag;
475
476 if( TstOtherSide )
477 {
478 diag = testRectangle( fpBBox, otherside );
479
480 if( diag != AR_FREE_CELL )
481 return diag;
482 }
483
484 int marge = KiROUND( ( m_matrix.m_GridRouting * aFootprint->GetPadCount() ) / AR_GAIN );
485
486 fpBBox.Inflate( marge );
487 return calculateKeepOutArea( fpBBox, side );
488}
489
490
492{
493 int error = 1;
494 double min_cost, curr_cost, Score;
495 bool testOtherSide;
496
497 VECTOR2I lastPosOK = m_matrix.m_BrdBox.GetOrigin();
498
499 VECTOR2I fpPos = aFootprint->GetPosition();
500 BOX2I fpBBox = aFootprint->GetBoundingBox( false );
501
502 // Move fpBBox to have the footprint position at (0,0)
503 fpBBox.Move( -fpPos );
504 VECTOR2I fpBBoxOrg = fpBBox.GetOrigin();
505
506 // Calculate the limit of the footprint position, relative to the routing matrix area
507 VECTOR2I xylimit = m_matrix.m_BrdBox.GetEnd() - fpBBox.GetEnd();
508
509 VECTOR2I initialPos = m_matrix.m_BrdBox.GetOrigin() - fpBBoxOrg;
510
511 // Stay on grid.
512 initialPos.x -= initialPos.x % m_matrix.m_GridRouting;
513 initialPos.y -= initialPos.y % m_matrix.m_GridRouting;
514
515 m_curPosition = initialPos;
516 VECTOR2I fpOffset = fpPos - m_curPosition;
517
518 // Examine pads, and set testOtherSide to true if a footprint has at least 1 pad through.
519 testOtherSide = false;
520
521 if( m_matrix.m_RoutingLayersCount > 1 )
522 {
523 LSET other( { aFootprint->GetLayer() == B_Cu ? F_Cu : B_Cu } );
524
525 for( PAD* pad : aFootprint->Pads() )
526 {
527 if( !( pad->GetLayerSet() & other ).any() )
528 continue;
529
530 testOtherSide = true;
531 break;
532 }
533 }
534
535 fpBBox.SetOrigin( fpBBoxOrg + m_curPosition );
536
537 min_cost = -1.0;
538// m_frame->SetStatusText( wxT( "Score ??, pos ??" ) );
539
540
541 for( ; m_curPosition.x < xylimit.x; m_curPosition.x += m_matrix.m_GridRouting )
542 {
543 m_curPosition.y = initialPos.y;
544
545 for( ; m_curPosition.y < xylimit.y; m_curPosition.y += m_matrix.m_GridRouting )
546 {
547
548 fpBBox.SetOrigin( fpBBoxOrg + m_curPosition );
549 fpOffset = fpPos - m_curPosition;
550 int keepOutCost = testFootprintOnBoard( aFootprint, testOtherSide, fpOffset );
551
552 if( keepOutCost >= 0 ) // i.e. if the footprint can be put here
553 {
554 error = 0;
555 // m_frame->build_ratsnest_footprint( aFootprint ); // fixme
556 curr_cost = computePlacementRatsnestCost( aFootprint, fpOffset );
557 Score = curr_cost + keepOutCost;
558
559 if( (min_cost >= Score ) || (min_cost < 0 ) )
560 {
561 lastPosOK = m_curPosition;
562 min_cost = Score;
563 }
564 }
565 }
566 }
567
568 // Regeneration of the modified variable.
569 m_curPosition = lastPosOK;
570
571 m_minCost = min_cost;
572 return error;
573}
574
575
576const PAD* AR_AUTOPLACER::nearestPad( FOOTPRINT* aRefFP, PAD* aRefPad, const VECTOR2I& aOffset )
577{
578 const PAD* nearest = nullptr;
579 int64_t nearestDist = INT64_MAX;
580
581 for( FOOTPRINT* footprint : m_board->Footprints() )
582 {
583 if ( footprint == aRefFP )
584 continue;
585
586 if( !m_matrix.m_BrdBox.Contains( footprint->GetPosition() ) )
587 continue;
588
589 for( PAD* pad: footprint->Pads() )
590 {
591 if( pad->GetNetCode() != aRefPad->GetNetCode() || pad->GetNetCode() <= 0 )
592 continue;
593
594 auto dist = ( VECTOR2I( aRefPad->GetPosition() - aOffset ) -
595 VECTOR2I( pad->GetPosition() ) ).EuclideanNorm();
596
597 if ( dist < nearestDist )
598 {
599 nearestDist = dist;
600 nearest = pad;
601 }
602 }
603 }
604
605 return nearest;
606}
607
608
610{
611 double curr_cost = 0;
612
613 for( PAD* pad : aFootprint->Pads() )
614 {
615 const PAD* nearest = nearestPad( aFootprint, pad, aOffset );
616
617 if( !nearest )
618 continue;
619
620 VECTOR2I start = VECTOR2I( pad->GetPosition() ) - VECTOR2I(aOffset);
621 VECTOR2I end = VECTOR2I( nearest->GetPosition() );
622
623 //m_overlay->SetIsStroke( true );
624 //m_overlay->SetStrokeColor( COLOR4D(0.0, 1.0, 0.0, 1.0) );
625 //m_overlay->Line( start, end );
626
627 // Cost of the ratsnest.
628 int dx = abs( end.x - start.x );
629 int dy = abs( end.y - start.y );
630
631 // try to have always dx >= dy to calculate the cost of the ratsnest
632 if( dx < dy )
633 std::swap( dx, dy );
634
635 // Cost of the connection = length + penalty due to the slope
636 // dx is the biggest length relative to the X or Y axis
637 // the penalty is max for 45 degrees ratsnests,
638 // and 0 for horizontal or vertical ratsnests.
639 // For Horizontal and Vertical ratsnests, dy = 0;
640 double conn_cost = hypot( dx, dy * 2.0 );
641 curr_cost += conn_cost; // Total cost = sum of costs of each connection
642 }
643
644 return curr_cost;
645}
646
647
648// Sort routines
649static bool sortFootprintsByComplexity( FOOTPRINT* ref, FOOTPRINT* compare )
650{
651 double ff1 = ref->GetArea() * ref->GetPadCount();
652 double ff2 = compare->GetArea() * compare->GetPadCount();
653 return ff2 < ff1;
654}
655
656
658{
659 double ff1 = ref->GetArea() * ref->GetFlag();
660 double ff2 = compare->GetArea() * compare->GetFlag();
661 return ff2 < ff1;
662}
663
664
666{
667 std::vector<FOOTPRINT*> fpList;
668
669 for( FOOTPRINT* footprint : m_board->Footprints() )
670 fpList.push_back( footprint );
671
672 sort( fpList.begin(), fpList.end(), sortFootprintsByComplexity );
673
674 for( FOOTPRINT* footprint : fpList )
675 {
676 footprint->SetFlag( 0 );
677
678 if( !footprint->NeedsPlaced() )
679 continue;
680
681 m_connectivity->Update( footprint );
682 }
683
684 m_connectivity->RecalculateRatsnest();
685
686 for( FOOTPRINT* footprint : fpList )
687 {
688 auto edges = m_connectivity->GetRatsnestForComponent( footprint, true );
689
690 footprint->SetFlag( edges.size() ) ;
691 }
692
693 sort( fpList.begin(), fpList.end(), sortFootprintsByRatsnestSize );
694
695 // Search for "best" footprint.
696 FOOTPRINT* bestFootprint = nullptr;
697 FOOTPRINT* altFootprint = nullptr;
698
699 for( FOOTPRINT* footprint : fpList )
700 {
701 if( !footprint->NeedsPlaced() )
702 continue;
703
704 altFootprint = footprint;
705
706 if( footprint->GetFlag() == 0 )
707 continue;
708
709 bestFootprint = footprint;
710 break;
711 }
712
713 if( bestFootprint )
714 return bestFootprint;
715 else
716 return altFootprint;
717}
718
719
721{
722 // Draw the board free area
723 m_overlay->Clear();
724 m_overlay->SetIsFill( true );
725 m_overlay->SetIsStroke( false );
726
727 SHAPE_POLY_SET freeArea = m_topFreeArea.CloneDropTriangulation();
728 freeArea.Fracture();
729
730 // Draw the free polygon areas, top side:
731 if( freeArea.OutlineCount() > 0 )
732 {
733 m_overlay->SetIsFill( true );
734 m_overlay->SetIsStroke( false );
735 m_overlay->SetFillColor( COLOR4D(0.7, 0.0, 0.1, 0.2) );
736 m_overlay->Polygon( freeArea );
737 }
738
739 freeArea = m_bottomFreeArea;
740 freeArea.Fracture();
741
742 // Draw the free polygon areas, bottom side:
743 if( freeArea.OutlineCount() > 0 )
744 {
745 m_overlay->SetFillColor( COLOR4D(0.0, 0.7, 0.0, 0.2) );
746 m_overlay->Polygon( freeArea );
747 }
748}
749
750
751AR_RESULT AR_AUTOPLACER::AutoplaceFootprints( std::vector<FOOTPRINT*>& aFootprints,
752 BOARD_COMMIT* aCommit,
753 bool aPlaceOffboardModules )
754{
755 VECTOR2I memopos;
756 int error;
757 bool cancelled = false;
758
759 memopos = m_curPosition;
760
761 m_matrix.m_GridRouting = m_gridSize; //(int) m_frame->GetScreen()->GetGridSize().x;
762
763 // Ensure Board.m_GridRouting has a reasonable value:
764 if( m_matrix.m_GridRouting < pcbIUScale.mmToIU( 0.25 ) )
765 m_matrix.m_GridRouting = pcbIUScale.mmToIU( 0.25 );
766
767 // Compute footprint parameters used in autoplace
768 if( genPlacementRoutingMatrix( ) == 0 )
769 return AR_FAILURE;
770
771 int placedCount = 0;
772
773 for( FOOTPRINT* footprint : m_board->Footprints() )
774 footprint->SetNeedsPlaced( false );
775
776 std::vector<FOOTPRINT*> offboardMods;
777
778 if( aPlaceOffboardModules )
779 {
780 for( FOOTPRINT* footprint : m_board->Footprints() )
781 {
782 if( !m_matrix.m_BrdBox.Contains( footprint->GetPosition() ) )
783 offboardMods.push_back( footprint );
784 }
785 }
786
787 for( FOOTPRINT* footprint : aFootprints )
788 {
789 footprint->SetNeedsPlaced( true );
790 aCommit->Modify( footprint );
791 }
792
793 for( FOOTPRINT* footprint : offboardMods )
794 {
795 footprint->SetNeedsPlaced( true );
796 aCommit->Modify( footprint );
797 }
798
799 for( FOOTPRINT* footprint : m_board->Footprints() )
800 {
801 if( footprint->NeedsPlaced() ) // Erase from screen
802 placedCount++;
803 else
804 genModuleOnRoutingMatrix( footprint );
805 }
806
808 {
809 m_progressReporter->Report( _( "Autoplacing components..." ) );
810 m_progressReporter->SetMaxProgress( placedCount );
811 }
812
814
816 m_refreshCallback( nullptr );
817
818 FOOTPRINT* footprint;
819
820 while( ( footprint = pickFootprint() ) != nullptr )
821 {
822 // Display some info about activity, footprint placement can take a while:
823
825 m_progressReporter->SetTitle( wxString::Format( _( "Autoplacing %s" ),
826 footprint->GetReference() ) );
827
828 error = getOptimalFPPlacement( footprint );
829
830 if( error == AR_ABORT_PLACEMENT )
831 break;
832
833 // Place footprint.
834 placeFootprint( footprint, true, m_curPosition );
835
836 genModuleOnRoutingMatrix( footprint );
837 footprint->SetIsPlaced( true );
838 footprint->SetNeedsPlaced( false );
840
842 m_refreshCallback( footprint );
843
845 {
846 m_progressReporter->AdvanceProgress();
847
848 if ( !m_progressReporter->KeepRefreshing( false ) )
849 {
850 cancelled = true;
851 break;
852 }
853 }
854 }
855
856 m_curPosition = memopos;
857
858 m_matrix.UnInitRoutingMatrix();
859
860 return cancelled ? AR_CANCELLED : AR_COMPLETED;
861}
#define CELL_IS_MODULE
#define STEP_AR_MM
#define AR_KEEPOUT_MARGIN
#define AR_GAIN
#define CELL_IS_ZONE
#define CELL_IS_EDGE
static bool sortFootprintsByRatsnestSize(FOOTPRINT *ref, FOOTPRINT *compare)
#define AR_ABORT_PLACEMENT
#define CELL_IS_HOLE
static bool sortFootprintsByComplexity(FOOTPRINT *ref, FOOTPRINT *compare)
AR_RESULT
@ AR_COMPLETED
@ AR_FAILURE
@ AR_CANCELLED
@ AR_FREE_CELL
@ AR_OCCUIPED_BY_MODULE
@ AR_OUT_OF_BOARD
#define AR_SIDE_BOTTOM
Definition ar_matrix.h:37
#define AR_SIDE_TOP
Definition ar_matrix.h:36
constexpr EDA_IU_SCALE pcbIUScale
Definition base_units.h:121
BOX2< VECTOR2I > BOX2I
Definition box2.h:927
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:995
std::function< int(FOOTPRINT *aFootprint)> m_refreshCallback
std::unique_ptr< CONNECTIVITY_DATA > m_connectivity
void drawPlacementRoutingMatrix()
int getOptimalFPPlacement(FOOTPRINT *aFootprint)
AR_RESULT AutoplaceFootprints(std::vector< FOOTPRINT * > &aFootprints, BOARD_COMMIT *aCommit, bool aPlaceOffboardModules=false)
int testRectangle(const BOX2I &aRect, int side)
SHAPE_POLY_SET m_fpAreaTop
bool fillMatrix()
Fill m_matrix cells from m_boardShape.
AR_AUTOPLACER(BOARD *aBoard)
PROGRESS_REPORTER * m_progressReporter
const PAD * nearestPad(FOOTPRINT *aRefFP, PAD *aRefPad, const VECTOR2I &aOffset)
void buildFpAreas(FOOTPRINT *aFootprint, int aFpClearance)
unsigned int calculateKeepOutArea(const BOX2I &aRect, int side)
void placeFootprint(FOOTPRINT *aFootprint, bool aDoNotRecreateRatsnest, const VECTOR2I &aPos)
FOOTPRINT * pickFootprint()
Find the "best" footprint place.
void genModuleOnRoutingMatrix(FOOTPRINT *aFootprint)
SHAPE_POLY_SET m_topFreeArea
void addPad(PAD *aPad, int aClearance)
void addFpBody(const VECTOR2I &aStart, const VECTOR2I &aEnd, const LSET &aLayerMask)
int testFootprintOnBoard(FOOTPRINT *aFootprint, bool TstOtherSide, const VECTOR2I &aOffset)
AR_MATRIX m_matrix
SHAPE_POLY_SET m_fpAreaBottom
double computePlacementRatsnestCost(FOOTPRINT *aFootprint, const VECTOR2I &aOffset)
std::shared_ptr< KIGFX::VIEW_OVERLAY > m_overlay
SHAPE_POLY_SET m_boardShape
VECTOR2I m_curPosition
int genPlacementRoutingMatrix()
SHAPE_POLY_SET m_bottomFreeArea
unsigned char MATRIX_CELL
Definition ar_matrix.h:45
@ WRITE_OR_CELL
Definition ar_matrix.h:51
BASE_SET & set(size_t pos)
Definition base_set.h:126
Information pertinent to a Pcbnew printed circuit board.
Definition board.h:409
constexpr BOX2< Vec > & Inflate(coord_type dx, coord_type dy)
Inflates the rectangle horizontally by dx and vertically by dy.
Definition box2.h:553
constexpr const Vec GetEnd() const
Definition box2.h:209
constexpr void SetOrigin(const Vec &pos)
Definition box2.h:234
constexpr coord_type GetY() const
Definition box2.h:205
constexpr size_type GetWidth() const
Definition box2.h:211
constexpr coord_type GetX() const
Definition box2.h:204
constexpr size_type GetHeight() const
Definition box2.h:212
constexpr coord_type GetLeft() const
Definition box2.h:225
constexpr void Move(const Vec &aMoveVector)
Move the rectangle by the aMoveVector.
Definition box2.h:135
constexpr const Vec & GetOrigin() const
Definition box2.h:207
constexpr coord_type GetRight() const
Definition box2.h:214
constexpr coord_type GetTop() const
Definition box2.h:226
constexpr coord_type GetBottom() const
Definition box2.h:219
COMMIT & Modify(EDA_ITEM *aItem, BASE_SCREEN *aScreen=nullptr, RECURSE_MODE aRecurse=RECURSE_MODE::NO_RECURSE)
Modify a given item in the model.
Definition commit.h:102
void SetPosition(const VECTOR2I &aPos) override
void SetIsPlaced(bool isPlaced)
Definition footprint.h:717
unsigned GetPadCount() const
std::deque< PAD * > & Pads()
Definition footprint.h:404
PCB_LAYER_ID GetLayer() const override
Return the primary layer this item is on.
Definition footprint.h:449
void BuildCourtyardCaches(OUTLINE_ERROR_HANDLER *aErrorHandler=nullptr)
Build complex polygons of the courtyard areas from graphic items on the courtyard layers.
double GetArea(int aPadding=0) const
void SetNeedsPlaced(bool needsPlaced)
Definition footprint.h:726
const wxString & GetReference() const
Definition footprint.h:901
const SHAPE_POLY_SET & GetCourtyard(PCB_LAYER_ID aLayer) const
Used in DRC to test the courtyard area (a complex polygon).
int GetFlag() const
Definition footprint.h:564
VECTOR2I GetPosition() const override
Definition footprint.h:435
const BOX2I GetBoundingBox() const override
Return the orthogonal bounding box of this object for display purposes.
A color representation with 4 components: red, green, blue, alpha.
Definition color4d.h:101
LSET is a set of PCB_LAYER_IDs.
Definition lset.h:37
Definition pad.h:61
const BOX2I GetBoundingBox() const override
The bounding box is cached, so this will be efficient most of the time.
Definition pad.cpp:1623
bool IsOnLayer(PCB_LAYER_ID aLayer) const override
Test to see if this object is on the given layer.
Definition pad.h:919
VECTOR2I GetPosition() const override
Definition pad.cpp:246
Represent a polyline containing arcs as well as line segments: A chain of connected line and/or arc s...
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.
const BOX2I BBox(int aClearance=0) const override
Compute a bounding box of the shape, with a margin of aClearance a collision.
Represent a set of closed polygons.
SHAPE_LINE_CHAIN & Outline(int aIndex)
Return the reference to aIndex-th outline in the set.
int OutlineCount() const
Return the number of outlines in the set.
void Fracture(bool aSimplify=true)
Convert a set of polygons with holes to a single outline with "slits"/"fractures" connecting the oute...
This file is part of the common library.
#define _(s)
@ F_CrtYd
Definition layer_ids.h:112
@ Edge_Cuts
Definition layer_ids.h:108
@ B_Cu
Definition layer_ids.h:61
@ B_CrtYd
Definition layer_ids.h:111
@ F_Cu
Definition layer_ids.h:60
Message panel definition file.
Class that computes missing connections on a PCB.
VECTOR2I end
@ PCB_SHAPE_T
class PCB_SHAPE, a segment not on copper layers
Definition typeinfo.h:80
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:683