KiCad PCB EDA Suite
Loading...
Searching...
No Matches
board_constraint_adapter.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 <iterator>
24#include <ranges>
25#include <cmath>
26#include <cstdint>
27#include <cstring>
28#include <functional>
29#include <limits>
30#include <set>
31#include <unordered_map>
32#include <unordered_set>
33
34#include <wx/debug.h>
35
36#include <board.h>
37#include <footprint.h>
38#include <geometry/seg.h>
39#include <math/util.h>
40#include <pad.h>
41#include <pcb_dimension.h>
42#include <pcb_shape.h>
43
45
46#include <GCS.h>
47
48
49// IU are nanometres; one normalized unit is one millimetre (1e6 IU). Squaring raw IU in the
50// residuals (~1e16) is badly conditioned, so the cluster is solved in this millimetre frame.
51static constexpr double IU_PER_NORM_UNIT = 1e6;
52
53// Bound the solver so an interactive drag can never stall the UI thread.
54static constexpr int MAX_SOLVE_ITERATIONS = 100;
55
56// Shares the drag and stabilize temporary subsystem kept far weaker so it only fills the null space
57// and never fights a real drive or cursor pin
58static constexpr double STAY_PUT_WEIGHT = 1e-4;
59static constexpr double CURSOR_WEIGHT = 1e-2;
60
61
63{
64 if( !aBoard )
65 return false;
66
67 if( !aBoard->Constraints().empty() )
68 return true;
69
70 return aBoard->IsFootprintHolder()
71 && std::ranges::any_of( aBoard->Footprints(),
72 []( const FOOTPRINT* aFootprint )
73 { return !aFootprint->Constraints().empty(); } );
74}
75
76
77std::vector<VECTOR2I> ConstraintPinnedPositions( BOARD* aBoard, const std::set<KIID>& aItems )
78{
79 std::vector<VECTOR2I> positions;
80
81 if( !aBoard )
82 return positions;
83
84 for( const PCB_CONSTRAINT* constraint : CollectResolvedConstraints( aBoard ) )
85 {
86 if( constraint->GetConstraintType() != PCB_CONSTRAINT_TYPE::FIXED_POSITION )
87 continue;
88
89 for( const CONSTRAINT_MEMBER& member : constraint->GetMembers() )
90 {
91 if( !aItems.contains( member.m_item ) )
92 continue;
93
94 std::optional<VECTOR2I> pos = ConstraintAnchorPosition( aBoard, member );
95
96 if( pos && std::ranges::find( positions, *pos ) == positions.end() )
97 positions.push_back( *pos );
98 }
99 }
100
101 return positions;
102}
103
104
106{
107 if( !aItem )
108 return false;
109
110 if( aItem->IsLocked() )
111 return true;
112
113 const FOOTPRINT* parent = aItem->GetParentFootprint();
114
115 return parent && parent->IsLocked();
116}
117
118
119// The footprint @p aItem moves with as one body, or nullptr inside the footprint editor where a
120// footprint's children are the geometry being edited
121static FOOTPRINT* boardFootprintOf( const BOARD_ITEM* aItem )
122{
123 FOOTPRINT* footprint = aItem ? aItem->GetParentFootprint() : nullptr;
124
125 if( !footprint )
126 return nullptr;
127
128 const BOARD* board = footprint->GetBoard();
129
130 return board && !board->IsFootprintHolder() ? footprint : nullptr;
131}
132
133
134// A board-wide pass checks members against the board's ids first since a missing id costs a full
135// board scan in BOARD::ResolveItem()
136static BOARD_ITEM* resolveMember( BOARD* aBoard, const std::unordered_set<KIID>* aOnBoard, const KIID& aId )
137{
138 if( aOnBoard && !aOnBoard->contains( aId ) )
139 return nullptr;
140
141 return aBoard->ResolveItem( aId, true );
142}
143
144
145// Constraint adjacency by member KIID plus, for each footprint on a board, links between its
146// constrained children so the whole footprint lands in one cluster
148{
149 std::unordered_map<KIID, std::vector<PCB_CONSTRAINT*>> byMember;
150 std::unordered_map<KIID, std::vector<KIID>> rigidSiblings;
151
152 bool contains( const KIID& aId ) const { return byMember.contains( aId ); }
153};
154
155
156// Adjacency from a member KIID to the constraints touching it. When @p aErrored is given, any
157// constraint that cannot be satisfied -- it has no members, or a member that does not resolve to a
158// constrainable item (a shape or dimension) -- is recorded there (error state), since such a
159// constraint never reaches the solver's per-cluster mapping where the remaining error cases are caught.
160static CONSTRAINT_GRAPH
161buildShapeConstraintMap( BOARD* aBoard, const std::vector<PCB_CONSTRAINT*>& aConstraints,
162 std::vector<KIID>* aErrored = nullptr, const std::unordered_set<KIID>* aOnBoard = nullptr )
163{
164 CONSTRAINT_GRAPH graph;
165 std::unordered_map<KIID, std::vector<PCB_CONSTRAINT*>>& map = graph.byMember;
166
167 for( PCB_CONSTRAINT* constraint : aConstraints )
168 {
169 bool errored = constraint->GetMembers().empty();
170
171 for( const CONSTRAINT_MEMBER& member : constraint->GetMembers() )
172 {
173 map[member.m_item].push_back( constraint );
174
175 // Members must resolve to a constrainable item (shape or dimension); a deleted or
176 // wrong-typed item is an error.
177 if( aErrored && !IsConstrainableItem( resolveMember( aBoard, aOnBoard, member.m_item ) ) )
178 errored = true;
179 }
180
181 if( errored && aErrored )
182 aErrored->push_back( constraint->m_Uuid );
183 }
184
185 if( aBoard->IsFootprintHolder() )
186 return graph;
187
188 // Walk footprint children rather than resolve members since a dangling member costs a full
189 // board scan in BOARD::ResolveItem()
190 for( FOOTPRINT* footprint : aBoard->Footprints() )
191 {
192 std::vector<KIID> constrained;
193
194 auto visit = [&]( const BOARD_ITEM* aChild )
195 {
196 if( map.contains( aChild->m_Uuid ) )
197 constrained.push_back( aChild->m_Uuid );
198 };
199
200 for( const BOARD_ITEM* child : footprint->GraphicalItems() )
201 visit( child );
202
203 for( const PAD* pad : footprint->Pads() )
204 visit( pad );
205
206 if( constrained.size() < 2 )
207 continue;
208
209 // A star keeps the children connected without a quadratic all-pairs link set
210 for( size_t i = 1; i < constrained.size(); ++i )
211 {
212 graph.rigidSiblings[constrained.front()].push_back( constrained[i] );
213 graph.rigidSiblings[constrained[i]].push_back( constrained.front() );
214 }
215 }
216
217 return graph;
218}
219
220
221// Walk the connected component (shapes + constraints) that contains @p aSeed. Shapes reached are
222// added to @p aVisited when provided, so a caller iterating seeds can skip an already-walked one.
224 const CONSTRAINT_GRAPH& aGraph, const KIID& aSeed,
225 std::unordered_set<KIID>& aClusterShapes, std::vector<PCB_CONSTRAINT*>& aClusterConstraints,
226 std::set<KIID>* aVisited = nullptr )
227{
228 std::set<KIID> used;
229 std::vector<KIID> frontier{ aSeed };
230 aClusterShapes.insert( aSeed );
231
232 while( !frontier.empty() )
233 {
234 KIID shapeId = frontier.back();
235 frontier.pop_back();
236
237 if( aVisited )
238 aVisited->insert( shapeId );
239
240 if( auto siblings = aGraph.rigidSiblings.find( shapeId ); siblings != aGraph.rigidSiblings.end() )
241 {
242 for( const KIID& sibling : siblings->second )
243 {
244 if( aClusterShapes.insert( sibling ).second )
245 frontier.push_back( sibling );
246 }
247 }
248
249 auto it = aGraph.byMember.find( shapeId );
250
251 if( it == aGraph.byMember.end() )
252 continue;
253
254 for( PCB_CONSTRAINT* constraint : it->second )
255 {
256 if( used.insert( constraint->m_Uuid ).second )
257 aClusterConstraints.push_back( constraint );
258
259 for( const CONSTRAINT_MEMBER& member : constraint->GetMembers() )
260 {
261 if( aClusterShapes.insert( member.m_item ).second )
262 frontier.push_back( member.m_item );
263 }
264 }
265 }
266}
267
268
269// Resolve a set of shape KIIDs to the live PCB_SHAPEs, dropping any that no longer exist.
270// Resolve a set of KIIDs to the live items of type T among them, dropping other kinds and deleted
271// items.
272template <typename T>
273static std::vector<T*> resolveClusterItems( BOARD* aBoard, const std::unordered_set<KIID>& aIds,
274 const std::unordered_set<KIID>* aOnBoard )
275{
276 std::vector<T*> items;
277
278 for( const KIID& id : aIds )
279 {
280 if( T* item = dynamic_cast<T*>( resolveMember( aBoard, aOnBoard, id ) ) )
281 items.push_back( item );
282 }
283
284 return items;
285}
286
287
288static std::vector<PCB_SHAPE*> resolveClusterShapes( BOARD* aBoard, const std::unordered_set<KIID>& aIds,
289 const std::unordered_set<KIID>* aOnBoard = nullptr )
290{
291 return resolveClusterItems<PCB_SHAPE>( aBoard, aIds, aOnBoard );
292}
293
294
295static std::vector<PCB_DIMENSION_BASE*> resolveClusterDimensions( BOARD* aBoard,
296 const std::unordered_set<KIID>& aIds,
297 const std::unordered_set<KIID>* aOnBoard = nullptr )
298{
299 return resolveClusterItems<PCB_DIMENSION_BASE>( aBoard, aIds, aOnBoard );
300}
301
302
303static std::vector<PAD*> resolveClusterPads( BOARD* aBoard, const std::unordered_set<KIID>& aIds,
304 const std::unordered_set<KIID>* aOnBoard = nullptr )
305{
306 return resolveClusterItems<PAD>( aBoard, aIds, aOnBoard );
307}
308
309
310// The stored angular value is the undirected corner angle [0, 180]; planegcs drives the directed
311// angle from l1's direction (p1->p2) to l2's. Return the directed target (radians) that realizes
312// the corner for the present geometry.
313//
314// The corner rays run from the shared vertex outward, so the vertex's endpoint parity fixes how the
315// corner maps to the directed angle: corner = |Normalize180( theta + (vB - vA) * pi )|, where vA/vB
316// are the vertex endpoint indices (0 = p1, 1 = p2). Only two directed targets realize the corner
317// for that parity, { alpha, -alpha } shifted by (vB - vA) * pi; the one nearest the current directed
318// angle keeps the configuration rather than flipping to the mirror. Considering the other parity's
319// targets too (the naive four-candidate set) would let an obtuse->acute value edit pick the stale
320// complement and no-op the solve. Not shared with the arc-sweep mapping, which is mod 2*pi.
321// A zero-length line has no direction, so its angle equation is singular; skip mapping it.
322static bool isDegenerateLine( const GCS::Line& aLine )
323{
324 return std::hypot( *aLine.p2.x - *aLine.p1.x, *aLine.p2.y - *aLine.p1.y ) < 1e-9;
325}
326
327
328static double directedAngleForCorner( const GCS::Line& aL1, const GCS::Line& aL2, double aCornerDeg )
329{
330 const double ax[2] = { *aL1.p1.x, *aL1.p2.x };
331 const double ay[2] = { *aL1.p1.y, *aL1.p2.y };
332 const double bx[2] = { *aL2.p1.x, *aL2.p2.x };
333 const double by[2] = { *aL2.p1.y, *aL2.p2.y };
334
335 int vA = 0, vB = 0;
336 double best = std::numeric_limits<double>::max();
337
338 for( int i = 0; i < 2; ++i )
339 {
340 for( int j = 0; j < 2; ++j )
341 {
342 double dist = std::hypot( ax[i] - bx[j], ay[i] - by[j] );
343
344 if( dist < best )
345 {
346 best = dist;
347 vA = i;
348 vB = j;
349 }
350 }
351 }
352
353 double d1x = ax[1] - ax[0], d1y = ay[1] - ay[0];
354 double d2x = bx[1] - bx[0], d2y = by[1] - by[0];
355 double theta = std::atan2( d1x * d2y - d1y * d2x, d1x * d2x + d1y * d2y );
356
357 // Fold to [0, pi] so a value from an out-of-range file, API, or an earlier signed-angle board
358 // still maps to a well-defined corner.
359 double alpha = std::abs( std::remainder( aCornerDeg * M_PI / 180.0, 2.0 * M_PI ) );
360 double shift = ( vB - vA ) * M_PI;
361 double c1 = alpha - shift;
362 double c2 = -alpha - shift;
363
364 double d1 = std::abs( std::remainder( theta - c1, 2.0 * M_PI ) );
365 double d2 = std::abs( std::remainder( theta - c2, 2.0 * M_PI ) );
366
367 return d1 <= d2 ? c1 : c2;
368}
369
370
371// The stored value is the unsigned swept angle; the solver constrains the endpoints' polar
372// separation endAngle - startAngle. KiCad arcs are canonically positive-sweep (SetArcGeometry
373// swaps the ends so IsClockwiseArc is always false), so the target is +alpha. Return its
374// representative (mod 2*pi) nearest the current separation, so the solver only rotates an endpoint
375// rather than jumping the param a full turn. This is the arc's own mod-2*pi mapping, deliberately
376// not the line-angle mod-pi one.
377static double arcSweepTarget( double aStartAngle, double aEndAngle, double aSweepDeg )
378{
379 double current = aEndAngle - aStartAngle;
380 double alpha = std::abs( aSweepDeg ) * M_PI / 180.0;
381
382 return current - std::remainder( current - alpha, 2.0 * M_PI );
383}
384
385
387 m_gcs( &m_system.Solver() ),
388 m_params( m_system.ParameterStorage() )
389{
390}
391
392
396
397
399{
400 return m_system.AddParameter( aValue );
401}
402
403
405{
407 m_temporaryParams.push_back( pushParam( aValue ) );
408
410 m_params[index] = aValue;
411 return index;
412}
413
414
419
420
422{
423 if( aConstraint && !aConstraint->IsDriving() )
424 m_referenceConstraints.push_back( aConstraint );
425}
426
427
428void BOARD_CONSTRAINT_ADAPTER::ApplyReferenceValues( const std::function<void( BOARD_ITEM* )>& aBeforeWrite )
429{
430 if( !m_built )
431 return;
432
433 for( PCB_CONSTRAINT* constraint : m_referenceConstraints )
434 {
435 const std::vector<CONSTRAINT_MEMBER>& members = constraint->GetMembers();
436
437 if( members.empty() )
438 continue;
439
440 auto it = m_shapeVars.find( members.front().m_item );
441
442 if( it == m_shapeVars.end() )
443 continue;
444
445 const PCB_SHAPE* shape = it->second.shape;
446 std::optional<double> value;
447 double tol = 1.0; // IU for a length/radius; degrees for an angle
448
449 // Measure from the shape geometry Apply() just wrote, not the solver param, so a settled
450 // solve re-measures the same rounded value and never churns undo.
451 switch( constraint->GetConstraintType() )
452 {
454
455 // A two-point form has no owning segment so re-measure the distance between its two
456 // member anchors from the same solved params Apply rounded from
457 if( members.size() == 2 )
458 {
459 auto anchorPos = [&]( const CONSTRAINT_MEMBER& aMember ) -> std::optional<VECTOR2I>
460 {
461 ANCHOR_PARAMS anchor = anchorParams( aMember );
462
463 if( !anchor.IsValid() )
464 return std::nullopt;
465
468 };
469
470 std::optional<VECTOR2I> pa = anchorPos( members[0] );
471 std::optional<VECTOR2I> pb = anchorPos( members[1] );
472
473 if( pa && pb )
474 {
475 // An orthogonal dimension measures one axis so re-measure that axis component
476 // an aligned or radial two-point form measures the euclidean distance instead
478 {
479 bool horizontal = ortho->GetOrientation() == PCB_DIM_ORTHOGONAL::DIR::HORIZONTAL;
480 value = horizontal ? std::abs( pb->x - pa->x ) : std::abs( pb->y - pa->y );
481 }
482 else
483 {
484 value = ( *pb - *pa ).EuclideanNorm();
485 }
486 }
487 }
488 else
489 {
490 value = ( shape->GetEnd() - shape->GetStart() ).EuclideanNorm();
491 }
492
493 break;
494
496 value = shape->GetRadius();
497 break;
498
500 {
501 if( members.size() != 2 )
502 break;
503
504 auto other = m_shapeVars.find( members[1].m_item );
505
506 if( other == m_shapeVars.end() )
507 break;
508
509 const PCB_SHAPE* shapeB = other->second.shape;
510 value = MeasureCornerAngle( SEG( shape->GetStart(), shape->GetEnd() ),
511 SEG( shapeB->GetStart(), shapeB->GetEnd() ) )
512 .AsDegrees();
513 tol = 1e-3;
514 break;
515 }
516
518 value = shape->GetArcAngle().AsDegrees();
519 tol = 1e-3;
520 break;
521
522 default:
523 break;
524 }
525
526 if( !value )
527 continue;
528
529 std::optional<double> current = constraint->GetValue();
530
531 if( current && std::abs( *value - *current ) <= tol )
532 continue;
533
534 if( aBeforeWrite )
535 aBeforeWrite( constraint );
536
537 constraint->SetValue( value );
538 }
539}
540
541
543{
544 auto it = m_shapeVars.find( aMember.m_item );
545
546 if( it == m_shapeVars.end() )
547 return {};
548
549 const SHAPE_VARS& vars = it->second;
550
551 // Segment bezier and dimension point-pair store endpoints in startX and endX while a circle or
552 // closed ellipse parks its centre in startX instead so those kinds must never alias endpoints
553 bool hasEndpoints = vars.kind == SHAPE_KIND::SEGMENT || vars.kind == SHAPE_KIND::BEZIER
554 || vars.kind == SHAPE_KIND::POINT_PAIR;
555
556 // Consecutive x and y pair for these kinds
557 auto pairAt = []( int aXIndex ) -> ANCHOR_PARAMS
558 {
559 return aXIndex >= 0 ? ANCHOR_PARAMS{ aXIndex, aXIndex + 1 } : ANCHOR_PARAMS();
560 };
561
562 // A rect exposes only its four indexed corners each an alias over a mixed start and end pair so
563 // START END and CENTER never resolve indices 0 to 3 follow the canonical TL TR BR BL order
564 if( vars.kind == SHAPE_KIND::RECTANGLE )
565 {
566 if( aMember.m_anchor != CONSTRAINT_ANCHOR::VERTEX || aMember.m_index < 0 || aMember.m_index > 3 )
567 return {};
568
569 int leftX = vars.startIsLeft ? vars.startX : vars.endX;
570 int rightX = vars.startIsLeft ? vars.endX : vars.startX;
571 int topY = ( vars.startIsTop ? vars.startX : vars.endX ) + 1;
572 int botY = ( vars.startIsTop ? vars.endX : vars.startX ) + 1;
573
574 switch( aMember.m_index )
575 {
576 case 0: return { leftX, topY };
577 case 1: return { rightX, topY };
578 case 2: return { rightX, botY };
579 default: return { leftX, botY };
580 }
581 }
582
583 // A polygon exposes only its indexed outline-0 vertices each a consecutive pair at
584 // startX plus 2 times index a stale index from a shrunk outline resolves to nothing
585 if( vars.kind == SHAPE_KIND::POLYGON )
586 {
587 if( aMember.m_anchor != CONSTRAINT_ANCHOR::VERTEX || aMember.m_index < 0
588 || aMember.m_index >= vars.vertexCount )
589 {
590 return {};
591 }
592
593 return pairAt( vars.startX + 2 * aMember.m_index );
594 }
595
596 switch( aMember.m_anchor )
597 {
599 if( vars.kind == SHAPE_KIND::ARC || vars.kind == SHAPE_KIND::ELLIPSE_ARC )
600 return pairAt( vars.arcStartX );
601
602 return hasEndpoints ? pairAt( vars.startX ) : ANCHOR_PARAMS();
604 if( vars.kind == SHAPE_KIND::ARC || vars.kind == SHAPE_KIND::ELLIPSE_ARC )
605 return pairAt( vars.arcEndX );
606
607 return hasEndpoints ? pairAt( vars.endX ) : ANCHOR_PARAMS();
608 case CONSTRAINT_ANCHOR::CENTER: return hasEndpoints ? ANCHOR_PARAMS() : pairAt( vars.startX );
609 default: return {};
610 }
611}
612
613
615BOARD_CONSTRAINT_ADAPTER::orthogonalDimensionForMembers( const std::vector<CONSTRAINT_MEMBER>& aMembers ) const
616{
617 if( aMembers.size() != 2 || aMembers[0].m_item != aMembers[1].m_item )
618 return nullptr;
619
620 const CONSTRAINT_ANCHOR a0 = aMembers[0].m_anchor;
621 const CONSTRAINT_ANCHOR a1 = aMembers[1].m_anchor;
622
623 const bool startEnd = ( a0 == CONSTRAINT_ANCHOR::START && a1 == CONSTRAINT_ANCHOR::END )
625
626 if( !startEnd )
627 return nullptr;
628
629 auto it = m_shapeVars.find( aMembers[0].m_item );
630
631 if( it == m_shapeVars.end() || it->second.kind != SHAPE_KIND::POINT_PAIR || !it->second.dimension
632 || it->second.dimension->Type() != PCB_DIM_ORTHOGONAL_T )
633 {
634 return nullptr;
635 }
636
637 return static_cast<PCB_DIM_ORTHOGONAL*>( it->second.dimension );
638}
639
640
641bool BOARD_CONSTRAINT_ADAPTER::Build( const std::vector<PCB_SHAPE*>& aShapes,
642 const std::vector<PCB_CONSTRAINT*>& aConstraints,
643 const std::set<KIID>* aFixedShapes,
644 const std::vector<PCB_DIMENSION_BASE*>& aDimensions,
645 const std::vector<PAD*>& aPads )
646{
647 m_system.Clear();
648 m_shapeVars.clear();
649 m_rigidFootprints.clear();
650 m_rigidMembers.clear();
651 m_tagToConstraint.clear();
652 m_droppedTags.clear();
653 m_nonDrivingTags.clear();
654 m_tagMembers.clear();
656 m_unmapped.clear();
658 m_built = false;
659
660 // The temporary-parameter pool aliases indices into the parameter store just cleared above.
661 // Rebuilding without resetting it would hand out stale indices past the new store's end.
662 m_temporaryParams.clear();
664
665 if( aShapes.empty() && aDimensions.empty() && aPads.empty() )
666 return false;
667
668 // Centre on the first item's start point so normalized coordinates stay small for a board far
669 // from the origin.
670 VECTOR2I origin = !aShapes.empty() ? aShapes.front()->GetStart()
671 : !aDimensions.empty() ? aDimensions.front()->GetStart()
672 : aPads.front()->GetPosition();
674 m_invScale = 1.0 / m_scale;
675 m_system.SetCoordinateFrame( origin, m_scale );
676
677 // [first, last) parameter spans of locked shapes, folded into fixedParams below so the solver
678 // treats a locked shape as an immovable reference.
679 std::vector<std::pair<int, int>> lockedRanges;
680
681 // Fixed focus-offset params of ellipses, folded into fixedParams below.
682 std::vector<int> ellipseOffsetParams;
683
684 for( PCB_SHAPE* shape : aShapes )
685 {
686 SHAPE_VARS vars;
687 vars.shape = shape;
688 int firstParam = static_cast<int>( m_params.size() );
689
690 if( shape->GetShape() == SHAPE_T::SEGMENT )
691 {
693 vars.startX = pushParam( normalizeX( shape->GetStart().x ) );
694 pushParam( normalizeY( shape->GetStart().y ) );
695 vars.endX = pushParam( normalizeX( shape->GetEnd().x ) );
696 pushParam( normalizeY( shape->GetEnd().y ) );
697 }
698 else if( shape->GetShape() == SHAPE_T::RECTANGLE )
699 {
700 // Only the two stored corners are params the four VERTEX corners alias mixed pairs of
701 // them through anchorParams so rectness can never be violated corner roles frozen here
703 vars.startIsLeft = shape->GetStart().x <= shape->GetEnd().x;
704 vars.startIsTop = shape->GetStart().y <= shape->GetEnd().y;
705 vars.startX = pushParam( normalizeX( shape->GetStart().x ) );
706 pushParam( normalizeY( shape->GetStart().y ) );
707 vars.endX = pushParam( normalizeX( shape->GetEnd().x ) );
708 pushParam( normalizeY( shape->GetEnd().y ) );
709 }
710 else if( shape->GetShape() == SHAPE_T::POLY )
711 {
712 // Only a single hole-free arc-free outline is modeled since write-back rebuilds one
713 // outline and would destroy anything else so other polys are skipped and read unmapped
714 if( !ConstraintPolygonIsModelable( shape ) )
715 continue;
716
717 const SHAPE_LINE_CHAIN& outline = shape->GetPolyShape().COutline( 0 );
718
720 vars.vertexCount = outline.PointCount();
721 vars.startX = pushParam( normalizeX( outline.CPoint( 0 ).x ) );
722 pushParam( normalizeY( outline.CPoint( 0 ).y ) );
723
724 for( int i = 1; i < outline.PointCount(); ++i )
725 {
726 pushParam( normalizeX( outline.CPoint( i ).x ) );
727 pushParam( normalizeY( outline.CPoint( i ).y ) );
728 }
729 }
730 else if( shape->GetShape() == SHAPE_T::BEZIER )
731 {
732 // Only the endpoints participate in the solve the control handles are not solver
733 // variables and follow their adjacent endpoint in Apply
735 vars.startX = pushParam( normalizeX( shape->GetStart().x ) );
736 pushParam( normalizeY( shape->GetStart().y ) );
737 vars.endX = pushParam( normalizeX( shape->GetEnd().x ) );
738 pushParam( normalizeY( shape->GetEnd().y ) );
739 }
740 else if( shape->GetShape() == SHAPE_T::CIRCLE )
741 {
743 vars.startX = pushParam( normalizeX( shape->GetCenter().x ) );
744 pushParam( normalizeY( shape->GetCenter().y ) );
745 vars.radius = pushParam( shape->GetRadius() * m_invScale );
746 }
747 else if( shape->GetShape() == SHAPE_T::ARC )
748 {
749 vars.kind = SHAPE_KIND::ARC;
750
751 VECTOR2I center = shape->GetCenter();
752 VECTOR2I start = shape->GetStart();
753 VECTOR2I end = shape->GetEnd();
754
755 double cx = normalizeX( center.x );
756 double cy = normalizeY( center.y );
757 double sx = normalizeX( start.x );
758 double sy = normalizeY( start.y );
759 double ex = normalizeX( end.x );
760 double ey = normalizeY( end.y );
761
762 vars.startX = pushParam( cx );
763 pushParam( cy );
764 vars.radius = pushParam( shape->GetRadius() * m_invScale );
765 vars.arcStartX = pushParam( sx );
766 pushParam( sy );
767 vars.arcEndX = pushParam( ex );
768 pushParam( ey );
769 vars.startAngle = pushParam( std::atan2( sy - cy, sx - cx ) );
770 vars.endAngle = pushParam( std::atan2( ey - cy, ex - cx ) );
771
772 GCS::Arc arc;
773 arc.center = GCS::Point{ &m_params[vars.startX], &m_params[vars.startX + 1] };
774 arc.rad = &m_params[vars.radius];
775 arc.start = GCS::Point{ &m_params[vars.arcStartX], &m_params[vars.arcStartX + 1] };
776 arc.end = GCS::Point{ &m_params[vars.arcEndX], &m_params[vars.arcEndX + 1] };
777 arc.startAngle = &m_params[vars.startAngle];
778 arc.endAngle = &m_params[vars.endAngle];
779 m_gcs->addConstraintArcRules( arc );
780 }
781 else if( shape->GetShape() == SHAPE_T::ELLIPSE || shape->GetShape() == SHAPE_T::ELLIPSE_ARC )
782 {
784
785 VECTOR2I center = shape->GetEllipseCenter();
786 double major = shape->GetEllipseMajorRadius();
787 double minor = shape->GetEllipseMinorRadius();
788 double phi = shape->GetEllipseRotation().AsRadians();
789 EDA_ANGLE startAngle = shape->GetEllipseStartAngle();
790 EDA_ANGLE endAngle = shape->GetEllipseEndAngle();
791
792 if( minor > major )
793 {
794 std::swap( major, minor );
795 phi += M_PI / 2;
796 startAngle -= ANGLE_90;
797 endAngle -= ANGLE_90;
798 }
799
800 // GCS parameterizes an ellipse as center + first focus + minor radius.
801 double focal = std::sqrt( major * major - minor * minor );
802 double cx = normalizeX( center.x );
803 double cy = normalizeY( center.y );
804
805 vars.startX = pushParam( cx );
806 pushParam( cy );
807 vars.focusX = pushParam( cx + focal * m_invScale * std::cos( phi ) );
808 pushParam( cy + focal * m_invScale * std::sin( phi ) );
809 vars.radius = pushParam( minor * m_invScale );
810
811 // Tie the focus to the center, or a solve moving the center would leave the focus
812 // behind and distort the ellipse.
813 int offX = pushParam( focal * m_invScale * std::cos( phi ) );
814 int offY = pushParam( focal * m_invScale * std::sin( phi ) );
815 ellipseOffsetParams.push_back( offX );
816 ellipseOffsetParams.push_back( offY );
817
818 m_gcs->addConstraintDifference( &m_params[vars.startX], &m_params[vars.focusX], &m_params[offX] );
819 m_gcs->addConstraintDifference( &m_params[vars.startX + 1], &m_params[vars.focusX + 1], &m_params[offY] );
820
821 if( vars.kind == SHAPE_KIND::ELLIPSE_ARC )
822 {
823 VECTOR2I start = shape->GetStart();
824 VECTOR2I end = shape->GetEnd();
825
826 vars.arcStartX = pushParam( normalizeX( start.x ) );
827 pushParam( normalizeY( start.y ) );
828 vars.arcEndX = pushParam( normalizeX( end.x ) );
829 pushParam( normalizeY( end.y ) );
830 vars.startAngle = pushParam( startAngle.AsRadians() );
831 vars.endAngle = pushParam( endAngle.AsRadians() );
832
833 GCS::ArcOfEllipse arc;
834 arc.center = GCS::Point{ &m_params[vars.startX], &m_params[vars.startX + 1] };
835 arc.focus1 = GCS::Point{ &m_params[vars.focusX], &m_params[vars.focusX + 1] };
836 arc.radmin = &m_params[vars.radius];
837 arc.start = GCS::Point{ &m_params[vars.arcStartX], &m_params[vars.arcStartX + 1] };
838 arc.end = GCS::Point{ &m_params[vars.arcEndX], &m_params[vars.arcEndX + 1] };
839 arc.startAngle = &m_params[vars.startAngle];
840 arc.endAngle = &m_params[vars.endAngle];
841 m_gcs->addConstraintArcOfEllipseRules( arc );
842 }
843 }
844 else
845 {
846 continue; // other shapes are not mapped
847 }
848
849 // Freeze a locked or caller-pinned shape's whole span so the solver moves only the rest of
850 // the cluster.
851 if( ConstraintItemIsLocked( shape ) || ( aFixedShapes && aFixedShapes->count( shape->m_Uuid ) ) )
852 lockedRanges.emplace_back( firstParam, static_cast<int>( m_params.size() ) );
853
854 m_shapeVars[shape->m_Uuid] = vars;
855 }
856
857 // Each dimension contributes its two feature points, so a coincident constraint can pull the
858 // dimension along with the shape it is bound to.
859 for( PCB_DIMENSION_BASE* dimension : aDimensions )
860 {
861 SHAPE_VARS vars;
863 vars.dimension = dimension;
864 vars.startX = pushParam( normalizeX( dimension->GetStart().x ) );
865 pushParam( normalizeY( dimension->GetStart().y ) );
866
867 // Only aligned/orthogonal/radial dimensions have a second feature point; a leader or centre
868 // mark's end is a control point, so it is never a bindable anchor (endX stays -1).
869 switch( dimension->Type() )
870 {
873 case PCB_DIM_RADIAL_T:
874 vars.endX = pushParam( normalizeX( dimension->GetEnd().x ) );
875 pushParam( normalizeY( dimension->GetEnd().y ) );
876 break;
877
878 default:
879 break;
880 }
881
882 m_shapeVars[dimension->m_Uuid] = vars;
883 }
884
885 for( PAD* pad : aPads )
886 {
887 SHAPE_VARS vars;
889 vars.pad = pad;
890 vars.startX = pushParam( normalizeX( pad->GetPosition().x ) );
891 pushParam( normalizeY( pad->GetPosition().y ) );
892 m_shapeVars[pad->m_Uuid] = vars;
893 }
894
895 // Params the solver may not change. Grounded points, driving constants (lengths, radii) and
896 // locked-shape params go here; everything else stays an unknown.
897 std::set<int> fixedParams;
898
899 // Of those, the ones a FIXED_POSITION constraint nails down, kept apart because a block
900 // edit is allowed to place a locked shape but never a point the user pinned
901 std::set<int> groundedPositions;
902
903 for( const auto& [first, last] : lockedRanges )
904 {
905 for( int i = first; i < last; ++i )
906 fixedParams.insert( i );
907 }
908
909 for( int i : ellipseOffsetParams )
910 fixedParams.insert( i );
911
912 std::set<FOOTPRINT*> rigidFootprints;
913
914 for( const auto& [kiid, vars] : m_shapeVars )
915 {
916 if( FOOTPRINT* footprint = boardFootprintOf( itemOf( vars ) ) )
917 rigidFootprints.insert( footprint );
918 }
919
920 coupleRigidFootprints( rigidFootprints, aFixedShapes, fixedParams );
921
922 auto pointAt = [&]( int aXIndex ) -> GCS::Point
923 {
924 return GCS::Point{ &m_params[aXIndex], &m_params[aXIndex + 1] };
925 };
926
927 // Anchor x and y need not be consecutive since a rect corner aliases mixed start end params
928 // pointAt stays for SHAPE_VARS internal consecutive pairs
929 auto pointFor = [&]( const ANCHOR_PARAMS& aParams ) -> GCS::Point
930 {
931 return GCS::Point{ &m_params[aParams.x], &m_params[aParams.y] };
932 };
933
934 auto lineFor = [&]( const CONSTRAINT_MEMBER& aMember, GCS::Line& aLine ) -> bool
935 {
936 auto it = m_shapeVars.find( aMember.m_item );
937
938 if( it == m_shapeVars.end() || it->second.kind != SHAPE_KIND::SEGMENT
939 || aMember.m_anchor != CONSTRAINT_ANCHOR::WHOLE )
940 {
941 return false;
942 }
943
944 aLine.p1 = pointAt( it->second.startX );
945 aLine.p2 = pointAt( it->second.endX );
946 return true;
947 };
948
949 // A circle for radial constraints; an arc is accepted too (its center + radius are shared
950 // with the Circle base, which is all addConstraintEqualRadius/CircleRadius/concentric need).
951 auto circleFor = [&]( const CONSTRAINT_MEMBER& aMember, GCS::Circle& aCircle ) -> bool
952 {
953 auto it = m_shapeVars.find( aMember.m_item );
954
955 if( it == m_shapeVars.end()
956 || ( it->second.kind != SHAPE_KIND::CIRCLE && it->second.kind != SHAPE_KIND::ARC ) )
957 {
958 return false;
959 }
960
961 aCircle.center = pointAt( it->second.startX );
962 aCircle.rad = &m_params[it->second.radius];
963 return true;
964 };
965
966 // An ellipse for ellipse-target constraints; an elliptical arc is accepted too (its center,
967 // focus and minor radius are shared with the Ellipse base).
968 auto ellipseFor = [&]( const CONSTRAINT_MEMBER& aMember, GCS::Ellipse& aEllipse ) -> bool
969 {
970 auto it = m_shapeVars.find( aMember.m_item );
971
972 if( it == m_shapeVars.end()
973 || ( it->second.kind != SHAPE_KIND::ELLIPSE && it->second.kind != SHAPE_KIND::ELLIPSE_ARC ) )
974 {
975 return false;
976 }
977
978 aEllipse.center = pointAt( it->second.startX );
979 aEllipse.focus1 = pointAt( it->second.focusX );
980 aEllipse.radmin = &m_params[it->second.radius];
981 return true;
982 };
983
984 // Push a driving constant (length/radius), normalized from IU, returning its stable index.
985 auto pushConstant = [&]( double aIU ) -> int
986 {
987 int idx = pushParam( aIU * m_invScale );
988 fixedParams.insert( idx );
989 return idx;
990 };
991
992 int tag = 1;
993
994 for( PCB_CONSTRAINT* constraint : aConstraints )
995 {
996 const std::vector<CONSTRAINT_MEMBER>& members = constraint->GetMembers();
997 bool mapped = false;
998
999 switch( constraint->GetConstraintType() )
1000 {
1002 {
1003 GCS::Line l1, l2;
1004
1005 if( members.size() == 2 && lineFor( members[0], l1 ) && lineFor( members[1], l2 ) )
1006 {
1007 m_gcs->addConstraintParallel( l1, l2, tag );
1008 mapped = true;
1009 }
1010
1011 break;
1012 }
1013
1015 {
1016 // One whole segment aligns its own two endpoints while two point anchors align the pair
1017 // the user picked so a corner can be leveled without a segment between the points
1018 if( members.size() == 1 )
1019 {
1020 GCS::Line l;
1021
1022 if( lineFor( members[0], l ) )
1023 {
1024 m_gcs->addConstraintHorizontal( l, tag );
1025 mapped = true;
1026 }
1027 }
1028 else if( members.size() == 2 )
1029 {
1030 ANCHOR_PARAMS a = anchorParams( members[0] );
1031 ANCHOR_PARAMS b = anchorParams( members[1] );
1032
1033 if( a.IsValid() && b.IsValid() )
1034 {
1035 GCS::Point p1 = pointFor( a );
1036 GCS::Point p2 = pointFor( b );
1037 m_gcs->addConstraintHorizontal( p1, p2, tag );
1038 mapped = true;
1039 }
1040 }
1041
1042 break;
1043 }
1044
1046 {
1047 if( members.size() == 1 )
1048 {
1049 GCS::Line l;
1050
1051 if( lineFor( members[0], l ) )
1052 {
1053 m_gcs->addConstraintVertical( l, tag );
1054 mapped = true;
1055 }
1056 }
1057 else if( members.size() == 2 )
1058 {
1059 ANCHOR_PARAMS a = anchorParams( members[0] );
1060 ANCHOR_PARAMS b = anchorParams( members[1] );
1061
1062 if( a.IsValid() && b.IsValid() )
1063 {
1064 GCS::Point p1 = pointFor( a );
1065 GCS::Point p2 = pointFor( b );
1066 m_gcs->addConstraintVertical( p1, p2, tag );
1067 mapped = true;
1068 }
1069 }
1070
1071 break;
1072 }
1073
1075 {
1076 ANCHOR_PARAMS a = members.size() == 2 ? anchorParams( members[0] ) : ANCHOR_PARAMS();
1077 ANCHOR_PARAMS b = members.size() == 2 ? anchorParams( members[1] ) : ANCHOR_PARAMS();
1078
1079 if( a.IsValid() && b.IsValid() )
1080 {
1081 GCS::Point p1 = pointFor( a );
1082 GCS::Point p2 = pointFor( b );
1083 m_gcs->addConstraintP2PCoincident( p1, p2, tag );
1084 mapped = true;
1085 }
1086
1087 break;
1088 }
1089
1091 {
1092 ANCHOR_PARAMS a = members.size() == 1 ? anchorParams( members[0] ) : ANCHOR_PARAMS();
1093
1094 if( a.IsValid() )
1095 {
1096 fixedParams.insert( a.x );
1097 fixedParams.insert( a.y );
1098 groundedPositions.insert( a.x );
1099 groundedPositions.insert( a.y );
1100 mapped = true; // enforced by omission from the unknowns, not a solver constraint
1101 }
1102
1103 break;
1104 }
1105
1107 {
1108 GCS::Line l1, l2;
1109
1110 if( members.size() == 2 && lineFor( members[0], l1 ) && lineFor( members[1], l2 ) )
1111 {
1112 m_gcs->addConstraintPerpendicular( l1, l2, tag );
1113 mapped = true;
1114 }
1115
1116 break;
1117 }
1118
1120 {
1121 GCS::Line l1, l2;
1122
1123 if( members.size() == 2 && lineFor( members[0], l1 ) && lineFor( members[1], l2 ) )
1124 {
1125 m_gcs->addConstraintEqualLength( l1, l2, tag );
1126 mapped = true;
1127 }
1128
1129 break;
1130 }
1131
1133 {
1134 ANCHOR_PARAMS p = members.size() == 2 ? anchorParams( members[0] ) : ANCHOR_PARAMS();
1135 GCS::Line l;
1136 GCS::Circle circ;
1137 GCS::Ellipse ell;
1138
1139 if( p.IsValid() && lineFor( members[1], l ) )
1140 {
1141 GCS::Point point = pointFor( p );
1142 m_gcs->addConstraintPointOnLine( point, l, tag );
1143 mapped = true;
1144 }
1145 else if( p.IsValid() && circleFor( members[1], circ ) )
1146 {
1147 // A circle or arc target keeps the point on its circumference.
1148 GCS::Point point = pointFor( p );
1149 m_gcs->addConstraintPointOnCircle( point, circ, tag );
1150 mapped = true;
1151 }
1152 else if( p.IsValid() && ellipseFor( members[1], ell ) )
1153 {
1154 GCS::Point point = pointFor( p );
1155 m_gcs->addConstraintPointOnEllipse( point, ell, tag );
1156 mapped = true;
1157 }
1158
1159 break;
1160 }
1161
1163 {
1164 ANCHOR_PARAMS p = members.size() == 2 ? anchorParams( members[0] ) : ANCHOR_PARAMS();
1165 GCS::Line seg;
1166
1167 // A midpoint constraint is the segment's endpoints being symmetric about the point.
1168 if( p.IsValid() && lineFor( members[1], seg ) )
1169 {
1170 GCS::Point mid = pointFor( p );
1171 m_gcs->addConstraintP2PSymmetric( seg.p1, seg.p2, mid, tag );
1172 mapped = true;
1173 }
1174
1175 break;
1176 }
1177
1179 {
1180 GCS::Line l1, l2;
1181
1182 // Both endpoints of the second segment lie on the first's supporting line.
1183 if( members.size() == 2 && lineFor( members[0], l1 ) && lineFor( members[1], l2 ) )
1184 {
1185 m_gcs->addConstraintPointOnLine( l2.p1, l1, tag );
1186 m_gcs->addConstraintPointOnLine( l2.p2, l1, tag );
1187 mapped = true;
1188 }
1189
1190 break;
1191 }
1192
1194 {
1195 ANCHOR_PARAMS a = members.size() == 3 ? anchorParams( members[0] ) : ANCHOR_PARAMS();
1196 ANCHOR_PARAMS b = members.size() == 3 ? anchorParams( members[1] ) : ANCHOR_PARAMS();
1197 GCS::Line axis;
1198
1199 if( a.IsValid() && b.IsValid() && lineFor( members[2], axis ) )
1200 {
1201 GCS::Point pa = pointFor( a );
1202 GCS::Point pb = pointFor( b );
1203 m_gcs->addConstraintP2PSymmetric( pa, pb, axis, tag );
1204 mapped = true;
1205 }
1206
1207 break;
1208 }
1209
1211 {
1212 GCS::Line l;
1213
1214 if( members.size() == 1 && constraint->HasValue() && lineFor( members[0], l ) )
1215 {
1216 int len = pushConstant( *constraint->GetValue() );
1217 m_gcs->addConstraintP2PDistance( l.p1, l.p2, &m_params[len], tag, constraint->IsDriving() );
1218 recordReferenceValue( constraint );
1219
1220 if( constraint->IsDriving() )
1221 {
1222 if( auto it = m_shapeVars.find( members[0].m_item ); it != m_shapeVars.end() )
1223 it->second.fixedLengthParam = len;
1224 }
1225
1226 mapped = true;
1227 }
1228 // Two point anchors fix the distance between them with no segment between so a driving
1229 // aligned dimension can drive its own endpoints and the geometry coincident with them
1230 else if( members.size() == 2 && constraint->HasValue() )
1231 {
1232 ANCHOR_PARAMS a = anchorParams( members[0] );
1233 ANCHOR_PARAMS b = anchorParams( members[1] );
1234
1235 if( a.IsValid() && b.IsValid() )
1236 {
1238
1239 if( ortho )
1240 {
1241 // An orthogonal dimension measures one axis so the driving length fixes that
1242 // axis and matches updateGeometry sign convention keeping the current side
1243 bool horiz = ortho->GetOrientation() == PCB_DIM_ORTHOGONAL::DIR::HORIZONTAL;
1244 int aAxis = horiz ? a.x : a.y;
1245 int bAxis = horiz ? b.x : b.y;
1246 double gap = m_params[bAxis] - m_params[aAxis];
1247 double sign = gap >= 0.0 ? 1.0 : -1.0;
1248 int len = pushConstant( sign * *constraint->GetValue() );
1249
1250 m_gcs->addConstraintDifference( &m_params[aAxis], &m_params[bAxis],
1251 &m_params[len], tag, constraint->IsDriving() );
1252 }
1253 else
1254 {
1255 GCS::Point pa = pointFor( a );
1256 GCS::Point pb = pointFor( b );
1257 int len = pushConstant( *constraint->GetValue() );
1258 m_gcs->addConstraintP2PDistance( pa, pb, &m_params[len], tag,
1259 constraint->IsDriving() );
1260 }
1261
1262 recordReferenceValue( constraint );
1263 mapped = true;
1264 }
1265 }
1266
1267 break;
1268 }
1269
1271 {
1272 GCS::Circle c;
1273
1274 if( members.size() == 1 && constraint->HasValue() && circleFor( members[0], c ) )
1275 {
1276 int rad = pushConstant( *constraint->GetValue() );
1277 m_gcs->addConstraintCircleRadius( c, &m_params[rad], tag, constraint->IsDriving() );
1278 recordReferenceValue( constraint );
1279 mapped = true;
1280 }
1281
1282 break;
1283 }
1284
1286 {
1287 GCS::Circle c1, c2;
1288
1289 if( members.size() == 2 && circleFor( members[0], c1 ) && circleFor( members[1], c2 ) )
1290 {
1291 m_gcs->addConstraintEqualRadius( c1, c2, tag );
1292 mapped = true;
1293 }
1294
1295 break;
1296 }
1297
1299 {
1300 // Any center-bearing shape can be concentric, ellipses included.
1301 auto centerOf = [&]( const CONSTRAINT_MEMBER& aMember, GCS::Point& aOut ) -> bool
1302 {
1303 GCS::Circle c;
1304 GCS::Ellipse e;
1305
1306 if( circleFor( aMember, c ) )
1307 {
1308 aOut = c.center;
1309 return true;
1310 }
1311
1312 if( ellipseFor( aMember, e ) )
1313 {
1314 aOut = e.center;
1315 return true;
1316 }
1317
1318 return false;
1319 };
1320
1321 GCS::Point p1, p2;
1322
1323 if( members.size() == 2 && centerOf( members[0], p1 ) && centerOf( members[1], p2 ) )
1324 {
1325 m_gcs->addConstraintP2PCoincident( p1, p2, tag );
1326 mapped = true;
1327 }
1328
1329 break;
1330 }
1331
1333 {
1334 GCS::Line l1, l2;
1335
1336 if( members.size() == 2 && constraint->HasValue() && lineFor( members[0], l1 )
1337 && lineFor( members[1], l2 ) && !isDegenerateLine( l1 ) && !isDegenerateLine( l2 ) )
1338 {
1339 int angle = pushParam( directedAngleForCorner( l1, l2, *constraint->GetValue() ) );
1340 fixedParams.insert( angle );
1341 m_gcs->addConstraintL2LAngle( l1, l2, &m_params[angle], tag, constraint->IsDriving() );
1342 recordReferenceValue( constraint );
1343 mapped = true;
1344 }
1345
1346 break;
1347 }
1348
1350 {
1351 auto vit = members.size() == 1 ? m_shapeVars.find( members[0].m_item ) : m_shapeVars.end();
1352
1353 // A value outside (0, 360) is a degenerate sweep (from a corrupt file or the API); leave
1354 // it unmapped so it reads as errored rather than merging the endpoints.
1355 bool validSweep = constraint->HasValue() && *constraint->GetValue() > 0.0
1356 && *constraint->GetValue() < 360.0;
1357
1358 if( vit != m_shapeVars.end() && vit->second.kind == SHAPE_KIND::ARC && validSweep )
1359 {
1360 const SHAPE_VARS& vars = vit->second;
1361 double target = arcSweepTarget( m_params[vars.startAngle], m_params[vars.endAngle],
1362 *constraint->GetValue() );
1363 int tgt = pushParam( target );
1364 fixedParams.insert( tgt );
1365 m_gcs->addConstraintDifference( &m_params[vars.startAngle], &m_params[vars.endAngle],
1366 &m_params[tgt], tag, constraint->IsDriving() );
1367 recordReferenceValue( constraint );
1368 mapped = true;
1369 }
1370
1371 break;
1372 }
1373
1375 {
1376 if( members.size() != 2 )
1377 break;
1378
1379 GCS::Line l;
1380 GCS::Circle c1, c2;
1381 GCS::Ellipse ell;
1382
1383 // The members may come in either order.
1384 int lineIdx = lineFor( members[0], l ) ? 0 : ( lineFor( members[1], l ) ? 1 : -1 );
1385
1386 if( lineIdx >= 0 )
1387 {
1388 const CONSTRAINT_MEMBER& other = members[lineIdx == 0 ? 1 : 0];
1389
1390 if( circleFor( other, c1 ) )
1391 {
1392 // Keep the circle on the side of the line it is on now.
1393 double dx = *l.p2.x - *l.p1.x;
1394 double dy = *l.p2.y - *l.p1.y;
1395 double cross = dx * ( *c1.center.y - *l.p1.y ) - dy * ( *c1.center.x - *l.p1.x );
1396
1397 m_gcs->addConstraintTangent( l, c1, cross > 0.0, tag );
1398 mapped = true;
1399 }
1400 else if( ellipseFor( other, ell ) )
1401 {
1402 m_gcs->addConstraintTangent( l, ell, tag );
1403 mapped = true;
1404 }
1405 }
1406 else if( circleFor( members[0], c1 ) && circleFor( members[1], c2 ) )
1407 {
1408 m_gcs->addConstraintTangent( c1, c2, tag );
1409 mapped = true;
1410 }
1411
1412 break;
1413 }
1414
1415 default:
1416 break; // UNDEFINED and point-anchored families handled elsewhere
1417 }
1418
1419 // An unmappable constraint (wrong member count/kind for its type) is skipped so it cannot
1420 // disable solving for the whole connected cluster; the remaining constraints still solve.
1421 // It is recorded so the caller can flag it as errored rather than dropping it silently.
1422 if( !mapped )
1423 {
1424 m_unmapped.push_back( constraint->m_Uuid );
1425 continue;
1426 }
1427
1428 // A fixed position is enforced by grounding, not by a solver constraint
1429 if( constraint->GetConstraintType() != PCB_CONSTRAINT_TYPE::FIXED_POSITION )
1430 m_tagToConstraint[tag] = constraint->m_Uuid;
1431
1432 if( !constraint->IsDriving() )
1433 m_nonDrivingTags.insert( tag );
1434
1435 for( const CONSTRAINT_MEMBER& member : constraint->GetMembers() )
1436 m_tagMembers[tag].push_back( member.m_item );
1437
1438 // Remember shapes a direction or angle constraint could shrink to a point so the stabilize
1439 // solve length-holds just those and leaves dragged-along neighbours free to grow
1440 switch( constraint->GetConstraintType() )
1441 {
1444
1445 // The two-point form aligns loose anchors not the owning segments lengths so only the
1446 // whole-segment form marks its member for the length-hold stabilization
1447 if( constraint->GetMembers().size() != 1 )
1448 break;
1449
1450 [[fallthrough]];
1451
1457 for( const CONSTRAINT_MEMBER& member : constraint->GetMembers() )
1458 m_angleConstrainedShapes.insert( member.m_item );
1459
1460 break;
1461
1462 default:
1463 break;
1464 }
1465
1466 tag++;
1467 }
1468
1469 // Reserve the hold tags just past the mapped constraints, so they can never collide with a
1470 // real constraint's tag however large the cluster grows.
1471 m_lengthHoldTag = tag;
1472 m_resizeRadiusTag = tag + 1;
1473
1474 // Ground each dimension endpoint no mapped constraint bound, so an attached dimension adds zero
1475 // free DOF and only its bound point can move (through the shape it is coincident with). A locked
1476 // dimension is grounded whole, like a locked shape.
1477 std::set<KIID> unmappedConstraints( m_unmapped.begin(), m_unmapped.end() );
1478 std::set<int> referencedDimParams;
1479
1480 for( PCB_CONSTRAINT* constraint : aConstraints )
1481 {
1482 if( unmappedConstraints.contains( constraint->m_Uuid ) )
1483 continue; // an unmapped constraint enforces nothing, so it references no param
1484
1485 for( const CONSTRAINT_MEMBER& member : constraint->GetMembers() )
1486 {
1487 auto it = m_shapeVars.find( member.m_item );
1488
1489 if( it != m_shapeVars.end() && it->second.kind == SHAPE_KIND::POINT_PAIR )
1490 {
1491 if( ANCHOR_PARAMS anchor = anchorParams( member ); anchor.IsValid() )
1492 referencedDimParams.insert( anchor.x );
1493 }
1494 }
1495 }
1496
1497 for( const auto& [kiid, vars] : m_shapeVars )
1498 {
1499 if( vars.kind == SHAPE_KIND::PAD_CENTER && !m_rigidMembers.contains( kiid ) )
1500 {
1501 fixedParams.insert( vars.startX );
1502 fixedParams.insert( vars.startX + 1 );
1503 continue;
1504 }
1505
1506 // A rigid footprint's dimension travels with the footprint instead of staying grounded
1507 if( vars.kind != SHAPE_KIND::POINT_PAIR || m_rigidMembers.contains( kiid ) )
1508 continue;
1509
1510 bool locked = ConstraintItemIsLocked( vars.dimension );
1511
1512 for( int pointX : { vars.startX, vars.endX } )
1513 {
1514 if( pointX >= 0 && ( locked || !referencedDimParams.contains( pointX ) ) )
1515 {
1516 fixedParams.insert( pointX );
1517 fixedParams.insert( pointX + 1 );
1518 }
1519 }
1520 }
1521
1522 // Everything not grounded or held as a driving constant is an unknown the solver may move.
1523 GCS::VEC_pD unknowns;
1524
1525 for( int i = 0; i < static_cast<int>( m_params.size() ); ++i )
1526 {
1527 if( !fixedParams.contains( i ) )
1528 unknowns.push_back( &m_params[i] );
1529 }
1530
1531 m_fixedParams = fixedParams;
1532 m_groundedPositionParams = groundedPositions;
1533 m_gcs->declareUnknowns( unknowns );
1534 m_gcs->initSolution();
1535 m_gcs->maxIter = MAX_SOLVE_ITERATIONS;
1536
1537 m_dragTargetX = pushParam( 0.0 );
1538 m_dragTargetY = pushParam( 0.0 );
1539 m_coDragTargetX = pushParam( 0.0 );
1540 m_coDragTargetY = pushParam( 0.0 );
1541
1542 m_built = true;
1543 return true;
1544}
1545
1546
1548{
1549 if( aVars.shape )
1550 return aVars.shape;
1551
1552 if( aVars.dimension )
1553 return aVars.dimension;
1554
1555 return aVars.pad;
1556}
1557
1558
1559void BOARD_CONSTRAINT_ADAPTER::coupleRigidFootprints( const std::set<FOOTPRINT*>& aFootprints,
1560 const std::set<KIID>* aFixedShapes, std::set<int>& aFixed )
1561{
1562 for( FOOTPRINT* footprint : aFootprints )
1563 {
1564 std::set<KIID> children;
1565 bool frozen = false;
1566
1567 for( const auto& [kiid, vars] : m_shapeVars )
1568 {
1569 BOARD_ITEM* item = itemOf( vars );
1570
1571 if( boardFootprintOf( item ) != footprint )
1572 continue;
1573
1574 children.insert( kiid );
1575 frozen |= ConstraintItemIsLocked( item ) || ( aFixedShapes && aFixedShapes->contains( kiid ) );
1576 }
1577
1578 m_rigidMembers.insert( children.begin(), children.end() );
1579
1580 RIGID_STATE state = collectRigidState( children );
1581
1582 // Translation alone can never resize a child
1583 for( const RIGID_RADIUS_HOLD& hold : state.radii )
1584 aFixed.insert( hold.radius );
1585
1586 if( frozen )
1587 {
1588 for( int pointX : state.points )
1589 {
1590 aFixed.insert( pointX );
1591 aFixed.insert( pointX + 1 );
1592 }
1593
1594 continue;
1595 }
1596
1597 RIGID_FOOTPRINT body;
1598 body.footprint = footprint;
1599 body.buildPosition = footprint->GetPosition();
1600 body.translationX = pushParam( 0.0 );
1601 pushParam( 0.0 );
1602
1603 for( int pointX : state.points )
1604 {
1605 for( int axis : { 0, 1 } )
1606 {
1607 int origin = pushParam( m_params[pointX + axis] );
1608 aFixed.insert( origin );
1609 m_gcs->addConstraintDifference( &m_params[origin], &m_params[pointX + axis],
1610 &m_params[body.translationX + axis] );
1611 }
1612 }
1613
1614 m_rigidFootprints.push_back( body );
1615 }
1616}
1617
1618
1619bool BOARD_CONSTRAINT_ADAPTER::Solve( bool aStabilize )
1620{
1621 if( !m_built )
1622 return false;
1623
1625
1626 // A hard hold here (no drag pin) so a contradiction cannot hide by collapsing a segment or arc.
1627 if( aStabilize )
1628 {
1631 }
1632
1633 // With no shape singled out as edited hold every shape where it sits for a minimal-movement solve
1634 // these soft pins live in the null space of the hard constraints so the diagnosis stays untouched
1635 pinUneditedShapes( {}, GCS::DefaultTemporaryConstraint );
1636
1637 m_gcs->initSolution();
1638 int ret = m_gcs->solve();
1639 m_gcs->applySolution();
1640
1641 bool solved = solveSucceeded( ret );
1642
1643 m_gcs->clearByTag( GCS::DefaultTemporaryConstraint );
1644
1645 if( aStabilize )
1646 m_gcs->clearByTag( m_lengthHoldTag );
1647
1648 return solved;
1649}
1650
1651
1653{
1654 if( !m_built )
1655 return false;
1656
1658
1659 for( const auto& [kiid, vars] : m_shapeVars )
1660 {
1661 // Preserve every curve's free radius while re-solving the resized cluster. This covers
1662 // ellipses too; their focus-to-center offset params are fixed at Build, so pinning the
1663 // minor radius pins the whole shape (focal distance and rotation cannot drift).
1664 if( vars.radius < 0 )
1665 continue;
1666
1667 int target = temporaryParam( m_params[vars.radius] );
1668 GCS::Circle c;
1669 c.center = GCS::Point{ &m_params[vars.startX], &m_params[vars.startX + 1] };
1670 c.rad = &m_params[vars.radius];
1671
1672 if( kiid == aResizedShape )
1673 {
1674 // The user set this radius, so hold it hard. Pin the centre yielding so the shape moves
1675 // only if a locked neighbour leaves no other way to stay tangent.
1676 m_gcs->addConstraintCircleRadius( c, &m_params[target], m_resizeRadiusTag, true );
1677
1678 int cx = temporaryParam( m_params[vars.startX] );
1679 int cy = temporaryParam( m_params[vars.startX + 1] );
1680 m_gcs->addConstraintCoordinateX( c.center, &m_params[cx], GCS::DefaultTemporaryConstraint );
1681 m_gcs->addConstraintCoordinateY( c.center, &m_params[cy], GCS::DefaultTemporaryConstraint );
1682 }
1683 else
1684 {
1685 // Neighbours keep their size unless a real radius constraint says otherwise.
1686 m_gcs->addConstraintCircleRadius( c, &m_params[target], GCS::DefaultTemporaryConstraint );
1687 }
1688 }
1689
1690 // Hold every neighbour where it sits so a resize translates only the shapes a constraint forces
1691 // the resized shape's own centre is pinned above so exclude it here
1692 pinUneditedShapes( { aResizedShape }, GCS::DefaultTemporaryConstraint );
1693
1694 // The radius loop above holds nothing of a polygon so a resized polygon needs its own
1695 // minimal-movement vertex pins here
1696 holdPolygonVertices( { aResizedShape }, GCS::DefaultTemporaryConstraint );
1697
1698 m_gcs->initSolution();
1699 int ret = m_gcs->solve();
1700 m_gcs->applySolution();
1701
1702 bool solved = solveSucceeded( ret );
1703
1704 m_gcs->clearByTag( GCS::DefaultTemporaryConstraint );
1705 m_gcs->clearByTag( m_resizeRadiusTag );
1706
1707 return solved;
1708}
1709
1710
1711bool BOARD_CONSTRAINT_ADAPTER::Solve( const CONSTRAINT_MEMBER& aDragged, const VECTOR2I& aCursor, bool aStabilize,
1712 const std::set<KIID>& aEdited,
1713 const std::optional<std::pair<CONSTRAINT_MEMBER, VECTOR2I>>& aCoDragged,
1714 bool aHoldDraggedRigid )
1715{
1716 if( !m_built )
1717 return false;
1718
1720
1721 ANCHOR_PARAMS params = anchorParams( aDragged );
1722
1723 if( !params.IsValid() )
1724 return false;
1725
1726 // Reuse fixed backing slots for the cursor target so repeated drag solves (warm-started from
1727 // the previous solution still in m_params) never grow the backing store.
1728 double targetX = normalizeX( aCursor.x );
1729 double targetY = normalizeY( aCursor.y );
1730
1731 // For an arc endpoint, project the target onto the arc's current circle so the cursor pin agrees
1732 // with the centre + radius holds pinDraggedShapeRest adds, regardless of whether the caller
1733 // already projected. Without this an off-circle target and the holds fight and the arc drifts.
1734 if( auto it = m_shapeVars.find( aDragged.m_item );
1735 !aStabilize && it != m_shapeVars.end() && it->second.kind == SHAPE_KIND::ARC
1736 && ( aDragged.m_anchor == CONSTRAINT_ANCHOR::START || aDragged.m_anchor == CONSTRAINT_ANCHOR::END ) )
1737 {
1738 const SHAPE_VARS& vars = it->second;
1739 double dx = targetX - m_params[vars.startX];
1740 double dy = targetY - m_params[vars.startX + 1];
1741 double len = std::hypot( dx, dy );
1742
1743 if( len > 1e-9 )
1744 {
1745 double radius = m_params[vars.radius];
1746 targetX = m_params[vars.startX] + dx * radius / len;
1747 targetY = m_params[vars.startX + 1] + dy * radius / len;
1748 }
1749 }
1750
1751 if( auto it = m_shapeVars.find( aDragged.m_item );
1752 !aStabilize && it != m_shapeVars.end() && it->second.kind == SHAPE_KIND::SEGMENT
1753 && it->second.fixedLengthParam >= 0
1754 && ( aDragged.m_anchor == CONSTRAINT_ANCHOR::START || aDragged.m_anchor == CONSTRAINT_ANCHOR::END ) )
1755 {
1756 const SHAPE_VARS& vars = it->second;
1757 int farX = aDragged.m_anchor == CONSTRAINT_ANCHOR::START ? vars.endX : vars.startX;
1758 double segLen = m_params[vars.fixedLengthParam];
1759 double dx = targetX - m_params[farX];
1760 double dy = targetY - m_params[farX + 1];
1761 double len = std::hypot( dx, dy );
1762
1763 if( len > 1e-9 && segLen > 1e-9 )
1764 {
1765 targetX = m_params[farX] + dx * segLen / len;
1766 targetY = m_params[farX + 1] + dy * segLen / len;
1767 }
1768 }
1769
1770 m_params[m_dragTargetX] = targetX;
1771 m_params[m_dragTargetY] = targetY;
1772
1773 GCS::Point anchor = GCS::Point{ &m_params[params.x], &m_params[params.y] };
1774
1775 // A temporary negatively tagged pin yields to the real constraints when over-constrained and
1776 // keeps the default weight far above the stay-put pins so a hard-linked neighbour follows it
1777 m_gcs->addConstraintCoordinateX( anchor, &m_params[m_dragTargetX], GCS::DefaultTemporaryConstraint );
1778 m_gcs->addConstraintCoordinateY( anchor, &m_params[m_dragTargetY], GCS::DefaultTemporaryConstraint );
1779
1780 // The co-dragged anchor gets a plain pin at the same weight since only polygon edge drags carry
1781 // one the rest-hold exclusion below shares the same validity check so it is never left unheld
1782 const CONSTRAINT_MEMBER* coDragged = nullptr;
1783
1784 if( aCoDragged )
1785 {
1786 ANCHOR_PARAMS coParams = anchorParams( aCoDragged->first );
1787
1788 if( coParams.IsValid() )
1789 {
1790 coDragged = &aCoDragged->first;
1791
1792 m_params[m_coDragTargetX] = normalizeX( aCoDragged->second.x );
1793 m_params[m_coDragTargetY] = normalizeY( aCoDragged->second.y );
1794
1795 GCS::Point coAnchor = GCS::Point{ &m_params[coParams.x], &m_params[coParams.y] };
1796
1797 m_gcs->addConstraintCoordinateX( coAnchor, &m_params[m_coDragTargetX], GCS::DefaultTemporaryConstraint );
1798 m_gcs->addConstraintCoordinateY( coAnchor, &m_params[m_coDragTargetY], GCS::DefaultTemporaryConstraint );
1799 }
1800 }
1801
1802 // Only while live-dragging one handle. The settle/apply paths (aStabilize) instead let the
1803 // pinned shape's rest move to meet a newly applied relation, e.g. a fixed-length shrink.
1804 if( !aStabilize )
1805 pinDraggedShapeRest( aDragged, GCS::DefaultTemporaryConstraint, coDragged );
1806
1807 // Protect only shapes a direction or angle constraint could collapse a merely dragged-along
1808 // neighbour keeps its own stay-put pins instead
1809 if( aStabilize )
1810 {
1811 holdFreeSegmentLengths( GCS::DefaultTemporaryConstraint, m_angleConstrainedShapes );
1812 holdFreeArcRadii( GCS::DefaultTemporaryConstraint, m_angleConstrainedShapes );
1813
1814 if( aHoldDraggedRigid )
1815 holdShapesRigid( GCS::DefaultTemporaryConstraint, { aDragged.m_item } );
1816 }
1817
1818 // Hold every other cluster shape where it sits so only edited shapes and whatever a hard
1819 // constraint forces actually move every genuinely edited shape is excluded here
1820 std::set<KIID> editedShapes = aEdited;
1821 editedShapes.insert( aDragged.m_item );
1822
1823 if( coDragged )
1824 editedShapes.insert( coDragged->m_item );
1825
1826 pinUneditedShapes( editedShapes, GCS::DefaultTemporaryConstraint );
1827
1828 // An edited polygon is excluded above but its unbound vertices still need minimal-movement pins
1829 // a live-dragged polygon is left out too since pinDraggedShapeRest already holds its other vertices
1830 std::set<KIID> heldPolygons = editedShapes;
1831
1832 if( !aStabilize )
1833 heldPolygons.erase( aDragged.m_item );
1834
1835 holdPolygonVertices( heldPolygons, GCS::DefaultTemporaryConstraint );
1836
1837 m_gcs->initSolution();
1838 int ret = m_gcs->solve();
1839 m_gcs->applySolution();
1840
1841 bool solved = solveSucceeded( ret );
1842
1843 m_gcs->clearByTag( GCS::DefaultTemporaryConstraint );
1844
1845 return solved;
1846}
1847
1848
1850 const std::vector<SNAP_CANDIDATE>& aCandidates,
1851 const VECTOR2I& aOffset )
1852{
1853 GCS::Point anchor{ &m_params[aAnchor.x], &m_params[aAnchor.y] };
1854 bool addedRelation = false;
1855
1856 const auto addCoordinateX = [&]( double aCoordinate )
1857 {
1858 int target = temporaryParam( normalizeX( KiROUND( aCoordinate ) + aOffset.x ) );
1859 m_gcs->addConstraintCoordinateX( anchor, &m_params[target], GCS::DefaultTemporaryConstraint );
1860 addedRelation = true;
1861 };
1862 const auto addCoordinateY = [&]( double aCoordinate )
1863 {
1864 int target = temporaryParam( normalizeY( KiROUND( aCoordinate ) + aOffset.y ) );
1865 m_gcs->addConstraintCoordinateY( anchor, &m_params[target], GCS::DefaultTemporaryConstraint );
1866 addedRelation = true;
1867 };
1868 const auto addLine = [&]( const SNAP_CANDIDATE& aCandidate )
1869 {
1870 if( aCandidate.direction.SquaredEuclideanNorm() <= 1e-12 )
1871 return;
1872
1873 VECTOR2D direction = aCandidate.direction * ( 1000000.0 / aCandidate.direction.EuclideanNorm() );
1874 VECTOR2D origin = aCandidate.origin + VECTOR2D( aOffset );
1875 int x1 = temporaryParam( normalizeX( KiROUND( origin.x ) ) );
1876 int y1 = temporaryParam( normalizeY( KiROUND( origin.y ) ) );
1877 int x2 = temporaryParam( normalizeX( KiROUND( origin.x + direction.x ) ) );
1878 int y2 = temporaryParam( normalizeY( KiROUND( origin.y + direction.y ) ) );
1879 GCS::Line line;
1880 line.p1 = GCS::Point{ &m_params[x1], &m_params[y1] };
1881 line.p2 = GCS::Point{ &m_params[x2], &m_params[y2] };
1882 m_gcs->addConstraintPointOnLine( anchor, line, GCS::DefaultTemporaryConstraint );
1883 addedRelation = true;
1884 };
1885
1886 for( const SNAP_CANDIDATE& candidate : aCandidates )
1887 {
1888 switch( candidate.relation )
1889 {
1893 addCoordinateX( candidate.origin.x );
1894 addCoordinateY( candidate.origin.y );
1895 break;
1896
1898 case SNAP_RELATION::GRID_X: addCoordinateX( candidate.origin.x ); break;
1899
1901 case SNAP_RELATION::GRID_Y: addCoordinateY( candidate.origin.y ); break;
1902
1905 if( candidate.direction.x != 0.0 )
1906 addCoordinateX( candidate.origin.x );
1907 else if( candidate.direction.y != 0.0 )
1908 addCoordinateY( candidate.origin.y );
1909
1910 break;
1911
1915 case SNAP_RELATION::ANGLE: addLine( candidate ); break;
1916
1919 {
1920 if( !candidate.manifold )
1921 break;
1922
1924 int radius = 0;
1925
1926 if( const CIRCLE* circle = std::get_if<CIRCLE>( &*candidate.manifold ) )
1927 {
1928 center = circle->Center;
1929 radius = circle->Radius;
1930 }
1931 else if( const SHAPE_ARC* arc = std::get_if<SHAPE_ARC>( &*candidate.manifold ) )
1932 {
1933 center = arc->GetCenter();
1934 radius = arc->GetRadius();
1935 }
1936 else
1937 {
1938 break;
1939 }
1940
1941 center += aOffset;
1942 int centerX = temporaryParam( normalizeX( center.x ) );
1943 int centerY = temporaryParam( normalizeY( center.y ) );
1944 int radiusParam = temporaryParam( radius * m_invScale );
1945 GCS::Circle circle;
1946 circle.center = GCS::Point{ &m_params[centerX], &m_params[centerY] };
1947 circle.rad = &m_params[radiusParam];
1948 m_gcs->addConstraintPointOnCircle( anchor, circle, GCS::DefaultTemporaryConstraint );
1949 addedRelation = true;
1950 break;
1951 }
1952 }
1953 }
1954
1955 return addedRelation;
1956}
1957
1958
1960BOARD_CONSTRAINT_ADAPTER::collectRigidState( const std::set<KIID>& aEditedShapes ) const
1961{
1962 RIGID_STATE state;
1963
1964 const auto addPoint = [&]( int aPointX )
1965 {
1966 if( aPointX >= 0 )
1967 state.points.insert( aPointX );
1968 };
1969
1970 for( const KIID& id : aEditedShapes )
1971 {
1972 auto it = m_shapeVars.find( id );
1973
1974 if( it == m_shapeVars.end() )
1975 continue;
1976
1977 const SHAPE_VARS& vars = it->second;
1978
1979 switch( vars.kind )
1980 {
1983 case SHAPE_KIND::BEZIER:
1985 addPoint( vars.startX );
1986 addPoint( vars.endX );
1987 break;
1988
1989 case SHAPE_KIND::CIRCLE:
1990 addPoint( vars.startX );
1991 state.radii.push_back( { vars.startX, vars.radius } );
1992 break;
1993
1995 addPoint( vars.startX );
1996 addPoint( vars.focusX );
1997 state.radii.push_back( { vars.startX, vars.radius } );
1998 break;
1999
2000 case SHAPE_KIND::ARC:
2001 addPoint( vars.startX );
2002 addPoint( vars.arcStartX );
2003 addPoint( vars.arcEndX );
2004 state.radii.push_back( { vars.startX, vars.radius } );
2005 break;
2006
2008 addPoint( vars.startX );
2009 addPoint( vars.focusX );
2010 addPoint( vars.arcStartX );
2011 addPoint( vars.arcEndX );
2012 state.radii.push_back( { vars.startX, vars.radius } );
2013 break;
2014
2016 for( int i = 0; i < vars.vertexCount; ++i )
2017 addPoint( vars.startX + 2 * i );
2018
2019 break;
2020
2022 addPoint( vars.startX );
2023 break;
2024 }
2025 }
2026
2027 return state;
2028}
2029
2030
2031void BOARD_CONSTRAINT_ADAPTER::holdRigidRadii( const std::vector<RIGID_RADIUS_HOLD>& aRadii, int aTag )
2032{
2033 for( const RIGID_RADIUS_HOLD& hold : aRadii )
2034 {
2035 int target = temporaryParam( m_params[hold.radius] );
2036 GCS::Circle circle;
2037 circle.center = GCS::Point{ &m_params[hold.centerX], &m_params[hold.centerX + 1] };
2038 circle.rad = &m_params[hold.radius];
2039 m_gcs->addConstraintCircleRadius( circle, &m_params[target], aTag );
2040 }
2041}
2042
2043
2045 const std::vector<SNAP_CANDIDATE>& aCandidates,
2046 const VECTOR2I& aCursor )
2047{
2048 if( !m_built )
2049 return false;
2050
2051 ANCHOR_PARAMS params = anchorParams( aDragged );
2052
2053 if( !params.IsValid() )
2054 return false;
2055
2057
2058 if( !addSnapRelations( params, aCandidates, {} ) )
2059 return false;
2060
2061 GCS::Point anchor{ &m_params[params.x], &m_params[params.y] };
2062
2063 int cursorX = temporaryParam( normalizeX( aCursor.x ) );
2064 int cursorY = temporaryParam( normalizeY( aCursor.y ) );
2065 int xPin = m_gcs->addConstraintCoordinateX( anchor, &m_params[cursorX], GCS::DefaultTemporaryConstraint );
2066 int yPin = m_gcs->addConstraintCoordinateY( anchor, &m_params[cursorY], GCS::DefaultTemporaryConstraint );
2067 m_gcs->rescaleConstraint( xPin, CURSOR_WEIGHT );
2068 m_gcs->rescaleConstraint( yPin, CURSOR_WEIGHT );
2069
2070 pinDraggedShapeRest( aDragged, GCS::DefaultTemporaryConstraint );
2071 pinUneditedShapes( { aDragged.m_item }, GCS::DefaultTemporaryConstraint );
2072
2073 m_gcs->initSolution();
2074 int ret = m_gcs->solve();
2075 m_gcs->applySolution();
2076 bool solved = solveSucceeded( ret );
2077
2078 m_gcs->clearByTag( GCS::DefaultTemporaryConstraint );
2079 return solved;
2080}
2081
2082
2083bool BOARD_CONSTRAINT_ADAPTER::TravelsWhole( const std::set<KIID>& aEditedShapes ) const
2084{
2085 return std::ranges::all_of( m_shapeVars,
2086 [&]( const auto& aEntry )
2087 {
2088 return aEditedShapes.contains( aEntry.first )
2089 && !ConstraintItemIsLocked( aEntry.second.shape )
2090 && !ConstraintItemIsLocked( aEntry.second.dimension );
2091 } );
2092}
2093
2094
2095bool BOARD_CONSTRAINT_ADAPTER::SolveRigidTranslation( const std::set<KIID>& aEditedShapes,
2096 const VECTOR2I& aTranslation )
2097{
2098 if( !m_built || aEditedShapes.empty() )
2099 return false;
2100
2101 RIGID_STATE state = collectRigidState( aEditedShapes );
2102
2103 if( state.points.empty() )
2104 return false;
2105
2106 const bool movesGroundedPoint =
2107 std::ranges::any_of( state.points,
2108 [&]( int aPointX )
2109 {
2110 return m_fixedParams.contains( aPointX ) || m_fixedParams.contains( aPointX + 1 );
2111 } );
2112
2113 // A pinned or locked coordinate cannot travel
2114 if( movesGroundedPoint && aTranslation != VECTOR2I() )
2115 return false;
2116
2117 const double dx = aTranslation.x * m_invScale;
2118 const double dy = aTranslation.y * m_invScale;
2119 std::map<int, VECTOR2I> exactTargets;
2120
2121 for( int pointX : state.points )
2122 {
2123 m_params[pointX] += dx;
2124 m_params[pointX + 1] += dy;
2125 exactTargets.emplace( pointX, VECTOR2I( KiROUND( denormalizeX( m_params[pointX] ) ),
2126 KiROUND( denormalizeY( m_params[pointX + 1] ) ) ) );
2127 }
2128
2129 // Moving every shape a constraint touches cannot change what it measures
2130 if( TravelsWhole( aEditedShapes ) )
2131 return true;
2132
2134
2135 for( int pointX : state.points )
2136 softPinPoint( pointX, GCS::DefaultTemporaryConstraint );
2137
2138 holdRigidRadii( state.radii, GCS::DefaultTemporaryConstraint );
2139
2140 pinUneditedShapes( aEditedShapes, GCS::DefaultTemporaryConstraint );
2141 m_gcs->initSolution();
2142 int ret = m_gcs->solve();
2143 m_gcs->applySolution();
2144 bool solved = solveSucceeded( ret );
2145
2146 for( const auto& [pointX, target] : exactTargets )
2147 {
2148 VECTOR2I resolved( KiROUND( denormalizeX( m_params[pointX] ) ),
2149 KiROUND( denormalizeY( m_params[pointX + 1] ) ) );
2150 solved = solved && resolved == target;
2151 }
2152
2153 m_gcs->clearByTag( GCS::DefaultTemporaryConstraint );
2154 return solved && QuantizedRelationsSatisfied();
2155}
2156
2157
2159BOARD_CONSTRAINT_ADAPTER::SolveBlockEdit( const std::vector<std::pair<CONSTRAINT_MEMBER, VECTOR2I>>& aPinnedAnchors,
2160 const std::set<KIID>& aTranslatedShapes, const VECTOR2I& aTranslation )
2161{
2162 if( !m_built )
2164
2165 // The held coordinates and their IU targets, keyed by parameter index so a coordinate
2166 // two anchors name is held once. The axes are kept apart because a rectangle corner
2167 // shares one stored corner's x with the other's y.
2168 std::map<int, int> targetsX;
2169 std::map<int, int> targetsY;
2170
2171 const RIGID_STATE carried = collectRigidState( aTranslatedShapes );
2172
2173 // A shape travelling whole cannot carry a point the user pinned, the same refusal
2174 // SolveRigidTranslation makes. A locked shape is different and stays placeable, since
2175 // the caller has already put it where the user asked
2176 const bool carriesGroundedPoint = std::ranges::any_of(
2177 carried.points,
2178 [&]( int aPointX )
2179 {
2180 return m_groundedPositionParams.contains( aPointX ) || m_groundedPositionParams.contains( aPointX + 1 );
2181 } );
2182
2183 if( carriesGroundedPoint && aTranslation != VECTOR2I() )
2185
2186 for( int pointX : carried.points )
2187 {
2188 targetsX[pointX] = KiROUND( denormalizeX( m_params[pointX] ) ) + aTranslation.x;
2189 targetsY[pointX + 1] = KiROUND( denormalizeY( m_params[pointX + 1] ) ) + aTranslation.y;
2190 }
2191
2192 // Whether the user picked a point this cluster nails down. The solve still has to run in
2193 // that case, with nothing commanded, so the point is put back where the constraint says
2194 bool groundedAnchorPicked = false;
2195
2196 for( const auto& [member, target] : aPinnedAnchors )
2197 {
2198 // An anchor this cluster does not cover, say a corner of a polygon the solver cannot
2199 // model, is skipped so the rest of the block still solves
2200 if( ANCHOR_PARAMS anchor = anchorParams( member ); anchor.IsValid() )
2201 {
2202 // A FIXED_POSITION constraint grounds this point. The caller has already written
2203 // the cursor into the item, so commanding it here would hold the violation and
2204 // then report it solved, because the check below reads back what was just written
2205 // A rectangle corner shares each axis with a different neighbour, so check them apart
2206 if( m_groundedPositionParams.contains( anchor.x ) )
2207 groundedAnchorPicked = true;
2208 else
2209 targetsX[anchor.x] = target.x;
2210
2211 if( m_groundedPositionParams.contains( anchor.y ) )
2212 groundedAnchorPicked = true;
2213 else
2214 targetsY[anchor.y] = target.y;
2215 }
2216 }
2217
2218 if( targetsX.empty() && targetsY.empty() && !groundedAnchorPicked )
2220
2222
2223 std::set<int> commanded;
2224
2225 for( const auto& [param, target] : targetsX )
2226 {
2227 m_params[param] = normalizeX( target );
2228 commanded.insert( param );
2229 }
2230
2231 for( const auto& [param, target] : targetsY )
2232 {
2233 m_params[param] = normalizeY( target );
2234 commanded.insert( param );
2235 }
2236
2237 // The anchors keep the default weight, far above the stay-put tier, and the whole
2238 // temporary subsystem is minimized inside the null space of the real constraints. A
2239 // constraint therefore always wins, and a contradiction turns up as an unreachable
2240 // target in the check below
2241 for( int param : commanded )
2242 softPinCoordinate( param, GCS::DefaultTemporaryConstraint );
2243
2244 pinUncommandedCoordinates( commanded, GCS::DefaultTemporaryConstraint );
2245
2246 m_gcs->initSolution();
2247 int ret = m_gcs->solve();
2248 m_gcs->applySolution();
2249
2250 bool solved = solveSucceeded( ret );
2251
2252 for( const auto& [param, target] : targetsX )
2253 solved = solved && KiROUND( denormalizeX( m_params[param] ) ) == target;
2254
2255 for( const auto& [param, target] : targetsY )
2256 solved = solved && KiROUND( denormalizeY( m_params[param] ) ) == target;
2257
2258 m_gcs->clearByTag( GCS::DefaultTemporaryConstraint );
2259
2261}
2262
2263
2264bool BOARD_CONSTRAINT_ADAPTER::SolveRigidSnapRelations( const std::set<KIID>& aEditedShapes, const VECTOR2I& aReference,
2265 const std::vector<SNAP_CANDIDATE>& aCandidates,
2266 const VECTOR2I& aCursor, VECTOR2I& aResolvedCursor )
2267{
2268 if( !m_built || aEditedShapes.empty() )
2269 return false;
2270
2271 RIGID_STATE state = collectRigidState( aEditedShapes );
2272
2273 if( state.points.empty() )
2274 return false;
2275
2277 const int anchorX = *state.points.begin();
2278 const VECTOR2I anchorAtBaseline( KiROUND( denormalizeX( m_params[anchorX] ) ),
2279 KiROUND( denormalizeY( m_params[anchorX + 1] ) ) );
2280 const VECTOR2I cursorToAnchor = anchorAtBaseline - aReference;
2281 std::map<int, VECTOR2I> baselinePoints;
2282
2283 for( int pointX : state.points )
2284 {
2285 baselinePoints.emplace( pointX, VECTOR2I( KiROUND( denormalizeX( m_params[pointX] ) ),
2286 KiROUND( denormalizeY( m_params[pointX + 1] ) ) ) );
2287
2288 if( pointX == anchorX )
2289 continue;
2290
2291 int offsetX = temporaryParam( m_params[pointX] - m_params[anchorX] );
2292 int offsetY = temporaryParam( m_params[pointX + 1] - m_params[anchorX + 1] );
2293 m_gcs->addConstraintDifference( &m_params[anchorX], &m_params[pointX], &m_params[offsetX],
2294 GCS::DefaultTemporaryConstraint );
2295 m_gcs->addConstraintDifference( &m_params[anchorX + 1], &m_params[pointX + 1], &m_params[offsetY],
2296 GCS::DefaultTemporaryConstraint );
2297 }
2298
2299 bool addedRelation = addSnapRelations( { anchorX, anchorX + 1 }, aCandidates, cursorToAnchor );
2300 holdRigidRadii( state.radii, GCS::DefaultTemporaryConstraint );
2301
2302 GCS::Point anchor{ &m_params[anchorX], &m_params[anchorX + 1] };
2303 int cursorX = temporaryParam( normalizeX( aCursor.x + cursorToAnchor.x ) );
2304 int cursorY = temporaryParam( normalizeY( aCursor.y + cursorToAnchor.y ) );
2305 int xPin = m_gcs->addConstraintCoordinateX( anchor, &m_params[cursorX], GCS::DefaultTemporaryConstraint );
2306 int yPin = m_gcs->addConstraintCoordinateY( anchor, &m_params[cursorY], GCS::DefaultTemporaryConstraint );
2307 m_gcs->rescaleConstraint( xPin, CURSOR_WEIGHT );
2308 m_gcs->rescaleConstraint( yPin, CURSOR_WEIGHT );
2309 pinUneditedShapes( aEditedShapes, GCS::DefaultTemporaryConstraint );
2310 m_gcs->initSolution();
2311 int ret = m_gcs->solve();
2312 m_gcs->applySolution();
2313 bool solved = solveSucceeded( ret ) && ( addedRelation || aCandidates.empty() );
2314
2315 VECTOR2I resolvedAnchor( KiROUND( denormalizeX( m_params[anchorX] ) ),
2316 KiROUND( denormalizeY( m_params[anchorX + 1] ) ) );
2317 aResolvedCursor = resolvedAnchor - cursorToAnchor;
2318 VECTOR2I translation = aResolvedCursor - aReference;
2319
2320 for( const auto& [pointX, baseline] : baselinePoints )
2321 {
2322 VECTOR2I resolved( KiROUND( denormalizeX( m_params[pointX] ) ),
2323 KiROUND( denormalizeY( m_params[pointX + 1] ) ) );
2324 solved = solved && resolved == baseline + translation;
2325 }
2326
2327 m_gcs->clearByTag( GCS::DefaultTemporaryConstraint );
2328
2329 if( !solved || !QuantizedRelationsSatisfied() )
2330 return false;
2331
2332 SNAP_SOURCE_CONTEXT verifyContext;
2333 verifyContext.sourcePoint = aResolvedCursor;
2334 SNAP_RESOLVER verify;
2335
2336 for( const SNAP_CANDIDATE& candidate : aCandidates )
2337 verify.AddCandidate( candidate );
2338
2339 SNAP_RESULT verified = verify.Resolve( verifyContext );
2340
2341 for( const SNAP_CANDIDATE& candidate : aCandidates )
2342 {
2343 if( !verified.Accepted( candidate.id ) )
2344 return false;
2345 }
2346
2347 return verified.position == aResolvedCursor;
2348}
2349
2350
2351std::optional<VECTOR2I> BOARD_CONSTRAINT_ADAPTER::AnchorPosition( const CONSTRAINT_MEMBER& aMember ) const
2352{
2353 ANCHOR_PARAMS params = anchorParams( aMember );
2354
2355 if( !params.IsValid() )
2356 return std::nullopt;
2357
2358 return VECTOR2I( KiROUND( denormalizeX( m_params[params.x] ) ),
2359 KiROUND( denormalizeY( m_params[params.y] ) ) );
2360}
2361
2362
2364{
2365 if( ( aSolveResult == GCS::Success || aSolveResult == GCS::Converged ) && parametersFinite() )
2366 return true;
2367
2368 return hardRelationsSatisfied();
2369}
2370
2371
2373{
2374 return std::ranges::all_of( m_params,
2375 []( double aParam )
2376 {
2377 return std::isfinite( aParam );
2378 } );
2379}
2380
2381
2383{
2384 // Every residual test below is false for NaN, so a diverged state would otherwise read as satisfied
2385 if( !parametersFinite() )
2386 return false;
2387
2388 // planegcs bases Success only on the hard subsystem residual but the soft stay-put subsystem
2389 // perturbs the SQP trajectory so a valid solve often still reports Failed judge the hard
2390 // constraints directly instead a genuine contradiction still leaves a large or non-finite residual
2391 const double residualTol = 1e-3;
2392
2393 // Tag-0 residual is the structural curve rules for arc ellipse and focus which must hold for
2394 // coherent geometry a NaN means no tag-0 constraint exists for a segment-only cluster not a failure
2395 double structuralErr = m_gcs->calculateConstraintErrorByTag( 0 );
2396
2397 if( std::isfinite( structuralErr ) && std::abs( structuralErr ) > residualTol )
2398 return false;
2399
2400 return staleRelationTags().empty();
2401}
2402
2403
2405{
2406 const double residualTol = 1e-3;
2407 std::vector<int> stale;
2408
2409 for( const auto& [tag, kiid] : m_tagToConstraint )
2410 {
2411 // A reference non-driving constraint only measures so its residual is never a failure
2412 if( m_nonDrivingTags.contains( tag ) || m_droppedTags.contains( tag ) )
2413 continue;
2414
2415 double err = m_gcs->calculateConstraintErrorByTag( tag );
2416
2417 if( !std::isfinite( err ) || std::abs( err ) > residualTol )
2418 stale.push_back( tag );
2419 }
2420
2421 return stale;
2422}
2423
2424
2426{
2427 const std::vector<int> stale = staleRelationTags();
2428
2429 for( int tag : stale )
2430 {
2431 m_gcs->clearByTag( tag );
2432
2433 // The mapping stays so Diagnose() can still attribute the relation to its constraint
2434 m_droppedTags.insert( tag );
2435 }
2436
2437 if( !stale.empty() )
2438 m_gcs->initSolution();
2439
2440 return (int) stale.size();
2441}
2442
2443
2445{
2446 SNAPSHOT snapshot = Snapshot();
2447 std::set<int> xParams;
2448 std::set<int> yParams;
2449 std::set<int> radiusParams;
2450
2451 const auto addPoint =
2452 [&]( int aX )
2453 {
2454 if( aX >= 0 )
2455 {
2456 xParams.insert( aX );
2457 yParams.insert( aX + 1 );
2458 }
2459 };
2460
2461 for( const auto& [kiid, vars] : m_shapeVars )
2462 {
2463 addPoint( vars.startX );
2464 addPoint( vars.endX );
2465 addPoint( vars.arcStartX );
2466 addPoint( vars.arcEndX );
2467 addPoint( vars.focusX );
2468
2469 if( vars.kind == SHAPE_KIND::POLYGON )
2470 {
2471 for( int i = 0; i < vars.vertexCount; ++i )
2472 addPoint( vars.startX + 2 * i );
2473 }
2474
2475 if( vars.radius >= 0 )
2476 radiusParams.insert( vars.radius );
2477 }
2478
2479 for( int index : xParams )
2481
2482 for( int index : yParams )
2484
2485 for( int index : radiusParams )
2487
2488 bool valid = hardRelationsSatisfied();
2489 Restore( snapshot );
2490 return valid;
2491}
2492
2493
2494void BOARD_CONSTRAINT_ADAPTER::softPinPoint( const ANCHOR_PARAMS& aPoint, int aTag, std::optional<double> aWeight )
2495{
2496 // A zero weight would neutralize the pin instead of tiering it
2497 wxASSERT( !aWeight || *aWeight > 0 );
2498
2499 if( !aPoint.IsValid() )
2500 return;
2501
2502 int pinX = temporaryParam( m_params[aPoint.x] );
2503 int pinY = temporaryParam( m_params[aPoint.y] );
2504 GCS::Point point{ &m_params[aPoint.x], &m_params[aPoint.y] };
2505
2506 int cx = m_gcs->addConstraintCoordinateX( point, &m_params[pinX], aTag );
2507 int cy = m_gcs->addConstraintCoordinateY( point, &m_params[pinY], aTag );
2508
2509 if( aWeight )
2510 {
2511 m_gcs->rescaleConstraint( cx, *aWeight );
2512 m_gcs->rescaleConstraint( cy, *aWeight );
2513 }
2514}
2515
2516
2517void BOARD_CONSTRAINT_ADAPTER::softPinPoint( int aPointX, int aTag, std::optional<double> aWeight )
2518{
2519 if( aPointX >= 0 )
2520 softPinPoint( ANCHOR_PARAMS{ aPointX, aPointX + 1 }, aTag, aWeight );
2521}
2522
2523
2524void BOARD_CONSTRAINT_ADAPTER::softPinCoordinate( int aParam, int aTag, std::optional<double> aWeight )
2525{
2526 // A zero weight would neutralize the pin instead of tiering it
2527 wxASSERT( !aWeight || *aWeight > 0 );
2528
2529 if( aParam < 0 )
2530 return;
2531
2532 int pin = temporaryParam( m_params[aParam] );
2533 int id = m_gcs->addConstraintEqual( &m_params[aParam], &m_params[pin], aTag );
2534
2535 if( aWeight )
2536 m_gcs->rescaleConstraint( id, *aWeight );
2537}
2538
2539
2540void BOARD_CONSTRAINT_ADAPTER::pinUncommandedCoordinates( const std::set<int>& aCommanded, int aTag )
2541{
2542 for( const auto& [kiid, vars] : m_shapeVars )
2543 {
2544 // Build already froze a locked shape or dimension, so a pin here adds nothing
2545 if( ConstraintItemIsLocked( vars.shape ) || ConstraintItemIsLocked( vars.dimension ) )
2546 continue;
2547
2548 const RIGID_STATE state = collectRigidState( { kiid } );
2549 bool commandedShape = false;
2550
2551 for( int pointX : state.points )
2552 commandedShape = commandedShape || aCommanded.contains( pointX ) || aCommanded.contains( pointX + 1 );
2553
2554 // Holding one coordinate at a time keeps a rectangle corner the user placed apart
2555 // from the free corner it shares stored parameters with
2556 for( int pointX : state.points )
2557 {
2558 if( !aCommanded.contains( pointX ) )
2559 softPinCoordinate( pointX, aTag, STAY_PUT_WEIGHT );
2560
2561 if( !aCommanded.contains( pointX + 1 ) )
2562 softPinCoordinate( pointX + 1, aTag, STAY_PUT_WEIGHT );
2563 }
2564
2565 // A shape the user placed keeps its size exactly, while an untouched one only prefers to
2566 for( const RIGID_RADIUS_HOLD& hold : state.radii )
2567 {
2568 int target = temporaryParam( m_params[hold.radius] );
2569 GCS::Circle circle;
2570 circle.center = GCS::Point{ &m_params[hold.centerX], &m_params[hold.centerX + 1] };
2571 circle.rad = &m_params[hold.radius];
2572
2573 int id = m_gcs->addConstraintCircleRadius( circle, &m_params[target], aTag );
2574
2575 if( !commandedShape )
2576 m_gcs->rescaleConstraint( id, STAY_PUT_WEIGHT );
2577 }
2578 }
2579}
2580
2581
2583 const CONSTRAINT_MEMBER* aCoDragged )
2584{
2585 auto it = m_shapeVars.find( aDragged.m_item );
2586
2587 if( it == m_shapeVars.end() )
2588 return;
2589
2590 const SHAPE_VARS& vars = it->second;
2591
2592 // The pins are temporary and keep the default weight far above the stay-put pins so they hold
2593 // the dragged shape rest against a neighbour weaker stay-put pin while a real constraint still wins
2594 if( vars.kind == SHAPE_KIND::SEGMENT || vars.kind == SHAPE_KIND::BEZIER )
2595 {
2596 if( aDragged.m_anchor == CONSTRAINT_ANCHOR::START )
2597 softPinPoint( vars.endX, aTag );
2598 else if( aDragged.m_anchor == CONSTRAINT_ANCHOR::END )
2599 softPinPoint( vars.startX, aTag );
2600 }
2601 else if( vars.kind == SHAPE_KIND::ARC )
2602 {
2603 if( aDragged.m_anchor == CONSTRAINT_ANCHOR::START || aDragged.m_anchor == CONSTRAINT_ANCHOR::END )
2604 {
2605 // Hold the circle (centre + radius) and the far endpoint, so only the dragged endpoint
2606 // sweeps along the arc instead of the whole arc drifting or ballooning.
2607 softPinPoint( vars.startX, aTag );
2608 holdArcRadius( vars, aTag );
2609 softPinPoint( aDragged.m_anchor == CONSTRAINT_ANCHOR::START ? vars.arcEndX : vars.arcStartX, aTag );
2610 }
2611 else if( aDragged.m_anchor == CONSTRAINT_ANCHOR::CENTER )
2612 {
2613 // Hold both endpoints, so dragging the centre changes the radius but keeps the ends.
2614 softPinPoint( vars.arcStartX, aTag );
2615 softPinPoint( vars.arcEndX, aTag );
2616 }
2617 }
2618 else if( vars.kind == SHAPE_KIND::RECTANGLE && aDragged.m_anchor == CONSTRAINT_ANCHOR::VERTEX )
2619 {
2620 // Hold the diagonally opposite corner so grabbing a corner handle resizes the rectangle
2621 // about it instead of the whole shape drifting
2623 ( aDragged.m_index + 2 ) % 4 ) ),
2624 aTag );
2625 }
2626 else if( vars.kind == SHAPE_KIND::POLYGON && aDragged.m_anchor == CONSTRAINT_ANCHOR::VERTEX )
2627 {
2628 // Hold every other vertex so grabbing one handle moves only its own vertices an edge drag
2629 // names its second vertex through the co-dragged member whose pin must not be fought here
2630 for( int i = 0; i < vars.vertexCount; ++i )
2631 {
2632 if( i == aDragged.m_index )
2633 continue;
2634
2635 if( aCoDragged && aCoDragged->m_item == aDragged.m_item && i == aCoDragged->m_index )
2636 continue;
2637
2638 softPinPoint( vars.startX + 2 * i, aTag );
2639 }
2640 }
2641}
2642
2643
2644void BOARD_CONSTRAINT_ADAPTER::pinUneditedShapes( const std::set<KIID>& aEdited, int aTag )
2645{
2646 // The stay-put pins are the weakest tier so the drive pins and hard constraints all win while a
2647 // neighbour with slack still holds exactly since nothing else acts on its coordinates
2648
2649 // Hold a curve radius scalar so a circle or ellipse with slack keeps its size
2650 auto holdRadius = [&]( const SHAPE_VARS& aVars )
2651 {
2652 GCS::Circle circle;
2653 circle.center = GCS::Point{ &m_params[aVars.startX], &m_params[aVars.startX + 1] };
2654 circle.rad = &m_params[aVars.radius];
2655
2656 int rad = temporaryParam( m_params[aVars.radius] );
2657 m_gcs->rescaleConstraint( m_gcs->addConstraintCircleRadius( circle, &m_params[rad], aTag ), STAY_PUT_WEIGHT );
2658 };
2659
2660 for( const auto& [kiid, vars] : m_shapeVars )
2661 {
2662 if( aEdited.contains( kiid ) )
2663 continue;
2664
2665 // A locked shape or dimension is already frozen at Build so a soft pin would only add
2666 // redundant work
2667 if( ConstraintItemIsLocked( vars.shape ) || ConstraintItemIsLocked( vars.dimension ) )
2668 continue;
2669
2670 switch( vars.kind )
2671 {
2673 case SHAPE_KIND::BEZIER:
2676 // Pinning both stored points fixes the whole shape a segment entirely and a rect four
2677 // corners with them since the corners alias these params
2678 softPinPoint( vars.startX, aTag, STAY_PUT_WEIGHT );
2679 softPinPoint( vars.endX, aTag, STAY_PUT_WEIGHT );
2680 break;
2681
2682 case SHAPE_KIND::CIRCLE:
2684 // A circle or closed ellipse has no endpoints so hold the centre and the radius scalar
2685 // the ellipse focus-to-centre offset is fixed at Build so this pins the whole shape
2686 softPinPoint( vars.startX, aTag, STAY_PUT_WEIGHT );
2687 holdRadius( vars );
2688 break;
2689
2690 case SHAPE_KIND::ARC:
2692 softPinPoint( vars.startX, aTag, STAY_PUT_WEIGHT );
2693 softPinPoint( vars.arcStartX, aTag, STAY_PUT_WEIGHT );
2694 softPinPoint( vars.arcEndX, aTag, STAY_PUT_WEIGHT );
2695 holdRadius( vars );
2696 break;
2697
2699 // Every vertex bound ones included the pins live in the null space of the hard
2700 // constraints so a driving length still moves the vertices it binds
2701 for( int i = 0; i < vars.vertexCount; ++i )
2702 softPinPoint( vars.startX + 2 * i, aTag, STAY_PUT_WEIGHT );
2703
2704 break;
2705
2707 softPinPoint( vars.startX, aTag, STAY_PUT_WEIGHT );
2708 break;
2709 }
2710 }
2711}
2712
2713
2714void BOARD_CONSTRAINT_ADAPTER::holdPolygonVertices( const std::set<KIID>& aShapes, int aTag )
2715{
2716 for( const auto& [kiid, vars] : m_shapeVars )
2717 {
2718 if( vars.kind != SHAPE_KIND::POLYGON || ConstraintItemIsLocked( vars.shape ) )
2719 continue;
2720
2721 if( !aShapes.contains( kiid ) )
2722 continue;
2723
2724 for( int i = 0; i < vars.vertexCount; ++i )
2725 softPinPoint( vars.startX + 2 * i, aTag, STAY_PUT_WEIGHT );
2726 }
2727}
2728
2729
2730void BOARD_CONSTRAINT_ADAPTER::holdFreeSegmentLengths( int aTag, const std::set<KIID>& aShapes )
2731{
2732 // Hold each named free segment length so an angle constraint cannot collapse it to a point
2733 for( const auto& [kiid, vars] : m_shapeVars )
2734 {
2735 if( vars.kind != SHAPE_KIND::SEGMENT || ConstraintItemIsLocked( vars.shape ) )
2736 continue;
2737
2738 if( !aShapes.contains( kiid ) )
2739 continue;
2740
2741 GCS::Point p1{ &m_params[vars.startX], &m_params[vars.startX + 1] };
2742 GCS::Point p2{ &m_params[vars.endX], &m_params[vars.endX + 1] };
2743 double dx = m_params[vars.endX] - m_params[vars.startX];
2744 double dy = m_params[vars.endX + 1] - m_params[vars.startX + 1];
2745 int len = temporaryParam( std::hypot( dx, dy ) );
2746 m_gcs->addConstraintP2PDistance( p1, p2, &m_params[len], aTag );
2747 }
2748}
2749
2750
2752{
2753 GCS::Circle circle;
2754 circle.center = GCS::Point{ &m_params[aVars.startX], &m_params[aVars.startX + 1] };
2755 circle.rad = &m_params[aVars.radius];
2756
2757 int rad = temporaryParam( m_params[aVars.radius] );
2758 m_gcs->addConstraintCircleRadius( circle, &m_params[rad], aTag );
2759}
2760
2761
2762void BOARD_CONSTRAINT_ADAPTER::holdFreeArcRadii( int aTag, const std::set<KIID>& aShapes )
2763{
2764 // Hold each named free arc radius so an ARC_ANGLE change rotates an endpoint instead of the
2765 // solver collapsing the arc to a point a real FIXED_RADIUS still wins since this hold is temporary
2766 for( const auto& [kiid, vars] : m_shapeVars )
2767 {
2768 if( vars.kind != SHAPE_KIND::ARC || ConstraintItemIsLocked( vars.shape ) )
2769 continue;
2770
2771 if( !aShapes.contains( kiid ) )
2772 continue;
2773
2774 holdArcRadius( vars, aTag );
2775 }
2776}
2777
2778
2779void BOARD_CONSTRAINT_ADAPTER::holdShapesRigid( int aTag, const std::set<KIID>& aShapes )
2780{
2781 for( const auto& [kiid, vars] : m_shapeVars )
2782 {
2783 // A dimension has no shape params to hold, and a locked shape is frozen at Build already.
2784 if( !vars.shape || ConstraintItemIsLocked( vars.shape ) || !aShapes.contains( kiid ) )
2785 continue;
2786
2787 RIGID_STATE state = collectRigidState( { kiid } );
2788
2789 if( state.points.empty() )
2790 continue;
2791
2792 // Every other point holds its offset from the first, so the shape travels but cannot deform.
2793 const int anchorX = *state.points.begin();
2794
2795 for( int pointX : state.points )
2796 {
2797 if( pointX == anchorX )
2798 continue;
2799
2800 int offsetX = temporaryParam( m_params[pointX] - m_params[anchorX] );
2801 int offsetY = temporaryParam( m_params[pointX + 1] - m_params[anchorX + 1] );
2802
2803 m_gcs->addConstraintDifference( &m_params[anchorX], &m_params[pointX], &m_params[offsetX], aTag );
2804 m_gcs->addConstraintDifference( &m_params[anchorX + 1], &m_params[pointX + 1], &m_params[offsetY], aTag );
2805 }
2806
2807 holdRigidRadii( state.radii, aTag );
2808 }
2809}
2810
2811
2812std::vector<PCB_SHAPE*> BOARD_CONSTRAINT_ADAPTER::Apply( const std::function<void( BOARD_ITEM* )>& aBeforeWrite )
2813{
2814 std::vector<PCB_SHAPE*> changed;
2815
2816 if( !m_built )
2817 return changed;
2818
2819 // The solved point at param index aX (its y is the next slot), back in IU.
2820 auto pointAt = [&]( int aX )
2821 {
2822 return VECTOR2I( KiROUND( denormalizeX( m_params[aX] ) ), KiROUND( denormalizeY( m_params[aX + 1] ) ) );
2823 };
2824
2825 for( const RIGID_FOOTPRINT& body : m_rigidFootprints )
2826 {
2827 // A drag session re-applies every frame from its baseline so target the solved position
2828 // rather than stacking each frame's translation
2829 VECTOR2I translation( KiROUND( m_params[body.translationX] * m_scale ),
2830 KiROUND( m_params[body.translationX + 1] * m_scale ) );
2831 VECTOR2I delta = body.buildPosition + translation - body.footprint->GetPosition();
2832
2833 if( delta == VECTOR2I() )
2834 continue;
2835
2836 if( aBeforeWrite )
2837 aBeforeWrite( body.footprint );
2838
2839 body.footprint->Move( delta );
2840 }
2841
2842 for( const auto& [kiid, vars] : m_shapeVars )
2843 {
2844 // Rigid children already moved with their footprint and a pad never moves on its own
2845 if( m_rigidMembers.contains( kiid ) || vars.kind == SHAPE_KIND::PAD_CENTER )
2846 continue;
2847
2848 if( vars.kind == SHAPE_KIND::POINT_PAIR )
2849 {
2850 VECTOR2I start = pointAt( vars.startX );
2851
2852 // A leader or centre mark has no bindable end (endX == -1); leave its end untouched.
2853 VECTOR2I end = vars.endX >= 0 ? pointAt( vars.endX ) : vars.dimension->GetEnd();
2854
2855 if( start == vars.dimension->GetStart() && end == vars.dimension->GetEnd() )
2856 continue;
2857
2858 if( aBeforeWrite )
2859 aBeforeWrite( vars.dimension );
2860
2861 PCB_DIM_RADIAL* radial = vars.dimension->Type() == PCB_DIM_RADIAL_T
2862 ? static_cast<PCB_DIM_RADIAL*>( vars.dimension )
2863 : nullptr;
2864 VECTOR2I oldKnee = radial ? radial->GetKnee() : VECTOR2I();
2865
2866 vars.dimension->SetStart( start );
2867 vars.dimension->SetEnd( end );
2868
2869 if( radial )
2870 radial->SetTextPos( radial->GetTextPos() + radial->GetKnee() - oldKnee );
2871
2872 vars.dimension->Update(); // SetStart/SetEnd alone do not re-derive the crossbar and text
2873 continue;
2874 }
2875
2876 if( vars.kind == SHAPE_KIND::CIRCLE )
2877 {
2878 VECTOR2I center = pointAt( vars.startX );
2879 int radius = KiROUND( m_params[vars.radius] * m_scale );
2880
2881 if( center == vars.shape->GetCenter() && radius == vars.shape->GetRadius() )
2882 continue;
2883
2884 if( aBeforeWrite )
2885 aBeforeWrite( vars.shape );
2886
2887 vars.shape->SetCenter( center );
2888 vars.shape->SetRadius( radius );
2889 changed.push_back( vars.shape );
2890 continue;
2891 }
2892
2893 if( vars.kind == SHAPE_KIND::ARC )
2894 {
2895 // A sub-micron radius is a collapse, not intent, so leave the arc as it was rather than
2896 // write a degenerate ring the diagnostics would not catch.
2897 if( m_params[vars.radius] * m_scale < 1000.0 && vars.shape->GetRadius() >= 1000 )
2898 continue;
2899
2900 VECTOR2I center = pointAt( vars.startX );
2901 VECTOR2I start = pointAt( vars.arcStartX );
2902 VECTOR2I end = pointAt( vars.arcEndX );
2903
2904 if( start == vars.shape->GetStart() && end == vars.shape->GetEnd()
2905 && center == vars.shape->GetCenter() )
2906 {
2907 continue;
2908 }
2909
2910 if( aBeforeWrite )
2911 aBeforeWrite( vars.shape );
2912
2913 // The mid lies on the solved circle at the bisector of the swept angles. Take the
2914 // bisector on the side that keeps the original winding so the arc does not flip.
2915 double rad = m_params[vars.radius] * m_scale;
2916 double sa = std::atan2( start.y - center.y, start.x - center.x );
2917 double ea = std::atan2( end.y - center.y, end.x - center.x );
2918
2919 if( vars.shape->IsClockwiseArc() )
2920 {
2921 if( ea > sa )
2922 ea -= 2.0 * M_PI;
2923 }
2924 else if( ea < sa )
2925 {
2926 ea += 2.0 * M_PI;
2927 }
2928
2929 double midAngle = 0.5 * ( sa + ea );
2930 VECTOR2I mid( KiROUND( center.x + rad * std::cos( midAngle ) ),
2931 KiROUND( center.y + rad * std::sin( midAngle ) ) );
2932
2933 vars.shape->SetArcGeometry( start, mid, end );
2934 changed.push_back( vars.shape );
2935 continue;
2936 }
2937
2938 if( vars.kind == SHAPE_KIND::ELLIPSE || vars.kind == SHAPE_KIND::ELLIPSE_ARC )
2939 {
2940 VECTOR2I center = pointAt( vars.startX );
2941
2942 // Recover major radius and rotation from the solved focus.
2943 double fx = ( m_params[vars.focusX] - m_params[vars.startX] ) * m_scale;
2944 double fy = ( m_params[vars.focusX + 1] - m_params[vars.startX + 1] ) * m_scale;
2945 double focal = std::hypot( fx, fy );
2946 double minor = m_params[vars.radius] * m_scale;
2947 double major = std::sqrt( focal * focal + minor * minor );
2948
2949 // A focal distance below 1 IU means a circle-degenerate ellipse with no defined
2950 // rotation, so keep the shape's current one.
2951 EDA_ANGLE rotation =
2952 focal > 1.0 ? EDA_ANGLE( std::atan2( fy, fx ), RADIANS_T ) : vars.shape->GetEllipseRotation();
2953
2954 EDA_ANGLE startAngle = vars.shape->GetEllipseStartAngle();
2955 EDA_ANGLE endAngle = vars.shape->GetEllipseEndAngle();
2956
2957 if( vars.kind == SHAPE_KIND::ELLIPSE_ARC )
2958 {
2959 startAngle = EDA_ANGLE( m_params[vars.startAngle], RADIANS_T );
2960 endAngle = EDA_ANGLE( m_params[vars.endAngle], RADIANS_T );
2961 }
2962
2963 auto sameAngle = []( const EDA_ANGLE& aA, const EDA_ANGLE& aB )
2964 {
2965 return std::abs( ( aA - aB ).Normalize180().AsDegrees() ) < 1e-6;
2966 };
2967
2968 if( center == vars.shape->GetEllipseCenter() && KiROUND( major ) == vars.shape->GetEllipseMajorRadius()
2969 && KiROUND( minor ) == vars.shape->GetEllipseMinorRadius()
2970 && sameAngle( rotation, vars.shape->GetEllipseRotation() )
2971 && sameAngle( startAngle, vars.shape->GetEllipseStartAngle() )
2972 && sameAngle( endAngle, vars.shape->GetEllipseEndAngle() ) )
2973 {
2974 continue;
2975 }
2976
2977 if( aBeforeWrite )
2978 aBeforeWrite( vars.shape );
2979
2980 vars.shape->SetEllipseCenter( center );
2981 vars.shape->SetEllipseRotation( rotation );
2982 vars.shape->SetEllipseMajorRadius( KiROUND( major ) );
2983 vars.shape->SetEllipseMinorRadius( KiROUND( minor ) );
2984
2985 if( vars.kind == SHAPE_KIND::ELLIPSE_ARC )
2986 {
2987 vars.shape->SetEllipseStartAngle( startAngle );
2988 vars.shape->SetEllipseEndAngle( endAngle );
2989 }
2990
2991 changed.push_back( vars.shape );
2992 continue;
2993 }
2994
2995 if( vars.kind == SHAPE_KIND::BEZIER )
2996 {
2997 VECTOR2I start = pointAt( vars.startX );
2998 VECTOR2I end = pointAt( vars.endX );
2999
3000 if( start == vars.shape->GetStart() && end == vars.shape->GetEnd() )
3001 continue;
3002
3003 if( aBeforeWrite )
3004 aBeforeWrite( vars.shape );
3005
3006 // Translate each control handle by its adjacent endpoint delta so the curve shape rides
3007 // along instead of shearing when an endpoint moves
3008 VECTOR2I startDelta = start - vars.shape->GetStart();
3009 VECTOR2I endDelta = end - vars.shape->GetEnd();
3010
3011 vars.shape->SetBezierC1( vars.shape->GetBezierC1() + startDelta );
3012 vars.shape->SetBezierC2( vars.shape->GetBezierC2() + endDelta );
3013 vars.shape->SetStart( start );
3014 vars.shape->SetEnd( end );
3015 vars.shape->RebuildBezierToSegmentsPointsList();
3016 changed.push_back( vars.shape );
3017 continue;
3018 }
3019
3020 if( vars.kind == SHAPE_KIND::POLYGON )
3021 {
3022 const SHAPE_POLY_SET& polySet = vars.shape->GetPolyShape();
3023
3024 // A vertex-count mismatch means an external edit changed the outline CPoint wraps indices
3025 // so a stale count would silently resurrect dropped vertices skip the write instead
3026 if( polySet.OutlineCount() != 1 || polySet.HoleCount( 0 ) != 0
3027 || polySet.COutline( 0 ).PointCount() != vars.vertexCount )
3028 {
3029 continue;
3030 }
3031
3032 std::vector<VECTOR2I> points;
3033 points.reserve( vars.vertexCount );
3034
3035 for( int i = 0; i < vars.vertexCount; ++i )
3036 points.push_back( pointAt( vars.startX + 2 * i ) );
3037
3038 const SHAPE_LINE_CHAIN& outline = polySet.COutline( 0 );
3039 bool moved = false;
3040
3041 for( int i = 0; i < vars.vertexCount; ++i )
3042 {
3043 if( points[i] != outline.CPoint( i ) )
3044 {
3045 moved = true;
3046 break;
3047 }
3048 }
3049
3050 if( !moved )
3051 continue;
3052
3053 if( aBeforeWrite )
3054 aBeforeWrite( vars.shape );
3055
3056 // SetPolyPoints rebuilds the poly wholesale dropping cached derived geometry with it
3057 // ingestion only admits single-outline hole-free polys so nothing else is lost here
3058 vars.shape->SetPolyPoints( points );
3059 changed.push_back( vars.shape );
3060 continue;
3061 }
3062
3063 if( vars.kind == SHAPE_KIND::RECTANGLE )
3064 {
3065 VECTOR2I start = pointAt( vars.startX );
3066 VECTOR2I end = pointAt( vars.endX );
3067
3068 if( start == vars.shape->GetStart() && end == vars.shape->GetEnd() )
3069 continue;
3070
3071 // A sub-micron side is a collapse not intent and a zero-area rect vanishes from the
3072 // canvas so drop the write using the segment guard floor applied per axis
3073 const int collapseFloor = 1000;
3074 int newWidth = std::abs( end.x - start.x );
3075 int newHeight = std::abs( end.y - start.y );
3076 int curWidth = std::abs( vars.shape->GetEnd().x - vars.shape->GetStart().x );
3077 int curHeight = std::abs( vars.shape->GetEnd().y - vars.shape->GetStart().y );
3078
3079 if( ( newWidth < collapseFloor && curWidth >= collapseFloor )
3080 || ( newHeight < collapseFloor && curHeight >= collapseFloor ) )
3081 {
3082 continue;
3083 }
3084
3085 if( aBeforeWrite )
3086 aBeforeWrite( vars.shape );
3087
3088 // SetStart and SetEnd do not re-clamp the stored corner radius so re-apply it through the
3089 // setter whose half-shorter-side clamp keeps a shrunk rect radius in range
3090 int cornerRadius = vars.shape->GetCornerRadius();
3091
3092 vars.shape->SetStart( start );
3093 vars.shape->SetEnd( end );
3094
3095 if( cornerRadius > 0 )
3096 vars.shape->SetCornerRadius( cornerRadius );
3097
3098 changed.push_back( vars.shape );
3099 continue;
3100 }
3101
3102 VECTOR2I start = pointAt( vars.startX );
3103 VECTOR2I end = pointAt( vars.endX );
3104
3105 if( start == vars.shape->GetStart() && end == vars.shape->GetEnd() )
3106 continue;
3107
3108 // A sub-micron result is a collapse, not intent, and a zero-length line vanishes from the
3109 // canvas, so drop it.
3110 const double collapseFloor = 1000.0;
3111 double newLen = ( end - start ).EuclideanNorm();
3112 double curLen = ( vars.shape->GetEnd() - vars.shape->GetStart() ).EuclideanNorm();
3113
3114 if( newLen < collapseFloor && curLen >= collapseFloor )
3115 continue;
3116
3117 if( aBeforeWrite )
3118 aBeforeWrite( vars.shape );
3119
3120 vars.shape->SetStart( start );
3121 vars.shape->SetEnd( end );
3122 changed.push_back( vars.shape );
3123 }
3124
3125 return changed;
3126}
3127
3128
3130{
3132
3133 if( !m_built )
3134 return diag;
3135
3136 m_gcs->diagnose();
3137 diag.freeDof = m_gcs->dofsNumber();
3138
3139 GCS::VEC_I conflictingTags;
3140 GCS::VEC_I redundantTags;
3141 m_gcs->getConflicting( conflictingTags );
3142 m_gcs->getRedundant( redundantTags );
3143
3144 auto tagsToKiids = [&]( const GCS::VEC_I& aTags, std::vector<KIID>& aOut )
3145 {
3146 for( int t : aTags )
3147 {
3148 auto it = m_tagToConstraint.find( t );
3149
3150 if( it != m_tagToConstraint.end() )
3151 aOut.push_back( it->second );
3152 }
3153 };
3154
3155 tagsToKiids( conflictingTags, diag.conflicting );
3156 tagsToKiids( redundantTags, diag.redundant );
3157
3158 auto flagConflict = [&]( const KIID& aKiid )
3159 {
3160 if( std::ranges::find( diag.conflicting, aKiid ) == diag.conflicting.end() )
3161 diag.conflicting.push_back( aKiid );
3162 };
3163
3164 // Also flag any constraint the geometry does not satisfy. The rank analysis can miss it.
3165 const double residualTol = 1e-3;
3166
3167 for( const auto& [tag, kiid] : m_tagToConstraint )
3168 {
3169 // A reference constraint only measures; its stored value drifting from the geometry is
3170 // never a contradiction.
3171 if( m_nonDrivingTags.contains( tag ) )
3172 continue;
3173
3174 double err = m_gcs->calculateConstraintErrorByTag( tag );
3175
3176 // A nan is a degenerate system, not a conflict. A real contradiction leaves a finite error.
3177 if( !std::isfinite( err ) || std::abs( err ) <= residualTol )
3178 continue;
3179
3180 flagConflict( kiid );
3181 }
3182
3183 // The solve collapsing a segment to a point (e.g. horizontal and vertical at once) satisfies the
3184 // constraints with zero residual, so flag the constraints incident on the collapsed segments.
3185 const double normFloor = 1e-3;
3186 std::set<KIID> collapsedShapes;
3187
3188 for( const auto& [k, vars] : m_shapeVars )
3189 {
3190 if( vars.kind != SHAPE_KIND::SEGMENT )
3191 continue;
3192
3193 double solvedLen = std::hypot( m_params[vars.endX] - m_params[vars.startX],
3194 m_params[vars.endX + 1] - m_params[vars.startX + 1] );
3195 double origLen = ( vars.shape->GetEnd() - vars.shape->GetStart() ).EuclideanNorm() * m_invScale;
3196
3197 if( origLen > normFloor && solvedLen < normFloor )
3198 collapsedShapes.insert( k );
3199 }
3200
3201 if( !collapsedShapes.empty() )
3202 {
3203 bool attributed = false;
3204
3205 for( const auto& [tag, kiid] : m_tagToConstraint )
3206 {
3207 // A reference measurement never causes a collapse.
3208 if( m_nonDrivingTags.contains( tag ) )
3209 continue;
3210
3211 auto members = m_tagMembers.find( tag );
3212
3213 if( members == m_tagMembers.end() )
3214 continue;
3215
3216 bool incident = std::any_of( members->second.begin(), members->second.end(),
3217 [&]( const KIID& aMember )
3218 {
3219 return collapsedShapes.contains( aMember );
3220 } );
3221
3222 if( incident )
3223 {
3224 flagConflict( kiid );
3225 attributed = true;
3226 }
3227 }
3228
3229 // A collapse no mapped constraint touches should not happen; keep the whole-cluster flag
3230 // as a fallback so the contradiction is never silently dropped.
3231 if( !attributed )
3232 {
3233 for( const auto& [tag, kiid] : m_tagToConstraint )
3234 {
3235 if( !m_nonDrivingTags.contains( tag ) )
3236 flagConflict( kiid );
3237 }
3238 }
3239 }
3240
3241 // .solved reflects the last Solve(), which Diagnose() does not run; the caller sets it.
3242 return diag;
3243}
3244
3245
3247{
3248 m_adapter.reset();
3249 m_baseline.clear();
3250 m_baseConflict = false;
3251}
3252
3253
3255 const std::unordered_set<KIID>& aClusterShapes,
3256 const std::vector<PCB_CONSTRAINT*>& aConstraints )
3257{
3258 m_board = aBoard;
3259 reset();
3260
3261 std::vector<PCB_SHAPE*> shapes = resolveClusterShapes( aBoard, aClusterShapes );
3262 std::vector<PCB_DIMENSION_BASE*> dimensions = resolveClusterDimensions( aBoard, aClusterShapes );
3263 std::vector<PAD*> pads = resolveClusterPads( aBoard, aClusterShapes );
3264
3265 if( ( shapes.empty() && dimensions.empty() && pads.empty() ) || aConstraints.empty() )
3266 return false;
3267
3268 auto adapter = std::make_unique<BOARD_CONSTRAINT_ADAPTER>();
3269
3270 if( !adapter->Build( shapes, aConstraints, nullptr, dimensions, pads ) )
3271 return false;
3272
3273 m_adapter = std::move( adapter );
3274 m_baseline = m_adapter->Snapshot();
3275 m_baseConflict = !m_adapter->CurrentRelationsSatisfied();
3276 return true;
3277}
3278
3279
3281{
3283 result.position = aContext.sourcePoint;
3284
3285 if( m_baseConflict )
3287 else if( !m_adapter )
3289
3290 return result;
3291}
3292
3293
3295 double aResidual )
3296{
3297 aResult.quantizedResiduals.push_back( aResidual );
3298 aResult.remainingDof = std::max( 0, aResult.remainingDof - aCandidate.consumedDof );
3299}
3300
3301
3303 const std::vector<PCB_SHAPE*>& aEditedShapes,
3304 const VECTOR2I& aReference )
3305{
3306 m_reference = aReference;
3307 m_edited.clear();
3308 reset();
3309
3310 if( !aBoard || aEditedShapes.empty() )
3311 return false;
3312
3313 auto shapeToConstraints = buildShapeConstraintMap( aBoard, CollectResolvedConstraints( aBoard ) );
3314 std::set<KIID> visited;
3315 std::unordered_set<KIID> sessionShapes;
3316 std::vector<PCB_CONSTRAINT*> sessionConstraints;
3317
3318 // Every seed's cluster joins one adapter: a move is rigid, so shapes that constrain each
3319 // other must be solved together even when the user grabbed them separately.
3320 for( PCB_SHAPE* seed : aEditedShapes )
3321 {
3322 if( !seed || visited.contains( seed->m_Uuid )
3323 || !shapeToConstraints.contains( seed->m_Uuid ) )
3324 {
3325 continue;
3326 }
3327
3328 std::unordered_set<KIID> clusterShapes;
3329 std::vector<PCB_CONSTRAINT*> clusterConstraints;
3330 collectConstraintCluster( shapeToConstraints, seed->m_Uuid, clusterShapes,
3331 clusterConstraints, &visited );
3332
3333 for( PCB_SHAPE* edited : aEditedShapes )
3334 {
3335 if( edited && clusterShapes.contains( edited->m_Uuid ) )
3336 m_edited.insert( edited->m_Uuid );
3337 }
3338
3339 sessionShapes.insert( clusterShapes.begin(), clusterShapes.end() );
3340 sessionConstraints.insert( sessionConstraints.end(), clusterConstraints.begin(),
3341 clusterConstraints.end() );
3342 }
3343
3344 if( m_edited.empty() )
3345 return false;
3346
3347 return buildCluster( aBoard, sessionShapes, sessionConstraints );
3348}
3349
3350
3352{
3353 if( !usable() )
3354 return false;
3355
3356 bool feasible = rewind() && m_adapter->SolveRigidTranslation( m_edited, aTarget - m_reference );
3357 rewind();
3358 return feasible;
3359}
3360
3361
3363 const SNAP_SOURCE_CONTEXT& aContext, const std::vector<SNAP_CANDIDATE>& aCandidates )
3364{
3365 SNAP_RESULT result = startResult( aContext );
3366
3367 if( result.status != SNAP_RESULT_STATUS::SUCCESS )
3368 return result;
3369
3370 // The cluster may already sit on every candidate, in which case the move is a no-op and the
3371 // unconstrained answer is the right one.
3372 if( !aCandidates.empty() && feasibleAt( m_reference ) )
3373 {
3374 SNAP_SOURCE_CONTEXT referenceContext = aContext;
3375 referenceContext.sourcePoint = m_reference;
3376 SNAP_RESOLVER referenceResolver;
3377
3378 for( const SNAP_CANDIDATE& candidate : aCandidates )
3379 referenceResolver.AddCandidate( candidate );
3380
3381 SNAP_RESULT referenceResult = referenceResolver.Resolve( referenceContext );
3382 bool allAccepted = referenceResult.position == m_reference;
3383
3384 for( const SNAP_CANDIDATE& candidate : aCandidates )
3385 allAccepted = allAccepted && referenceResult.Accepted( candidate.id );
3386
3387 if( allAccepted )
3388 return referenceResult;
3389 }
3390
3391 VECTOR2I projected;
3392 bool solved = rewind()
3393 && m_adapter->SolveRigidSnapRelations( m_edited, m_reference, aCandidates,
3394 aContext.sourcePoint, projected );
3395 rewind();
3396
3397 if( !solved )
3398 {
3399 if( aCandidates.empty() && feasibleAt( m_reference ) )
3400 {
3401 result.position = m_reference;
3402 return result;
3403 }
3404
3406 return result;
3407 }
3408
3409 if( !feasibleAt( projected ) )
3410 {
3412 return result;
3413 }
3414
3415 result.position = projected;
3416
3417 // A rigid move lands the cluster exactly on whatever it accepted, so every residual is zero.
3418 for( const SNAP_CANDIDATE& candidate : aCandidates )
3419 accept( result, candidate, 0.0 );
3420
3421 return result;
3422}
3423
3424
3426 const VECTOR2I& aTarget, std::vector<PCB_SHAPE*>* aModified,
3427 const std::function<void( BOARD_ITEM* )>& aBeforeModify )
3428{
3429 // A cluster that travels whole carries any base conflict along unchanged, so the conflict is no
3430 // reason to refuse the move
3431 if( !m_adapter || ( HasBaseConflict() && !m_adapter->TravelsWhole( m_edited ) ) )
3432 return false;
3433
3434 if( !rewind() || !m_adapter->SolveRigidTranslation( m_edited, aTarget - m_reference ) )
3435 {
3436 rewind();
3437 return false;
3438 }
3439
3440 std::vector<PCB_SHAPE*> changed = m_adapter->Apply( aBeforeModify );
3441 m_adapter->ApplyReferenceValues( aBeforeModify );
3442
3443 if( aModified )
3444 aModified->insert( aModified->end(), changed.begin(), changed.end() );
3445
3446 return true;
3447}
3448
3449
3450bool BOARD_CONSTRAINT_BLOCK_SESSION::Build( BOARD* aBoard, const std::vector<BOARD_ITEM*>& aBlockItems )
3451{
3452 reset();
3453
3454 if( !aBoard || aBlockItems.empty() )
3455 return false;
3456
3457 auto shapeToConstraints = buildShapeConstraintMap( aBoard, CollectResolvedConstraints( aBoard ) );
3458 std::set<KIID> visited;
3459 std::unordered_set<KIID> sessionShapes;
3460 std::vector<PCB_CONSTRAINT*> sessionConstraints;
3461
3462 // Every cluster the block touches goes into one adapter. Two block shapes can constrain
3463 // each other, and a cluster solved on its own would pull the other's anchors back
3464 for( BOARD_ITEM* seed : aBlockItems )
3465 {
3466 if( !seed || visited.contains( seed->m_Uuid ) || !shapeToConstraints.contains( seed->m_Uuid ) )
3467 continue;
3468
3469 std::unordered_set<KIID> clusterShapes;
3470 std::vector<PCB_CONSTRAINT*> clusterConstraints;
3471 collectConstraintCluster( shapeToConstraints, seed->m_Uuid, clusterShapes, clusterConstraints, &visited );
3472
3473 sessionShapes.insert( clusterShapes.begin(), clusterShapes.end() );
3474 sessionConstraints.insert( sessionConstraints.end(), clusterConstraints.begin(), clusterConstraints.end() );
3475 }
3476
3477 if( sessionShapes.empty() )
3478 return false;
3479
3480 if( !buildCluster( aBoard, sessionShapes, sessionConstraints ) )
3481 return false;
3482
3483 // One constraint that the geometry already fails marks the whole cluster conflicted, and a
3484 // conflicted cluster is solved not at all, so the constraints that do hold are dropped with
3485 // it. Take the stale ones out instead and keep enforcing the rest
3486 if( m_baseConflict && m_adapter->DropStaleRelations() > 0 )
3487 m_baseConflict = !m_adapter->CurrentRelationsSatisfied();
3488
3489 return true;
3490}
3491
3492
3494BOARD_CONSTRAINT_BLOCK_SESSION::Solve( const std::vector<std::pair<CONSTRAINT_MEMBER, VECTOR2I>>& aPinnedAnchors,
3495 const std::set<KIID>& aTranslatedShapes, const VECTOR2I& aTranslation,
3496 std::vector<PCB_SHAPE*>* aModified,
3497 const std::function<void( BOARD_ITEM* )>& aBeforeModify )
3498{
3499 // Leave a cluster that was already broken before the drag alone, so the drag does not
3500 // quietly repair geometry the user did not touch
3501 if( !usable() || !rewind() )
3503
3504 CONSTRAINT_BLOCK_RESULT result = m_adapter->SolveBlockEdit( aPinnedAnchors, aTranslatedShapes, aTranslation );
3505
3507 {
3508 rewind();
3509 return result;
3510 }
3511
3512 // The starting geometry stays as it was when the session was built, so every frame
3513 // solves the same system and only the final offset decides the result
3514 std::vector<PCB_SHAPE*> changed = m_adapter->Apply( aBeforeModify );
3515 m_adapter->ApplyReferenceValues( aBeforeModify );
3516
3517 if( aModified )
3518 aModified->insert( aModified->end(), changed.begin(), changed.end() );
3519
3520 return result;
3521}
3522
3523
3525{
3526 m_board = aBoard;
3527 m_dragged = aDragged;
3528 m_draggedShape = nullptr;
3529 reset();
3530
3531 if( !m_board )
3532 return false;
3533
3534 auto shapeToConstraints = buildShapeConstraintMap( m_board, CollectResolvedConstraints( m_board ) );
3535 std::unordered_set<KIID> clusterShapes;
3536 std::vector<PCB_CONSTRAINT*> clusterConstraints;
3537 collectConstraintCluster( shapeToConstraints, m_dragged.m_item, clusterShapes, clusterConstraints );
3538
3539 if( !buildCluster( m_board, clusterShapes, clusterConstraints ) )
3540 return false;
3541
3542 m_draggedShape = dynamic_cast<PCB_SHAPE*>( m_board->ResolveItem( m_dragged.m_item, true ) );
3543 return true;
3544}
3545
3546
3548{
3549 return m_adapter && m_dragged.m_item == aDragged.m_item
3550 && m_dragged.m_anchor == aDragged.m_anchor && m_dragged.m_index == aDragged.m_index;
3551}
3552
3553
3555{
3556 if( !usable() || !rewind() )
3557 return false;
3558
3559 bool solved = m_adapter->Solve( m_dragged, aTarget, false );
3560 std::optional<VECTOR2I> resolved = solved ? m_adapter->AnchorPosition( m_dragged ) : std::nullopt;
3561 bool quantizedValid = resolved && *resolved == aTarget && m_adapter->QuantizedRelationsSatisfied();
3562 rewind();
3563 return quantizedValid;
3564}
3565
3566
3568 const SNAP_SOURCE_CONTEXT& aContext, const std::vector<SNAP_CANDIDATE>& aCandidates )
3569{
3570 SNAP_RESULT result = startResult( aContext );
3571
3572 if( result.status != SNAP_RESULT_STATUS::SUCCESS || aCandidates.empty() )
3573 return result;
3574
3575 if( !rewind() )
3576 {
3578 return result;
3579 }
3580
3581 if( !m_adapter->SolveSnapRelations( m_dragged, aCandidates, aContext.sourcePoint ) )
3582 {
3583 rewind();
3585 return result;
3586 }
3587
3588 std::optional<VECTOR2I> resolved = m_adapter->AnchorPosition( m_dragged );
3589
3590 if( !resolved )
3591 {
3592 rewind();
3594 return result;
3595 }
3596
3597 result.position = *resolved;
3598
3599 const auto candidateResidual =
3600 [&]( const SNAP_CANDIDATE& aCandidate ) -> std::optional<double>
3601 {
3602 VECTOR2D point( result.position );
3603
3604 switch( aCandidate.relation )
3605 {
3609 return ( point - aCandidate.origin ).EuclideanNorm();
3610
3613 return std::abs( point.x - aCandidate.origin.x );
3614
3617 return std::abs( point.y - aCandidate.origin.y );
3618
3621 if( aCandidate.direction.x != 0.0 )
3622 return std::abs( point.x - aCandidate.origin.x );
3623
3624 if( aCandidate.direction.y != 0.0 )
3625 return std::abs( point.y - aCandidate.origin.y );
3626
3627 return std::nullopt;
3628
3633 {
3634 double divisor = aCandidate.direction.SquaredEuclideanNorm();
3635
3636 if( divisor <= 1e-12 )
3637 return std::nullopt;
3638
3639 VECTOR2D offset = point - aCandidate.origin;
3640 double parameter = offset.Dot( aCandidate.direction ) / divisor;
3641
3642 if( aCandidate.relation == SNAP_RELATION::POINT_ON_RAY && parameter < 0.0 )
3643 return std::nullopt;
3644
3645 if( aCandidate.relation == SNAP_RELATION::POINT_ON_SEGMENT
3646 && ( parameter < 0.0 || parameter > 1.0 ) )
3647 {
3648 return std::nullopt;
3649 }
3650
3651 return std::abs( offset.x * aCandidate.direction.y
3652 - offset.y * aCandidate.direction.x )
3653 / std::sqrt( divisor );
3654 }
3655
3658 {
3659 if( !aCandidate.manifold )
3660 return std::nullopt;
3661
3662 if( const CIRCLE* circle = std::get_if<CIRCLE>( &*aCandidate.manifold ) )
3663 {
3664 return std::abs( result.position.Distance( circle->Center )
3665 - circle->Radius );
3666 }
3667
3668 if( const SHAPE_ARC* arc = std::get_if<SHAPE_ARC>( &*aCandidate.manifold ) )
3669 {
3670 if( !arc->Collide( result.position, 2 ) )
3671 return std::nullopt;
3672
3673 return std::abs( result.position.Distance( arc->GetCenter() )
3674 - arc->GetRadius() );
3675 }
3676
3677 return std::nullopt;
3678 }
3679 }
3680
3681 return std::nullopt;
3682 };
3683
3684 for( const SNAP_CANDIDATE& candidate : aCandidates )
3685 {
3686 std::optional<double> residual = candidateResidual( candidate );
3687 bool discrete = candidate.relation == SNAP_RELATION::COINCIDENCE
3688 || candidate.relation == SNAP_RELATION::TANGENT
3689 || candidate.relation == SNAP_RELATION::NORMAL
3690 || candidate.relation == SNAP_RELATION::X_COORDINATE
3691 || candidate.relation == SNAP_RELATION::Y_COORDINATE
3692 || candidate.relation == SNAP_RELATION::GRID_X
3693 || candidate.relation == SNAP_RELATION::GRID_Y
3694 || candidate.relation == SNAP_RELATION::BBOX_ALIGNMENT
3695 || candidate.relation == SNAP_RELATION::BBOX_EQUAL_GAP;
3696
3697 if( !residual || ( discrete ? *residual != 0.0 : *residual > 2.0 ) )
3698 {
3699 rewind();
3701 return result;
3702 }
3703
3704 accept( result, candidate, *residual );
3705 }
3706
3707 if( !m_adapter->QuantizedRelationsSatisfied() )
3709
3710 rewind();
3711 return result;
3712}
3713
3714
3716 const VECTOR2I& aCursor, std::vector<PCB_SHAPE*>* aModified,
3717 const std::function<void( BOARD_ITEM* )>& aBeforeModify, bool aIncludeDragged,
3718 bool aStabilize, const std::set<KIID>& aEdited,
3719 const std::optional<std::pair<CONSTRAINT_MEMBER, VECTOR2I>>& aCoDragged )
3720{
3722
3723 if( !rewind() )
3724 return diag;
3725
3726 const auto notifyModify = [&]( BOARD_ITEM* aItem )
3727 {
3728 if( ( aIncludeDragged || aItem != m_draggedShape ) && aBeforeModify )
3729 aBeforeModify( aItem );
3730 };
3731
3732 if( m_baseConflict )
3733 {
3734 m_adapter->Apply( notifyModify );
3735 return m_adapter->Diagnose();
3736 }
3737
3738 if( !m_adapter->Solve( m_dragged, aCursor, aStabilize, aEdited, aCoDragged ) )
3739 {
3740 rewind();
3741 m_adapter->Apply( notifyModify );
3742 return diag;
3743 }
3744
3745 std::vector<PCB_SHAPE*> changed = m_adapter->Apply( notifyModify );
3746
3747 m_adapter->ApplyReferenceValues( aBeforeModify );
3748 m_baseline = m_adapter->Snapshot();
3749 diag = m_adapter->Diagnose();
3750 diag.solved = true;
3751
3752 if( aModified )
3753 {
3754 std::ranges::copy_if( changed, std::back_inserter( *aModified ),
3755 [&]( const PCB_SHAPE* aShape )
3756 {
3757 return aIncludeDragged || aShape != m_draggedShape;
3758 } );
3759 }
3760
3761 return diag;
3762}
3763
3764
3765CONSTRAINT_DIAGNOSIS SolveCluster( BOARD* aBoard, const CONSTRAINT_MEMBER& aDragged, const VECTOR2I& aCursor,
3766 std::vector<PCB_SHAPE*>* aModified,
3767 const std::function<void( BOARD_ITEM* )>& aBeforeModify, bool aIncludeDragged,
3768 bool aStabilize, const std::set<KIID>& aEdited,
3769 const std::optional<std::pair<CONSTRAINT_MEMBER, VECTOR2I>>& aCoDragged,
3770 const std::set<KIID>& aFixedShapes, bool aHoldDraggedRigid )
3771{
3773
3774 if( !aBoard )
3775 return diag;
3776
3777 // The cluster is the connected component of the shape<->constraint graph containing the
3778 // dragged shape, since a constraint links the shapes of all its members.
3779 auto shapeToConstraints = buildShapeConstraintMap( aBoard, CollectResolvedConstraints( aBoard ) );
3780
3781 std::unordered_set<KIID> clusterShapes;
3782 std::vector<PCB_CONSTRAINT*> clusterConstraints;
3783 collectConstraintCluster( shapeToConstraints, aDragged.m_item, clusterShapes, clusterConstraints );
3784
3785 std::vector<PCB_SHAPE*> shapes = resolveClusterShapes( aBoard, clusterShapes );
3786 std::vector<PCB_DIMENSION_BASE*> dimensions = resolveClusterDimensions( aBoard, clusterShapes );
3787 std::vector<PAD*> pads = resolveClusterPads( aBoard, clusterShapes );
3788
3789 if( ( shapes.empty() && dimensions.empty() && pads.empty() ) || clusterConstraints.empty() )
3790 return diag;
3791
3793
3794 if( !adapter.Build( shapes, clusterConstraints, &aFixedShapes, dimensions, pads ) )
3795 return diag;
3796
3797 bool solved = adapter.Solve( aDragged, aCursor, aStabilize, aEdited, aCoDragged, aHoldDraggedRigid );
3798
3799 if( !solved )
3800 return diag; // leave geometry untouched on a failed/diverged solve
3801
3802 PCB_SHAPE* draggedShape = dynamic_cast<PCB_SHAPE*>( aBoard->ResolveItem( aDragged.m_item, true ) );
3803
3804 // Stage each neighbor (not the dragged shape, which the caller stages itself) just before
3805 // its geometry is written, so the whole re-derivation is one undoable transaction.
3806 std::vector<PCB_SHAPE*> changed = adapter.Apply(
3807 [&]( BOARD_ITEM* aItem )
3808 {
3809 if( ( aIncludeDragged || aItem != draggedShape ) && aBeforeModify )
3810 aBeforeModify( aItem );
3811 } );
3812
3813 adapter.ApplyReferenceValues( aBeforeModify );
3814
3815 diag = adapter.Diagnose();
3816 diag.solved = true;
3817
3818 if( aModified )
3819 {
3820 std::ranges::copy_if( changed, std::back_inserter( *aModified ),
3821 [&]( const PCB_SHAPE* aShape )
3822 { return aIncludeDragged || aShape != draggedShape; } );
3823 }
3824
3825 return diag;
3826}
3827
3828
3829std::set<KIID> ConstraintReferenceShapes( BOARD* aBoard, const PCB_CONSTRAINT* aConstraint )
3830{
3831 if( !aBoard || !aConstraint )
3832 return {};
3833
3834 PCB_CONSTRAINT_TYPE type = aConstraint->GetConstraintType();
3835
3837 return {};
3838
3839 const std::vector<CONSTRAINT_MEMBER>& members = aConstraint->GetMembers();
3840
3841 if( members.size() != 2 || members.front().m_item == members.back().m_item )
3842 return {};
3843
3844 // Build freezes shapes only, so a reference it cannot freeze must not be named as one.
3845 if( members.back().m_anchor != CONSTRAINT_ANCHOR::WHOLE
3846 || !dynamic_cast<PCB_SHAPE*>( aBoard->ResolveItem( members.back().m_item, true ) ) )
3847 {
3848 return {};
3849 }
3850
3851 // Freezing the line as well would leave nothing able to move, so let the line move to the point.
3852 if( ConstraintItemIsLocked( aBoard->ResolveItem( members.front().m_item, true ) ) )
3853 return {};
3854
3855 auto pinsThePoint = [&]( const PCB_CONSTRAINT* aOther )
3856 {
3857 return aOther->GetConstraintType() == PCB_CONSTRAINT_TYPE::FIXED_POSITION && !aOther->GetMembers().empty()
3858 && aOther->GetMembers().front() == members.front();
3859 };
3860
3861 if( std::ranges::any_of( CollectResolvedConstraints( aBoard ), pinsThePoint ) )
3862 return {};
3863
3864 return { members.back().m_item };
3865}
3866
3867
3869 std::vector<PCB_SHAPE*>* aModified,
3870 const std::function<void( BOARD_ITEM* )>& aBeforeModify,
3871 const std::set<KIID>& aFixedShapes )
3872{
3873 if( !aBoard || !aConstraint || aConstraint->GetMembers().empty() )
3874 return {};
3875
3876 // Pin the first member's anchor where it is; the solver moves the rest of the cluster (and the
3877 // pinned shape's own free geometry) to meet the new relation. A WHOLE member is pinned at the
3878 // shape's first concrete anchor -- START for a segment/arc, CENTER for a circle.
3879 CONSTRAINT_MEMBER pin = aConstraint->GetMembers().front();
3880
3881 if( pin.m_anchor == CONSTRAINT_ANCHOR::WHOLE )
3882 {
3883 PCB_SHAPE* shape = dynamic_cast<PCB_SHAPE*>( aBoard->ResolveItem( pin.m_item, true ) );
3884
3885 if( !shape )
3886 return {};
3887
3888 std::vector<CONSTRAINT_ANCHOR_POINT> anchors = ConstraintShapeAnchors( shape );
3889
3890 if( anchors.empty() )
3891 return {};
3892
3893 pin.m_anchor = anchors.front().anchor;
3894 pin.m_index = anchors.front().index;
3895 }
3896
3897 std::optional<VECTOR2I> pos = ConstraintAnchorPosition( aBoard, pin );
3898
3899 if( !pos )
3900 return {};
3901
3902 // The pinned shape itself can move (e.g. a fixed-length segment's far end), and the caller does
3903 // not stage it separately, so report it too.
3904 return SolveCluster( aBoard, pin, *pos, aModified, aBeforeModify, /* aIncludeDragged */ true,
3905 /* aStabilize */ true, /* aEdited */ {}, /* aCoDragged */ std::nullopt, aFixedShapes,
3906 /* aHoldDraggedRigid */ !aFixedShapes.empty() );
3907}
3908
3909
3910void ReSolveShapeClusters( BOARD* aBoard, const std::vector<PCB_SHAPE*>& aShapes, std::vector<PCB_SHAPE*>* aModified,
3911 const std::function<void( BOARD_ITEM* )>& aBeforeModify )
3912{
3913 if( !aBoard )
3914 return;
3915
3916 auto shapeToConstraints = buildShapeConstraintMap( aBoard, CollectResolvedConstraints( aBoard ) );
3917
3918 // Solve each affected cluster once, no matter how many of its shapes were edited.
3919 std::set<KIID> visited;
3920
3921 for( PCB_SHAPE* shape : aShapes )
3922 {
3923 if( !shape || visited.contains( shape->m_Uuid ) || !shapeToConstraints.contains( shape->m_Uuid ) )
3924 continue;
3925
3926 std::unordered_set<KIID> clusterShapes;
3927 std::vector<PCB_CONSTRAINT*> clusterConstraints;
3928 collectConstraintCluster( shapeToConstraints, shape->m_Uuid, clusterShapes, clusterConstraints, &visited );
3929
3930 std::vector<CONSTRAINT_ANCHOR_POINT> anchors = ConstraintShapeAnchors( shape );
3931
3932 if( anchors.empty() )
3933 continue;
3934
3935 // Every edited shape that fell into this cluster must stay free only the untouched
3936 // neighbours get stay-put pins solving from a single seed would pin the others back
3937 std::set<KIID> edited;
3938
3939 for( PCB_SHAPE* other : aShapes )
3940 {
3941 if( other && clusterShapes.contains( other->m_Uuid ) )
3942 edited.insert( other->m_Uuid );
3943 }
3944
3945 SolveCluster( aBoard, { shape->m_Uuid, anchors.front().anchor, anchors.front().index }, anchors.front().pos,
3946 aModified, aBeforeModify,
3947 /* aIncludeDragged */ true, /* aStabilize */ false, edited );
3948 }
3949}
3950
3951
3952bool ReSolveShapeClustersHoldingEdited( BOARD* aBoard, const std::vector<PCB_SHAPE*>& aEditedShapes,
3953 std::vector<PCB_SHAPE*>* aModified,
3954 const std::function<void( BOARD_ITEM* )>& aBeforeModify )
3955{
3956 if( !aBoard )
3957 return false;
3958
3959 auto shapeToConstraints = buildShapeConstraintMap( aBoard, CollectResolvedConstraints( aBoard ) );
3960 std::set<KIID> visited;
3961 std::vector<std::unique_ptr<BOARD_CONSTRAINT_ADAPTER>> solvedClusters;
3962
3963 for( PCB_SHAPE* seed : aEditedShapes )
3964 {
3965 if( !seed || visited.contains( seed->m_Uuid ) || !shapeToConstraints.contains( seed->m_Uuid ) )
3966 continue;
3967
3968 std::unordered_set<KIID> clusterShapes;
3969 std::vector<PCB_CONSTRAINT*> clusterConstraints;
3970 collectConstraintCluster( shapeToConstraints, seed->m_Uuid, clusterShapes, clusterConstraints, &visited );
3971
3972 std::vector<PCB_SHAPE*> shapes = resolveClusterShapes( aBoard, clusterShapes );
3973 std::vector<PCB_DIMENSION_BASE*> dimensions = resolveClusterDimensions( aBoard, clusterShapes );
3974 std::vector<PAD*> pads = resolveClusterPads( aBoard, clusterShapes );
3975
3976 if( shapes.empty() || clusterConstraints.empty() )
3977 continue;
3978
3979 // A properties edit is authoritative since the user typed exact values so every edited shape
3980 // is held fixed across all its DOF and only constrained neighbours move to satisfy relations
3981 std::set<KIID> fixed;
3982
3983 for( PCB_SHAPE* edited : aEditedShapes )
3984 {
3985 if( edited && clusterShapes.contains( edited->m_Uuid ) )
3986 fixed.insert( edited->m_Uuid );
3987 }
3988
3989 auto adapter = std::make_unique<BOARD_CONSTRAINT_ADAPTER>();
3990
3991 if( !adapter->Build( shapes, clusterConstraints, &fixed, dimensions, pads )
3992 || !adapter->Solve( true ) || !adapter->CurrentRelationsSatisfied() )
3993 {
3994 return false;
3995 }
3996
3997 solvedClusters.push_back( std::move( adapter ) );
3998 }
3999
4000 for( const std::unique_ptr<BOARD_CONSTRAINT_ADAPTER>& adapter : solvedClusters )
4001 {
4002 std::vector<PCB_SHAPE*> changed = adapter->Apply( aBeforeModify );
4003
4004 // Driven reference values re-measure against the held geometry so a dimension bound to an
4005 // edited shape reads its new size instead of the stale one
4006 adapter->ApplyReferenceValues( aBeforeModify );
4007
4008 if( aModified )
4009 aModified->insert( aModified->end(), changed.begin(), changed.end() );
4010 }
4011
4012 return true;
4013}
4014
4015
4016void ReSolveAfterShapeResize( BOARD* aBoard, PCB_SHAPE* aShape, std::vector<PCB_SHAPE*>* aModified,
4017 const std::function<void( BOARD_ITEM* )>& aBeforeModify )
4018{
4019 if( !aBoard || !aShape )
4020 return;
4021
4022 auto shapeToConstraints = buildShapeConstraintMap( aBoard, CollectResolvedConstraints( aBoard ) );
4023
4024 if( !shapeToConstraints.contains( aShape->m_Uuid ) )
4025 return;
4026
4027 std::unordered_set<KIID> clusterShapes;
4028 std::vector<PCB_CONSTRAINT*> clusterConstraints;
4029 collectConstraintCluster( shapeToConstraints, aShape->m_Uuid, clusterShapes, clusterConstraints );
4030
4031 std::vector<PCB_SHAPE*> shapes = resolveClusterShapes( aBoard, clusterShapes );
4032 std::vector<PCB_DIMENSION_BASE*> dimensions = resolveClusterDimensions( aBoard, clusterShapes );
4033 std::vector<PAD*> pads = resolveClusterPads( aBoard, clusterShapes );
4034
4035 if( shapes.empty() || clusterConstraints.empty() )
4036 return;
4037
4039
4040 if( !adapter.Build( shapes, clusterConstraints, nullptr, dimensions, pads )
4041 || !adapter.SolveAfterResize( aShape->m_Uuid ) )
4042 {
4043 return;
4044 }
4045
4046 std::vector<PCB_SHAPE*> changed = adapter.Apply(
4047 [&]( BOARD_ITEM* aChanged )
4048 {
4049 if( aBeforeModify )
4050 aBeforeModify( aChanged );
4051 } );
4052
4053 adapter.ApplyReferenceValues( aBeforeModify );
4054
4055 if( aModified )
4056 aModified->insert( aModified->end(), changed.begin(), changed.end() );
4057}
4058
4059
4060// Diagnose one cluster in isolation an unbuildable cluster with no resolvable members or no
4061// constraints contributes nothing so its result stays empty
4063 const std::unordered_set<KIID>& aClusterShapes,
4064 const std::vector<PCB_CONSTRAINT*>& aClusterConstraints,
4065 const std::unordered_set<KIID>& aOnBoard )
4066{
4068
4069 std::vector<PCB_SHAPE*> shapes = resolveClusterShapes( aBoard, aClusterShapes, &aOnBoard );
4070 std::vector<PCB_DIMENSION_BASE*> dimensions = resolveClusterDimensions( aBoard, aClusterShapes, &aOnBoard );
4071 std::vector<PAD*> pads = resolveClusterPads( aBoard, aClusterShapes, &aOnBoard );
4072
4074
4075 if( ( shapes.empty() && dimensions.empty() && pads.empty() ) || aClusterConstraints.empty()
4076 || !adapter.Build( shapes, aClusterConstraints, nullptr, dimensions, pads ) )
4077 {
4078 return result;
4079 }
4080
4081 // A constraint Build() could not map (e.g. a shape was changed to an incompatible kind) is not
4082 // enforced; flag it so the user sees it is broken rather than silently ignored.
4083 result.erroredUnmapped = adapter.UnmappedConstraints();
4084
4085 // Solve first so the residual check sees a real contradiction not an unsolved constraint a
4086 // contradictory cluster deliberately diverges here since the stabilize holds forbid the escape
4087 adapter.Solve( true );
4088
4089 CONSTRAINT_DIAGNOSIS diag = adapter.Diagnose();
4090
4091 if( diag.IsOverConstrained() )
4093 else if( diag.IsUnderConstrained() )
4095 else
4097
4098 for( PCB_SHAPE* shape : shapes )
4099 result.shapeIds.push_back( shape->m_Uuid );
4100
4101 // Bound dimensions join their cluster's verdict so the overlay can mark them; a free dimension
4102 // never reaches a cluster and so keeps no state.
4103 for( PCB_DIMENSION_BASE* dimension : dimensions )
4104 result.dimensionIds.push_back( dimension->m_Uuid );
4105
4106 for( PAD* pad : pads )
4107 result.padIds.push_back( pad->m_Uuid );
4108
4109 if( diag.freeDof > 0 )
4110 result.freeDof = diag.freeDof;
4111
4112 result.conflicting = diag.conflicting;
4113 result.redundant = diag.redundant;
4114
4115 return result;
4116}
4117
4118
4119// Fold one cluster's verdict into the board-wide result an empty unbuildable cluster leaves
4120// aResult untouched
4122{
4123 for( const KIID& id : aCluster.shapeIds )
4124 aResult.shapeStates[id] = aCluster.state;
4125
4126 for( const KIID& id : aCluster.dimensionIds )
4127 aResult.shapeStates[id] = aCluster.state;
4128
4129 for( const KIID& id : aCluster.padIds )
4130 aResult.shapeStates[id] = aCluster.state;
4131
4132 aResult.totalFreeDof += aCluster.freeDof;
4133
4134 aResult.conflicting.insert( aResult.conflicting.end(), aCluster.conflicting.begin(),
4135 aCluster.conflicting.end() );
4136 aResult.redundant.insert( aResult.redundant.end(), aCluster.redundant.begin(),
4137 aCluster.redundant.end() );
4138 aResult.errored.insert( aResult.errored.end(), aCluster.erroredUnmapped.begin(),
4139 aCluster.erroredUnmapped.end() );
4140}
4141
4142
4143// A constraint with a dangling member is unmappable so it can be flagged by both the adjacency
4144// scan and Build report each errored constraint once here
4146{
4147 std::sort( aResult.errored.begin(), aResult.errored.end() );
4148 aResult.errored.erase( std::unique( aResult.errored.begin(), aResult.errored.end() ),
4149 aResult.errored.end() );
4150}
4151
4152
4154{
4156
4157 if( !aBoard )
4158 return result;
4159
4160 std::vector<PCB_CONSTRAINT*> boardConstraints = CollectResolvedConstraints( aBoard );
4161
4162 if( boardConstraints.empty() )
4163 return result;
4164
4165 std::unordered_set<KIID> onBoard = CollectMemberCandidateIds( aBoard );
4166
4167 CONSTRAINT_GRAPH shapeToConstraints =
4168 buildShapeConstraintMap( aBoard, boardConstraints, &result.errored, &onBoard );
4169
4170 std::set<KIID> visitedShapes;
4171
4172 for( const auto& [seedShape, seedConstraints] : shapeToConstraints.byMember )
4173 {
4174 if( visitedShapes.contains( seedShape ) )
4175 continue;
4176
4177 std::unordered_set<KIID> clusterShapes;
4178 std::vector<PCB_CONSTRAINT*> clusterConstraints;
4179 collectConstraintCluster( shapeToConstraints, seedShape, clusterShapes, clusterConstraints,
4180 &visitedShapes );
4181
4183 diagnoseSingleCluster( aBoard, clusterShapes, clusterConstraints, onBoard ) );
4184 }
4185
4187
4188 return result;
4189}
4190
4191
4192// Boost-style mix so a change in any hashed field changes the cluster hash
4193static void hashCombine( std::size_t& aSeed, std::size_t aValue )
4194{
4195 aSeed ^= aValue + 0x9e3779b97f4a7c15ULL + ( aSeed << 6 ) + ( aSeed >> 2 );
4196}
4197
4198
4199static void hashInt( std::size_t& aSeed, long long aValue )
4200{
4201 hashCombine( aSeed, static_cast<std::size_t>( aValue ) );
4202}
4203
4204
4205static void hashDouble( std::size_t& aSeed, double aValue )
4206{
4207 // Hash the exact bit pattern so any coordinate or value change invalidates the cache folding
4208 // both 32-bit halves so a double change is never lost where size_t is only 32 bits wide
4209 std::uint64_t bits = 0;
4210 static_assert( sizeof( bits ) == sizeof( aValue ) );
4211 std::memcpy( &bits, &aValue, sizeof( bits ) );
4212 hashCombine( aSeed, static_cast<std::size_t>( bits & 0xFFFFFFFFULL ) );
4213 hashCombine( aSeed, static_cast<std::size_t>( bits >> 32 ) );
4214}
4215
4216
4217static void hashPoint( std::size_t& aSeed, const VECTOR2I& aPoint )
4218{
4219 hashInt( aSeed, aPoint.x );
4220 hashInt( aSeed, aPoint.y );
4221}
4222
4223
4224static void hashKiid( std::size_t& aSeed, const KIID& aId )
4225{
4226 hashCombine( aSeed, std::hash<KIID>{}( aId ) );
4227}
4228
4229
4230// Hash every solve input a PCB_SHAPE contributes dispatched by kind so no getter is called on a
4231// shape type it asserts for since GetRadius and GetCenter are unimplemented for the wrong kinds
4232static void hashShape( std::size_t& aSeed, const PCB_SHAPE* aShape )
4233{
4234 hashInt( aSeed, static_cast<int>( aShape->GetShape() ) );
4235
4236 // Build freezes a locked shape including via its parent footprint so the lock state changes
4237 // the solve even when the geometry does not
4238 hashInt( aSeed, ConstraintItemIsLocked( aShape ) ? 1 : 0 );
4239
4240 switch( aShape->GetShape() )
4241 {
4242 case SHAPE_T::SEGMENT:
4243 case SHAPE_T::RECTANGLE:
4244 hashPoint( aSeed, aShape->GetStart() );
4245 hashPoint( aSeed, aShape->GetEnd() );
4246 break;
4247
4248 case SHAPE_T::BEZIER:
4249 hashPoint( aSeed, aShape->GetStart() );
4250 hashPoint( aSeed, aShape->GetEnd() );
4251 hashPoint( aSeed, aShape->GetBezierC1() );
4252 hashPoint( aSeed, aShape->GetBezierC2() );
4253 break;
4254
4255 case SHAPE_T::CIRCLE:
4256 hashPoint( aSeed, aShape->GetCenter() );
4257 hashInt( aSeed, aShape->GetRadius() );
4258 break;
4259
4260 case SHAPE_T::POLY:
4261 {
4262 const SHAPE_POLY_SET& poly = aShape->GetPolyShape();
4263
4264 // The outline hole and arc counts gate ingestion so any of them changing must invalidate
4265 // even when no vertex moved
4266 hashInt( aSeed, poly.OutlineCount() );
4267
4268 if( poly.OutlineCount() > 0 )
4269 {
4270 hashInt( aSeed, poly.HoleCount( 0 ) );
4271
4272 const SHAPE_LINE_CHAIN& outline = poly.COutline( 0 );
4273
4274 hashInt( aSeed, static_cast<long long>( outline.ArcCount() ) );
4275
4276 for( int i = 0; i < outline.PointCount(); ++i )
4277 hashPoint( aSeed, outline.CPoint( i ) );
4278 }
4279
4280 break;
4281 }
4282
4283 case SHAPE_T::ARC:
4284 hashPoint( aSeed, aShape->GetStart() );
4285 hashPoint( aSeed, aShape->GetEnd() );
4286 hashPoint( aSeed, aShape->GetCenter() );
4287 hashInt( aSeed, aShape->GetRadius() );
4288 break;
4289
4290 case SHAPE_T::ELLIPSE:
4292 hashPoint( aSeed, aShape->GetEllipseCenter() );
4293 hashInt( aSeed, aShape->GetEllipseMajorRadius() );
4294 hashInt( aSeed, aShape->GetEllipseMinorRadius() );
4295 hashDouble( aSeed, aShape->GetEllipseRotation().AsRadians() );
4296
4297 if( aShape->GetShape() == SHAPE_T::ELLIPSE_ARC )
4298 {
4299 hashPoint( aSeed, aShape->GetStart() );
4300 hashPoint( aSeed, aShape->GetEnd() );
4301 hashDouble( aSeed, aShape->GetEllipseStartAngle().AsRadians() );
4302 hashDouble( aSeed, aShape->GetEllipseEndAngle().AsRadians() );
4303 }
4304
4305 break;
4306
4307 default:
4308 // Build reads the front shape start for the cluster normalization origin even when the kind
4309 // is unmapped so a change there can still shift the solve hash it here too
4310 hashPoint( aSeed, aShape->GetStart() );
4311 break;
4312 }
4313}
4314
4315
4316static void hashDimension( std::size_t& aSeed, const PCB_DIMENSION_BASE* aDimension )
4317{
4318 hashInt( aSeed, static_cast<int>( aDimension->Type() ) );
4319 hashPoint( aSeed, aDimension->GetStart() );
4320 hashPoint( aSeed, aDimension->GetEnd() );
4321
4322 // An orthogonal dimension driving length fixes the axis its orientation selects so a
4323 // horizontal to vertical flip changes the solve without moving the endpoints
4324 if( aDimension->Type() == PCB_DIM_ORTHOGONAL_T )
4325 {
4326 hashInt( aSeed, static_cast<int>(
4327 static_cast<const PCB_DIM_ORTHOGONAL*>( aDimension )->GetOrientation() ) );
4328 }
4329}
4330
4331
4332static void hashConstraint( std::size_t& aSeed, const PCB_CONSTRAINT* aConstraint )
4333{
4334 hashKiid( aSeed, aConstraint->m_Uuid );
4335 hashInt( aSeed, static_cast<int>( aConstraint->GetConstraintType() ) );
4336 hashInt( aSeed, aConstraint->IsDriving() ? 1 : 0 );
4337 hashInt( aSeed, aConstraint->HasValue() ? 1 : 0 );
4338
4339 if( aConstraint->HasValue() )
4340 hashDouble( aSeed, *aConstraint->GetValue() );
4341
4342 for( const CONSTRAINT_MEMBER& member : aConstraint->GetMembers() )
4343 {
4344 hashKiid( aSeed, member.m_item );
4345 hashInt( aSeed, static_cast<int>( member.m_anchor ) );
4346 hashInt( aSeed, member.m_index );
4347 }
4348}
4349
4350
4351// A hash over every input diagnoseSingleCluster would solve on so any geometry value or membership
4352// change invalidates the cached result err toward hashing more since a missed field leaves it stale
4353static std::size_t hashCluster( BOARD* aBoard, const std::unordered_set<KIID>& aClusterShapes,
4354 const std::vector<PCB_CONSTRAINT*>& aClusterConstraints,
4355 const std::unordered_set<KIID>& aOnBoard )
4356{
4357 std::size_t seed = 0;
4358
4359 std::vector<KIID> ids( aClusterShapes.begin(), aClusterShapes.end() );
4360 std::sort( ids.begin(), ids.end() );
4361
4362 for( const KIID& id : ids )
4363 {
4364 BOARD_ITEM* item = resolveMember( aBoard, &aOnBoard, id );
4365
4366 if( PCB_SHAPE* shape = dynamic_cast<PCB_SHAPE*>( item ) )
4367 hashShape( seed, shape );
4368 else if( PCB_DIMENSION_BASE* dimension = dynamic_cast<PCB_DIMENSION_BASE*>( item ) )
4369 hashDimension( seed, dimension );
4370 else if( PAD* pad = dynamic_cast<PAD*>( item ) )
4371 {
4372 hashInt( seed, ConstraintItemIsLocked( pad ) ? 1 : 0 );
4373 hashPoint( seed, pad->GetPosition() );
4374 }
4375 }
4376
4377 std::vector<PCB_CONSTRAINT*> constraints = aClusterConstraints;
4378 std::sort( constraints.begin(), constraints.end(),
4379 []( const PCB_CONSTRAINT* aLhs, const PCB_CONSTRAINT* aRhs )
4380 { return aLhs->m_Uuid < aRhs->m_Uuid; } );
4381
4382 for( const PCB_CONSTRAINT* constraint : constraints )
4383 hashConstraint( seed, constraint );
4384
4385 return seed;
4386}
4387
4388
4390{
4391 m_cache.clear();
4392}
4393
4394
4396{
4398
4399 if( !aBoard )
4400 {
4401 m_cache.clear();
4402 return result;
4403 }
4404
4405 std::vector<PCB_CONSTRAINT*> boardConstraints = CollectResolvedConstraints( aBoard );
4406
4407 if( boardConstraints.empty() )
4408 {
4409 m_cache.clear();
4410 return result;
4411 }
4412
4413 std::unordered_set<KIID> onBoard = CollectMemberCandidateIds( aBoard );
4414
4415 // The map-scan errored dangling members is recomputed in full every call so it can never go
4416 // stale however aggressively the per-cluster diagnoses are cached
4417 CONSTRAINT_GRAPH shapeToConstraints =
4418 buildShapeConstraintMap( aBoard, boardConstraints, &result.errored, &onBoard );
4419
4420 std::set<KIID> visitedShapes;
4421 std::set<std::vector<KIID>> seenKeys;
4422
4423 for( const auto& [seedShape, seedConstraints] : shapeToConstraints.byMember )
4424 {
4425 if( visitedShapes.contains( seedShape ) )
4426 continue;
4427
4428 std::unordered_set<KIID> clusterShapes;
4429 std::vector<PCB_CONSTRAINT*> clusterConstraints;
4430 collectConstraintCluster( shapeToConstraints, seedShape, clusterShapes, clusterConstraints,
4431 &visitedShapes );
4432
4433 // Clusters partition the board constraints so the sorted constraint-id set uniquely
4434 // identifies a cluster and stays put across a geometry or value edit the hash catches those
4435 std::vector<KIID> key;
4436
4437 for( const PCB_CONSTRAINT* constraint : clusterConstraints )
4438 key.push_back( constraint->m_Uuid );
4439
4440 std::sort( key.begin(), key.end() );
4441
4442 std::size_t hash = hashCluster( aBoard, clusterShapes, clusterConstraints, onBoard );
4443 auto it = m_cache.find( key );
4444
4445 if( it == m_cache.end() || it->second.hash != hash )
4446 {
4447 CLUSTER_DIAGNOSIS cluster =
4448 diagnoseSingleCluster( aBoard, clusterShapes, clusterConstraints, onBoard );
4449 m_solveCount++;
4450 it = m_cache.insert_or_assign( key, CACHE_ENTRY{ hash, std::move( cluster ) } ).first;
4451 }
4452
4453 assembleClusterInto( result, it->second.result );
4454 seenKeys.insert( key );
4455 }
4456
4457 // Drop cache entries for clusters no longer present so a stale result can never leak into a
4458 // later pass that happens to rebuild the same key
4459 std::erase_if( m_cache, [&seenKeys]( const auto& entry ) { return !seenKeys.contains( entry.first ); } );
4460
4462
4463 return result;
4464}
int index
std::set< KIID > ConstraintReferenceShapes(BOARD *aBoard, const PCB_CONSTRAINT *aConstraint)
The shapes a just-authored constraint should treat as an immovable reference, for the caller to pass ...
static void hashCombine(std::size_t &aSeed, std::size_t aValue)
static void hashConstraint(std::size_t &aSeed, const PCB_CONSTRAINT *aConstraint)
static constexpr double STAY_PUT_WEIGHT
static void hashKiid(std::size_t &aSeed, const KIID &aId)
static void hashShape(std::size_t &aSeed, const PCB_SHAPE *aShape)
std::vector< VECTOR2I > ConstraintPinnedPositions(BOARD *aBoard, const std::set< KIID > &aItems)
The distinct board positions that fixed positions pin on aItems.
void ReSolveAfterShapeResize(BOARD *aBoard, PCB_SHAPE *aShape, std::vector< PCB_SHAPE * > *aModified, const std::function< void(BOARD_ITEM *)> &aBeforeModify)
Re-solve after a resize, e.g. a circle radius edit. Holds aShape fixed so its neighbors adjust.
static std::size_t hashCluster(BOARD *aBoard, const std::unordered_set< KIID > &aClusterShapes, const std::vector< PCB_CONSTRAINT * > &aClusterConstraints, const std::unordered_set< KIID > &aOnBoard)
bool BoardHasConstraints(BOARD *aBoard)
True if aBoard resolves at least one geometric constraint (see CollectResolvedConstraints()).
static void assembleClusterInto(BOARD_CONSTRAINT_DIAGNOSTICS &aResult, const CLUSTER_DIAGNOSIS &aCluster)
static constexpr double IU_PER_NORM_UNIT
CONSTRAINT_DIAGNOSIS ApplyConstraintImmediately(BOARD *aBoard, const PCB_CONSTRAINT *aConstraint, std::vector< PCB_SHAPE * > *aModified, const std::function< void(BOARD_ITEM *)> &aBeforeModify, const std::set< KIID > &aFixedShapes)
Solve a just-created constraint's cluster so the geometry snaps to satisfy it (SolidWorks-style),...
static std::vector< PAD * > resolveClusterPads(BOARD *aBoard, const std::unordered_set< KIID > &aIds, const std::unordered_set< KIID > *aOnBoard=nullptr)
static void hashPoint(std::size_t &aSeed, const VECTOR2I &aPoint)
CONSTRAINT_DIAGNOSIS SolveCluster(BOARD *aBoard, const CONSTRAINT_MEMBER &aDragged, const VECTOR2I &aCursor, std::vector< PCB_SHAPE * > *aModified, const std::function< void(BOARD_ITEM *)> &aBeforeModify, bool aIncludeDragged, bool aStabilize, const std::set< KIID > &aEdited, const std::optional< std::pair< CONSTRAINT_MEMBER, VECTOR2I > > &aCoDragged, const std::set< KIID > &aFixedShapes, bool aHoldDraggedRigid)
Gather the cluster of shapes transitively constrained with the dragged shape, solve with the dragged ...
static std::vector< PCB_SHAPE * > resolveClusterShapes(BOARD *aBoard, const std::unordered_set< KIID > &aIds, const std::unordered_set< KIID > *aOnBoard=nullptr)
static void hashDimension(std::size_t &aSeed, const PCB_DIMENSION_BASE *aDimension)
static double arcSweepTarget(double aStartAngle, double aEndAngle, double aSweepDeg)
static CLUSTER_DIAGNOSIS diagnoseSingleCluster(BOARD *aBoard, const std::unordered_set< KIID > &aClusterShapes, const std::vector< PCB_CONSTRAINT * > &aClusterConstraints, const std::unordered_set< KIID > &aOnBoard)
static double directedAngleForCorner(const GCS::Line &aL1, const GCS::Line &aL2, double aCornerDeg)
static constexpr double CURSOR_WEIGHT
void ReSolveShapeClusters(BOARD *aBoard, const std::vector< PCB_SHAPE * > &aShapes, std::vector< PCB_SHAPE * > *aModified, const std::function< void(BOARD_ITEM *)> &aBeforeModify)
Re-solve the clusters of shapes edited outside the solver, e.g.
static void hashInt(std::size_t &aSeed, long long aValue)
bool ReSolveShapeClustersHoldingEdited(BOARD *aBoard, const std::vector< PCB_SHAPE * > &aEditedShapes, std::vector< PCB_SHAPE * > *aModified, const std::function< void(BOARD_ITEM *)> &aBeforeModify)
Re-solve clusters whose new geometry is authoritative holding every edited shape fully fixed so only ...
bool ConstraintItemIsLocked(const BOARD_ITEM *aItem)
True when the solver must treat aItem as immovable, either locked itself or living inside a locked fo...
static CONSTRAINT_GRAPH buildShapeConstraintMap(BOARD *aBoard, const std::vector< PCB_CONSTRAINT * > &aConstraints, std::vector< KIID > *aErrored=nullptr, const std::unordered_set< KIID > *aOnBoard=nullptr)
static void dedupErrored(BOARD_CONSTRAINT_DIAGNOSTICS &aResult)
static void collectConstraintCluster(const CONSTRAINT_GRAPH &aGraph, const KIID &aSeed, std::unordered_set< KIID > &aClusterShapes, std::vector< PCB_CONSTRAINT * > &aClusterConstraints, std::set< KIID > *aVisited=nullptr)
static std::vector< PCB_DIMENSION_BASE * > resolveClusterDimensions(BOARD *aBoard, const std::unordered_set< KIID > &aIds, const std::unordered_set< KIID > *aOnBoard=nullptr)
BOARD_CONSTRAINT_DIAGNOSTICS DiagnoseBoardConstraints(BOARD *aBoard)
Diagnose every constraint cluster on the board (validate only – geometry is not changed) and return t...
static FOOTPRINT * boardFootprintOf(const BOARD_ITEM *aItem)
static constexpr int MAX_SOLVE_ITERATIONS
static BOARD_ITEM * resolveMember(BOARD *aBoard, const std::unordered_set< KIID > *aOnBoard, const KIID &aId)
static std::vector< T * > resolveClusterItems(BOARD *aBoard, const std::unordered_set< KIID > &aIds, const std::unordered_set< KIID > *aOnBoard)
static bool isDegenerateLine(const GCS::Line &aLine)
static void hashDouble(std::size_t &aSeed, double aValue)
@ OVER_CONSTRAINED
In a cluster the solver reports as conflicting.
@ UNDER_CONSTRAINED
In a cluster with remaining free degrees of freedom.
@ WELL_CONSTRAINED
In a fully-determined cluster (zero free DOF).
bool ConstraintItemIsLocked(const BOARD_ITEM *aItem)
True when the solver must treat aItem as immovable, either locked itself or living inside a locked fo...
CONSTRAINT_BLOCK_RESULT
How a block edit solve turned out.
@ REFUSED
No arrangement fits the pinned points, and the geometry is untouched.
@ SOLVED
The constraints hold and every pinned point is exactly where it was put.
@ NOT_MODELED
Nothing the caller pinned belongs to this cluster.
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:985
Translates KiCad board geometry to and from the planegcs solver (issue #2329).
void recordReferenceValue(PCB_CONSTRAINT *aConstraint)
Note a non-driving valued constraint so its measured value can be read back after a solve.
void holdShapesRigid(int aTag, const std::set< KIID > &aShapes)
Hold the shapes in aShapes rigid, tagged aTag, so a shape the solve moves translates instead of stret...
std::set< int > m_droppedTags
Stale relations taken out of the system.
int m_coDragTargetY
Backing slot for the co-dragged pin y target.
std::vector< int > staleRelationTags() const
Driving constraint tags whose residual is already out of tolerance, ignoring dropped ones.
PCB_DIM_ORTHOGONAL * orthogonalDimensionForMembers(const std::vector< CONSTRAINT_MEMBER > &aMembers) const
The orthogonal dimension a two-point length constraint drives or nullptr requires both members to be ...
void coupleRigidFootprints(const std::set< FOOTPRINT * > &aFootprints, const std::set< KIID > *aFixedShapes, std::set< int > &aFixed)
Tie every mapped child of each footprint in aFootprints to one shared translation,...
std::vector< KIID > m_unmapped
Constraints Build() could not map (not enforced).
double denormalizeX(double aNorm) const
std::set< int > m_fixedParams
Parameter indices the solver may not move, so a rigid translation may not either.
void softPinPoint(const ANCHOR_PARAMS &aPoint, int aTag, std::optional< double > aWeight=std::nullopt)
Pin the point at aPoint where it sits tagged aTag with aWeight rescaling the tier or the default weig...
bool addSnapRelations(const ANCHOR_PARAMS &aAnchor, const std::vector< SNAP_CANDIDATE > &aCandidates, const VECTOR2I &aOffset)
std::set< KIID > m_rigidMembers
Mapped items that move only with their footprint.
void pinUneditedShapes(const std::set< KIID > &aEdited, int aTag)
Soft-pin every cluster shape not in aEdited at its current geometry tagged aTag for a minimal-movemen...
bool Solve(const CONSTRAINT_MEMBER &aDragged, const VECTOR2I &aCursor, bool aStabilize=false, const std::set< KIID > &aEdited={}, const std::optional< std::pair< CONSTRAINT_MEMBER, VECTOR2I > > &aCoDragged=std::nullopt, bool aHoldDraggedRigid=false)
Solve the system, pinning a dragged anchor to a cursor position.
void softPinCoordinate(int aParam, int aTag, std::optional< double > aWeight=std::nullopt)
Hold the one coordinate at aParam where it sits, tagged aTag, with aWeight scaling the tier.
RIGID_STATE collectRigidState(const std::set< KIID > &aEditedShapes) const
int m_dragTargetX
Stable backing slot for the drag pin's x target (-1 = unset).
void holdFreeSegmentLengths(int aTag, const std::set< KIID > &aShapes)
Length hold on the free segments in aShapes tagged aTag so only those shapes are protected while a me...
std::vector< PCB_CONSTRAINT * > m_referenceConstraints
Non-driving valued, read back after a solve.
bool solveSucceeded(int aSolveResult)
Decide whether a solve reached a usable result a raw Success or Converged qualifies while a Failed co...
void holdRigidRadii(const std::vector< RIGID_RADIUS_HOLD > &aRadii, int aTag)
const std::vector< KIID > & UnmappedConstraints() const
Constraints from the last Build() that could not be mapped onto a solver primitive (wrong member coun...
ANCHOR_PARAMS anchorParams(const CONSTRAINT_MEMBER &aMember) const
Indices into m_params of the coordinates an anchor maps to invalid if the shape has no such anchor fo...
std::map< KIID, SHAPE_VARS > m_shapeVars
std::vector< RIGID_FOOTPRINT > m_rigidFootprints
bool SolveAfterResize(const KIID &aResizedShape)
Solve after a resize.
int m_coDragTargetX
Backing slot for the co-dragged pin x target.
CONSTRAINT_SYSTEM_2D::SNAPSHOT SNAPSHOT
double denormalizeY(double aNorm) const
void pinDraggedShapeRest(const CONSTRAINT_MEMBER &aDragged, int aTag, const CONSTRAINT_MEMBER *aCoDragged=nullptr)
Hold the parts of the dragged shape meant to stay put tagged aTag a segment holds its far endpoint an...
std::map< int, std::vector< KIID > > m_tagMembers
Member items per tag, for collapse attribution.
int m_dragTargetY
Stable backing slot for the drag pin's y target.
double m_scale
IU per normalized unit.
std::optional< VECTOR2I > AnchorPosition(const CONSTRAINT_MEMBER &aMember) const
bool Restore(const SNAPSHOT &aSnapshot)
bool SolveRigidTranslation(const std::set< KIID > &aEditedShapes, const VECTOR2I &aTranslation)
std::map< int, KIID > m_tagToConstraint
std::set< KIID > m_angleConstrainedShapes
Shapes a direction or angle constraint could collapse to a point only these get a stabilize length or...
void holdFreeArcRadii(int aTag, const std::set< KIID > &aShapes)
Radius hold on the free arcs in aShapes tagged aTag so an angle change rotates an endpoint instead of...
bool SolveRigidSnapRelations(const std::set< KIID > &aEditedShapes, const VECTOR2I &aReference, const std::vector< SNAP_CANDIDATE > &aCandidates, const VECTOR2I &aCursor, VECTOR2I &aResolvedCursor)
std::set< int > m_groundedPositionParams
The subset of those grounded by a FIXED_POSITION constraint rather than by a lock or a driving consta...
void holdPolygonVertices(const std::set< KIID > &aShapes, int aTag)
Soft-pin every vertex of each POLYGON in aShapes tagged aTag for edited shapes pinUneditedShapes excl...
std::vector< PCB_SHAPE * > Apply(const std::function< void(BOARD_ITEM *)> &aBeforeWrite={})
Write the solved coordinates back into the shapes, de-normalized to IU.
void pinUncommandedCoordinates(const std::set< int > &aCommanded, int aTag)
Weakly hold every cluster coordinate outside aCommanded where it sits, tagged aTag,...
bool Build(const std::vector< PCB_SHAPE * > &aShapes, const std::vector< PCB_CONSTRAINT * > &aConstraints, const std::set< KIID > *aFixedShapes=nullptr, const std::vector< PCB_DIMENSION_BASE * > &aDimensions={}, const std::vector< PAD * > &aPads={})
Translate a cluster into a planegcs system.
bool TravelsWhole(const std::set< KIID > &aEditedShapes) const
True when every shape in the cluster is in aEditedShapes and free to travel with it.
int pushParam(double aValue)
Append a normalized coordinate to the backing store, returning its stable index.
static BOARD_ITEM * itemOf(const SHAPE_VARS &aVars)
CONSTRAINT_DIAGNOSIS Diagnose()
Report degrees of freedom and conflicting/redundant constraints.
CONSTRAINT_BLOCK_RESULT SolveBlockEdit(const std::vector< std::pair< CONSTRAINT_MEMBER, VECTOR2I > > &aPinnedAnchors, const std::set< KIID > &aTranslatedShapes, const VECTOR2I &aTranslation)
Solve a block edit whose geometry the caller has already written.
int DropStaleRelations()
Remove the constraints the current geometry already fails to satisfy.
std::set< int > m_nonDrivingTags
Measurement-only; excluded from conflict residuals.
double normalizeX(int aIU) const
IU <-> normalized (millimetre, cluster-centred) frame, per axis.
@ PAD_CENTER
A pad's centre point, which only ever moves with its footprint.
@ RECTANGLE
An axis-aligned rectangle whose four corners alias the two stored corners params so rectness holds by...
@ POINT_PAIR
A dimension's two feature points (start + end); no line/curve geometry.
@ POLYGON
A single hole-free outline with one free param pair per vertex since write-back rebuilds one outline ...
@ BEZIER
A cubic bezier only its start and end endpoints are exposed as free points.
bool SolveSnapRelations(const CONSTRAINT_MEMBER &aDragged, const std::vector< SNAP_CANDIDATE > &aCandidates, const VECTOR2I &aCursor)
void ApplyReferenceValues(const std::function< void(BOARD_ITEM *)> &aBeforeWrite={})
Propagate solved reference (non-driving) constraint values back into their m_value so a reference dim...
void holdArcRadius(const SHAPE_VARS &aVars, int aTag)
Hold aVars's arc at its current radius (tagged aTag).
bool Build(BOARD *aBoard, const std::vector< BOARD_ITEM * > &aBlockItems)
Build one adapter over the clusters holding aBlockItems.
CONSTRAINT_BLOCK_RESULT Solve(const std::vector< std::pair< CONSTRAINT_MEMBER, VECTOR2I > > &aPinnedAnchors, const std::set< KIID > &aTranslatedShapes, const VECTOR2I &aTranslation, std::vector< PCB_SHAPE * > *aModified, const std::function< void(BOARD_ITEM *)> &aBeforeModify)
Solve one frame of the block edit and apply it.
BOARD_CONSTRAINT_DIAGNOSTICS Diagnose(BOARD *aBoard)
Diagnose every cluster reusing cached per-cluster results whose solve inputs are unchanged.
std::map< std::vector< KIID >, CACHE_ENTRY > m_cache
void Clear()
Drop the cache call when the board or view reloads and item-identity assumptions break.
bool IsExactFeasible(const VECTOR2I &aTarget)
bool Build(BOARD *aBoard, const CONSTRAINT_MEMBER &aDragged)
CONSTRAINT_DIAGNOSIS Solve(const VECTOR2I &aCursor, std::vector< PCB_SHAPE * > *aModified, const std::function< void(BOARD_ITEM *)> &aBeforeModify, bool aIncludeDragged, bool aStabilize, const std::set< KIID > &aEdited={}, const std::optional< std::pair< CONSTRAINT_MEMBER, VECTOR2I > > &aCoDragged=std::nullopt)
SNAP_RESULT ResolveCandidates(const SNAP_SOURCE_CONTEXT &aContext, const std::vector< SNAP_CANDIDATE > &aCandidates)
bool Matches(const CONSTRAINT_MEMBER &aDragged) const
bool feasibleAt(const VECTOR2I &aTarget)
bool Solve(const VECTOR2I &aTarget, std::vector< PCB_SHAPE * > *aModified, const std::function< void(BOARD_ITEM *)> &aBeforeModify)
bool Build(BOARD *aBoard, const std::vector< PCB_SHAPE * > &aEditedShapes, const VECTOR2I &aReference)
SNAP_RESULT ResolveCandidates(const SNAP_SOURCE_CONTEXT &aContext, const std::vector< SNAP_CANDIDATE > &aCandidates)
BOARD_CONSTRAINT_ADAPTER::SNAPSHOT m_baseline
bool rewind()
Rewind to the state the next speculative solve starts from.
SNAP_RESULT startResult(const SNAP_SOURCE_CONTEXT &aContext) const
Seed a snap result at the cursor, rejecting a cluster that was already broken.
void reset()
Drop the built cluster, leaving the session unusable until the next successful build.
bool buildCluster(BOARD *aBoard, const std::unordered_set< KIID > &aClusterShapes, const std::vector< PCB_CONSTRAINT * > &aConstraints)
Assemble the adapter for one cluster and record its baseline.
std::unique_ptr< BOARD_CONSTRAINT_ADAPTER > m_adapter
static void accept(SNAP_RESULT &aResult, const SNAP_CANDIDATE &aCandidate, double aResidual)
Record one candidate the session honoured.
A base class for any item which can be embedded within the BOARD container class, and therefore insta...
Definition board_item.h:99
bool IsLocked() const override
virtual const BOARD * GetBoard() const
Return the BOARD in which this BOARD_ITEM resides, or NULL if none.
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
BOARD_ITEM * ResolveItem(const KIID &aID, bool aAllowNullptrReturn=false) const
Definition board.cpp:2176
Represent basic circle geometry with utility geometry functions.
Definition circle.h:33
double AsDegrees() const
Definition eda_angle.h:115
double AsRadians() const
Definition eda_angle.h:119
const KIID m_Uuid
Definition eda_item.h:599
KICAD_T Type() const
Returns the type of object.
Definition eda_item.h:110
EDA_ANGLE GetArcAngle() const
int GetEllipseMinorRadius() const
Definition eda_shape.h:404
const VECTOR2I & GetBezierC2() const
Definition eda_shape.h:377
const VECTOR2I & GetEllipseCenter() const
Definition eda_shape.h:386
EDA_ANGLE GetEllipseEndAngle() const
Definition eda_shape.h:432
int GetEllipseMajorRadius() const
Definition eda_shape.h:395
SHAPE_POLY_SET & GetPolyShape()
EDA_ANGLE GetEllipseRotation() const
Definition eda_shape.h:413
int GetRadius() const
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
EDA_ANGLE GetEllipseStartAngle() const
Definition eda_shape.h:423
const VECTOR2I & GetBezierC1() const
Definition eda_shape.h:374
virtual void SetTextPos(const VECTOR2I &aPoint)
Definition eda_text.cpp:557
Definition kiid.h:46
Definition pad.h:61
A geometric constraint between board items (issue #2329).
const std::vector< CONSTRAINT_MEMBER > & GetMembers() const
std::optional< double > GetValue() const
bool IsDriving() const
A driving constraint forces its value; a reference (non-driving) one only measures it.
PCB_CONSTRAINT_TYPE GetConstraintType() const
bool HasValue() const
Abstract dimension API.
virtual VECTOR2I GetEnd() const
virtual VECTOR2I GetStart() const
The dimension's origin is the first feature point for the dimension.
An orthogonal dimension is like an aligned dimension, but the extension lines are locked to the X or ...
A radial dimension indicates either the radius or diameter of an arc or circle.
VECTOR2I GetKnee() const
VECTOR2I GetCenter() const override
This defaults to the center of the bounding box if not overridden.
Definition pcb_shape.h:80
VECTOR2I GetTextPos() const override
Definition pcb_text.cpp:463
Definition seg.h:38
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.
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
SNAP_RESULT Resolve(const SNAP_SOURCE_CONTEXT &aContext) const
void AddCandidate(SNAP_CANDIDATE aCandidate)
constexpr extended_type Dot(const VECTOR2< T > &aVector) const
Compute dot product of self with aVector.
Definition vector2d.h:567
bool IsConstrainableItem(const BOARD_ITEM *aItem)
True when aItem is one ResolveConstrainableItem() accepts: a PCB_SHAPE, a dimension or a pad.
EDA_ANGLE MeasureCornerAngle(const SEG &aA, const SEG &aB)
The corner angle between two segments, in the closed range [0, 180] degrees.
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::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< 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...
std::vector< PCB_CONSTRAINT * > CollectResolvedConstraints(const BOARD *aBoard)
The constraints the editor resolves on aBoard.
static constexpr EDA_ANGLE ANGLE_90
Definition eda_angle.h:474
@ RADIANS_T
Definition eda_angle.h:31
@ 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
EDA_ANGLE abs(const EDA_ANGLE &aAngle)
Definition eda_angle.h:461
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.
Param indices of an anchor coordinates a rect corner aliases mixed start end params so y is not alway...
A footprint moving as one body with its translation from buildPosition held in the params at translat...
int radius
radius scalar (circle, arc) / minor radius (ellipse).
bool startIsLeft
Rect corner roles frozen at Build so VERTEX 0 to 3 as TL TR BR BL bind the same physical corners what...
int fixedLengthParam
param index of a driving fixed-length target, or -1.
int focusX
first focus.x (ellipse kinds only).
int startX
start.x (segment) / center.x (circle, arc, ellipse).
PAD * pad
set instead of shape for a PAD_CENTER
PCB_DIMENSION_BASE * dimension
set instead of shape for a POINT_PAIR
int vertexCount
Outline-0 vertex count of a POLYGON vertex i x param is startX plus 2 times i.
Board-wide diagnostics for the constraint overlay and info bar.
std::map< KIID, CONSTRAINT_STATE > shapeStates
std::vector< KIID > errored
Invalid constraints (member missing, deleted, or of a kind incompatible with the type).
One cluster's diagnosis, the unit DiagnoseBoardConstraints assembles the board-wide result from and B...
int freeDof
Remaining free DOF folded into the board total.
std::vector< KIID > dimensionIds
Cluster dimensions.
std::vector< KIID > conflicting
std::vector< KIID > padIds
Cluster pads.
std::vector< KIID > erroredUnmapped
Constraints Build could not map and so not enforced.
std::vector< KIID > shapeIds
Cluster shapes in the order the state is written.
std::vector< KIID > redundant
The outcome of a constraint solve, in plain data so callers need not know planegcs.
bool solved
Solver reached Success or Converged.
std::vector< KIID > conflicting
Constraints the solver reports as over-constraining.
std::vector< KIID > redundant
Constraints the solver reports as redundant.
int freeDof
Remaining degrees of freedom (-1 if not diagnosed).
std::unordered_map< KIID, std::vector< KIID > > rigidSiblings
std::unordered_map< KIID, std::vector< PCB_CONSTRAINT * > > byMember
bool contains(const KIID &aId) const
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.
std::vector< double > quantizedResiduals
VECTOR2I position
bool Accepted(const SNAP_STABLE_ID &aId) const
bool moved
std::vector< double > vA
KIBIS_PIN * pin
VECTOR2I center
int radius
VECTOR2I end
SHAPE_CIRCLE circle(c.m_circle_center, c.m_circle_radius)
wxString result
Test unit parsing edge cases and error handling.
int delta
#define M_PI
@ 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_DIM_RADIAL_T
class PCB_DIM_RADIAL, a radius or diameter dimension
Definition typeinfo.h:97
constexpr int sign(T val)
Definition util.h:167
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708
VECTOR2< double > VECTOR2D
Definition vector2d.h:707