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