]> SALOME platform Git repositories - modules/shaper.git/blob - src/SketchSolver/SketchSolver_Group.cpp
Salome HOME
First phase of SketchSolver refactoring
[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_Builder.h>
14 #include <SketchSolver_Manager.h>
15
16 #include <Events_Error.h>
17 #include <Events_Loop.h>
18 ////#include <GeomAPI_XY.h>
19 ////#include <GeomAPI_Dir2d.h>
20 ////#include <GeomAPI_Pnt2d.h>
21 ////#include <GeomDataAPI_Dir.h>
22 ////#include <GeomDataAPI_Point.h>
23 ////#include <GeomDataAPI_Point2D.h>
24 ////#include <ModelAPI_AttributeDouble.h>
25 #include <ModelAPI_AttributeString.h>
26 ////#include <ModelAPI_Document.h>
27 #include <ModelAPI_Events.h>
28 ////#include <ModelAPI_ResultConstruction.h>
29 #include <ModelAPI_Session.h>
30 #include <ModelAPI_Validator.h>
31 ////
32 ////#include <SketchPlugin_Constraint.h>
33 #include <SketchPlugin_ConstraintAngle.h>
34 #include <SketchPlugin_ConstraintCoincidence.h>
35 #include <SketchPlugin_ConstraintDistance.h>
36 #include <SketchPlugin_ConstraintEqual.h>
37 #include <SketchPlugin_ConstraintHorizontal.h>
38 #include <SketchPlugin_ConstraintLength.h>
39 #include <SketchPlugin_ConstraintFillet.h>
40 #include <SketchPlugin_ConstraintMirror.h>
41 #include <SketchPlugin_ConstraintParallel.h>
42 #include <SketchPlugin_ConstraintPerpendicular.h>
43 #include <SketchPlugin_ConstraintRadius.h>
44 #include <SketchPlugin_ConstraintRigid.h>
45 #include <SketchPlugin_ConstraintTangent.h>
46 #include <SketchPlugin_ConstraintVertical.h>
47 ////#include <SketchPlugin_Feature.h>
48 #include <SketchPlugin_MultiRotation.h>
49 #include <SketchPlugin_MultiTranslation.h>
50 ////#include <SketchPlugin_Sketch.h>
51 ////
52 ////#include <SketchPlugin_Arc.h>
53 ////#include <SketchPlugin_Circle.h>
54 ////#include <SketchPlugin_Line.h>
55 ////#include <SketchPlugin_Point.h>
56 ////#include <SketchPlugin_Sketch.h>
57
58 #include <math.h>
59 #include <assert.h>
60
61
62 /// \brief This class is used to give unique index to the groups
63 class GroupIndexer
64 {
65 public:
66   /// \brief Return vacant index
67   static GroupID NEW_GROUP() { return ++myGroupIndex; }
68   /// \brief Removes the index
69   static void REMOVE_GROUP(const GroupID& theIndex) {
70     if (myGroupIndex == theIndex)
71       myGroupIndex--;
72   }
73
74 private:
75   GroupIndexer() {};
76
77   static GroupID myGroupIndex; ///< index of the group
78 };
79
80 GroupID GroupIndexer::myGroupIndex = GID_OUTOFGROUP;
81
82
83 static void sendMessage(const char* theMessageName)
84 {
85   std::shared_ptr<Events_Message> aMessage = std::shared_ptr<Events_Message>(
86       new Events_Message(Events_Loop::eventByName(theMessageName)));
87   Events_Loop::loop()->send(aMessage);
88 }
89
90
91
92 // ========================================================
93 // =========  SketchSolver_Group  ===============
94 // ========================================================
95
96 SketchSolver_Group::SketchSolver_Group(
97     std::shared_ptr<ModelAPI_CompositeFeature> theWorkplane)
98     : myID(GroupIndexer::NEW_GROUP()),
99       myPrevSolved(true)
100 {
101   // Initialize workplane
102   myWorkplaneID = EID_UNKNOWN;
103   addWorkplane(theWorkplane);
104 }
105
106 SketchSolver_Group::~SketchSolver_Group()
107 {
108   myConstraints.clear();
109   GroupIndexer::REMOVE_GROUP(myID);
110 }
111
112 // ============================================================================
113 //  Function: isBaseWorkplane
114 //  Class:    SketchSolver_Group
115 //  Purpose:  verify the group is based on the given workplane
116 // ============================================================================
117 bool SketchSolver_Group::isBaseWorkplane(CompositeFeaturePtr theWorkplane) const
118 {
119   return theWorkplane == mySketch;
120 }
121
122 // ============================================================================
123 //  Function: isInteract
124 //  Class:    SketchSolver_Group
125 //  Purpose:  verify are there any entities in the group used by given constraint
126 // ============================================================================
127 bool SketchSolver_Group::isInteract(
128     std::shared_ptr<SketchPlugin_Feature> theFeature) const
129 {
130   // Empty group interacts with everything
131   if (isEmpty())
132     return true;
133   // Check interaction with the storage
134   return myStorage->isInteract(theFeature);
135 }
136
137 // ============================================================================
138 //  Function: changeConstraint
139 //  Class:    SketchSolver_Group
140 //  Purpose:  create/update the constraint in the group
141 // ============================================================================
142 bool SketchSolver_Group::changeConstraint(
143     std::shared_ptr<SketchPlugin_Constraint> theConstraint)
144 {
145   // There is no workplane yet, something wrong
146   if (myWorkplaneID == EID_UNKNOWN)
147     return false;
148
149   if (!theConstraint || !theConstraint->data())
150     return false;
151
152   if (!checkFeatureValidity(theConstraint))
153     return false;
154
155   BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
156
157   bool isNewConstraint = myConstraints.find(theConstraint) == myConstraints.end();
158   if (isNewConstraint) {
159     // Add constraint to the current group
160     SolverConstraintPtr aConstraint = aBuilder->createConstraint(theConstraint);
161     if (!aConstraint)
162       return false;
163     aConstraint->process(myStorage, getId(), getWorkplaneId());
164     if (!aConstraint->error().empty()) {
165       if (aConstraint->error() == SketchSolver_Error::NOT_INITIALIZED())
166         return false; // some attribute are not initialized yet, don't show message
167       Events_Error::send(aConstraint->error(), this);
168     }
169
170 ////    // Additional verification of coincidence of several points
171 ////    if (aConstraint->getType() == CONSTRAINT_PT_PT_COINCIDENT) {
172 ////      bool hasMultiCoincidence = false;
173 ////      std::shared_ptr<SketchSolver_ConstraintCoincidence> aCoincidence =
174 ////          std::dynamic_pointer_cast<SketchSolver_ConstraintCoincidence>(aConstraint);
175 ////
176 ////      ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
177 ////      for (; aCIter != myConstraints.end(); ++aCIter) {
178 ////        if (aCIter->second->getType() != CONSTRAINT_PT_PT_COINCIDENT)
179 ////          continue;
180 ////
181 ////        std::shared_ptr<SketchSolver_ConstraintCoincidence> aCurCoinc =
182 ////          std::dynamic_pointer_cast<SketchSolver_ConstraintCoincidence>(aCIter->second);
183 ////        if (aCoincidence != aCurCoinc && aCurCoinc->isCoincide(aCoincidence)) {
184 ////          aCoincidence->attach(aCurCoinc);
185 ////////          // update other coincidences
186 ////////          ConstraintConstraintMap::iterator anIt = aCIter;
187 ////////          for (++anIt; anIt != myConstraints.end(); ++anIt)
188 ////////            if (anIt->second == aCIter->second)
189 ////////              anIt->second = aCoincidence;
190 ////          aCIter->second = aCoincidence;
191 ////          hasMultiCoincidence = true;
192 ////        }
193 ////      }
194 ////
195 ////      if (hasMultiCoincidence)
196 ////        notifyMultiConstraints();
197 ////    }
198     myConstraints[theConstraint] = aConstraint;
199   }
200   else
201     myConstraints[theConstraint]->update();
202
203 ////  // Fix base features for fillet
204 ////  if (isNewConstraint && theConstraint->getKind() == SketchPlugin_ConstraintFillet::ID()) {
205 ////    std::list<AttributePtr> anAttrList =
206 ////        theConstraint->data()->attributes(ModelAPI_AttributeRefAttr::typeId());
207 ////    std::list<AttributePtr>::iterator anAttrIter = anAttrList.begin();
208 ////    for (; anAttrIter != anAttrList.end(); anAttrIter++) {
209 ////      AttributeRefAttrPtr aRefAttr =
210 ////          std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(*anAttrIter);
211 ////      if (!aRefAttr || !aRefAttr->isObject())
212 ////        continue;
213 ////      FeaturePtr aFeature = ModelAPI_Feature::feature(aRefAttr->object());
214 ////      SolverConstraintPtr aConstraint = aBuilder->createRigidConstraint(aFeature);
215 ////      if (!aConstraint)
216 ////        continue;
217 ////      aConstraint->setGroup(this);
218 ////      aConstraint->setStorage(myStorage);
219 ////      setTemporary(aConstraint);
220 ////    }
221 ////  }
222
223   // Fix mirror line
224   if (theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID()) {
225     AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
226         theConstraint->attribute(SketchPlugin_ConstraintMirror::ENTITY_A()));
227     if (aRefAttr && aRefAttr->isObject()) {
228       std::shared_ptr<SketchPlugin_Feature> aFeature =
229           std::dynamic_pointer_cast<SketchPlugin_Feature>(
230           ModelAPI_Feature::feature(aRefAttr->object()));
231       if (aFeature) {
232         SolverConstraintPtr aConstraint = aBuilder->createFixedConstraint(aFeature);
233         if (aConstraint) {
234           aConstraint->process(myStorage, getId(), getWorkplaneId());
235           setTemporary(aConstraint);
236         }
237       }
238     }
239   }
240
241 ////  // Check the attributes of constraint are given by parametric expression
242 ////  std::list<AttributePtr> anAttributes =
243 ////      theConstraint->data()->attributes(ModelAPI_AttributeRefAttr::typeId());
244 ////  std::list<AttributePtr>::iterator anAttrIt = anAttributes.begin();
245 ////  for (; anAttrIt != anAttributes.end(); ++anAttrIt) {
246 ////    AttributeRefAttrPtr aRefAttr =
247 ////        std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(*anAttrIt);
248 ////    if (!aRefAttr)
249 ////      continue;
250 ////
251 ////    std::shared_ptr<GeomDataAPI_Point2D> aPoint;
252 ////    if (aRefAttr->isObject()) {
253 ////      FeaturePtr aFeat = ModelAPI_Feature::feature(aRefAttr->object());
254 ////      if (aFeat->getKind() != SketchPlugin_Point::ID())
255 ////        continue;
256 ////      aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
257 ////          aFeat->attribute(SketchPlugin_Point::COORD_ID()));
258 ////    } else
259 ////      aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aRefAttr->attr());
260 ////
261 ////    if (!aPoint || (aPoint->textX().empty() && aPoint->textY().empty()))
262 ////      continue;
263 ////
264 ////    std::map<AttributePtr, SolverConstraintPtr>::iterator aFound =
265 ////        myParametricConstraints.find(aPoint);
266 ////    if (aFound == myParametricConstraints.end()) {
267 ////      SolverConstraintPtr aConstraint = aBuilder->createParametricConstraint(aPoint);
268 ////      if (!aConstraint)
269 ////        continue;
270 ////      aConstraint->setGroup(this);
271 ////      aConstraint->setStorage(myStorage);
272 ////      myParametricConstraints[aPoint] = aConstraint;
273 ////    } else
274 ////      aFound->second->update();
275 ////  }
276
277   return true;
278 }
279
280
281 void SketchSolver_Group::updateConstraints()
282 {
283   std::set<SolverConstraintPtr> aPostponed; // postponed constraints Multi-Rotation and Multi-Translation
284
285   ConstraintConstraintMap::iterator anIt = myConstraints.begin();
286   for (; anIt != myConstraints.end(); ++anIt) {
287     if (myChangedConstraints.find(anIt->first) == myChangedConstraints.end())
288       continue;
289     if (anIt->first->getKind() == SketchPlugin_MultiRotation::ID() ||
290         anIt->first->getKind() == SketchPlugin_MultiTranslation::ID())
291       aPostponed.insert(anIt->second);
292     else
293       anIt->second->update();
294   }
295
296   // Update postponed constraints
297   std::set<SolverConstraintPtr>::iterator aSCIter = aPostponed.begin();
298   for (; aSCIter != aPostponed.end(); ++aSCIter)
299     (*aSCIter)->update();
300
301   myChangedConstraints.clear();
302 }
303
304 bool SketchSolver_Group::updateFeature(std::shared_ptr<SketchPlugin_Feature> theFeature)
305 {
306   if (!checkFeatureValidity(theFeature))
307     return false;
308
309   bool isUpdated = myStorage->update(theFeature);
310
311 ////  // Search attributes of the feature in the set of parametric constraints and update them
312 ////  std::list<AttributePtr> anAttrList =
313 ////      theFeature->data()->attributes(GeomDataAPI_Point2D::typeId());
314 ////  std::list<AttributePtr>::iterator anAttrIt = anAttrList.begin();
315 ////  for (; anAttrIt != anAttrList.end(); ++anAttrIt) {
316 ////    std::map<AttributePtr, SolverConstraintPtr>::iterator aFound =
317 ////        myParametricConstraints.find(*anAttrIt);
318 ////    if (aFound != myParametricConstraints.end())
319 ////      aFound->second->update();
320 ////    else {
321 ////      std::shared_ptr<GeomDataAPI_Point2D> aPoint =
322 ////          std::dynamic_pointer_cast<GeomDataAPI_Point2D>(*anAttrIt);
323 ////      if (aPoint && (!aPoint->textX().empty() || !aPoint->textY().empty())) {
324 ////        // Create new parametric constraint
325 ////        SolverConstraintPtr aConstraint =
326 ////            SketchSolver_Builder::getInstance()->createParametricConstraint(*anAttrIt);
327 ////        if (!aConstraint)
328 ////          continue;
329 ////        aConstraint->setGroup(this);
330 ////        aConstraint->setStorage(myStorage);
331 ////        myParametricConstraints[*anAttrIt] = aConstraint;
332 ////      }
333 ////    }
334 ////  }
335   return isUpdated;
336 }
337
338 void SketchSolver_Group::moveFeature(std::shared_ptr<SketchPlugin_Feature> theFeature)
339 {
340   BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
341
342   // Firstly, revert changes in the fixed entities
343   myStorage->refresh(true);
344
345   // Secondly, search attributes of the feature in the list of the Multi constraints and update them
346   ConstraintConstraintMap::iterator aCIt = myConstraints.begin();
347   for (; aCIt != myConstraints.end(); ++aCIt) {
348     if ((aCIt->second->getType() == CONSTRAINT_MULTI_ROTATION ||
349          aCIt->second->getType() == CONSTRAINT_MULTI_TRANSLATION)
350         && aCIt->second->isUsed(theFeature))
351       std::dynamic_pointer_cast<SketchSolver_ConstraintMulti>(aCIt->second)->update(true);
352   }
353
354   // Then, create temporary rigid constraint
355   SolverConstraintPtr aConstraint = aBuilder->createMovementConstraint(theFeature);
356   if (!aConstraint)
357     return;
358   aConstraint->process(myStorage, getId(), getWorkplaneId());
359   if (aConstraint->error().empty())
360     setTemporary(aConstraint);
361 }
362
363 // ============================================================================
364 //  Function: addWorkplane
365 //  Class:    SketchSolver_Group
366 //  Purpose:  create workplane for the group
367 // ============================================================================
368 bool SketchSolver_Group::addWorkplane(CompositeFeaturePtr theSketch)
369 {
370   if (myWorkplaneID != EID_UNKNOWN || theSketch->getKind() != SketchPlugin_Sketch::ID())
371     return false;  // the workplane already exists or the function parameter is not Sketch
372
373   mySketch = theSketch;
374   if (!updateWorkplane()) {
375     mySketch = CompositeFeaturePtr();
376     return false;
377   }
378   return true;
379 }
380
381 // ============================================================================
382 //  Function: updateWorkplane
383 //  Class:    SketchSolver_Group
384 //  Purpose:  update parameters of workplane
385 // ============================================================================
386 bool SketchSolver_Group::updateWorkplane()
387 {
388   BuilderPtr aBuilder = SketchSolver_Manager::instance()->builder();
389   if (!myStorage) // Create storage if not exists
390     myStorage = aBuilder->createStorage(getId());
391
392   // sketch should be unchanged, set it out of current group
393   bool isUpdated = myStorage->update(mySketch, GID_OUTOFGROUP);
394   if (isUpdated) {
395     EntityWrapperPtr anEntity = myStorage->entity(mySketch);
396     myWorkplaneID = anEntity->id();
397   }
398   return isUpdated;
399 }
400
401 // ============================================================================
402 //  Function: resolveConstraints
403 //  Class:    SketchSolver_Group
404 //  Purpose:  solve the set of constraints for the current group
405 // ============================================================================
406 bool SketchSolver_Group::resolveConstraints()
407 {
408   if (!myChangedConstraints.empty())
409     updateConstraints();
410
411   bool aResolved = false;
412   bool isGroupEmpty = isEmpty();
413   if (myStorage->isNeedToResolve() && !isGroupEmpty) {
414     if (!mySketchSolver)
415       mySketchSolver = SketchSolver_Manager::instance()->builder()->createSolver();
416
417     mySketchSolver->setGroup(myID);
418     mySketchSolver->calculateFailedConstraints(false);
419     myStorage->initializeSolver(mySketchSolver);
420
421     SketchSolver_SolveStatus aResult = STATUS_OK;
422     try {
423       if (myStorage->hasDuplicatedConstraint())
424         aResult = STATUS_INCONSISTENT;
425       else {
426         // To avoid overconstraint situation, we will remove temporary constraints one-by-one
427         // and try to find the case without overconstraint
428         bool isLastChance = false;
429         size_t aNbTemp = myStorage->nbTemporary();
430         while (true) {
431           aResult = mySketchSolver->solve();
432           if (aResult == STATUS_OK || aResult == STATUS_EMPTYSET || isLastChance)
433             break;
434           if (aNbTemp == 0) {
435             // try to update parameters and resolve once again
436             ConstraintConstraintMap::iterator aConstrIt = myConstraints.begin();
437             for (; aConstrIt != myConstraints.end(); ++aConstrIt)
438               aConstrIt->second->update();
439             isLastChance = true;
440           } else
441             aNbTemp = myStorage->removeTemporary();
442           mySketchSolver->calculateFailedConstraints(true); // something failed => need to find it
443           myStorage->initializeSolver(mySketchSolver);
444         }
445       }
446     } catch (...) {
447 //      Events_Error::send(SketchSolver_Error::SOLVESPACE_CRASH(), this);
448       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::SOLVESPACE_CRASH());
449       if (myPrevSolved) {
450         // the error message should be changed before sending the message
451         sendMessage(EVENT_SOLVER_FAILED);
452         myPrevSolved = false;
453       }
454       return false;
455     }
456     if (aResult == STATUS_OK || aResult == STATUS_EMPTYSET) {  // solution succeeded, store results into correspondent attributes
457       myStorage->refresh();
458 ////      myFeatureStorage->blockEvents(true);
459 ////      // First refresh parametric constraints to satisfy parameters
460 ////      std::map<AttributePtr, SolverConstraintPtr>::iterator aParIter = myParametricConstraints.begin();
461 ////      for (; aParIter != myParametricConstraints.end(); ++aParIter)
462 ////        aParIter->second->refresh();
463 ////      // Update all other constraints
464 ////      ConstraintConstraintMap::iterator aConstrIter = myConstraints.begin();
465 ////      for (; aConstrIter != myConstraints.end(); ++aConstrIter)
466 ////        aConstrIter->second->refresh();
467 ////      myFeatureStorage->blockEvents(false);
468       if (!myPrevSolved) {
469         getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
470         // the error message should be changed before sending the message
471         sendMessage(EVENT_SOLVER_REPAIRED);
472         myPrevSolved = true;
473       }
474     } else if (!myConstraints.empty()) {
475 //      Events_Error::send(SketchSolver_Error::CONSTRAINTS(), this);
476       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::CONSTRAINTS());
477       if (myPrevSolved) {
478         // the error message should be changed before sending the message
479         sendMessage(EVENT_SOLVER_FAILED);
480         myPrevSolved = false;
481       }
482     }
483
484     aResolved = true;
485   } else if (!isGroupEmpty) {
486 ////    myFeatureStorage->blockEvents(true);
487     // Check there are constraints Fixed. If they exist, update parameters by stored values
488     ConstraintConstraintMap::iterator aCIt = myConstraints.begin();
489     for (; aCIt != myConstraints.end(); ++aCIt)
490       if (aCIt->first->getKind() == SketchPlugin_ConstraintRigid::ID()) {
491 ////        aCIt->second->refresh();
492         aResolved = true;
493         break;
494       }
495 ////     myFeatureStorage->blockEvents(false);
496     if (aCIt != myConstraints.end())
497       myStorage->refresh();
498   }
499   removeTemporaryConstraints();
500   myStorage->setNeedToResolve(false);
501   return aResolved;
502 }
503
504 // ============================================================================
505 //  Function: mergeGroups
506 //  Class:    SketchSolver_Group
507 //  Purpose:  append specified group to the current group
508 // ============================================================================
509 void SketchSolver_Group::mergeGroups(const SketchSolver_Group& theGroup)
510 {
511   // If specified group is empty, no need to merge
512   if (theGroup.isEmpty())
513     return;
514
515   std::set<ObjectPtr> aConstraints;
516   ConstraintConstraintMap::const_iterator aConstrIter = theGroup.myConstraints.begin();
517   for (; aConstrIter != theGroup.myConstraints.end(); aConstrIter++)
518     aConstraints.insert(aConstrIter->first);
519
520   std::list<FeaturePtr> aSortedConstraints = selectApplicableFeatures(aConstraints);
521   std::list<FeaturePtr>::iterator aSCIter = aSortedConstraints.begin();
522   for (; aSCIter != aSortedConstraints.end(); ++aSCIter) {
523     ConstraintPtr aConstr = std::dynamic_pointer_cast<SketchPlugin_Constraint>(*aSCIter);
524     if (!aConstr)
525       continue;
526     changeConstraint(aConstr);
527   }
528 }
529
530 // ============================================================================
531 //  Function: splitGroup
532 //  Class:    SketchSolver_Group
533 //  Purpose:  divide the group into several subgroups
534 // ============================================================================
535 void SketchSolver_Group::splitGroup(std::list<SketchSolver_Group*>& theCuts)
536 {
537   // New storage will be used in trimmed way to store the list of constraint interacted together.
538   StoragePtr aNewStorage = SketchSolver_Manager::instance()->builder()->createStorage(getId());
539   std::list<ConstraintWrapperPtr> aDummyVec; // empty vector to avoid creation of solver's constraints
540
541   // Obtain constraints, which should be separated
542   std::list<ConstraintPtr> anUnusedConstraints;
543   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
544   for ( ; aCIter != myConstraints.end(); aCIter++) {
545     if (aNewStorage->isInteract(aCIter->first))
546       aNewStorage->addConstraint(aCIter->first, aDummyVec);
547     else
548       anUnusedConstraints.push_back(aCIter->first);
549   }
550
551   // Check the unused constraints once again, because they may become interacted with new storage since adding constraints
552   std::list<ConstraintPtr>::iterator aUnuseIt = anUnusedConstraints.begin();
553   while (aUnuseIt != anUnusedConstraints.end()) {
554     if (aNewStorage->isInteract(*aUnuseIt)) {
555       aNewStorage->addConstraint(*aUnuseIt, aDummyVec);
556       anUnusedConstraints.erase(aUnuseIt);
557       aUnuseIt = anUnusedConstraints.begin();
558       continue;
559     }
560     aUnuseIt++;
561   }
562
563   std::list<SketchSolver_Group*>::iterator aCutsIter;
564   aUnuseIt = anUnusedConstraints.begin();
565   for ( ; aUnuseIt != anUnusedConstraints.end(); ++aUnuseIt) {
566     // Remove unused constraints
567     removeConstraint(*aUnuseIt);
568     // Try to append constraint to already existent group
569     for (aCutsIter = theCuts.begin(); aCutsIter != theCuts.end(); ++aCutsIter)
570       if ((*aCutsIter)->isInteract(*aUnuseIt)) {
571         (*aCutsIter)->changeConstraint(*aUnuseIt);
572         break;
573       }
574     if (aCutsIter == theCuts.end()) {
575       // Add new group
576       SketchSolver_Group* aGroup = new SketchSolver_Group(mySketch);
577       aGroup->changeConstraint(*aUnuseIt);
578       theCuts.push_back(aGroup);
579     } else {
580       // Find other groups interacting with constraint
581       std::list<SketchSolver_Group*>::iterator aBaseGroupIt = aCutsIter;
582       for (++aCutsIter; aCutsIter != theCuts.end(); ++aCutsIter)
583         if ((*aCutsIter)->isInteract(*aUnuseIt)) {
584           (*aBaseGroupIt)->mergeGroups(**aCutsIter);
585           std::list<SketchSolver_Group*>::iterator aRemoveIt = aCutsIter--;
586           theCuts.erase(aRemoveIt);
587         }
588     }
589   }
590 }
591
592 // ============================================================================
593 //  Function: isConsistent
594 //  Class:    SketchSolver_Group
595 //  Purpose:  search removed entities and constraints
596 // ============================================================================
597 bool SketchSolver_Group::isConsistent()
598 {
599   if (isEmpty()) // no one constraint is initialized yet
600     return true;
601
602   // Check the features and constraint is the storage are valid
603   bool aResult = myStorage->isConsistent();
604   if (aResult) {
605     // additional check of consistency of the Fixed constraint,
606     // because they are not added to the storage
607     ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
608     for (; aCIter != myConstraints.end(); ++aCIter)
609       if (aCIter->first->getKind() == SketchPlugin_ConstraintRigid::ID() &&
610          (!aCIter->first->data() || !aCIter->first->data()->isValid())) {
611         aResult = false;
612         break;
613       }
614   }
615   if (!aResult) {
616     // remove invalid constraints
617     std::set<ConstraintPtr> anInvalidConstraints;
618     ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
619     for (; aCIter != myConstraints.end(); ++aCIter) {
620       if (!aCIter->first->data() || !aCIter->first->data()->isValid())
621         anInvalidConstraints.insert(aCIter->first);
622     }
623     std::set<ConstraintPtr>::const_iterator aRemoveIt = anInvalidConstraints.begin();
624     for (; aRemoveIt != anInvalidConstraints.end(); ++aRemoveIt)
625       removeConstraint(*aRemoveIt);
626     // remove invalid features
627     myStorage->removeInvalidEntities();
628   }
629   return aResult;
630 }
631
632 // ============================================================================
633 //  Function: removeTemporaryConstraints
634 //  Class:    SketchSolver_Group
635 //  Purpose:  remove all transient SLVS_C_WHERE_DRAGGED constraints after
636 //            resolving the set of constraints
637 // ============================================================================
638 void SketchSolver_Group::removeTemporaryConstraints()
639 {
640   std::set<SolverConstraintPtr>::iterator aTmpIt = myTempConstraints.begin();
641   for (; aTmpIt != myTempConstraints.end(); ++aTmpIt)
642     (*aTmpIt)->remove();
643
644   size_t aNbTemp = myStorage->nbTemporary();
645   if (aNbTemp > 0)
646     myStorage->removeTemporary(aNbTemp);
647 ////  // Clean lists of removed entities in the storage
648 ////  std::set<Slvs_hParam> aRemPar;
649 ////  std::set<Slvs_hEntity> aRemEnt;
650 ////  std::set<Slvs_hConstraint> aRemCon;
651 ////  myStorage->getRemoved(aRemPar, aRemEnt, aRemCon);
652
653   if (!myTempConstraints.empty())
654     myStorage->verifyFixed();
655   myStorage->setNeedToResolve(false);
656   myTempConstraints.clear();
657 }
658
659 // ============================================================================
660 //  Function: removeConstraint
661 //  Class:    SketchSolver_Group
662 //  Purpose:  remove constraint and all unused entities
663 // ============================================================================
664 void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
665 {
666   bool isFullyRemoved = true;
667   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
668   for (; aCIter != myConstraints.end(); aCIter++)
669     if (aCIter->first == theConstraint) {
670       if (!aCIter->second->remove()) // the constraint is not fully removed
671         isFullyRemoved = false;
672       break;
673     }
674   if (aCIter == myConstraints.end())
675     return;
676
677 ////  // Remove entities not used by constraints
678 ////  myStorage->removeUnusedEntities();
679
680   if (isFullyRemoved)
681     myConstraints.erase(aCIter);
682   else if (aCIter != myConstraints.end() &&
683            aCIter->first->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
684     // Update multicoincidence
685     std::list<ConstraintPtr> aMultiCoinc;
686     SolverConstraintPtr aCoincidence = aCIter->second;
687     while (aCIter != myConstraints.end()) {
688       if (aCIter->second != aCoincidence) {
689         ++aCIter;
690         continue;
691       }
692       if (aCIter->first != theConstraint)
693         aMultiCoinc.push_back(aCIter->first);
694       aCIter->second->remove();
695       ConstraintConstraintMap::iterator aRemoveIt = aCIter++;
696       myConstraints.erase(aRemoveIt);
697     }
698
699     std::list<ConstraintPtr>::iterator anIt = aMultiCoinc.begin();
700     for (; anIt != aMultiCoinc.end(); ++anIt)
701       changeConstraint(*anIt);
702
703     notifyMultiConstraints();
704   }
705 }
706
707 // ============================================================================
708 //  Function: isComplexConstraint
709 //  Class:    SketchSolver_Group
710 //  Purpose:  verifies the constraint is complex, i.e. it needs another constraints to be created before
711 // ============================================================================
712 bool SketchSolver_Group::isComplexConstraint(FeaturePtr theConstraint)
713 {
714   return theConstraint->getKind() == SketchPlugin_ConstraintFillet::ID() ||
715          theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID() ||
716          theConstraint->getKind() == SketchPlugin_ConstraintTangent::ID();
717 }
718
719 // ============================================================================
720 //  Function: setTemporary
721 //  Class:    SketchSolver_Group
722 //  Purpose:  append given constraint to the group of temporary constraints
723 // ============================================================================
724 void SketchSolver_Group::setTemporary(SolverConstraintPtr theConstraint)
725 {
726   theConstraint->makeTemporary();
727   myTempConstraints.insert(theConstraint);
728 }
729
730
731 // ============================================================================
732 //  Function: checkFeatureValidity
733 //  Class:    SketchSolver_Group
734 //  Purpose:  verifies is the feature valid
735 // ============================================================================
736 bool SketchSolver_Group::checkFeatureValidity(FeaturePtr theFeature)
737 {
738   if (!theFeature || !theFeature->data()->isValid())
739     return true;
740
741   SessionPtr aMgr = ModelAPI_Session::get();
742   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
743   return aFactory->validate(theFeature);
744 }
745
746 // ============================================================================
747 //  Function: notifyMultiConstraints
748 //  Class:    SketchSolver_Group
749 //  Purpose:  Update Multi-Translation/-Rotation constraints due to multi coincidence appears/disappears
750 // ============================================================================
751 void SketchSolver_Group::notifyMultiConstraints()
752 {
753 ////  ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
754 ////  for (; aCIter != myConstraints.end(); ++aCIter) {
755 ////    if (aCIter->first->getKind() == SketchPlugin_MultiRotation::ID() ||
756 ////        aCIter->first->getKind() == SketchPlugin_MultiTranslation::ID()) {
757 ////      std::shared_ptr<SketchSolver_ConstraintMulti> aMulti = 
758 ////          std::dynamic_pointer_cast<SketchSolver_ConstraintMulti>(aCIter->second);
759 ////      aMulti->checkCoincidence();
760 ////    }
761 ////  }
762 }
763
764
765
766
767 // ===========   Auxiliary functions   ========================================
768 static double featureToVal(FeaturePtr theFeature)
769 {
770   if (theFeature->getKind() == SketchPlugin_Sketch::ID())
771     return 0.0; // sketch
772   ConstraintPtr aConstraint = std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
773   if (!aConstraint)
774     return 1.0; // features (arc, circle, line, point)
775
776   const std::string& anID = aConstraint->getKind();
777   if (anID == SketchPlugin_ConstraintCoincidence::ID()) {
778     AttributeRefAttrPtr anAttrA = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
779         aConstraint->attribute(SketchPlugin_Constraint::ENTITY_A()));
780     AttributeRefAttrPtr anAttrB = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
781         aConstraint->attribute(SketchPlugin_Constraint::ENTITY_B()));
782     if (anAttrA && anAttrB && (anAttrA->isObject() || anAttrB->isObject()))
783       return 2.0; // point-on-line and point-on-circle should go before points coincidence constraint
784     return 2.5;
785   }
786   if (anID == SketchPlugin_ConstraintDistance::ID() ||
787       anID == SketchPlugin_ConstraintLength::ID() ||
788       anID == SketchPlugin_ConstraintRadius::ID())
789     return 3.0;
790   if (anID == SketchPlugin_ConstraintAngle::ID())
791     return 3.5;
792   if (anID == SketchPlugin_ConstraintHorizontal::ID() ||
793       anID == SketchPlugin_ConstraintVertical::ID() ||
794       anID == SketchPlugin_ConstraintParallel::ID() ||
795       anID == SketchPlugin_ConstraintPerpendicular::ID())
796     return 4.0;
797   if (anID == SketchPlugin_ConstraintEqual::ID())
798     return 5.0;
799   if (anID == SketchPlugin_ConstraintTangent::ID() ||
800       anID == SketchPlugin_ConstraintMirror::ID())
801     return 6.0;
802   if (anID == SketchPlugin_ConstraintRigid::ID())
803     return 7.0;
804   if (anID == SketchPlugin_MultiRotation::ID() ||
805       anID == SketchPlugin_MultiTranslation::ID())
806     return 8.0;
807
808   // all other constraints are placed between Equal and Tangent constraints
809   return 5.5;
810 }
811
812 static bool isLess(FeaturePtr theFeature1, FeaturePtr theFeature2)
813 {
814   return featureToVal(theFeature1) < featureToVal(theFeature2);
815 }
816
817 std::list<FeaturePtr> SketchSolver_Group::selectApplicableFeatures(const std::set<ObjectPtr>& theObjects)
818 {
819   std::list<FeaturePtr> aResult;
820   std::list<FeaturePtr>::iterator aResIt;
821
822   std::set<ObjectPtr>::const_iterator anObjIter = theObjects.begin();
823   for (; anObjIter != theObjects.end(); ++anObjIter) {
824     // Operate sketch itself and SketchPlugin features only.
825     // Also, the Fillet need to be skipped, because there are several separated constraints composing it.
826     FeaturePtr aFeature = std::dynamic_pointer_cast<ModelAPI_Feature>(*anObjIter);
827     if (!aFeature)
828       continue;
829     std::shared_ptr<SketchPlugin_Feature> aSketchFeature = 
830         std::dynamic_pointer_cast<SketchPlugin_Feature>(aFeature);
831     if ((aFeature->getKind() != SketchPlugin_Sketch::ID() && !aSketchFeature) ||
832         aFeature->getKind() == SketchPlugin_ConstraintFillet::ID())
833       continue;
834
835     // Find the place where to insert a feature
836     for (aResIt = aResult.begin(); aResIt != aResult.end(); ++aResIt)
837       if (isLess(aFeature, *aResIt))
838         break;
839     aResult.insert(aResIt, aFeature);
840   }
841
842   return aResult;
843 }
844