KiCad PCB EDA Suite
Loading...
Searching...
No Matches
constraint_builder.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 The KiCad Developers, see AUTHORS.txt for contributors.
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
21
22#include <algorithm>
23#include <cmath>
24#include <ranges>
25#include <set>
26#include <unordered_set>
27
28#include <base_units.h>
29#include <board.h>
30#include <core/kicad_algo.h>
31#include <footprint.h>
32#include <geometry/eda_angle.h>
33#include <geometry/seg.h>
36#include <pad.h>
37#include <pcb_dimension.h>
38#include <pcb_shape.h>
39#include <pcb_table.h>
40#include <pcb_tablecell.h>
41
42
43namespace
44{
45// UNDEFINED_LAYER means no filter so click authoring still reaches the whole board
46// IsOnLayer not GetLayer since a mask relieved copper shape is also present on its mask layer
47bool layerMatches( const BOARD_ITEM* aItem, PCB_LAYER_ID aLayer )
48{
49 return aLayer == UNDEFINED_LAYER || aItem->IsOnLayer( aLayer );
50}
51
52
53bool isSegment( const BOARD_ITEM* aItem )
54{
55 return aItem->Type() == PCB_SHAPE_T
56 && static_cast<const PCB_SHAPE*>( aItem )->GetShape() == SHAPE_T::SEGMENT;
57}
58
59
60bool isCircleOrArc( const BOARD_ITEM* aItem )
61{
62 if( aItem->Type() != PCB_SHAPE_T )
63 return false;
64
65 SHAPE_T shape = static_cast<const PCB_SHAPE*>( aItem )->GetShape();
66 return shape == SHAPE_T::CIRCLE || shape == SHAPE_T::ARC;
67}
68
69
70bool isArc( const BOARD_ITEM* aItem )
71{
72 return aItem->Type() == PCB_SHAPE_T
73 && static_cast<const PCB_SHAPE*>( aItem )->GetShape() == SHAPE_T::ARC;
74}
75
76
77bool isEllipseKind( const BOARD_ITEM* aItem )
78{
79 if( aItem->Type() != PCB_SHAPE_T )
80 return false;
81
82 SHAPE_T shape = static_cast<const PCB_SHAPE*>( aItem )->GetShape();
83 return shape == SHAPE_T::ELLIPSE || shape == SHAPE_T::ELLIPSE_ARC;
84}
85
86
87bool allSegments( const std::vector<BOARD_ITEM*>& aItems )
88{
89 return std::ranges::all_of( aItems, isSegment );
90}
91
92
93// Circles and arcs have a radius the solver can equate or fix.
94bool allRadial( const std::vector<BOARD_ITEM*>& aItems )
95{
96 return std::ranges::all_of( aItems, isCircleOrArc );
97}
98
99
100// Circles, arcs and ellipses all have a centre the solver can make concentric.
101bool allCentered( const std::vector<BOARD_ITEM*>& aItems )
102{
103 return std::ranges::all_of( aItems,
104 []( const BOARD_ITEM* aItem )
105 {
106 return isCircleOrArc( aItem ) || isEllipseKind( aItem );
107 } );
108}
109}
110
111
112EDA_ANGLE MeasureCornerAngle( const SEG& aA, const SEG& aB )
113{
114 const VECTOR2I aEnds[2] = { aA.A, aA.B };
115 const VECTOR2I bEnds[2] = { aB.A, aB.B };
116
117 // The vertex is the closest endpoint pair; the rays run from it toward each other endpoint.
118 int vA = 0, vB = 0;
119 SEG::ecoord best = ( aEnds[0] - bEnds[0] ).SquaredEuclideanNorm();
120
121 for( int i = 0; i < 2; ++i )
122 {
123 for( int j = 0; j < 2; ++j )
124 {
125 SEG::ecoord dist = ( aEnds[i] - bEnds[j] ).SquaredEuclideanNorm();
126
127 if( dist < best )
128 {
129 best = dist;
130 vA = i;
131 vB = j;
132 }
133 }
134 }
135
136 // Orient both segments from the shared vertex outward so SEG::Angle reads the corner the rays
137 // open. It uses each segment's true direction (not a midpoint ray), so a small gap between the
138 // near endpoints does not skew the measurement, and it returns [0, 180] without folding past 90.
139 return SEG( aEnds[vA], aEnds[1 - vA] ).Angle( SEG( bEnds[vB], bEnds[1 - vB] ) );
140}
141
142
143std::unique_ptr<PCB_CONSTRAINT> BuildConstraintFromItems( BOARD_ITEM* aParent,
145 const std::vector<BOARD_ITEM*>& aItems )
146{
147 // Build a constraint of aType with every selected item bound by its WHOLE anchor.
148 auto makeWhole = [&]()
149 {
150 std::unique_ptr<PCB_CONSTRAINT> c = std::make_unique<PCB_CONSTRAINT>( aParent, aType );
151
152 for( BOARD_ITEM* item : aItems )
153 c->AddMember( item->m_Uuid, CONSTRAINT_ANCHOR::WHOLE );
154
155 return c;
156 };
157
158 switch( aType )
159 {
164 {
165 if( aItems.size() != 2 || !allSegments( aItems ) )
166 return nullptr;
167
168 return makeWhole();
169 }
170
173 {
174 if( aItems.size() != 1 || !isSegment( aItems[0] ) )
175 return nullptr;
176
177 return makeWhole();
178 }
179
181 {
182 if( aItems.size() != 1 || !isSegment( aItems[0] ) )
183 return nullptr;
184
185 const PCB_SHAPE* seg = static_cast<const PCB_SHAPE*>( aItems[0] );
186
187 std::unique_ptr<PCB_CONSTRAINT> c = makeWhole();
188 c->SetValue( ( seg->GetEnd() - seg->GetStart() ).EuclideanNorm() );
189 return c;
190 }
191
193 {
194 if( aItems.size() != 2 || !allCentered( aItems ) )
195 return nullptr;
196
197 return makeWhole();
198 }
199
201 {
202 if( aItems.size() != 2 || !allRadial( aItems ) )
203 return nullptr;
204
205 return makeWhole();
206 }
207
209 {
210 if( aItems.size() != 2 || !allSegments( aItems ) )
211 return nullptr;
212
213 const PCB_SHAPE* a = static_cast<const PCB_SHAPE*>( aItems[0] );
214 const PCB_SHAPE* b = static_cast<const PCB_SHAPE*>( aItems[1] );
215
216 // A zero-length segment has no direction, so the corner angle is undefined and the solver's
217 // angle equation is singular.
218 if( a->GetStart() == a->GetEnd() || b->GetStart() == b->GetEnd() )
219 return nullptr;
220
221 std::unique_ptr<PCB_CONSTRAINT> c = makeWhole();
222 c->SetValue( MeasureCornerAngle( SEG( a->GetStart(), a->GetEnd() ),
223 SEG( b->GetStart(), b->GetEnd() ) ).AsDegrees() );
224 return c;
225 }
226
228 {
229 if( aItems.size() != 1 || !isCircleOrArc( aItems[0] ) )
230 return nullptr;
231
232 std::unique_ptr<PCB_CONSTRAINT> c = makeWhole();
233 c->SetValue( static_cast<const PCB_SHAPE*>( aItems[0] )->GetRadius() );
234 return c;
235 }
236
238 {
239 if( aItems.size() != 1 || !isArc( aItems[0] ) )
240 return nullptr;
241
242 std::unique_ptr<PCB_CONSTRAINT> c = makeWhole();
243 c->SetValue( static_cast<const PCB_SHAPE*>( aItems[0] )->GetArcAngle().AsDegrees() );
244 return c;
245 }
246
248 {
249 if( aItems.size() != 2 )
250 return nullptr;
251
252 const BOARD_ITEM* a = aItems[0];
253 const BOARD_ITEM* b = aItems[1];
254
255 auto isCurve = []( const BOARD_ITEM* aItem )
256 {
257 return isCircleOrArc( aItem ) || isEllipseKind( aItem );
258 };
259
260 bool lineCurve = ( isSegment( a ) && isCurve( b ) ) || ( isSegment( b ) && isCurve( a ) );
261 bool curveCurve = isCircleOrArc( a ) && isCircleOrArc( b );
262
263 if( !lineCurve && !curveCurve )
264 return nullptr;
265
266 return makeWhole();
267 }
268
269 default:
270 // Point-anchored families (coincident, midpoint, symmetric, ...) need point selection,
271 // which the whole-shape authoring tool does not yet provide.
272 return nullptr;
273 }
274}
275
276
278{
279 wxString format;
280
281 // No default: an added type must be classified here, or the build fails rather than shipping
282 // a silently hintless constraint. Each arm mirrors the matching BuildConstraintFromItems rule.
283 switch( aType )
284 {
289 format = _( "%s needs two line segments. Click them to constrain." );
290 break;
291
292 // A zero-length segment has no direction, so the corner angle would be singular
294 format = _( "%s needs two line segments of nonzero length. Click them to constrain." );
295 break;
296
299 format = _( "%s needs one line segment, or two anchor points. Click them to constrain." );
300 break;
301
303 format = _( "%s needs one line segment. Click it to constrain." );
304 break;
305
306 // allCentered also accepts ellipses, which have a centre but no single radius
308 format = _( "%s needs two arcs, circles or ellipses. Click them to constrain." );
309 break;
310
312 format = _( "%s needs two arcs or circles. Click them to constrain." );
313 break;
314
316 format = _( "%s needs one arc or circle. Click it to constrain." );
317 break;
318
320 format = _( "%s needs one arc. Click it to constrain." );
321 break;
322
323 // Two curves must both be arcs or circles; an ellipse pairs only with a line
325 format = _( "%s needs a line and a curve, or two arcs or circles. Click them to constrain." );
326 break;
327
328 // Authored by clicking anchors, so there is never a selection to reject
335 return wxEmptyString;
336 }
337
338 return wxString::Format( format, ConstraintTypeLabel( aType ) );
339}
340
341
342std::vector<CONSTRAINT_ANCHOR_POINT> ConstraintShapeAnchors( const PCB_SHAPE* aShape )
343{
344 std::vector<CONSTRAINT_ANCHOR_POINT> anchors;
345
346 if( !aShape )
347 return anchors;
348
349 switch( aShape->GetShape() )
350 {
351 case SHAPE_T::SEGMENT:
352 case SHAPE_T::BEZIER:
353 return { { CONSTRAINT_ANCHOR::START, aShape->GetStart() },
354 { CONSTRAINT_ANCHOR::END, aShape->GetEnd() } };
355
356 case SHAPE_T::ARC:
358 return { { CONSTRAINT_ANCHOR::START, aShape->GetStart() },
359 { CONSTRAINT_ANCHOR::END, aShape->GetEnd() },
360 { CONSTRAINT_ANCHOR::CENTER, aShape->GetCenter() } };
361
362 case SHAPE_T::CIRCLE:
363 case SHAPE_T::ELLIPSE:
364 return { { CONSTRAINT_ANCHOR::CENTER, aShape->GetCenter() } };
365
367 {
368 // TL TR BR BL order must match frozen corner roles of adapter
369 VECTOR2I s = aShape->GetStart();
370 VECTOR2I e = aShape->GetEnd();
371 VECTOR2I tl( std::min( s.x, e.x ), std::min( s.y, e.y ) );
372 VECTOR2I br( std::max( s.x, e.x ), std::max( s.y, e.y ) );
373
374 return { { CONSTRAINT_ANCHOR::VERTEX, tl, 0 },
375 { CONSTRAINT_ANCHOR::VERTEX, VECTOR2I( br.x, tl.y ), 1 },
376 { CONSTRAINT_ANCHOR::VERTEX, br, 2 },
377 { CONSTRAINT_ANCHOR::VERTEX, VECTOR2I( tl.x, br.y ), 3 } };
378 }
379
380 case SHAPE_T::POLY:
381 {
382 // Same eligibility gate as adapter ingestion so picker never offers unmappable anchor
383 if( !ConstraintPolygonIsModelable( aShape ) )
384 return anchors;
385
386 const SHAPE_LINE_CHAIN& outline = aShape->GetPolyShape().COutline( 0 );
387
388 for( int i = 0; i < outline.PointCount(); ++i )
389 anchors.push_back( { CONSTRAINT_ANCHOR::VERTEX, outline.CPoint( i ), i } );
390
391 return anchors;
392 }
393
394 default:
395 return anchors;
396 }
397}
398
399
401{
402 if( !aShape || aShape->GetShape() != SHAPE_T::POLY )
403 return false;
404
405 const SHAPE_POLY_SET& polySet = aShape->GetPolyShape();
406
407 if( polySet.OutlineCount() != 1 || polySet.HoleCount( 0 ) > 0 )
408 return false;
409
410 const SHAPE_LINE_CHAIN& outline = polySet.COutline( 0 );
411
412 return outline.PointCount() > 0 && outline.ArcCount() == 0;
413}
414
415
416std::optional<CONSTRAINT_ANCHOR_POINT> ConstraintShapeVertex( const PCB_SHAPE* aShape, int aIndex )
417{
418 if( !aShape || aIndex < 0 )
419 return std::nullopt;
420
421 if( aShape->GetShape() != SHAPE_T::RECTANGLE && aShape->GetShape() != SHAPE_T::POLY )
422 return std::nullopt;
423
424 std::vector<CONSTRAINT_ANCHOR_POINT> anchors = ConstraintShapeAnchors( aShape );
425
426 if( aIndex >= (int) anchors.size() )
427 return std::nullopt;
428
429 return anchors[aIndex];
430}
431
432
433std::optional<CONSTRAINT_MEMBER> NearestAnchorAmong( const std::vector<PCB_SHAPE*>& aShapes,
434 const VECTOR2I& aPos, double aMaxDist )
435{
436 double best = aMaxDist;
437 std::optional<CONSTRAINT_MEMBER> result;
438
439 for( const PCB_SHAPE* shape : aShapes )
440 {
441 for( const CONSTRAINT_ANCHOR_POINT& a : ConstraintShapeAnchors( shape ) )
442 {
443 double dist = ( a.pos - aPos ).EuclideanNorm();
444
445 if( dist <= best )
446 {
447 best = dist;
448 result = CONSTRAINT_MEMBER( shape->m_Uuid, a.anchor, a.index );
449 }
450 }
451 }
452
453 return result;
454}
455
456
457std::vector<PCB_SHAPE*> CollectConstraintShapes( const BOARD* aBoard, PCB_LAYER_ID aLayer )
458{
459 std::vector<PCB_SHAPE*> shapes;
460
461 if( !aBoard )
462 return shapes;
463
464 auto collect =
465 [&]( const auto& aContainer )
466 {
467 for( BOARD_ITEM* item : aContainer )
468 {
469 if( PCB_SHAPE* shape = dynamic_cast<PCB_SHAPE*>( item );
470 shape && aBoard->IsLayerVisible( shape->GetLayer() ) && layerMatches( shape, aLayer ) )
471 {
472 shapes.push_back( shape );
473 }
474 }
475 };
476
477 collect( aBoard->Drawings() );
478
479 for( FOOTPRINT* footprint : aBoard->Footprints() )
480 collect( footprint->GraphicalItems() );
481
482 return shapes;
483}
484
485
486std::vector<BOARD_ITEM*> CollectConstrainableItems( const BOARD* aBoard, PCB_LAYER_ID aLayer )
487{
488 std::vector<BOARD_ITEM*> items;
489
490 if( !aBoard )
491 return items;
492
493 auto collect =
494 [&]( const auto& aContainer )
495 {
496 for( BOARD_ITEM* item : aContainer )
497 {
498 if( ( item->Type() == PCB_SHAPE_T || dynamic_cast<PCB_DIMENSION_BASE*>( item ) )
499 && aBoard->IsLayerVisible( item->GetLayer() ) && layerMatches( item, aLayer ) )
500 {
501 items.push_back( item );
502 }
503 }
504 };
505
506 collect( aBoard->Drawings() );
507
508 for( FOOTPRINT* footprint : aBoard->Footprints() )
509 {
510 collect( footprint->GraphicalItems() );
511
512 // A pad spans several layers so its principal layer alone would hide an NPTH mounting hole
513 for( PAD* pad : footprint->Pads() )
514 {
515 bool visible = std::ranges::any_of( pad->GetLayerSet().Seq(),
516 [&]( PCB_LAYER_ID aPadLayer )
517 {
518 return aBoard->IsLayerVisible( aPadLayer );
519 } );
520
521 if( visible && layerMatches( pad, aLayer ) )
522 items.push_back( pad );
523 }
524 }
525
526 return items;
527}
528
529
530std::optional<CONSTRAINT_MEMBER> NearestConstraintAnchor( const BOARD* aBoard, const VECTOR2I& aPos, double aMaxDist,
531 const std::vector<CONSTRAINT_MEMBER>& aExclude,
532 PCB_LAYER_ID aLayer )
533{
534 double best = aMaxDist;
535 std::optional<CONSTRAINT_MEMBER> result;
536
537 for( BOARD_ITEM* item : CollectConstrainableItems( aBoard, aLayer ) )
538 {
539 for( const CONSTRAINT_ANCHOR_POINT& a : ConstraintItemAnchors( item ) )
540 {
541 CONSTRAINT_MEMBER candidate( item->m_Uuid, a.anchor, a.index );
542
543 // Skip already picked handle so distinct coincident endpoint stays reachable
544 if( alg::contains( aExclude, candidate ) )
545 continue;
546
547 double dist = ( a.pos - aPos ).EuclideanNorm();
548
549 if( dist <= best )
550 {
551 best = dist;
552 result = candidate;
553 }
554 }
555 }
556
557 return result;
558}
559
560
561std::vector<ENDPOINT_BINDING> SelectEndpointBindings( const BOARD* aBoard, const KIID& aItem, const VECTOR2I& aStart,
562 const std::optional<VECTOR2I>& aEnd, double aMaxDist,
563 PCB_LAYER_ID aLayer )
564{
565 std::vector<ENDPOINT_BINDING> bindings;
566
567 if( !aBoard )
568 return bindings;
569
570 // Best pair of distinct anchors on one item within aMaxDist minimizing summed distance
571 // Distinct anchors required or endpoints merge and pairs judged jointly not per end nearest
572 using ANCHOR_PAIR = std::pair<CONSTRAINT_MEMBER, CONSTRAINT_MEMBER>;
573
574 auto bestPairOn = [&]( BOARD_ITEM* aCandidate ) -> std::optional<std::pair<ANCHOR_PAIR, double>>
575 {
576 std::vector<CONSTRAINT_ANCHOR_POINT> anchors = ConstraintItemAnchors( aCandidate );
577
578 // Sum decomposes per endpoint best and runner up END anchors computed once serve every
579 // START candidate keeps a dense polygon linear in vertex count instead of quadratic
580 const size_t none = anchors.size();
581 size_t bestEnd = none;
582 size_t secondEnd = none;
583 std::vector<double> dEnd( anchors.size(), 0.0 );
584
585 for( size_t j = 0; j < anchors.size(); ++j )
586 {
587 dEnd[j] = ( anchors[j].pos - *aEnd ).EuclideanNorm();
588
589 if( dEnd[j] > aMaxDist )
590 continue;
591
592 if( bestEnd == none || dEnd[j] < dEnd[bestEnd] )
593 {
594 secondEnd = bestEnd;
595 bestEnd = j;
596 }
597 else if( secondEnd == none || dEnd[j] < dEnd[secondEnd] )
598 {
599 secondEnd = j;
600 }
601 }
602
603 if( bestEnd == none )
604 return std::nullopt;
605
606 std::optional<std::pair<ANCHOR_PAIR, double>> best;
607
608 for( size_t i = 0; i < anchors.size(); ++i )
609 {
610 double dStart = ( anchors[i].pos - aStart ).EuclideanNorm();
611
612 if( dStart > aMaxDist )
613 continue;
614
615 size_t j = ( i == bestEnd ) ? secondEnd : bestEnd;
616
617 if( j == none )
618 continue;
619
620 double sum = dStart + dEnd[j];
621
622 if( !best || sum < best->second )
623 {
624 best = std::make_pair(
625 ANCHOR_PAIR{ CONSTRAINT_MEMBER( aCandidate->m_Uuid, anchors[i].anchor, anchors[i].index ),
626 CONSTRAINT_MEMBER( aCandidate->m_Uuid, anchors[j].anchor, anchors[j].index ) },
627 sum );
628 }
629 }
630
631 return best;
632 };
633
634 // Prefer single object reaching both endpoints so a single feature dimension stays bound at
635 // both ends
636 if( aEnd )
637 {
638 std::optional<ANCHOR_PAIR> bestPair;
639 double bestSum = 0.0;
640
641 for( BOARD_ITEM* item : CollectConstrainableItems( aBoard, aLayer ) )
642 {
643 if( item->m_Uuid == aItem )
644 continue;
645
646 auto pair = bestPairOn( item );
647
648 if( !pair )
649 continue;
650
651 if( !bestPair || pair->second < bestSum )
652 {
653 bestSum = pair->second;
654 bestPair = pair->first;
655 }
656 }
657
658 if( bestPair )
659 {
660 bindings.push_back( { CONSTRAINT_ANCHOR::START, bestPair->first } );
661 bindings.push_back( { CONSTRAINT_ANCHOR::END, bestPair->second } );
662 return bindings;
663 }
664 }
665
666 // Else bind each endpoint to its own nearest anchor the two may land on different objects
667 // and either may find nothing
668 std::vector<CONSTRAINT_MEMBER> exclude{ { aItem, CONSTRAINT_ANCHOR::START }, { aItem, CONSTRAINT_ANCHOR::END } };
669
670 if( auto startTarget = NearestConstraintAnchor( aBoard, aStart, aMaxDist, exclude, aLayer ) )
671 {
672 bindings.push_back( { CONSTRAINT_ANCHOR::START, *startTarget } );
673 exclude.push_back( *startTarget );
674 }
675
676 if( aEnd )
677 {
678 if( auto endTarget = NearestConstraintAnchor( aBoard, *aEnd, aMaxDist, exclude, aLayer ) )
679 bindings.push_back( { CONSTRAINT_ANCHOR::END, *endTarget } );
680 }
681
682 return bindings;
683}
684
685
686BOARD_ITEM* ResolveConstrainableItem( const BOARD* aBoard, const KIID& aId )
687{
688 if( !aBoard )
689 return nullptr;
690
691 BOARD_ITEM* item = aBoard->ResolveItem( aId, true );
692
693 return IsConstrainableItem( item ) ? item : nullptr;
694}
695
696
697bool IsConstrainableItem( const BOARD_ITEM* aItem )
698{
699 return aItem
700 && ( aItem->Type() == PCB_SHAPE_T || aItem->Type() == PCB_PAD_T
701 || dynamic_cast<const PCB_DIMENSION_BASE*>( aItem ) );
702}
703
704
705std::optional<KIID> NearestOutlineShape( const BOARD* aBoard, const VECTOR2I& aPos, double aMaxDist, bool aAllowCircle,
706 PCB_LAYER_ID aLayer )
707{
708 double best = aMaxDist;
709 std::optional<KIID> result;
710
711 for( PCB_SHAPE* shape : CollectConstraintShapes( aBoard, aLayer ) )
712 {
713 const SHAPE_T shapeType = shape->GetShape();
714 double dist = 0;
715
716 if( shapeType == SHAPE_T::SEGMENT )
717 {
718 dist = SEG( shape->GetStart(), shape->GetEnd() ).Distance( aPos );
719 }
720 else if( aAllowCircle && ( shapeType == SHAPE_T::CIRCLE || shapeType == SHAPE_T::ARC ) )
721 {
722 dist = std::abs( ( aPos - shape->GetCenter() ).EuclideanNorm() - shape->GetRadius() );
723 }
724 else if( aAllowCircle && ( shapeType == SHAPE_T::ELLIPSE || shapeType == SHAPE_T::ELLIPSE_ARC ) )
725 {
726 // Radial distance to the outline at the click's polar angle in the ellipse frame.
727 // Not the exact outline distance, but exact on the outline, which is all a snap needs.
728 double a = shape->GetEllipseMajorRadius();
729 double b = shape->GetEllipseMinorRadius();
730 double phi = shape->GetEllipseRotation().AsRadians();
731 VECTOR2D d = VECTOR2D( aPos - shape->GetEllipseCenter() );
732 double lx = d.x * std::cos( phi ) + d.y * std::sin( phi );
733 double ly = -d.x * std::sin( phi ) + d.y * std::cos( phi );
734 double r = std::hypot( lx, ly );
735
736 if( a <= 0 || b <= 0 )
737 continue;
738
739 double theta = std::atan2( ly, lx );
740 double re = a * b / std::hypot( b * std::cos( theta ), a * std::sin( theta ) );
741
742 dist = std::abs( r - re );
743 }
744 else
745 {
746 continue;
747 }
748
749 if( dist <= best )
750 {
751 best = dist;
752 result = shape->m_Uuid;
753 }
754 }
755
756 return result;
757}
758
759
760std::vector<CONSTRAINT_ANCHOR_POINT> ConstraintItemAnchors( const BOARD_ITEM* aItem )
761{
762 if( !aItem )
763 return {};
764
765 if( aItem->Type() == PCB_SHAPE_T )
766 return ConstraintShapeAnchors( static_cast<const PCB_SHAPE*>( aItem ) );
767
768 if( const PCB_DIMENSION_BASE* dim = dynamic_cast<const PCB_DIMENSION_BASE*>( aItem ) )
769 {
770 std::vector<CONSTRAINT_ANCHOR_POINT> anchors;
771 anchors.push_back( { CONSTRAINT_ANCHOR::START, dim->GetStart() } );
772
773 // Only aligned/orthogonal/radial dimensions have a second measured feature point; a leader
774 // or centre mark's second point is a control point.
775 switch( aItem->Type() )
776 {
779 case PCB_DIM_RADIAL_T:
780 anchors.push_back( { CONSTRAINT_ANCHOR::END, dim->GetEnd() } );
781 break;
782
783 default:
784 break;
785 }
786
787 return anchors;
788 }
789
790 if( aItem->Type() == PCB_PAD_T )
791 return { { CONSTRAINT_ANCHOR::CENTER, static_cast<const PAD*>( aItem )->GetPosition() } };
792
793 return {};
794}
795
796
797std::optional<VECTOR2I> ConstraintAnchorPosition( const BOARD* aBoard, const CONSTRAINT_MEMBER& aMember )
798{
800 {
801 // VERTEX anchor needs its ordinal too else every vertex member resolves to vertex 0
802 if( a.anchor == aMember.m_anchor
803 && ( a.anchor != CONSTRAINT_ANCHOR::VERTEX || a.index == aMember.m_index ) )
804 {
805 return a.pos;
806 }
807 }
808
809 return std::nullopt;
810}
811
812
813double InitialConstraintValue( PCB_CONSTRAINT_TYPE aType, double aMeasured,
814 const std::map<PCB_CONSTRAINT_TYPE, double>& aRemembered )
815{
816 auto it = aRemembered.find( aType );
817
818 return it != aRemembered.end() ? it->second : aMeasured;
819}
820
821
822std::optional<KIID> NearestConstrainedShape( const BOARD* aBoard, const std::vector<KIID>& aCandidates,
823 const VECTOR2I& aPos, int aMaxDist )
824{
825 if( !aBoard )
826 return std::nullopt;
827
828 for( const KIID& id : aCandidates )
829 {
830 PCB_SHAPE* shape = dynamic_cast<PCB_SHAPE*>( aBoard->ResolveItem( id, true ) );
831
832 if( shape && shape->HitTest( aPos, aMaxDist ) )
833 return id;
834 }
835
836 return std::nullopt;
837}
838
839
840std::unordered_set<KIID> CollectMemberCandidateIds( const BOARD* aBoard )
841{
842 std::unordered_set<KIID> ids;
843
844 if( !aBoard )
845 return ids;
846
847 auto collect =
848 [&]( const auto& aContainer )
849 {
850 for( BOARD_ITEM* item : aContainer )
851 {
852 if( dynamic_cast<PCB_SHAPE*>( item ) || dynamic_cast<PCB_DIMENSION_BASE*>( item ) )
853 ids.insert( item->m_Uuid );
854
855 if( PCB_TABLE* table = dynamic_cast<PCB_TABLE*>( item ) )
856 {
857 for( PCB_TABLECELL* cell : table->GetCells() )
858 ids.insert( cell->m_Uuid );
859 }
860 }
861 };
862
863 collect( aBoard->Drawings() );
864
865 for( FOOTPRINT* footprint : aBoard->Footprints() )
866 {
867 collect( footprint->GraphicalItems() );
868
869 for( PAD* pad : footprint->Pads() )
870 ids.insert( pad->m_Uuid );
871 }
872
873 return ids;
874}
875
876
877std::vector<KIID> ConstrainedShapeIds( const BOARD* aBoard )
878{
879 std::vector<KIID> ids;
880
881 if( !aBoard )
882 return ids;
883
884 std::unordered_set<KIID> onBoard = CollectMemberCandidateIds( aBoard );
885 std::unordered_set<KIID> seen;
886
887 for( PCB_CONSTRAINT* constraint : CollectResolvedConstraints( aBoard ) )
888 {
889 for( const CONSTRAINT_MEMBER& member : constraint->GetMembers() )
890 {
891 if( onBoard.contains( member.m_item ) && seen.insert( member.m_item ).second )
892 ids.push_back( member.m_item );
893 }
894 }
895
896 return ids;
897}
898
899
900std::vector<PCB_CONSTRAINT*> CollectResolvedConstraints( const BOARD* aBoard )
901{
902 std::vector<PCB_CONSTRAINT*> constraints;
903
904 if( !aBoard )
905 return constraints;
906
907 constraints.assign( aBoard->Constraints().begin(), aBoard->Constraints().end() );
908
909 if( !aBoard->IsFootprintHolder() )
910 return constraints;
911
912 for( FOOTPRINT* footprint : aBoard->Footprints() )
913 constraints.insert( constraints.end(), footprint->Constraints().begin(), footprint->Constraints().end() );
914
915 return constraints;
916}
917
918
919std::optional<KIID> SelectRadialDimensionTarget( const BOARD* aBoard, const KIID& aDimension, const VECTOR2I& aCenter,
920 const VECTOR2I& aRim, double aMaxDist )
921{
922 if( !aBoard )
923 return std::nullopt;
924
925 std::optional<KIID> best;
926 double bestErr = 0.0;
927
928 for( PCB_SHAPE* shape : CollectConstraintShapes( aBoard ) )
929 {
930 if( shape->m_Uuid == aDimension || !isCircleOrArc( shape ) )
931 continue;
932
933 // Centre and rim must land on the same circle or arc centre and circumference or else a
934 // radial dimension over unrelated geometry would bind spuriously
935 std::optional<VECTOR2I> centerPos;
936
937 for( const CONSTRAINT_ANCHOR_POINT& a : ConstraintShapeAnchors( shape ) )
938 {
939 if( a.anchor == CONSTRAINT_ANCHOR::CENTER )
940 centerPos = a.pos;
941 }
942
943 if( !centerPos )
944 continue;
945
946 double centerErr = ( *centerPos - aCenter ).EuclideanNorm();
947
948 if( centerErr > aMaxDist )
949 continue;
950
951 double rimErr = std::abs( ( aRim - *centerPos ).EuclideanNorm() - shape->GetRadius() );
952
953 if( rimErr > aMaxDist )
954 continue;
955
956 // Arc outline is swept portion only not the whole circle so a rim point off the arc must
957 // not bind
958 if( shape->GetShape() == SHAPE_T::ARC && !shape->HitTest( aRim, KiROUND( aMaxDist ) ) )
959 continue;
960
961 double err = centerErr + rimErr;
962
963 if( !best || err < bestErr )
964 {
965 bestErr = err;
966 best = shape->m_Uuid;
967 }
968 }
969
970 return best;
971}
972
973
974bool DimensionEndpointsBound( const BOARD* aBoard, const PCB_DIMENSION_BASE* aDimension )
975{
976 if( !aBoard || !aDimension )
977 return false;
978
979 const CONSTRAINT_MEMBER startMember( aDimension->m_Uuid, CONSTRAINT_ANCHOR::START );
980 const CONSTRAINT_MEMBER endMember( aDimension->m_Uuid, CONSTRAINT_ANCHOR::END );
981
982 const std::vector<PCB_CONSTRAINT*> resolved = CollectResolvedConstraints( aBoard );
983
984 auto anyConstraint = [&]( const auto& aMatch )
985 {
986 return std::ranges::any_of( resolved, aMatch );
987 };
988
989 // Radial dimension binds centre coincident plus rim on outline of one circle or arc
990 // Legs on different objects or an object that cannot play the radius role never offer Driving
991 if( aDimension->Type() == PCB_DIM_RADIAL_T )
992 {
993 auto rimOnItem = [&]( const KIID& aItem )
994 {
995 return anyConstraint(
996 [&]( const PCB_CONSTRAINT* aConstraint )
997 {
999 return false;
1000
1001 // Point on line binding is asymmetric the dimension rim point is member 0
1002 // and the object outline WHOLE anchor is member 1
1003 const std::vector<CONSTRAINT_MEMBER>& members = aConstraint->GetMembers();
1004
1005 return members.size() == 2 && members[0] == endMember
1006 && members[1] == CONSTRAINT_MEMBER( aItem, CONSTRAINT_ANCHOR::WHOLE );
1007 } );
1008 };
1009
1010 return anyConstraint(
1011 [&]( const PCB_CONSTRAINT* aConstraint )
1012 {
1014 return false;
1015
1016 const std::vector<CONSTRAINT_MEMBER>& members = aConstraint->GetMembers();
1017
1018 if( members.size() != 2 )
1019 return false;
1020
1021 // Authored dimension first but coincident is symmetric so accept either order
1022 const CONSTRAINT_MEMBER* target = nullptr;
1023
1024 if( members[0] == startMember )
1025 target = &members[1];
1026 else if( members[1] == startMember )
1027 target = &members[0];
1028
1029 if( !target || target->m_anchor != CONSTRAINT_ANCHOR::CENTER )
1030 return false;
1031
1032 BOARD_ITEM* item = ResolveConstrainableItem( aBoard, target->m_item );
1033
1034 return item && isCircleOrArc( item ) && rimOnItem( target->m_item );
1035 } );
1036 }
1037
1038 // Aligned or orthogonal needs a coincident per endpoint whose target still resolves a target
1039 // pointing at a deleted item or a stale vertex index does not count
1040 auto hasCoincident = [&]( const CONSTRAINT_MEMBER& aMember )
1041 {
1042 return anyConstraint(
1043 [&]( const PCB_CONSTRAINT* aConstraint )
1044 {
1046 return false;
1047
1048 const std::vector<CONSTRAINT_MEMBER>& members = aConstraint->GetMembers();
1049
1050 // Must pair with a distinct target not itself
1051 if( members.size() != 2 || members[0].m_item == members[1].m_item )
1052 return false;
1053
1054 if( members[0] == aMember )
1055 return ConstraintAnchorPosition( aBoard, members[1] ).has_value();
1056
1057 return members[1] == aMember
1058 && ConstraintAnchorPosition( aBoard, members[0] ).has_value();
1059 } );
1060 };
1061
1062 return hasCoincident( startMember ) && hasCoincident( endMember );
1063}
1064
1065
1067{
1068 if( !aDimension )
1069 return false;
1070
1071 switch( aDimension->Type() )
1072 {
1073 case PCB_DIM_ALIGNED_T:
1075 case PCB_DIM_RADIAL_T:
1076 return true;
1077
1078 default:
1079 return false;
1080 }
1081}
1082
1083
1085{
1086 if( !aBoard || !aDimension )
1087 return nullptr;
1088
1089 const CONSTRAINT_MEMBER startMember( aDimension->m_Uuid, CONSTRAINT_ANCHOR::START );
1090 const CONSTRAINT_MEMBER endMember( aDimension->m_Uuid, CONSTRAINT_ANCHOR::END );
1091
1092 auto matches = [&]( const PCB_CONSTRAINT* aConstraint )
1093 {
1094 if( aConstraint->GetConstraintType() != PCB_CONSTRAINT_TYPE::FIXED_LENGTH )
1095 return false;
1096
1097 const std::vector<CONSTRAINT_MEMBER>& members = aConstraint->GetMembers();
1098
1099 return members.size() == 2
1100 && ( ( members[0] == startMember && members[1] == endMember )
1101 || ( members[0] == endMember && members[1] == startMember ) );
1102 };
1103
1104 const std::vector<PCB_CONSTRAINT*> resolved = CollectResolvedConstraints( aBoard );
1105 auto it = std::ranges::find_if( resolved, matches );
1106
1107 return it != resolved.end() ? *it : nullptr;
1108}
1109
1110
1111bool DimensionCanDrive( const BOARD* aBoard, const PCB_DIMENSION_BASE* aDimension )
1112{
1113 if( !DimensionHasValueMode( aDimension ) )
1114 return false;
1115
1116 if( DimensionEndpointsBound( aBoard, aDimension ) )
1117 return true;
1118
1119 PCB_CONSTRAINT* existing = FindDimensionLengthConstraint( aBoard, aDimension );
1120
1121 return existing && existing->IsDriving();
1122}
1123
1124
1126{
1127 PCB_CONSTRAINT* lengthConstraint = FindDimensionLengthConstraint( aBoard, aDimension );
1128
1129 if( lengthConstraint && lengthConstraint->IsDriving() )
1131
1132 if( aDimension && aDimension->GetOverrideTextEnabled() )
1134
1136}
1137
1138
1140 std::optional<int> aDrivingLengthIU,
1141 const std::optional<wxString>& aOverrideText,
1142 const std::function<void( BOARD_ITEM* )>& aBeforeModify,
1143 const std::function<void( BOARD_ITEM* )>& aStageAdd,
1144 const std::function<void( BOARD_ITEM* )>& aBeforeRemove )
1145{
1146 if( !aBoard || !DimensionHasValueMode( aDimension ) )
1147 return nullptr;
1148
1149 PCB_CONSTRAINT* existing = FindDimensionLengthConstraint( aBoard, aDimension );
1150
1151 if( aMode == DIM_VALUE_MODE::DRIVING )
1152 {
1153 // Unbound dimension has no geometry to drive and a non positive length would collapse the
1154 // constraint so the transition rejects with the board untouched
1155 if( !aDrivingLengthIU || *aDrivingLengthIU <= 0 || !DimensionCanDrive( aBoard, aDimension ) )
1156 return nullptr;
1157
1158 aBeforeModify( aDimension );
1159 aDimension->SetOverrideTextEnabled( false );
1160 aDimension->Update();
1161
1162 if( existing )
1163 {
1164 aBeforeModify( existing );
1165 existing->SetValue( *aDrivingLengthIU );
1166 existing->SetDriving( true );
1167 return existing;
1168 }
1169
1170 // A footprint owns its constraints only in the footprint editor since the board never
1171 // resolves them
1172 BOARD_ITEM* parent = aBoard->IsFootprintHolder() && aDimension->GetParentFootprint()
1173 ? static_cast<BOARD_ITEM*>( aDimension->GetParentFootprint() )
1174 : static_cast<BOARD_ITEM*>( aBoard );
1175
1176 auto constraint = std::make_unique<PCB_CONSTRAINT>( parent, PCB_CONSTRAINT_TYPE::FIXED_LENGTH );
1177 constraint->AddMember( aDimension->m_Uuid, CONSTRAINT_ANCHOR::START );
1178 constraint->AddMember( aDimension->m_Uuid, CONSTRAINT_ANCHOR::END );
1179 constraint->SetValue( *aDrivingLengthIU );
1180 constraint->SetDriving( true );
1181
1182 PCB_CONSTRAINT* added = constraint.get();
1183 aStageAdd( constraint.release() );
1184 return added;
1185 }
1186
1187 aBeforeModify( aDimension );
1188 aDimension->SetOverrideTextEnabled( aMode == DIM_VALUE_MODE::ARBITRARY );
1189
1190 if( aMode == DIM_VALUE_MODE::ARBITRARY && aOverrideText )
1191 aDimension->SetOverrideText( *aOverrideText );
1192
1193 aDimension->Update();
1194
1195 // Driven and Arbitrary both measure geometry natively so any driving length is dropped
1196 if( existing )
1197 aBeforeRemove( existing );
1198
1199 return nullptr;
1200}
1201
1202
1203void RemapPolygonVertexMembers( BOARD* aBoard, const KIID& aPoly, int aChangedIndex, int aDelta,
1204 const std::function<void( BOARD_ITEM* )>& aBeforeModify,
1205 const std::function<void( BOARD_ITEM* )>& aBeforeRemove )
1206{
1207 if( !aBoard || aDelta == 0 )
1208 return;
1209
1210 auto remapIn = [&]( const CONSTRAINTS& aConstraints )
1211 {
1212 for( PCB_CONSTRAINT* constraint : aConstraints )
1213 {
1214 bool shifts = false;
1215 bool doomed = false;
1216
1217 for( const CONSTRAINT_MEMBER& member : constraint->GetMembers() )
1218 {
1219 if( member.m_item != aPoly || member.m_anchor != CONSTRAINT_ANCHOR::VERTEX )
1220 continue;
1221
1222 if( aDelta < 0 && member.m_index == aChangedIndex )
1223 doomed = true;
1224 else if( member.m_index >= aChangedIndex )
1225 shifts = true;
1226 }
1227
1228 // Deleted vertex drags its bound member down and no fixed arity solver form survives
1229 // losing one so the whole constraint retires left unedited the staged removal image
1230 // keeps the authored members for undo
1231 if( doomed )
1232 {
1233 aBeforeRemove( constraint );
1234 continue;
1235 }
1236
1237 if( !shifts )
1238 continue;
1239
1240 aBeforeModify( constraint );
1241
1242 for( CONSTRAINT_MEMBER& member : constraint->Members() )
1243 {
1244 if( member.m_item == aPoly && member.m_anchor == CONSTRAINT_ANCHOR::VERTEX
1245 && member.m_index >= aChangedIndex )
1246 {
1247 member.m_index += aDelta;
1248 }
1249 }
1250 }
1251 };
1252
1253 remapIn( aBoard->Constraints() );
1254
1255 for( FOOTPRINT* footprint : aBoard->Footprints() )
1256 remapIn( footprint->Constraints() );
1257}
1258
1259
1260bool ConstraintIsDuplicateOnBoard( const BOARD* aBoard, const PCB_CONSTRAINT* aConstraint )
1261{
1262 return std::ranges::any_of( CollectResolvedConstraints( aBoard ),
1263 [&]( const PCB_CONSTRAINT* aExisting )
1264 {
1265 return ConstraintsAreDuplicate( *aExisting, *aConstraint );
1266 } );
1267}
1268
1269
1270namespace
1271{
1272// Tuning knobs for draw time auto constraints
1273// The bind tolerance accepts only exact landings while the corridor also captures near misses
1274constexpr double AUTO_BIND_TOL_MM = 0.01;
1275constexpr double AUTO_CORRIDOR_MM = 0.25;
1276constexpr double AUTO_TANGENT_TOL_DEG = 10.0;
1277
1278
1279// Tangent direction of a segment or circular shape at aPos or nullopt for other kinds
1280std::optional<double> tangentDirAt( const PCB_SHAPE* aShape, const VECTOR2I& aPos )
1281{
1282 switch( aShape->GetShape() )
1283 {
1284 case SHAPE_T::SEGMENT:
1285 {
1286 VECTOR2D dir( aShape->GetEnd() - aShape->GetStart() );
1287
1288 if( dir.EuclideanNorm() == 0 )
1289 return std::nullopt;
1290
1291 return std::atan2( dir.y, dir.x );
1292 }
1293
1294 case SHAPE_T::ARC:
1295 case SHAPE_T::CIRCLE:
1296 {
1297 VECTOR2D radial( aPos - aShape->GetCenter() );
1298
1299 if( radial.EuclideanNorm() == 0 )
1300 return std::nullopt;
1301
1302 return std::atan2( radial.y, radial.x ) + M_PI / 2;
1303 }
1304
1305 default: return std::nullopt;
1306 }
1307}
1308
1309
1310// A drawn shape meeting aTarget within a few degrees of tangency gets a tangent constraint
1311// The target is the first member so the snap solve moves the drawn shape not the board
1312std::unique_ptr<PCB_CONSTRAINT> makeTangent( const PCB_SHAPE* aShape, const PCB_SHAPE* aTarget, const VECTOR2I& aPos,
1313 BOARD_ITEM* aParent )
1314{
1315 const double tangentTol = AUTO_TANGENT_TOL_DEG * M_PI / 180.0;
1316
1317 bool curveInvolved = aShape->GetShape() == SHAPE_T::ARC || aTarget->GetShape() == SHAPE_T::ARC
1318 || aTarget->GetShape() == SHAPE_T::CIRCLE;
1319
1320 if( !curveInvolved )
1321 return nullptr;
1322
1323 std::optional<double> myDir = tangentDirAt( aShape, aPos );
1324 std::optional<double> otherDir = tangentDirAt( aTarget, aPos );
1325
1326 if( !myDir || !otherDir )
1327 return nullptr;
1328
1329 double diff = std::fabs( std::fmod( *myDir - *otherDir, M_PI ) );
1330 diff = std::min( diff, M_PI - diff );
1331
1332 if( diff > tangentTol )
1333 return nullptr;
1334
1335 auto constraint = std::make_unique<PCB_CONSTRAINT>( aParent, PCB_CONSTRAINT_TYPE::TANGENT );
1336 constraint->AddMember( aTarget->m_Uuid, CONSTRAINT_ANCHOR::WHOLE );
1337 constraint->AddMember( aShape->m_Uuid, CONSTRAINT_ANCHOR::WHOLE );
1338
1339 return constraint;
1340}
1341
1342
1343// Append unless an equal constraint exists on the board or already in this batch
1344// One draw can touch the same target twice so the batch check matters
1345void addUnlessDuplicate( const BOARD* aBoard, std::vector<AUTO_CONSTRAINT>& aResult,
1346 std::unique_ptr<PCB_CONSTRAINT> aConstraint, bool aNeedsSolve )
1347{
1348 if( ConstraintIsDuplicateOnBoard( aBoard, aConstraint.get() ) )
1349 return;
1350
1351 if( std::ranges::any_of( aResult,
1352 [&]( const AUTO_CONSTRAINT& aEntry )
1353 {
1354 return ConstraintsAreDuplicate( *aEntry.constraint, *aConstraint );
1355 } ) )
1356 {
1357 return;
1358 }
1359
1360 aResult.push_back( { std::move( aConstraint ), aNeedsSolve } );
1361}
1362
1363
1364// A circle or closed ellipse has no endpoints so only its centre binds
1365// Another curve centre reads as concentric an anchor coincides and an outline holds the centre
1366std::vector<AUTO_CONSTRAINT> selectCenterBindings( const BOARD* aBoard, const PCB_SHAPE* aShape, BOARD_ITEM* aParent )
1367{
1368 std::vector<AUTO_CONSTRAINT> result;
1369
1370 const double tol = pcbIUScale.mmToIU( AUTO_BIND_TOL_MM );
1371 VECTOR2I center = aShape->GetCenter();
1372
1373 std::vector<CONSTRAINT_MEMBER> exclude = { { aShape->m_Uuid, CONSTRAINT_ANCHOR::CENTER } };
1374
1375 if( std::optional<CONSTRAINT_MEMBER> target =
1376 NearestConstraintAnchor( aBoard, center, tol, exclude, aShape->GetLayer() ) )
1377 {
1378 std::unique_ptr<PCB_CONSTRAINT> constraint;
1379
1380 if( target->m_anchor == CONSTRAINT_ANCHOR::CENTER )
1381 {
1382 constraint = std::make_unique<PCB_CONSTRAINT>( aParent, PCB_CONSTRAINT_TYPE::CONCENTRIC );
1383 constraint->AddMember( target->m_item, CONSTRAINT_ANCHOR::WHOLE );
1384 constraint->AddMember( aShape->m_Uuid, CONSTRAINT_ANCHOR::WHOLE );
1385 }
1386 else
1387 {
1388 constraint = std::make_unique<PCB_CONSTRAINT>( aParent, PCB_CONSTRAINT_TYPE::COINCIDENT );
1389 constraint->AddMember( aShape->m_Uuid, CONSTRAINT_ANCHOR::CENTER );
1390 constraint->AddMember( target->m_item, target->m_anchor, target->m_index );
1391 }
1392
1393 addUnlessDuplicate( aBoard, result, std::move( constraint ), false );
1394 }
1395 else if( std::optional<KIID> outline = NearestOutlineShape( aBoard, center, tol, true, aShape->GetLayer() ) )
1396 {
1397 if( *outline != aShape->m_Uuid )
1398 {
1399 auto constraint = std::make_unique<PCB_CONSTRAINT>( aParent, PCB_CONSTRAINT_TYPE::POINT_ON_LINE );
1400 constraint->AddMember( aShape->m_Uuid, CONSTRAINT_ANCHOR::CENTER );
1401 constraint->AddMember( *outline, CONSTRAINT_ANCHOR::WHOLE );
1402
1403 addUnlessDuplicate( aBoard, result, std::move( constraint ), false );
1404 }
1405 }
1406
1407 return result;
1408}
1409
1410
1411// Endpoints landing on existing anchors bind coincident
1412void selectEndpointCoincidents( const BOARD* aBoard, const PCB_SHAPE* aShape, BOARD_ITEM* aParent,
1413 std::vector<AUTO_CONSTRAINT>& aResult, std::set<CONSTRAINT_ANCHOR>& aBound,
1414 std::vector<std::pair<VECTOR2I, KIID>>& aTouches )
1415{
1416 const double tol = pcbIUScale.mmToIU( AUTO_BIND_TOL_MM );
1417
1418 std::vector<ENDPOINT_BINDING> bindings = SelectEndpointBindings( aBoard, aShape->m_Uuid, aShape->GetStart(),
1419 aShape->GetEnd(), tol, aShape->GetLayer() );
1420
1421 for( const ENDPOINT_BINDING& binding : bindings )
1422 {
1423 auto constraint = std::make_unique<PCB_CONSTRAINT>( aParent, PCB_CONSTRAINT_TYPE::COINCIDENT );
1424 constraint->AddMember( aShape->m_Uuid, binding.sourceAnchor );
1425 constraint->AddMember( binding.target.m_item, binding.target.m_anchor, binding.target.m_index );
1426
1427 aBound.insert( binding.sourceAnchor );
1428
1429 VECTOR2I pos = binding.sourceAnchor == CONSTRAINT_ANCHOR::START ? aShape->GetStart() : aShape->GetEnd();
1430 aTouches.emplace_back( pos, binding.target.m_item );
1431
1432 addUnlessDuplicate( aBoard, aResult, std::move( constraint ), false );
1433 }
1434}
1435
1436
1437// An endpoint with no anchor to coincide with but sitting on an outline binds point on line
1438// Landing on a segment midpoint means the midpoint snap was used so bind midpoint instead
1439void selectOutlineFallbacks( const BOARD* aBoard, const PCB_SHAPE* aShape, BOARD_ITEM* aParent,
1440 std::vector<AUTO_CONSTRAINT>& aResult, const std::set<CONSTRAINT_ANCHOR>& aBound,
1441 std::vector<std::pair<VECTOR2I, KIID>>& aTouches )
1442{
1443 const double tol = pcbIUScale.mmToIU( AUTO_BIND_TOL_MM );
1444
1446 {
1447 if( aBound.contains( anchor ) )
1448 continue;
1449
1450 VECTOR2I pos = anchor == CONSTRAINT_ANCHOR::START ? aShape->GetStart() : aShape->GetEnd();
1451 std::optional<KIID> target = NearestOutlineShape( aBoard, pos, tol, true, aShape->GetLayer() );
1452
1453 if( !target || *target == aShape->m_Uuid )
1454 continue;
1455
1457 PCB_SHAPE* targetShape = dynamic_cast<PCB_SHAPE*>( aBoard->ResolveItem( *target, true ) );
1458
1459 if( targetShape && targetShape->GetShape() == SHAPE_T::SEGMENT )
1460 {
1461 VECTOR2I mid = targetShape->GetStart() + ( targetShape->GetEnd() - targetShape->GetStart() ) / 2;
1462
1463 if( ( pos - mid ).EuclideanNorm() <= tol )
1465 }
1466
1467 auto constraint = std::make_unique<PCB_CONSTRAINT>( aParent, type );
1468 constraint->AddMember( aShape->m_Uuid, anchor );
1469 constraint->AddMember( *target, CONSTRAINT_ANCHOR::WHOLE );
1470
1471 aTouches.emplace_back( pos, *target );
1472
1473 addUnlessDuplicate( aBoard, aResult, std::move( constraint ), false );
1474 }
1475}
1476
1477
1478// A segment drawn through or near an existing shape anchor pins that point on the new segment
1479// Near misses within the corridor bind too and the post push solve pulls the line onto them
1480void selectCorridorPins( const BOARD* aBoard, const PCB_SHAPE* aShape, BOARD_ITEM* aParent,
1481 std::vector<AUTO_CONSTRAINT>& aResult )
1482{
1483 if( aShape->GetShape() != SHAPE_T::SEGMENT || aShape->GetStart() == aShape->GetEnd() )
1484 return;
1485
1486 const double tol = pcbIUScale.mmToIU( AUTO_BIND_TOL_MM );
1487 const double corridor = pcbIUScale.mmToIU( AUTO_CORRIDOR_MM );
1488
1489 SEG span( aShape->GetStart(), aShape->GetEnd() );
1490 std::vector<VECTOR2I> boundPos;
1491
1492 for( BOARD_ITEM* item : CollectConstrainableItems( aBoard, aShape->GetLayer() ) )
1493 {
1494 if( item->m_Uuid == aShape->m_Uuid || item->Type() != PCB_SHAPE_T )
1495 continue;
1496
1498 {
1499 if( span.Distance( anchor.pos ) > corridor )
1500 continue;
1501
1502 // The drawn endpoints already bound above so only true mid span hits count
1503 if( ( anchor.pos - aShape->GetStart() ).EuclideanNorm() <= corridor
1504 || ( anchor.pos - aShape->GetEnd() ).EuclideanNorm() <= corridor )
1505 {
1506 continue;
1507 }
1508
1509 // Chained corners stack two anchors on one spot and one binding is enough
1510 if( std::ranges::any_of( boundPos,
1511 [&]( const VECTOR2I& aP )
1512 {
1513 return ( anchor.pos - aP ).EuclideanNorm() <= tol;
1514 } ) )
1515 {
1516 continue;
1517 }
1518
1519 boundPos.push_back( anchor.pos );
1520
1521 auto constraint = std::make_unique<PCB_CONSTRAINT>( aParent, PCB_CONSTRAINT_TYPE::POINT_ON_LINE );
1522 constraint->AddMember( item->m_Uuid, anchor.anchor, anchor.index );
1523 constraint->AddMember( aShape->m_Uuid, CONSTRAINT_ANCHOR::WHOLE );
1524
1525 addUnlessDuplicate( aBoard, aResult, std::move( constraint ), true );
1526 }
1527 }
1528}
1529
1530
1531// Tangents where the drawn shape touched another shape near tangency
1532void selectTangents( const BOARD* aBoard, const PCB_SHAPE* aShape, BOARD_ITEM* aParent,
1533 std::vector<AUTO_CONSTRAINT>& aResult, const std::vector<std::pair<VECTOR2I, KIID>>& aTouches )
1534{
1535 for( const auto& [pos, id] : aTouches )
1536 {
1537 PCB_SHAPE* target = dynamic_cast<PCB_SHAPE*>( aBoard->ResolveItem( id, true ) );
1538
1539 if( target && target != aShape )
1540 {
1541 if( std::unique_ptr<PCB_CONSTRAINT> tangent = makeTangent( aShape, target, pos, aParent ) )
1542 addUnlessDuplicate( aBoard, aResult, std::move( tangent ), true );
1543 }
1544 }
1545}
1546
1547
1548// A segment drawn in a constrained line mode keeps its axis
1549void selectAxisConstraint( const BOARD* aBoard, const PCB_SHAPE* aShape, BOARD_ITEM* aParent,
1550 std::vector<AUTO_CONSTRAINT>& aResult )
1551{
1552 if( aShape->GetShape() != SHAPE_T::SEGMENT || aShape->GetStart() == aShape->GetEnd() )
1553 return;
1554
1555 bool horizontal = aShape->GetStart().y == aShape->GetEnd().y;
1556 bool vertical = aShape->GetStart().x == aShape->GetEnd().x;
1557
1558 if( !horizontal && !vertical )
1559 return;
1560
1561 auto constraint = std::make_unique<PCB_CONSTRAINT>( aParent, horizontal ? PCB_CONSTRAINT_TYPE::HORIZONTAL
1563 constraint->AddMember( aShape->m_Uuid, CONSTRAINT_ANCHOR::WHOLE );
1564
1565 addUnlessDuplicate( aBoard, aResult, std::move( constraint ), false );
1566}
1567} // namespace
1568
1569
1570std::vector<AUTO_CONSTRAINT> SelectShapeAutoConstraints( const BOARD* aBoard, const PCB_SHAPE* aShape,
1571 BOARD_ITEM* aParent, bool aAxisConstraint )
1572{
1573 std::vector<AUTO_CONSTRAINT> result;
1574
1575 if( !aBoard || !aShape )
1576 return result;
1577
1578 if( aShape->GetShape() == SHAPE_T::CIRCLE || aShape->GetShape() == SHAPE_T::ELLIPSE )
1579 return selectCenterBindings( aBoard, aShape, aParent );
1580
1581 std::set<CONSTRAINT_ANCHOR> bound;
1582 std::vector<std::pair<VECTOR2I, KIID>> touches;
1583
1584 selectEndpointCoincidents( aBoard, aShape, aParent, result, bound, touches );
1585 selectOutlineFallbacks( aBoard, aShape, aParent, result, bound, touches );
1586 selectCorridorPins( aBoard, aShape, aParent, result );
1587 selectTangents( aBoard, aShape, aParent, result, touches );
1588
1589 if( aAxisConstraint )
1590 selectAxisConstraint( aBoard, aShape, aParent, result );
1591
1592 return result;
1593}
constexpr EDA_IU_SCALE pcbIUScale
Definition base_units.h:128
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:985
A base class for any item which can be embedded within the BOARD container class, and therefore insta...
Definition board_item.h:99
virtual bool IsOnLayer(PCB_LAYER_ID aLayer) const
Test to see if this object is on the given layer.
Definition board_item.h:432
FOOTPRINT * GetParentFootprint() const
Information pertinent to a Pcbnew printed circuit board.
Definition board.h:411
bool IsFootprintHolder() const
Find out if the board is being used to hold a single footprint for editing/viewing.
Definition board.h:441
const FOOTPRINTS & Footprints() const
Definition board.h:465
const CONSTRAINTS & Constraints() const
Geometric constraints (#2329) owned by this board.
Definition board.h:522
bool IsLayerVisible(PCB_LAYER_ID aLayer) const
A proxy function that calls the correspondent function in m_BoardSettings tests whether a given layer...
Definition board.cpp:1208
BOARD_ITEM * ResolveItem(const KIID &aID, bool aAllowNullptrReturn=false) const
Definition board.cpp:2176
const DRAWINGS & Drawings() const
Definition board.h:467
double AsDegrees() const
Definition eda_angle.h:115
const KIID m_Uuid
Definition eda_item.h:599
KICAD_T Type() const
Returns the type of object.
Definition eda_item.h:110
SHAPE_POLY_SET & GetPolyShape()
SHAPE_T GetShape() const
Definition eda_shape.h:178
const VECTOR2I & GetEnd() const
Return the ending point of the graphic.
Definition eda_shape.h:334
const VECTOR2I & GetStart() const
Return the starting point of the graphic.
Definition eda_shape.h:284
Definition kiid.h:46
Definition pad.h:61
A geometric constraint between board items (issue #2329).
const std::vector< CONSTRAINT_MEMBER > & GetMembers() const
bool IsDriving() const
A driving constraint forces its value; a reference (non-driving) one only measures it.
PCB_CONSTRAINT_TYPE GetConstraintType() const
void SetValue(std::optional< double > aValue)
void SetDriving(bool aDriving)
Abstract dimension API.
void Update()
Update the dimension's cached text and geometry.
void SetOverrideTextEnabled(bool aOverride)
void SetOverrideText(const wxString &aValue)
bool GetOverrideTextEnabled() const
VECTOR2I GetCenter() const override
This defaults to the center of the bounding box if not overridden.
Definition pcb_shape.h:80
bool HitTest(const VECTOR2I &aPosition, int aAccuracy=0) const override
Test if aPosition is inside or on the boundary of this item.
Definition pcb_shape.h:162
PCB_LAYER_ID GetLayer() const override
Return the primary layer this item is on.
Definition pcb_shape.h:70
Definition seg.h:38
VECTOR2I A
Definition seg.h:45
VECTOR2I::extended_type ecoord
Definition seg.h:40
VECTOR2I B
Definition seg.h:46
int Distance(const SEG &aSeg) const
Compute minimum Euclidean distance to segment aSeg.
Definition seg.cpp:668
EDA_ANGLE Angle(const SEG &aOther) const
Determine the smallest angle between two segments.
Definition seg.cpp:66
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.
size_t ArcCount() const
Represent a set of closed polygons.
int HoleCount(int aOutline) const
Returns the number of holes in a given outline.
int OutlineCount() const
Return the number of outlines in the set.
const SHAPE_LINE_CHAIN & COutline(int aIndex) const
bool IsConstrainableItem(const BOARD_ITEM *aItem)
True when aItem is one ResolveConstrainableItem() accepts: a PCB_SHAPE, a dimension or a pad.
std::vector< ENDPOINT_BINDING > SelectEndpointBindings(const BOARD *aBoard, const KIID &aItem, const VECTOR2I &aStart, const std::optional< VECTOR2I > &aEnd, double aMaxDist, PCB_LAYER_ID aLayer)
Choose the coincident bindings a freshly drawn item endpoints should take so it tracks the geometry i...
std::optional< KIID > NearestConstrainedShape(const BOARD *aBoard, const std::vector< KIID > &aCandidates, const VECTOR2I &aPos, int aMaxDist)
The candidate shape whose outline aPos hits within aMaxDist, or std::nullopt.
void RemapPolygonVertexMembers(BOARD *aBoard, const KIID &aPoly, int aChangedIndex, int aDelta, const std::function< void(BOARD_ITEM *)> &aBeforeModify, const std::function< void(BOARD_ITEM *)> &aBeforeRemove)
Repoint persisted VERTEX constraint members after an outline edit of polygon aPoly inserts or removes...
std::vector< BOARD_ITEM * > CollectConstrainableItems(const BOARD *aBoard, PCB_LAYER_ID aLayer)
Every constrainable item on a visible layer – shapes, dimensions and pads – for board-wide anchor pic...
std::optional< KIID > NearestOutlineShape(const BOARD *aBoard, const VECTOR2I &aPos, double aMaxDist, bool aAllowCircle, PCB_LAYER_ID aLayer)
The shape whose outline is nearest aPos within aMaxDist.
std::vector< KIID > ConstrainedShapeIds(const BOARD *aBoard)
The member ids of every resolved constraint (see CollectResolvedConstraints()) that are on aBoard,...
double InitialConstraintValue(PCB_CONSTRAINT_TYPE aType, double aMeasured, const std::map< PCB_CONSTRAINT_TYPE, double > &aRemembered)
Value a freshly authored constraint dialog should open with.
EDA_ANGLE MeasureCornerAngle(const SEG &aA, const SEG &aB)
The corner angle between two segments, in the closed range [0, 180] degrees.
BOARD_ITEM * ResolveConstrainableItem(const BOARD *aBoard, const KIID &aId)
The board item a constraint may reference: a PCB_SHAPE, a dimension or a pad, or nullptr for anything...
bool DimensionHasValueMode(const PCB_DIMENSION_BASE *aDimension)
True for dimension types with a measured value aligned orthogonal or radial offering the Driven Drivi...
std::optional< CONSTRAINT_MEMBER > NearestConstraintAnchor(const BOARD *aBoard, const VECTOR2I &aPos, double aMaxDist, const std::vector< CONSTRAINT_MEMBER > &aExclude, PCB_LAYER_ID aLayer)
Find the constrainable-item anchor (a shape's segment/arc endpoint or centre, or a dimension's featur...
std::vector< CONSTRAINT_ANCHOR_POINT > ConstraintItemAnchors(const BOARD_ITEM *aItem)
The constraint anchors an item exposes.
std::optional< CONSTRAINT_ANCHOR_POINT > ConstraintShapeVertex(const PCB_SHAPE *aShape, int aIndex)
VERTEX anchor at ordinal aIndex of a rectangle or eligible polygon or std::nullopt if the shape has n...
wxString ConstraintSelectionHint(PCB_CONSTRAINT_TYPE aType)
A sentence naming what aType needs selected, for the moment a selection does not fit it and the tool ...
bool DimensionCanDrive(const BOARD *aBoard, const PCB_DIMENSION_BASE *aDimension)
True when Driving mode may be offered for aDimension needs both endpoints bound via DimensionEndpoint...
std::vector< AUTO_CONSTRAINT > SelectShapeAutoConstraints(const BOARD *aBoard, const PCB_SHAPE *aShape, BOARD_ITEM *aParent, bool aAxisConstraint)
Choose the constraints a freshly drawn shape should get from what its features landed on.
bool ConstraintIsDuplicateOnBoard(const BOARD *aBoard, const PCB_CONSTRAINT *aConstraint)
True if a resolved constraint (see CollectResolvedConstraints()) already equals aConstraint.
std::unique_ptr< PCB_CONSTRAINT > BuildConstraintFromItems(BOARD_ITEM *aParent, PCB_CONSTRAINT_TYPE aType, const std::vector< BOARD_ITEM * > &aItems)
Build a constraint of aType from a set of selected board items, or nullptr if the selection does not ...
std::vector< CONSTRAINT_ANCHOR_POINT > ConstraintShapeAnchors(const PCB_SHAPE *aShape)
Enumerate a shape constraint anchors with positions segment and arc endpoints arc centre circle centr...
std::optional< KIID > SelectRadialDimensionTarget(const BOARD *aBoard, const KIID &aDimension, const VECTOR2I &aCenter, const VECTOR2I &aRim, double aMaxDist)
Single circle or arc a radial dimension binds to or std::nullopt.
DIM_VALUE_MODE DimensionValueMode(const BOARD *aBoard, const PCB_DIMENSION_BASE *aDimension)
The value mode aDimension is in, derived from state: a self driving length means Driving,...
PCB_CONSTRAINT * FindDimensionLengthConstraint(const BOARD *aBoard, const PCB_DIMENSION_BASE *aDimension)
Self FIXED_LENGTH constraint whose members are exactly aDimension START and END or nullptr the drivin...
std::vector< PCB_SHAPE * > CollectConstraintShapes(const BOARD *aBoard, PCB_LAYER_ID aLayer)
Every PCB_SHAPE on a visible layer (drawings plus footprint graphics) – the candidates constraints ca...
std::unordered_set< KIID > CollectMemberCandidateIds(const BOARD *aBoard)
The ids of every item on aBoard a constraint member can resolve to (shapes, dimensions,...
bool ConstraintPolygonIsModelable(const PCB_SHAPE *aShape)
True when polygon has one non empty hole free arc free outline making it solver eligible Shared by ad...
std::optional< CONSTRAINT_MEMBER > NearestAnchorAmong(const std::vector< PCB_SHAPE * > &aShapes, const VECTOR2I &aPos, double aMaxDist)
The {shape, anchor} member nearest aPos within aMaxDist among aShapes, or std::nullopt.
std::optional< VECTOR2I > ConstraintAnchorPosition(const BOARD *aBoard, const CONSTRAINT_MEMBER &aMember)
Current location of a constraint member's anchor (its shape's START/END/CENTER, or a dimension's feat...
bool DimensionEndpointsBound(const BOARD *aBoard, const PCB_DIMENSION_BASE *aDimension)
True when both of aDimension measured endpoints are bound to anchors that still resolve a coincident ...
PCB_CONSTRAINT * SetDimensionValueMode(BOARD *aBoard, PCB_DIMENSION_BASE *aDimension, DIM_VALUE_MODE aMode, std::optional< int > aDrivingLengthIU, const std::optional< wxString > &aOverrideText, const std::function< void(BOARD_ITEM *)> &aBeforeModify, const std::function< void(BOARD_ITEM *)> &aStageAdd, const std::function< void(BOARD_ITEM *)> &aBeforeRemove)
Apply a value mode transition to aDimension Driving creates or updates the driving length with aDrivi...
std::vector< PCB_CONSTRAINT * > CollectResolvedConstraints(const BOARD *aBoard)
The constraints the editor resolves on aBoard.
DIM_VALUE_MODE
Mode a value bearing dimension value is in Driven mirrors measured geometry Driving forces geometry t...
#define _(s)
SHAPE_T
Definition eda_shape.h:55
@ ELLIPSE
Definition eda_shape.h:63
@ SEGMENT
Definition eda_shape.h:57
@ RECTANGLE
Use RECTANGLE instead of RECT to avoid collision in a Windows header.
Definition eda_shape.h:58
@ ELLIPSE_ARC
Definition eda_shape.h:64
PCB_LAYER_ID
A quick note on layer IDs:
Definition layer_ids.h:56
@ UNDEFINED_LAYER
Definition layer_ids.h:57
bool contains(const _Container &__container, _Value __value)
Returns true if the container contains the given value.
Definition kicad_algo.h:96
EDA_ANGLE abs(const EDA_ANGLE &aAngle)
Definition eda_angle.h:461
bool ConstraintsAreDuplicate(const PCB_CONSTRAINT &aA, const PCB_CONSTRAINT &aB)
True if two constraints express the same relation, meaning the same type and the same members compare...
wxString ConstraintTypeLabel(PCB_CONSTRAINT_TYPE aType)
Human-readable name of a constraint type (e.g. "Parallel"), for menus and lists.
CONSTRAINT_ANCHOR
Which feature of a referenced board item participates in a constraint.
@ VERTEX
An indexed rectangle corner or polygon outline vertex; pairs with CONSTRAINT_MEMBER::m_index.
@ WHOLE
The item as a whole (a segment as a line, a circle).
@ START
First endpoint of a segment or arc.
@ END
Second endpoint of a segment or arc.
@ CENTER
Center of an arc or circle.
PCB_CONSTRAINT_TYPE
The geometric relationship a PCB_CONSTRAINT enforces between its members.
@ CONCENTRIC
Two arcs/circles share a center.
@ SYMMETRIC
Two points are mirror images about an axis.
@ FIXED_POSITION
A point is locked at its current location.
@ VERTICAL
A segment (or two points) is vertical.
@ TANGENT
A line and a curve, or two curves, touch tangentially.
@ COINCIDENT
Two points are made to coincide.
@ PERPENDICULAR
Two segments are perpendicular.
@ FIXED_RADIUS
An arc/circle has a driving radius value.
@ HORIZONTAL
A segment (or two points) is horizontal.
@ EQUAL_RADIUS
Two arcs/circles have equal radius.
@ MIDPOINT
A point is the midpoint of a segment.
@ POINT_ON_LINE
A point lies on a segment's supporting line.
@ FIXED_LENGTH
A segment has a driving length value.
@ ANGULAR_DIMENSION
An angle between members (driving or reference).
@ COLLINEAR
Two segments lie on the same line.
@ ARC_ANGLE
An arc has a driving or reference swept-angle value.
@ PARALLEL
Two segments are parallel.
@ EQUAL_LENGTH
Two segments have equal length.
std::deque< PCB_CONSTRAINT * > CONSTRAINTS
One constraint chosen for a freshly drawn shape.
std::unique_ptr< PCB_CONSTRAINT > constraint
A selectable feature of a shape (a segment endpoint, arc centre, ...) and its location.
One participant in a constraint: a referenced board item plus the feature of that item that participa...
KIID m_item
Referenced board item, usually a PCB_SHAPE.
CONSTRAINT_ANCHOR m_anchor
Which feature of that item participates.
int m_index
Vertex ordinal; only meaningful for the VERTEX anchor.
One of a drawn item feature points bound coincident to an object anchor by draw time auto constrain s...
const std::string table
std::vector< double > vA
VECTOR2I center
wxString result
Test unit parsing edge cases and error handling.
#define M_PI
@ PCB_SHAPE_T
class PCB_SHAPE, a segment not on copper layers
Definition typeinfo.h:80
@ PCB_DIM_ORTHOGONAL_T
class PCB_DIM_ORTHOGONAL, a linear dimension constrained to x/y
Definition typeinfo.h:98
@ PCB_DIM_ALIGNED_T
class PCB_DIM_ALIGNED, a linear dimension (graphic item)
Definition typeinfo.h:94
@ PCB_PAD_T
class PAD, a pad in a footprint
Definition typeinfo.h:79
@ PCB_DIM_RADIAL_T
class PCB_DIM_RADIAL, a radius or diameter dimension
Definition typeinfo.h:97
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708
VECTOR2< double > VECTOR2D
Definition vector2d.h:707