Salome HOME
Collinear and coinciding point constraints problem (issue #1318)
[modules/shaper.git] / src / SketchSolver / SketchSolver_Group.cpp
1 // Copyright (C) 2014-20xx CEA/DEN, EDF R&D
2
3 // File:    SketchSolver_Group.cpp
4 // Created: 27 May 2014
5 // Author:  Artem ZHIDKOV
6
7 #include "SketchSolver_Group.h"
8
9 #include <SketchSolver_Constraint.h>
10 #include <SketchSolver_ConstraintCoincidence.h>
11 #include <SketchSolver_ConstraintMulti.h>
12 #include <SketchSolver_Error.h>
13 #include <SketchSolver_Manager.h>
14
15 #include <Events_Error.h>
16 #include <Events_Loop.h>
17 #include <ModelAPI_AttributeString.h>
18 #include <ModelAPI_Events.h>
19 #include <ModelAPI_Session.h>
20 #include <ModelAPI_Validator.h>
21
22 #include <SketchPlugin_Arc.h>
23 #include <SketchPlugin_ConstraintAngle.h>
24 #include <SketchPlugin_ConstraintCoincidence.h>
25 #include <SketchPlugin_ConstraintDistance.h>
26 #include <SketchPlugin_ConstraintEqual.h>
27 #include <SketchPlugin_ConstraintHorizontal.h>
28 #include <SketchPlugin_ConstraintLength.h>
29 #include <SketchPlugin_ConstraintFillet.h>
30 #include <SketchPlugin_ConstraintMirror.h>
31 #include <SketchPlugin_ConstraintParallel.h>
32 #include <SketchPlugin_ConstraintPerpendicular.h>
33 #include <SketchPlugin_ConstraintRadius.h>
34 #include <SketchPlugin_ConstraintRigid.h>
35 #include <SketchPlugin_ConstraintTangent.h>
36 #include <SketchPlugin_ConstraintVertical.h>
37 #include <SketchPlugin_MultiRotation.h>
38 #include <SketchPlugin_MultiTranslation.h>
39
40 #include <math.h>
41 #include <assert.h>
42
43
44 /// \brief This class is used to give unique index to the groups
45 class GroupIndexer
46 {
47 public:
48   /// \brief Return vacant index
49   static GroupID NEW_GROUP() { return ++myGroupIndex; }
50   /// \brief Removes the index
51   static void REMOVE_GROUP(const GroupID& theIndex) {
52     if (myGroupIndex == theIndex)
53       myGroupIndex--;
54   }
55
56 private:
57   GroupIndexer() {};
58
59   static GroupID myGroupIndex; ///< index of the group
60 };
61
62 GroupID GroupIndexer::myGroupIndex = GID_OUTOFGROUP;
63
64
65 static void sendMessage(const char* theMessageName)
66 {
67   std::shared_ptr<Events_Message> aMessage = std::shared_ptr<Events_Message>(
68       new Events_Message(Events_Loop::eventByName(theMessageName)));
69   Events_Loop::loop()->send(aMessage);
70 }
71
72 static void sendMessage(const char* theMessageName, const std::set<ObjectPtr>& theConflicting)
73 {
74   std::shared_ptr<ModelAPI_SolverFailedMessage> aMessage =
75       std::shared_ptr<ModelAPI_SolverFailedMessage>(
76       new ModelAPI_SolverFailedMessage(Events_Loop::eventByName(theMessageName)));
77   aMessage->setObjects(theConflicting);
78   Events_Loop::loop()->send(aMessage);
79 }
80
81
82
83 // ========================================================
84 // =========  SketchSolver_Group  ===============
85 // ========================================================
86
87 SketchSolver_Group::SketchSolver_Group(
88     std::shared_ptr<ModelAPI_CompositeFeature> theWorkplane)
89     : myID(GroupIndexer::NEW_GROUP()),
90       myPrevResult(STATUS_UNKNOWN)
91 {
92   // Initialize workplane
93   myWorkplaneID = EID_UNKNOWN;
94   addWorkplane(theWorkplane);
95 }
96
97 SketchSolver_Group::~SketchSolver_Group()
98 {
99   myConstraints.clear();
100   GroupIndexer::REMOVE_GROUP(myID);
101   // send the message that there is no more conflicting constraints
102   if (!myConflictingConstraints.empty()) {
103     sendMessage(EVENT_SOLVER_REPAIRED, myConflictingConstraints);
104     myConflictingConstraints.clear();
105   }
106 }
107
108 // ============================================================================
109 //  Function: isBaseWorkplane
110 //  Class:    SketchSolver_Group
111 //  Purpose:  verify the group is based on the given workplane
112 // ============================================================================
113 bool SketchSolver_Group::isBaseWorkplane(CompositeFeaturePtr theWorkplane) const
114 {
115   return theWorkplane == mySketch;
116 }
117
118 // ============================================================================
119 //  Function: isInteract
120 //  Class:    SketchSolver_Group
121 //  Purpose:  verify are there any entities in the group used by given constraint
122 // ============================================================================
123 bool SketchSolver_Group::isInteract(FeaturePtr theFeature) const
124 {
125   // Empty group interacts with everything
126   if (isEmpty())
127     return true;
128   // Check interaction with the storage
129   bool isInteracted = myStorage->isInteract(theFeature);
130   ConstraintConstraintMap::const_iterator anIt = myConstraints.begin();
131   for (; !isInteracted && anIt != myConstraints.end(); ++anIt)
132     if (anIt->first->getKind() == SketchPlugin_MultiRotation::ID() ||
133         anIt->first->getKind() == SketchPlugin_MultiTranslation::ID())
134       isInteracted = anIt->second->isUsed(theFeature);
135   return isInteracted;
136 }
137
138 // ============================================================================
139 //  Function: changeConstraint
140 //  Class:    SketchSolver_Group
141 //  Purpose:  create/update the constraint in the group
142 // ============================================================================
143 bool SketchSolver_Group::changeConstraint(
144     std::shared_ptr<SketchPlugin_Constraint> theConstraint)
145 {
146   // There is no workplane yet, something wrong
147   if (myWorkplaneID == EID_UNKNOWN)
148     return false;
149
150   if (!theConstraint || !theConstraint->data())
151     return false;
152
153   if (!checkFeatureValidity(theConstraint))
154     return false;
155
156   BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
157   myStorage->blockEvents(true);
158
159   bool isNewConstraint = myConstraints.find(theConstraint) == myConstraints.end();
160   if (isNewConstraint) {
161     // Add constraint to the current group
162     SolverConstraintPtr aConstraint = aBuilder->createConstraint(theConstraint);
163     if (!aConstraint)
164       return false;
165     aConstraint->process(myStorage, getId(), getWorkplaneId());
166     if (!aConstraint->error().empty()) {
167       if (aConstraint->error() == SketchSolver_Error::NOT_INITIALIZED())
168         return false; // some attribute are not initialized yet, don't show message
169       Events_Error::send(aConstraint->error(), this);
170     }
171     myConstraints[theConstraint] = aConstraint;
172
173     if (theConstraint->getKind() == SketchPlugin_ConstraintCoincidence::ID())
174       notifyCoincidenceChanged(myConstraints[theConstraint]);
175   }
176   else
177     myConstraints[theConstraint]->update();
178
179   // Fix mirror line
180   if (theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID()) {
181     AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
182         theConstraint->attribute(SketchPlugin_ConstraintMirror::ENTITY_A()));
183     if (aRefAttr && aRefAttr->isObject()) {
184       std::shared_ptr<SketchPlugin_Feature> aFeature =
185           std::dynamic_pointer_cast<SketchPlugin_Feature>(
186           ModelAPI_Feature::feature(aRefAttr->object()));
187       if (aFeature) {
188         SolverConstraintPtr aConstraint = aBuilder->createFixedConstraint(aFeature);
189         if (aConstraint) {
190           aConstraint->process(myStorage, getId(), getWorkplaneId());
191           setTemporary(aConstraint);
192         }
193       }
194     }
195   }
196   return true;
197 }
198
199 static void updateMultiConstraints(ConstraintConstraintMap& theConstraints, FeaturePtr theFeature)
200 {
201   ConstraintConstraintMap::iterator aCIt = theConstraints.begin();
202   for (; aCIt != theConstraints.end(); ++aCIt) {
203     SketchSolver_ConstraintType aType = aCIt->second->getType();
204     if ((aType == CONSTRAINT_MULTI_ROTATION ||
205          aType == CONSTRAINT_MULTI_TRANSLATION)
206         && aCIt->second->isUsed(theFeature))
207       std::dynamic_pointer_cast<SketchSolver_ConstraintMulti>(aCIt->second)->update(true);
208     else if ((aType == CONSTRAINT_TANGENT_CIRCLE_LINE ||
209               aType == CONSTRAINT_SYMMETRIC)
210              && aCIt->second->isUsed(theFeature))
211       aCIt->second->update();
212   }
213 }
214
215 bool SketchSolver_Group::updateFeature(FeaturePtr theFeature)
216 {
217   if (!checkFeatureValidity(theFeature))
218     return false;
219
220   bool isBlocked = myStorage->isEventsBlocked();
221   if (!isBlocked)
222     myStorage->blockEvents(true);
223
224   myStorage->refresh(true);
225   bool isUpdated = myStorage->update(theFeature);
226
227   updateMultiConstraints(myConstraints, theFeature);
228
229   // events were not blocked before, the feature has not been updated,
230   // so it is necessary to revert blocking
231   if (!isUpdated && !isBlocked)
232     myStorage->blockEvents(false);
233   return isUpdated;
234 }
235
236 void SketchSolver_Group::moveFeature(FeaturePtr theFeature)
237 {
238   BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
239
240   // Firstly, revert changes in the fixed entities
241   myStorage->blockEvents(true);
242   myStorage->refresh(true);
243
244   // Then, create temporary Fixed constraint
245   SolverConstraintPtr aConstraint = aBuilder->createMovementConstraint(theFeature);
246   if (!aConstraint)
247     return;
248   aConstraint->process(myStorage, getId(), getWorkplaneId());
249   if (aConstraint->error().empty())
250     setTemporary(aConstraint);
251
252   // Secondly, search attributes of the feature in the list of the Multi constraints and update them
253   updateMultiConstraints(myConstraints, theFeature);
254
255   // Workaround to process arcs.
256   // When move unconstrained arc, add temporary constraint to fix radius.
257   if (theFeature->getKind() == SketchPlugin_Arc::ID()) {
258     SolverConstraintPtr aFixedRadius = aBuilder->createFixedArcRadiusConstraint(theFeature);
259     if (aFixedRadius) {
260       aFixedRadius->process(myStorage, getId(), getWorkplaneId());
261       if (aFixedRadius->error().empty())
262         setTemporary(aFixedRadius);
263     }
264   }
265 }
266
267 // ============================================================================
268 //  Function: addWorkplane
269 //  Class:    SketchSolver_Group
270 //  Purpose:  create workplane for the group
271 // ============================================================================
272 bool SketchSolver_Group::addWorkplane(CompositeFeaturePtr theSketch)
273 {
274   if (myWorkplaneID != EID_UNKNOWN || theSketch->getKind() != SketchPlugin_Sketch::ID())
275     return false;  // the workplane already exists or the function parameter is not Sketch
276
277   mySketch = theSketch;
278   if (!updateWorkplane()) {
279     mySketch = CompositeFeaturePtr();
280     return false;
281   }
282   return true;
283 }
284
285 // ============================================================================
286 //  Function: updateWorkplane
287 //  Class:    SketchSolver_Group
288 //  Purpose:  update parameters of workplane
289 // ============================================================================
290 bool SketchSolver_Group::updateWorkplane()
291 {
292   BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
293   if (!myStorage) // Create storage if not exists
294     myStorage = aBuilder->createStorage(getId());
295
296   // sketch should be unchanged, set it out of current group
297   bool isUpdated = myStorage->update(FeaturePtr(mySketch), GID_OUTOFGROUP);
298   if (isUpdated) {
299     EntityWrapperPtr anEntity = myStorage->entity(FeaturePtr(mySketch));
300     myWorkplaneID = anEntity->id();
301   }
302   return isUpdated;
303 }
304
305 // ============================================================================
306 //  Function: resolveConstraints
307 //  Class:    SketchSolver_Group
308 //  Purpose:  solve the set of constraints for the current group
309 // ============================================================================
310 bool SketchSolver_Group::resolveConstraints()
311 {
312   bool aResolved = false;
313   bool isGroupEmpty = isEmpty() && myStorage->isEmpty();
314   if (myStorage->isNeedToResolve() && !isGroupEmpty) {
315     if (!mySketchSolver)
316       mySketchSolver = SketchSolver_Manager::instance()->builder()->createSolver();
317
318     mySketchSolver->setGroup(myID);
319     mySketchSolver->calculateFailedConstraints(false);
320     myStorage->initializeSolver(mySketchSolver);
321     mySketchSolver->prepare();
322
323     SketchSolver_SolveStatus aResult = STATUS_OK;
324     try {
325       if (myStorage->hasDuplicatedConstraint())
326         aResult = STATUS_INCONSISTENT;
327       else {
328         // To avoid overconstraint situation, we will remove temporary constraints one-by-one
329         // and try to find the case without overconstraint
330         bool isLastChance = false;
331         while (true) {
332           aResult = mySketchSolver->solve();
333           if (aResult == STATUS_OK || aResult == STATUS_EMPTYSET || isLastChance)
334             break;
335 ////          // try to update parameters and resolve once again
336 ////          ConstraintConstraintMap::iterator aConstrIt = myConstraints.begin();
337 ////          for (; aConstrIt != myConstraints.end(); ++aConstrIt)
338 ////            aConstrIt->second->update();
339           isLastChance = true;
340
341           removeTemporaryConstraints();
342           mySketchSolver->calculateFailedConstraints(true); // something failed => need to find it
343           myStorage->initializeSolver(mySketchSolver);
344         }
345       }
346     } catch (...) {
347 //      Events_Error::send(SketchSolver_Error::SOLVESPACE_CRASH(), this);
348       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::SOLVESPACE_CRASH());
349       if (myPrevResult == STATUS_OK || myPrevResult == STATUS_UNKNOWN) {
350         // the error message should be changed before sending the message
351         sendMessage(EVENT_SOLVER_FAILED);
352         myPrevResult = STATUS_FAILED;
353       }
354       mySketchSolver->undo();
355       return false;
356     }
357     if (aResult == STATUS_OK || aResult == STATUS_EMPTYSET) {  // solution succeeded, store results into correspondent attributes
358       myStorage->refresh();
359       if (myPrevResult != STATUS_OK || myPrevResult == STATUS_UNKNOWN) {
360         getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
361         // the error message should be changed before sending the message
362         sendMessage(EVENT_SOLVER_REPAIRED, myConflictingConstraints);
363         myConflictingConstraints.clear();
364         myPrevResult = STATUS_OK;
365       }
366     } else {
367       mySketchSolver->undo();
368       if (!myConstraints.empty()) {
369         // the error message should be changed before sending the message
370         getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::CONSTRAINTS());
371         if (myPrevResult != aResult || myPrevResult == STATUS_UNKNOWN) {
372           // Obtain list of conflicting constraints
373           std::set<ObjectPtr> aConflicting = myStorage->getConflictingConstraints(mySketchSolver);
374
375           if (myConflictingConstraints.empty())
376             sendMessage(EVENT_SOLVER_FAILED, aConflicting);
377           else {
378             std::set<ObjectPtr>::iterator anIt = aConflicting.begin();
379             for (; anIt != aConflicting.end(); ++anIt)
380               myConflictingConstraints.erase(*anIt);
381             if (!myConflictingConstraints.empty()) {
382               // some constraints does not conflict, send corresponding message
383               sendMessage(EVENT_SOLVER_REPAIRED, myConflictingConstraints);
384             }
385           }
386           myConflictingConstraints = aConflicting;
387           myPrevResult = aResult;
388         }
389       }
390     }
391
392     aResolved = true;
393   } else if (!isGroupEmpty) {
394     // Check there are constraints Fixed. If they exist, update parameters by stored values
395     ConstraintConstraintMap::iterator aCIt = myConstraints.begin();
396     for (; aCIt != myConstraints.end(); ++aCIt)
397       if (aCIt->first->getKind() == SketchPlugin_ConstraintRigid::ID()) {
398         aResolved = true;
399         break;
400       }
401     if (aCIt != myConstraints.end())
402       myStorage->refresh();
403   }
404   removeTemporaryConstraints();
405   myStorage->blockEvents(false);
406   myStorage->setNeedToResolve(false);
407   return aResolved;
408 }
409
410 // ============================================================================
411 //  Function: mergeGroups
412 //  Class:    SketchSolver_Group
413 //  Purpose:  append specified group to the current group
414 // ============================================================================
415 void SketchSolver_Group::mergeGroups(const SketchSolver_Group& theGroup)
416 {
417   // If specified group is empty, no need to merge
418   if (theGroup.isEmpty())
419     return;
420
421   std::set<ObjectPtr> aConstraints;
422   ConstraintConstraintMap::const_iterator aConstrIter = theGroup.myConstraints.begin();
423   for (; aConstrIter != theGroup.myConstraints.end(); aConstrIter++)
424     aConstraints.insert(aConstrIter->first);
425
426   std::list<FeaturePtr> aSortedConstraints = selectApplicableFeatures(aConstraints);
427   std::list<FeaturePtr>::iterator aSCIter = aSortedConstraints.begin();
428   for (; aSCIter != aSortedConstraints.end(); ++aSCIter) {
429     ConstraintPtr aConstr = std::dynamic_pointer_cast<SketchPlugin_Constraint>(*aSCIter);
430     if (!aConstr)
431       continue;
432     changeConstraint(aConstr);
433   }
434 }
435
436 // ============================================================================
437 //  Function: splitGroup
438 //  Class:    SketchSolver_Group
439 //  Purpose:  divide the group into several subgroups
440 // ============================================================================
441 void SketchSolver_Group::splitGroup(std::list<SketchSolver_Group*>& theCuts)
442 {
443   // New storage will be used in trimmed way to store the list of constraint interacted together.
444   StoragePtr aNewStorage = SketchSolver_Manager::instance()->builder()->createStorage(getId());
445   std::list<ConstraintWrapperPtr> aDummyVec; // empty vector to avoid creation of solver's constraints
446
447   // Obtain constraints, which should be separated
448   std::list<ConstraintPtr> anUnusedConstraints;
449   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
450   for ( ; aCIter != myConstraints.end(); aCIter++) {
451     if (aNewStorage->isInteract(FeaturePtr(aCIter->first)))
452       aNewStorage->addConstraint(aCIter->first, aDummyVec);
453     else
454       anUnusedConstraints.push_back(aCIter->first);
455   }
456
457   // Check the unused constraints once again, because they may become interacted with new storage since adding constraints
458   std::list<ConstraintPtr>::iterator aUnuseIt = anUnusedConstraints.begin();
459   while (aUnuseIt != anUnusedConstraints.end()) {
460     if (aNewStorage->isInteract(FeaturePtr(*aUnuseIt))) {
461       aNewStorage->addConstraint(*aUnuseIt, aDummyVec);
462       anUnusedConstraints.erase(aUnuseIt);
463       aUnuseIt = anUnusedConstraints.begin();
464       continue;
465     }
466     aUnuseIt++;
467   }
468
469   std::list<SketchSolver_Group*>::iterator aCutsIter;
470   aUnuseIt = anUnusedConstraints.begin();
471   for ( ; aUnuseIt != anUnusedConstraints.end(); ++aUnuseIt) {
472     // Remove unused constraints
473     removeConstraint(*aUnuseIt);
474     // Try to append constraint to already existent group
475     for (aCutsIter = theCuts.begin(); aCutsIter != theCuts.end(); ++aCutsIter)
476       if ((*aCutsIter)->isInteract(*aUnuseIt)) {
477         (*aCutsIter)->changeConstraint(*aUnuseIt);
478         break;
479       }
480     if (aCutsIter == theCuts.end()) {
481       // Add new group
482       SketchSolver_Group* aGroup = new SketchSolver_Group(mySketch);
483       aGroup->changeConstraint(*aUnuseIt);
484       theCuts.push_back(aGroup);
485     } else {
486       // Find other groups interacting with constraint
487       std::list<SketchSolver_Group*>::iterator aBaseGroupIt = aCutsIter;
488       for (++aCutsIter; aCutsIter != theCuts.end(); ++aCutsIter)
489         if ((*aCutsIter)->isInteract(*aUnuseIt)) {
490           (*aBaseGroupIt)->mergeGroups(**aCutsIter);
491           std::list<SketchSolver_Group*>::iterator aRemoveIt = aCutsIter--;
492           theCuts.erase(aRemoveIt);
493         }
494     }
495   }
496 }
497
498 // ============================================================================
499 //  Function: isConsistent
500 //  Class:    SketchSolver_Group
501 //  Purpose:  search removed entities and constraints
502 // ============================================================================
503 bool SketchSolver_Group::isConsistent()
504 {
505   if (isEmpty()) // no one constraint is initialized yet
506     return true;
507
508   // Check the features and constraint is the storage are valid
509   bool aResult = myStorage->isConsistent();
510   if (aResult) {
511     // additional check of consistency of the Fixed constraint,
512     // because they are not added to the storage
513     ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
514     for (; aCIter != myConstraints.end(); ++aCIter)
515       if (aCIter->first->getKind() == SketchPlugin_ConstraintRigid::ID() &&
516          (!aCIter->first->data() || !aCIter->first->data()->isValid())) {
517         aResult = false;
518         break;
519       }
520   }
521   if (!aResult) {
522     // remove invalid constraints
523     std::set<ConstraintPtr> anInvalidConstraints;
524     ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
525     for (; aCIter != myConstraints.end(); ++aCIter) {
526       if (!aCIter->first->data() || !aCIter->first->data()->isValid())
527         anInvalidConstraints.insert(aCIter->first);
528     }
529     std::set<ConstraintPtr>::const_iterator aRemoveIt = anInvalidConstraints.begin();
530     for (; aRemoveIt != anInvalidConstraints.end(); ++aRemoveIt)
531       removeConstraint(*aRemoveIt);
532     // remove invalid features
533     myStorage->removeInvalidEntities();
534   }
535   return aResult;
536 }
537
538 // ============================================================================
539 //  Function: removeTemporaryConstraints
540 //  Class:    SketchSolver_Group
541 //  Purpose:  remove all transient SLVS_C_WHERE_DRAGGED constraints after
542 //            resolving the set of constraints
543 // ============================================================================
544 void SketchSolver_Group::removeTemporaryConstraints()
545 {
546   std::set<SolverConstraintPtr>::iterator aTmpIt = myTempConstraints.begin();
547   for (; aTmpIt != myTempConstraints.end(); ++aTmpIt)
548     (*aTmpIt)->remove();
549
550   if (!myTempConstraints.empty())
551     myStorage->verifyFixed();
552   myStorage->setNeedToResolve(false);
553   myTempConstraints.clear();
554 }
555
556 // ============================================================================
557 //  Function: removeConstraint
558 //  Class:    SketchSolver_Group
559 //  Purpose:  remove constraint and all unused entities
560 // ============================================================================
561 void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
562 {
563   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
564   for (; aCIter != myConstraints.end(); aCIter++)
565     if (aCIter->first == theConstraint) {
566       aCIter->second->remove(); // the constraint is not fully removed
567       if (aCIter->first->getKind() == SketchPlugin_ConstraintCoincidence::ID())
568         notifyCoincidenceChanged(aCIter->second);
569       break;
570     }
571   if (aCIter != myConstraints.end())
572     myConstraints.erase(aCIter);
573 }
574
575 // ============================================================================
576 //  Function: setTemporary
577 //  Class:    SketchSolver_Group
578 //  Purpose:  append given constraint to the group of temporary constraints
579 // ============================================================================
580 void SketchSolver_Group::setTemporary(SolverConstraintPtr theConstraint)
581 {
582   myTempConstraints.insert(theConstraint);
583 }
584
585
586 // ============================================================================
587 //  Function: checkFeatureValidity
588 //  Class:    SketchSolver_Group
589 //  Purpose:  verifies is the feature valid
590 // ============================================================================
591 bool SketchSolver_Group::checkFeatureValidity(FeaturePtr theFeature)
592 {
593   if (!theFeature || !theFeature->data()->isValid())
594     return true;
595
596   SessionPtr aMgr = ModelAPI_Session::get();
597   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
598   return aFactory->validate(theFeature);
599 }
600
601
602
603
604 // ===========   Auxiliary functions   ========================================
605 static double featureToVal(FeaturePtr theFeature)
606 {
607   if (theFeature->getKind() == SketchPlugin_Sketch::ID())
608     return 0.0; // sketch
609   ConstraintPtr aConstraint = std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
610   if (!aConstraint)
611     return 1.0; // features (arc, circle, line, point)
612
613   const std::string& anID = aConstraint->getKind();
614   if (anID == SketchPlugin_ConstraintCoincidence::ID()) {
615     AttributeRefAttrPtr anAttrA = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
616         aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
617     AttributeRefAttrPtr anAttrB = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
618         aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
619     if (anAttrA && anAttrB && (anAttrA->isObject() || anAttrB->isObject()))
620       return 2.0; // point-on-line and point-on-circle should go before points coincidence constraint
621     return 2.5;
622   }
623   if (anID == SketchPlugin_ConstraintDistance::ID() ||
624       anID == SketchPlugin_ConstraintLength::ID() ||
625       anID == SketchPlugin_ConstraintRadius::ID())
626     return 3.0;
627   if (anID == SketchPlugin_ConstraintAngle::ID())
628     return 3.5;
629   if (anID == SketchPlugin_ConstraintHorizontal::ID() ||
630       anID == SketchPlugin_ConstraintVertical::ID() ||
631       anID == SketchPlugin_ConstraintParallel::ID() ||
632       anID == SketchPlugin_ConstraintPerpendicular::ID())
633     return 4.0;
634   if (anID == SketchPlugin_ConstraintEqual::ID())
635     return 5.0;
636   if (anID == SketchPlugin_ConstraintTangent::ID() ||
637       anID == SketchPlugin_ConstraintMirror::ID())
638     return 6.0;
639   if (anID == SketchPlugin_ConstraintRigid::ID())
640     return 7.0;
641   if (anID == SketchPlugin_MultiRotation::ID() ||
642       anID == SketchPlugin_MultiTranslation::ID())
643     return 8.0;
644
645   // all other constraints are placed between Equal and Tangent constraints
646   return 5.5;
647 }
648
649 static bool isLess(FeaturePtr theFeature1, FeaturePtr theFeature2)
650 {
651   return featureToVal(theFeature1) < featureToVal(theFeature2);
652 }
653
654 std::list<FeaturePtr> SketchSolver_Group::selectApplicableFeatures(const std::set<ObjectPtr>& theObjects)
655 {
656   std::list<FeaturePtr> aResult;
657   std::list<FeaturePtr>::iterator aResIt;
658
659   std::set<ObjectPtr>::const_iterator anObjIter = theObjects.begin();
660   for (; anObjIter != theObjects.end(); ++anObjIter) {
661     // Operate sketch itself and SketchPlugin features only.
662     // Also, the Fillet need to be skipped, because there are several separated constraints composing it.
663     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIter);
664     if (!aFeature)
665       continue;
666     std::shared_ptr<SketchPlugin_Feature> aSketchFeature = 
667         std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
668     if ((aFeature->getKind() != SketchPlugin_Sketch::ID() && !aSketchFeature) ||
669         aFeature->getKind() == SketchPlugin_ConstraintFillet::ID())
670       continue;
671
672     // Find the place where to insert a feature
673     for (aResIt = aResult.begin(); aResIt != aResult.end(); ++aResIt)
674       if (isLess(aFeature, *aResIt))
675         break;
676     aResult.insert(aResIt, aFeature);
677   }
678
679   return aResult;
680 }
681
682 void SketchSolver_Group::notifyCoincidenceChanged(SolverConstraintPtr theCoincidence)
683 {
684   const std::list<EntityWrapperPtr>& aCoincident = theCoincidence->attributes();
685   EntityWrapperPtr anAttr1 = aCoincident.front();
686   EntityWrapperPtr anAttr2 = aCoincident.back();
687
688   ConstraintConstraintMap::iterator anIt = myConstraints.begin();
689   for (; anIt != myConstraints.end(); ++anIt)
690     anIt->second->notifyCoincidenceChanged(anAttr1, anAttr2);
691 }