Salome HOME
Update processing of the Angle constraint in the sketch solver connectors
[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 // Update constraints if they contain specific feature
200 static void updateMultiConstraints(ConstraintConstraintMap& theConstraints, FeaturePtr theFeature)
201 {
202   ConstraintConstraintMap::iterator aCIt = theConstraints.begin();
203   for (; aCIt != theConstraints.end(); ++aCIt) {
204     SketchSolver_ConstraintType aType = aCIt->second->getType();
205     if ((aType == CONSTRAINT_MULTI_ROTATION ||
206          aType == CONSTRAINT_MULTI_TRANSLATION)
207         && aCIt->second->isUsed(theFeature))
208       std::dynamic_pointer_cast<SketchSolver_ConstraintMulti>(aCIt->second)->update(true);
209     else if ((aType == CONSTRAINT_TANGENT_CIRCLE_LINE ||
210               aType == CONSTRAINT_SYMMETRIC || aType == CONSTRAINT_ANGLE)
211              && aCIt->second->isUsed(theFeature))
212       aCIt->second->update();
213   }
214 }
215
216 // Recalculate slave features of the Multi constraints
217 static void updateMultiConstraints(ConstraintConstraintMap& theConstraints)
218 {
219   ConstraintConstraintMap::iterator aCIt = theConstraints.begin();
220   for (; aCIt != theConstraints.end(); ++aCIt) {
221     SketchSolver_ConstraintType aType = aCIt->second->getType();
222     if ((aType == CONSTRAINT_MULTI_ROTATION ||
223          aType == CONSTRAINT_MULTI_TRANSLATION))
224       std::dynamic_pointer_cast<SketchSolver_ConstraintMulti>(aCIt->second)->update(true);
225   }
226 }
227
228 bool SketchSolver_Group::updateFeature(FeaturePtr theFeature)
229 {
230   if (!checkFeatureValidity(theFeature))
231     return false;
232
233   bool isBlocked = myStorage->isEventsBlocked();
234   if (!isBlocked)
235     myStorage->blockEvents(true);
236
237   myStorage->refresh(true);
238   bool isUpdated = myStorage->update(theFeature);
239
240   updateMultiConstraints(myConstraints, theFeature);
241
242   // events were not blocked before, the feature has not been updated,
243   // so it is necessary to revert blocking
244   if (!isUpdated && !isBlocked)
245     myStorage->blockEvents(false);
246   return isUpdated;
247 }
248
249 void SketchSolver_Group::moveFeature(FeaturePtr theFeature)
250 {
251   BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
252
253   // Firstly, revert changes in the fixed entities
254   myStorage->blockEvents(true);
255   myStorage->refresh(true);
256
257   // Then, create temporary Fixed constraint
258   SolverConstraintPtr aConstraint = aBuilder->createMovementConstraint(theFeature);
259   if (!aConstraint)
260     return;
261   aConstraint->process(myStorage, getId(), getWorkplaneId());
262   if (aConstraint->error().empty())
263     setTemporary(aConstraint);
264
265   // Secondly, search attributes of the feature in the list of the Multi constraints and update them
266   updateMultiConstraints(myConstraints, theFeature);
267
268   // Workaround to process arcs.
269   // When move unconstrained arc, add temporary constraint to fix radius.
270   if (theFeature->getKind() == SketchPlugin_Arc::ID()) {
271     SolverConstraintPtr aFixedRadius = aBuilder->createFixedArcRadiusConstraint(theFeature);
272     if (aFixedRadius) {
273       aFixedRadius->process(myStorage, getId(), getWorkplaneId());
274       if (aFixedRadius->error().empty())
275         setTemporary(aFixedRadius);
276     }
277   }
278 }
279
280 // ============================================================================
281 //  Function: addWorkplane
282 //  Class:    SketchSolver_Group
283 //  Purpose:  create workplane for the group
284 // ============================================================================
285 bool SketchSolver_Group::addWorkplane(CompositeFeaturePtr theSketch)
286 {
287   if (myWorkplaneID != EID_UNKNOWN || theSketch->getKind() != SketchPlugin_Sketch::ID())
288     return false;  // the workplane already exists or the function parameter is not Sketch
289
290   mySketch = theSketch;
291   if (!updateWorkplane()) {
292     mySketch = CompositeFeaturePtr();
293     return false;
294   }
295   return true;
296 }
297
298 // ============================================================================
299 //  Function: updateWorkplane
300 //  Class:    SketchSolver_Group
301 //  Purpose:  update parameters of workplane
302 // ============================================================================
303 bool SketchSolver_Group::updateWorkplane()
304 {
305   BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
306   if (!myStorage) // Create storage if not exists
307     myStorage = aBuilder->createStorage(getId());
308
309   // sketch should be unchanged, set it out of current group
310   bool isUpdated = myStorage->update(FeaturePtr(mySketch), GID_OUTOFGROUP);
311   if (isUpdated) {
312     EntityWrapperPtr anEntity = myStorage->entity(FeaturePtr(mySketch));
313     myWorkplaneID = anEntity->id();
314   }
315   return isUpdated;
316 }
317
318 // ============================================================================
319 //  Function: resolveConstraints
320 //  Class:    SketchSolver_Group
321 //  Purpose:  solve the set of constraints for the current group
322 // ============================================================================
323 bool SketchSolver_Group::resolveConstraints()
324 {
325   bool aResolved = false;
326   bool isGroupEmpty = isEmpty() && myStorage->isEmpty();
327   if (myStorage->isNeedToResolve() && !isGroupEmpty) {
328     if (!mySketchSolver)
329       mySketchSolver = SketchSolver_Manager::instance()->builder()->createSolver();
330
331     mySketchSolver->setGroup(myID);
332     mySketchSolver->calculateFailedConstraints(false);
333     myStorage->initializeSolver(mySketchSolver);
334     mySketchSolver->prepare();
335
336     SketchSolver_SolveStatus aResult = STATUS_OK;
337     try {
338       if (myStorage->hasDuplicatedConstraint())
339         aResult = STATUS_INCONSISTENT;
340       else {
341         // To avoid overconstraint situation, we will remove temporary constraints one-by-one
342         // and try to find the case without overconstraint
343         bool isLastChance = false;
344         while (true) {
345           aResult = mySketchSolver->solve();
346           if (aResult == STATUS_OK || aResult == STATUS_EMPTYSET || isLastChance)
347             break;
348 ////          // try to update parameters and resolve once again
349 ////          ConstraintConstraintMap::iterator aConstrIt = myConstraints.begin();
350 ////          for (; aConstrIt != myConstraints.end(); ++aConstrIt)
351 ////            aConstrIt->second->update();
352           isLastChance = true;
353
354           removeTemporaryConstraints();
355           mySketchSolver->calculateFailedConstraints(true); // something failed => need to find it
356           myStorage->initializeSolver(mySketchSolver);
357         }
358       }
359     } catch (...) {
360 //      Events_Error::send(SketchSolver_Error::SOLVESPACE_CRASH(), this);
361       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::SOLVESPACE_CRASH());
362       if (myPrevResult == STATUS_OK || myPrevResult == STATUS_UNKNOWN) {
363         // the error message should be changed before sending the message
364         sendMessage(EVENT_SOLVER_FAILED);
365         myPrevResult = STATUS_FAILED;
366       }
367       mySketchSolver->undo();
368       return false;
369     }
370     if (aResult == STATUS_OK || aResult == STATUS_EMPTYSET) {  // solution succeeded, store results into correspondent attributes
371       myStorage->refresh();
372       updateMultiConstraints(myConstraints);
373       if (myPrevResult != STATUS_OK || myPrevResult == STATUS_UNKNOWN) {
374         getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
375         // the error message should be changed before sending the message
376         sendMessage(EVENT_SOLVER_REPAIRED, myConflictingConstraints);
377         myConflictingConstraints.clear();
378         myPrevResult = STATUS_OK;
379       }
380     } else {
381       mySketchSolver->undo();
382       if (!myConstraints.empty()) {
383         // the error message should be changed before sending the message
384         getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::CONSTRAINTS());
385         if (myPrevResult != aResult || myPrevResult == STATUS_UNKNOWN) {
386           // Obtain list of conflicting constraints
387           std::set<ObjectPtr> aConflicting = myStorage->getConflictingConstraints(mySketchSolver);
388
389           if (myConflictingConstraints.empty())
390             sendMessage(EVENT_SOLVER_FAILED, aConflicting);
391           else {
392             std::set<ObjectPtr>::iterator anIt = aConflicting.begin();
393             for (; anIt != aConflicting.end(); ++anIt)
394               myConflictingConstraints.erase(*anIt);
395             if (!myConflictingConstraints.empty()) {
396               // some constraints does not conflict, send corresponding message
397               sendMessage(EVENT_SOLVER_REPAIRED, myConflictingConstraints);
398             }
399           }
400           myConflictingConstraints = aConflicting;
401           myPrevResult = aResult;
402         }
403       }
404     }
405
406     aResolved = true;
407   } else if (!isGroupEmpty) {
408     // Check there are constraints Fixed. If they exist, update parameters by stored values
409     ConstraintConstraintMap::iterator aCIt = myConstraints.begin();
410     for (; aCIt != myConstraints.end(); ++aCIt)
411       if (aCIt->first->getKind() == SketchPlugin_ConstraintRigid::ID()) {
412         aResolved = true;
413         break;
414       }
415     if (aCIt != myConstraints.end())
416       myStorage->refresh();
417   }
418   removeTemporaryConstraints();
419   myStorage->blockEvents(false);
420   myStorage->setNeedToResolve(false);
421   return aResolved;
422 }
423
424 // ============================================================================
425 //  Function: mergeGroups
426 //  Class:    SketchSolver_Group
427 //  Purpose:  append specified group to the current group
428 // ============================================================================
429 void SketchSolver_Group::mergeGroups(const SketchSolver_Group& theGroup)
430 {
431   // If specified group is empty, no need to merge
432   if (theGroup.isEmpty())
433     return;
434
435   std::set<ObjectPtr> aConstraints;
436   ConstraintConstraintMap::const_iterator aConstrIter = theGroup.myConstraints.begin();
437   for (; aConstrIter != theGroup.myConstraints.end(); aConstrIter++)
438     aConstraints.insert(aConstrIter->first);
439
440   std::list<FeaturePtr> aSortedConstraints = selectApplicableFeatures(aConstraints);
441   std::list<FeaturePtr>::iterator aSCIter = aSortedConstraints.begin();
442   for (; aSCIter != aSortedConstraints.end(); ++aSCIter) {
443     ConstraintPtr aConstr = std::dynamic_pointer_cast<SketchPlugin_Constraint>(*aSCIter);
444     if (!aConstr)
445       continue;
446     changeConstraint(aConstr);
447   }
448 }
449
450 // ============================================================================
451 //  Function: splitGroup
452 //  Class:    SketchSolver_Group
453 //  Purpose:  divide the group into several subgroups
454 // ============================================================================
455 void SketchSolver_Group::splitGroup(std::list<SketchSolver_Group*>& theCuts)
456 {
457   // New storage will be used in trimmed way to store the list of constraint interacted together.
458   StoragePtr aNewStorage = SketchSolver_Manager::instance()->builder()->createStorage(getId());
459   std::list<ConstraintWrapperPtr> aDummyVec; // empty vector to avoid creation of solver's constraints
460
461   // Obtain constraints, which should be separated
462   std::list<ConstraintPtr> anUnusedConstraints;
463   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
464   for ( ; aCIter != myConstraints.end(); aCIter++) {
465     if (aNewStorage->isInteract(FeaturePtr(aCIter->first)))
466       aNewStorage->addConstraint(aCIter->first, aDummyVec);
467     else
468       anUnusedConstraints.push_back(aCIter->first);
469   }
470
471   // Check the unused constraints once again, because they may become interacted with new storage since adding constraints
472   std::list<ConstraintPtr>::iterator aUnuseIt = anUnusedConstraints.begin();
473   while (aUnuseIt != anUnusedConstraints.end()) {
474     if (aNewStorage->isInteract(FeaturePtr(*aUnuseIt))) {
475       aNewStorage->addConstraint(*aUnuseIt, aDummyVec);
476       anUnusedConstraints.erase(aUnuseIt);
477       aUnuseIt = anUnusedConstraints.begin();
478       continue;
479     }
480     aUnuseIt++;
481   }
482
483   std::list<SketchSolver_Group*>::iterator aCutsIter;
484   aUnuseIt = anUnusedConstraints.begin();
485   for ( ; aUnuseIt != anUnusedConstraints.end(); ++aUnuseIt) {
486     // Remove unused constraints
487     removeConstraint(*aUnuseIt);
488     // Try to append constraint to already existent group
489     for (aCutsIter = theCuts.begin(); aCutsIter != theCuts.end(); ++aCutsIter)
490       if ((*aCutsIter)->isInteract(*aUnuseIt)) {
491         (*aCutsIter)->changeConstraint(*aUnuseIt);
492         break;
493       }
494     if (aCutsIter == theCuts.end()) {
495       // Add new group
496       SketchSolver_Group* aGroup = new SketchSolver_Group(mySketch);
497       aGroup->changeConstraint(*aUnuseIt);
498       theCuts.push_back(aGroup);
499     } else {
500       // Find other groups interacting with constraint
501       std::list<SketchSolver_Group*>::iterator aBaseGroupIt = aCutsIter;
502       for (++aCutsIter; aCutsIter != theCuts.end(); ++aCutsIter)
503         if ((*aCutsIter)->isInteract(*aUnuseIt)) {
504           (*aBaseGroupIt)->mergeGroups(**aCutsIter);
505           std::list<SketchSolver_Group*>::iterator aRemoveIt = aCutsIter--;
506           theCuts.erase(aRemoveIt);
507         }
508     }
509   }
510 }
511
512 // ============================================================================
513 //  Function: isConsistent
514 //  Class:    SketchSolver_Group
515 //  Purpose:  search removed entities and constraints
516 // ============================================================================
517 bool SketchSolver_Group::isConsistent()
518 {
519   if (isEmpty()) // no one constraint is initialized yet
520     return true;
521
522   // Check the features and constraint is the storage are valid
523   bool aResult = myStorage->isConsistent();
524   if (aResult) {
525     // additional check of consistency of the Fixed constraint,
526     // because they are not added to the storage
527     ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
528     for (; aCIter != myConstraints.end(); ++aCIter)
529       if (aCIter->first->getKind() == SketchPlugin_ConstraintRigid::ID() &&
530          (!aCIter->first->data() || !aCIter->first->data()->isValid())) {
531         aResult = false;
532         break;
533       }
534   }
535   if (!aResult) {
536     // remove invalid constraints
537     std::set<ConstraintPtr> anInvalidConstraints;
538     ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
539     for (; aCIter != myConstraints.end(); ++aCIter) {
540       if (!aCIter->first->data() || !aCIter->first->data()->isValid())
541         anInvalidConstraints.insert(aCIter->first);
542     }
543     std::set<ConstraintPtr>::const_iterator aRemoveIt = anInvalidConstraints.begin();
544     for (; aRemoveIt != anInvalidConstraints.end(); ++aRemoveIt)
545       removeConstraint(*aRemoveIt);
546     // remove invalid features
547     myStorage->removeInvalidEntities();
548   }
549   return aResult;
550 }
551
552 // ============================================================================
553 //  Function: removeTemporaryConstraints
554 //  Class:    SketchSolver_Group
555 //  Purpose:  remove all transient SLVS_C_WHERE_DRAGGED constraints after
556 //            resolving the set of constraints
557 // ============================================================================
558 void SketchSolver_Group::removeTemporaryConstraints()
559 {
560   std::set<SolverConstraintPtr>::iterator aTmpIt = myTempConstraints.begin();
561   for (; aTmpIt != myTempConstraints.end(); ++aTmpIt)
562     (*aTmpIt)->remove();
563
564   if (!myTempConstraints.empty())
565     myStorage->verifyFixed();
566   myStorage->setNeedToResolve(false);
567   myTempConstraints.clear();
568 }
569
570 // ============================================================================
571 //  Function: removeConstraint
572 //  Class:    SketchSolver_Group
573 //  Purpose:  remove constraint and all unused entities
574 // ============================================================================
575 void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
576 {
577   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
578   for (; aCIter != myConstraints.end(); aCIter++)
579     if (aCIter->first == theConstraint) {
580       aCIter->second->remove(); // the constraint is not fully removed
581       if (aCIter->first->getKind() == SketchPlugin_ConstraintCoincidence::ID())
582         notifyCoincidenceChanged(aCIter->second);
583       break;
584     }
585   if (aCIter != myConstraints.end())
586     myConstraints.erase(aCIter);
587 }
588
589 // ============================================================================
590 //  Function: setTemporary
591 //  Class:    SketchSolver_Group
592 //  Purpose:  append given constraint to the group of temporary constraints
593 // ============================================================================
594 void SketchSolver_Group::setTemporary(SolverConstraintPtr theConstraint)
595 {
596   myTempConstraints.insert(theConstraint);
597 }
598
599
600 // ============================================================================
601 //  Function: checkFeatureValidity
602 //  Class:    SketchSolver_Group
603 //  Purpose:  verifies is the feature valid
604 // ============================================================================
605 bool SketchSolver_Group::checkFeatureValidity(FeaturePtr theFeature)
606 {
607   if (!theFeature || !theFeature->data()->isValid())
608     return true;
609
610   SessionPtr aMgr = ModelAPI_Session::get();
611   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
612   return aFactory->validate(theFeature);
613 }
614
615
616
617
618 // ===========   Auxiliary functions   ========================================
619 static double featureToVal(FeaturePtr theFeature)
620 {
621   if (theFeature->getKind() == SketchPlugin_Sketch::ID())
622     return 0.0; // sketch
623   ConstraintPtr aConstraint = std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
624   if (!aConstraint)
625     return 1.0; // features (arc, circle, line, point)
626
627   const std::string& anID = aConstraint->getKind();
628   if (anID == SketchPlugin_ConstraintCoincidence::ID()) {
629     AttributeRefAttrPtr anAttrA = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
630         aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
631     AttributeRefAttrPtr anAttrB = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
632         aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
633     if (anAttrA && anAttrB && (anAttrA->isObject() || anAttrB->isObject()))
634       return 2.0; // point-on-line and point-on-circle should go before points coincidence constraint
635     return 2.5;
636   }
637   if (anID == SketchPlugin_ConstraintDistance::ID() ||
638       anID == SketchPlugin_ConstraintLength::ID() ||
639       anID == SketchPlugin_ConstraintRadius::ID())
640     return 3.0;
641   if (anID == SketchPlugin_ConstraintAngle::ID())
642     return 3.5;
643   if (anID == SketchPlugin_ConstraintHorizontal::ID() ||
644       anID == SketchPlugin_ConstraintVertical::ID() ||
645       anID == SketchPlugin_ConstraintParallel::ID() ||
646       anID == SketchPlugin_ConstraintPerpendicular::ID())
647     return 4.0;
648   if (anID == SketchPlugin_ConstraintEqual::ID())
649     return 5.0;
650   if (anID == SketchPlugin_ConstraintTangent::ID() ||
651       anID == SketchPlugin_ConstraintMirror::ID())
652     return 6.0;
653   if (anID == SketchPlugin_ConstraintRigid::ID())
654     return 7.0;
655   if (anID == SketchPlugin_MultiRotation::ID() ||
656       anID == SketchPlugin_MultiTranslation::ID())
657     return 8.0;
658
659   // all other constraints are placed between Equal and Tangent constraints
660   return 5.5;
661 }
662
663 static bool isLess(FeaturePtr theFeature1, FeaturePtr theFeature2)
664 {
665   return featureToVal(theFeature1) < featureToVal(theFeature2);
666 }
667
668 std::list<FeaturePtr> SketchSolver_Group::selectApplicableFeatures(const std::set<ObjectPtr>& theObjects)
669 {
670   std::list<FeaturePtr> aResult;
671   std::list<FeaturePtr>::iterator aResIt;
672
673   std::set<ObjectPtr>::const_iterator anObjIter = theObjects.begin();
674   for (; anObjIter != theObjects.end(); ++anObjIter) {
675     // Operate sketch itself and SketchPlugin features only.
676     // Also, the Fillet need to be skipped, because there are several separated constraints composing it.
677     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIter);
678     if (!aFeature)
679       continue;
680     std::shared_ptr<SketchPlugin_Feature> aSketchFeature = 
681         std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
682     if ((aFeature->getKind() != SketchPlugin_Sketch::ID() && !aSketchFeature) ||
683         aFeature->getKind() == SketchPlugin_ConstraintFillet::ID())
684       continue;
685
686     // Find the place where to insert a feature
687     for (aResIt = aResult.begin(); aResIt != aResult.end(); ++aResIt)
688       if (isLess(aFeature, *aResIt))
689         break;
690     aResult.insert(aResIt, aFeature);
691   }
692
693   return aResult;
694 }
695
696 void SketchSolver_Group::notifyCoincidenceChanged(SolverConstraintPtr theCoincidence)
697 {
698   const std::list<EntityWrapperPtr>& aCoincident = theCoincidence->attributes();
699   EntityWrapperPtr anAttr1 = aCoincident.front();
700   EntityWrapperPtr anAttr2 = aCoincident.back();
701
702   ConstraintConstraintMap::iterator anIt = myConstraints.begin();
703   for (; anIt != myConstraints.end(); ++anIt)
704     anIt->second->notifyCoincidenceChanged(anAttr1, anAttr2);
705 }