Salome HOME
589b6a320385e25749b23f36cc8a0eed6f8110f9
[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_Builder.h>
10 #include <SketchSolver_Constraint.h>
11 #include <SketchSolver_ConstraintCoincidence.h>
12 #include <SketchSolver_Error.h>
13
14 #include <Events_Error.h>
15 #include <Events_Loop.h>
16 #include <GeomAPI_XY.h>
17 #include <GeomAPI_Dir2d.h>
18 #include <GeomAPI_Pnt2d.h>
19 #include <GeomDataAPI_Dir.h>
20 #include <GeomDataAPI_Point.h>
21 #include <GeomDataAPI_Point2D.h>
22 #include <ModelAPI_AttributeDouble.h>
23 #include <ModelAPI_AttributeString.h>
24 #include <ModelAPI_Document.h>
25 #include <ModelAPI_Events.h>
26 #include <ModelAPI_ResultConstruction.h>
27 #include <ModelAPI_Session.h>
28 #include <ModelAPI_Validator.h>
29
30 #include <SketchPlugin_Constraint.h>
31 #include <SketchPlugin_ConstraintCoincidence.h>
32 #include <SketchPlugin_ConstraintEqual.h>
33 #include <SketchPlugin_ConstraintFillet.h>
34 #include <SketchPlugin_ConstraintLength.h>
35 #include <SketchPlugin_ConstraintMirror.h>
36 #include <SketchPlugin_ConstraintRigid.h>
37 #include <SketchPlugin_ConstraintTangent.h>
38 #include <SketchPlugin_Feature.h>
39 #include <SketchPlugin_MultiRotation.h>
40 #include <SketchPlugin_MultiTranslation.h>
41 #include <SketchPlugin_Sketch.h>
42
43 #include <SketchPlugin_Arc.h>
44 #include <SketchPlugin_Circle.h>
45 #include <SketchPlugin_Line.h>
46 #include <SketchPlugin_Point.h>
47 #include <SketchPlugin_Sketch.h>
48
49 #include <math.h>
50 #include <assert.h>
51
52
53 /// \brief This class is used to give unique index to the groups
54 class GroupIndexer
55 {
56 public:
57   /// \brief Return vacant index
58   static Slvs_hGroup NEW_GROUP() { return ++myGroupIndex; }
59   /// \brief Removes the index
60   static void REMOVE_GROUP(const Slvs_hGroup& theIndex) {
61     if (myGroupIndex == theIndex)
62       myGroupIndex--;
63   }
64
65 private:
66   GroupIndexer() {};
67
68   static Slvs_hGroup myGroupIndex; ///< index of the group
69 };
70
71 Slvs_hGroup GroupIndexer::myGroupIndex = 0;
72
73
74 static void sendMessage(const char* theMessageName)
75 {
76   std::shared_ptr<Events_Message> aMessage = std::shared_ptr<Events_Message>(
77       new Events_Message(Events_Loop::eventByName(theMessageName)));
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       myPrevSolved(true)
91 {
92   // Initialize workplane
93   myWorkplaneID = SLVS_E_UNKNOWN;
94 #ifndef NDEBUG
95   assert(addWorkplane(theWorkplane));
96 #else
97   addWorkplane(theWorkplane);
98 #endif
99 }
100
101 SketchSolver_Group::~SketchSolver_Group()
102 {
103   myConstraints.clear();
104   GroupIndexer::REMOVE_GROUP(myID);
105 }
106
107 // ============================================================================
108 //  Function: isBaseWorkplane
109 //  Class:    SketchSolver_Group
110 //  Purpose:  verify the group is based on the given workplane
111 // ============================================================================
112 bool SketchSolver_Group::isBaseWorkplane(CompositeFeaturePtr theWorkplane) const
113 {
114   return theWorkplane == mySketch;
115 }
116
117 // ============================================================================
118 //  Function: isInteract
119 //  Class:    SketchSolver_Group
120 //  Purpose:  verify are there any entities in the group used by given constraint
121 // ============================================================================
122 bool SketchSolver_Group::isInteract(
123     std::shared_ptr<SketchPlugin_Feature> theFeature) const
124 {
125   // Empty group interacts with everything
126   if (isEmpty()) return true;
127   ConstraintPtr aConstraint = std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
128   if (aConstraint)
129     return myFeatureStorage->isInteract(aConstraint);
130   return myFeatureStorage->isInteract(std::dynamic_pointer_cast<ModelAPI_Feature>(theFeature));
131 }
132
133 // ============================================================================
134 //  Function: getFeatureId
135 //  Class:    SketchSolver_Group
136 //  Purpose:  Find the identifier of the feature, if it already exists in the group
137 // ============================================================================
138 Slvs_hEntity SketchSolver_Group::getFeatureId(FeaturePtr theFeature) const
139 {
140   Slvs_hEntity aResult = SLVS_E_UNKNOWN;
141   if (!myFeatureStorage)
142     return aResult;
143   std::set<ConstraintPtr> aConstraints = myFeatureStorage->getConstraints(theFeature);
144   if (aConstraints.empty())
145     return aResult;
146   std::set<ConstraintPtr>::iterator aConstrIter = aConstraints.begin();
147   for (; aConstrIter != aConstraints.end(); aConstrIter++) {
148     ConstraintConstraintMap::const_iterator aCIter = myConstraints.find(*aConstrIter);
149     if (aCIter == myConstraints.end())
150       continue;
151     aResult = aCIter->second->getId(theFeature);
152     if (aResult != SLVS_E_UNKNOWN)
153       return aResult;
154   }
155   return SLVS_E_UNKNOWN;
156 }
157
158 // ============================================================================
159 //  Function: getAttributeId
160 //  Class:    SketchSolver_Group
161 //  Purpose:  Find the identifier of the attribute, if it already exists in the group
162 // ============================================================================
163 Slvs_hEntity SketchSolver_Group::getAttributeId(AttributePtr theAttribute) const
164 {
165   Slvs_hEntity aResult = SLVS_E_UNKNOWN;
166   if (!myFeatureStorage)
167     return aResult;
168   std::set<ConstraintPtr> aConstraints = myFeatureStorage->getConstraints(theAttribute);
169   if (aConstraints.empty())
170     return aResult;
171   std::set<ConstraintPtr>::iterator aConstrIter = aConstraints.begin();
172   for (; aConstrIter != aConstraints.end(); aConstrIter++) {
173     ConstraintConstraintMap::const_iterator aCIter = myConstraints.find(*aConstrIter);
174     if (aCIter == myConstraints.end())
175       continue;
176     aResult = aCIter->second->getId(theAttribute);
177     if (aResult != SLVS_E_UNKNOWN)
178       return aResult;
179   }
180   return SLVS_E_UNKNOWN;
181 }
182
183 // ============================================================================
184 //  Function: changeConstraint
185 //  Class:    SketchSolver_Group
186 //  Purpose:  create/update the constraint in the group
187 // ============================================================================
188 bool SketchSolver_Group::changeConstraint(
189     std::shared_ptr<SketchPlugin_Constraint> theConstraint)
190 {
191   // There is no workplane yet, something wrong
192   if (myWorkplaneID == SLVS_E_UNKNOWN)
193     return false;
194
195   if (!theConstraint)
196     return false;
197
198   if (!checkFeatureValidity(theConstraint))
199     return false;
200
201   bool isNewConstraint = myConstraints.find(theConstraint) == myConstraints.end();
202   if (isNewConstraint) {
203     // Add constraint to the current group
204     SolverConstraintPtr aConstraint =
205         SketchSolver_Builder::getInstance()->createConstraint(theConstraint);
206     if (!aConstraint)
207       return false;
208     aConstraint->setGroup(this);
209     aConstraint->setStorage(myStorage);
210     if (!aConstraint->error().empty()) {
211       if (aConstraint->error() == SketchSolver_Error::NOT_INITIALIZED())
212         return false; // some attribute are not initialized yet, don't show message
213       Events_Error::send(aConstraint->error(), this);
214     }
215
216     // Additional verification of coincidence of several points
217     if (theConstraint->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
218       ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
219       for (; aCIter != myConstraints.end(); aCIter++) {
220         std::shared_ptr<SketchSolver_ConstraintCoincidence> aCoincidence =
221           std::dynamic_pointer_cast<SketchSolver_ConstraintCoincidence>(aCIter->second);
222         if (!aCoincidence)
223           continue;
224         std::shared_ptr<SketchSolver_ConstraintCoincidence> aCoinc2 =
225           std::dynamic_pointer_cast<SketchSolver_ConstraintCoincidence>(aConstraint);
226         if (aCoincidence != aCoinc2 && aCoincidence->isCoincide(aCoinc2)) {
227           aCoinc2->attach(aCoincidence);
228           // update other coincidences
229           ConstraintConstraintMap::iterator anIt = aCIter;
230           for (++anIt; anIt != myConstraints.end(); ++anIt)
231             if (anIt->second == aCIter->second)
232               anIt->second = aCoinc2;
233           aCIter->second = aCoinc2;
234         }
235       }
236     }
237     myConstraints[theConstraint] = aConstraint;
238   }
239   else
240     myConstraints[theConstraint]->update();
241
242   // Fix base features for fillet
243   if (isNewConstraint && theConstraint->getKind() == SketchPlugin_ConstraintFillet::ID()) {
244     std::list<AttributePtr> anAttrList =
245         theConstraint->data()->attributes(ModelAPI_AttributeRefAttr::typeId());
246     std::list<AttributePtr>::iterator anAttrIter = anAttrList.begin();
247     for (; anAttrIter != anAttrList.end(); anAttrIter++) {
248       AttributeRefAttrPtr aRefAttr =
249           std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(*anAttrIter);
250       if (!aRefAttr || !aRefAttr->isObject())
251         continue;
252       FeaturePtr aFeature = ModelAPI_Feature::feature(aRefAttr->object());
253       SolverConstraintPtr aConstraint =
254           SketchSolver_Builder::getInstance()->createRigidConstraint(aFeature);
255       if (!aConstraint)
256         continue;
257       aConstraint->setGroup(this);
258       aConstraint->setStorage(myStorage);
259       setTemporary(aConstraint);
260     }
261   }
262   // Fix mirror line
263   if (theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID()) {
264     AttributeRefAttrPtr aRefAttr = std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(
265         theConstraint->attribute(SketchPlugin_ConstraintMirror::ENTITY_A()));
266     if (aRefAttr && aRefAttr->isObject()) {
267       FeaturePtr aFeature = ModelAPI_Feature::feature(aRefAttr->object());
268       if (aFeature) {
269         SolverConstraintPtr aConstraint =
270             SketchSolver_Builder::getInstance()->createRigidConstraint(aFeature);
271         if (aConstraint) {
272           aConstraint->setGroup(this);
273           aConstraint->setStorage(myStorage);
274           setTemporary(aConstraint);
275         }
276       }
277     }
278   }
279
280   if (!myFeatureStorage)
281     myFeatureStorage = FeatureStoragePtr(new SketchSolver_FeatureStorage);
282   myFeatureStorage->changeConstraint(theConstraint);
283
284   return true;
285 }
286
287
288 bool SketchSolver_Group::updateFeature(std::shared_ptr<SketchPlugin_Feature> theFeature)
289 {
290   if (!checkFeatureValidity(theFeature))
291     return false;
292
293   std::set<ConstraintPtr> aConstraints =
294       myFeatureStorage->getConstraints(std::dynamic_pointer_cast<ModelAPI_Feature>(theFeature));
295   if (aConstraints.empty())
296     return false;
297   std::set<ConstraintPtr>::iterator aCIter = aConstraints.begin();
298   std::set<SolverConstraintPtr> aPostponed; // postponed constraints Multi-Rotation and Multi-Translation
299   for (; aCIter != aConstraints.end(); aCIter++) {
300     ConstraintConstraintMap::iterator aSolConIter = myConstraints.find(*aCIter);
301     if (aSolConIter == myConstraints.end() || !aSolConIter->first->data() ||
302         !aSolConIter->first->data()->isValid())
303       continue;
304     myFeatureStorage->changeFeature(theFeature, aSolConIter->first);
305
306     if (aSolConIter->first->getKind() == SketchPlugin_MultiRotation::ID() ||
307         aSolConIter->first->getKind() == SketchPlugin_MultiTranslation::ID()) {
308       aPostponed.insert(aSolConIter->second);
309       continue;
310     }
311     aSolConIter->second->addFeature(theFeature);
312     aSolConIter->second->update();
313   }
314
315   // Update postponed constraints
316   std::set<SolverConstraintPtr>::iterator aSCIter = aPostponed.begin();
317   for (; aSCIter != aPostponed.end(); ++aSCIter) {
318     (*aSCIter)->addFeature(theFeature);
319     (*aSCIter)->update();
320   }
321   return true;
322 }
323
324 void SketchSolver_Group::moveFeature(std::shared_ptr<SketchPlugin_Feature> theFeature)
325 {
326   // Firstly, create temporary rigid constraint
327   SolverConstraintPtr aConstraint =
328       SketchSolver_Builder::getInstance()->createMovementConstraint(theFeature);
329   if (!aConstraint)
330     return;
331   aConstraint->setGroup(this);
332   aConstraint->setStorage(myStorage);
333   if (aConstraint->error().empty())
334     setTemporary(aConstraint);
335   // Secondly, update the feature
336   updateFeature(theFeature);
337 }
338
339 // ============================================================================
340 //  Function: fixFeaturesList
341 //  Class:    SketchSolver_Group
342 //  Purpose:  Apply temporary rigid constraints for the list of features
343 // ============================================================================
344 void SketchSolver_Group::fixFeaturesList(AttributeRefListPtr theList)
345 {
346   std::list<ObjectPtr> aList = theList->list();
347   std::list<ObjectPtr>::iterator anIt = aList.begin();
348   std::list<FeaturePtr> aFeatures;
349   // Sort features, at begining there are features used by Equal constraint
350   for (; anIt != aList.end(); anIt++) {
351     if (!(*anIt))
352       continue;
353     FeaturePtr aFeature = ModelAPI_Feature::feature(*anIt);
354     std::set<ConstraintPtr> aConstraints = myFeatureStorage->getConstraints(aFeature);
355     std::set<ConstraintPtr>::iterator aCIter = aConstraints.begin();
356     for (; aCIter != aConstraints.end(); aCIter++)
357       if ((*aCIter)->getKind() == SketchPlugin_ConstraintEqual::ID())
358         break;
359     if (aCIter != aConstraints.end())
360       aFeatures.push_front(aFeature);
361     else
362       aFeatures.push_back(aFeature);
363   }
364
365   std::list<FeaturePtr>::iterator aFeatIter = aFeatures.begin();
366   for (; aFeatIter != aFeatures.end(); aFeatIter++) {
367     SolverConstraintPtr aConstraint =
368         SketchSolver_Builder::getInstance()->createRigidConstraint(*aFeatIter);
369     if (!aConstraint)
370       continue;
371     aConstraint->setGroup(this);
372     aConstraint->setStorage(myStorage);
373     setTemporary(aConstraint);
374   }
375 }
376
377 // ============================================================================
378 //  Function: addWorkplane
379 //  Class:    SketchSolver_Group
380 //  Purpose:  create workplane for the group
381 // ============================================================================
382 bool SketchSolver_Group::addWorkplane(CompositeFeaturePtr theSketch)
383 {
384   if (myWorkplaneID != SLVS_E_UNKNOWN || theSketch->getKind() != SketchPlugin_Sketch::ID())
385     return false;  // the workplane already exists or the function parameter is not Sketch
386
387   mySketch = theSketch;
388   updateWorkplane();
389   return true;
390 }
391
392 // ============================================================================
393 //  Function: updateWorkplane
394 //  Class:    SketchSolver_Group
395 //  Purpose:  update parameters of workplane
396 // ============================================================================
397 bool SketchSolver_Group::updateWorkplane()
398 {
399   if (!myStorage) // Create storage if not exists
400     myStorage = StoragePtr(new SketchSolver_Storage);
401   SketchSolver_Builder* aBuilder = SketchSolver_Builder::getInstance();
402
403   std::vector<Slvs_Entity> anEntities;
404   std::vector<Slvs_Param> aParams;
405   if (!aBuilder->createWorkplane(mySketch, anEntities, aParams))
406     return false;
407
408   if (myWorkplaneID == SLVS_E_UNKNOWN) {
409     myWorkplaneID = anEntities.back().h;
410     // Add new workplane elements
411     std::vector<Slvs_Param>::iterator aParIter = aParams.begin();
412     for (; aParIter != aParams.end(); aParIter++) {
413       aParIter->h = SLVS_E_UNKNOWN; // the ID should be generated by storage
414       aParIter->group = myID;
415       aParIter->h = myStorage->addParameter(*aParIter);
416     }
417     std::vector<Slvs_Entity>::iterator anEntIter = anEntities.begin();
418     for (; anEntIter != anEntities.end(); anEntIter++) {
419       anEntIter->h = SLVS_E_UNKNOWN; // the ID should be generated by storage
420       anEntIter->group = myID;
421       anEntIter->wrkpl = myWorkplaneID;
422       for (int i = 0; i < 4; i++)
423         if (anEntIter->param[i] != SLVS_E_UNKNOWN)
424           anEntIter->param[i] = aParams[anEntIter->param[i]-1].h;
425       for (int i = 0; i < 4; i++)
426         if (anEntIter->point[i] != SLVS_E_UNKNOWN)
427           anEntIter->point[i] = anEntities[anEntIter->point[i]-1].h;
428       anEntIter->h = myStorage->addEntity(*anEntIter);
429     }
430   } else {
431     // Update existent workplane
432     const Slvs_Entity& aWP = myStorage->getEntity(myWorkplaneID);
433     const Slvs_Entity& anOrigin = myStorage->getEntity(aWP.point[0]);
434     const Slvs_Entity& aNormal = myStorage->getEntity(aWP.normal);
435     // Get parameters and update them
436     Slvs_hParam aWPParams[7] = {
437         anOrigin.param[0], anOrigin.param[1], anOrigin.param[2],
438         aNormal.param[0], aNormal.param[1], aNormal.param[2], aNormal.param[3]
439       };
440     std::vector<Slvs_Param>::iterator aParIter = aParams.begin();
441     for (int i = 0; aParIter != aParams.end(); aParIter++, i++) {
442       Slvs_Param aParam = myStorage->getParameter(aWPParams[i]);
443       aParam.val = aParIter->val;
444       myStorage->updateParameter(aParam);
445     }
446   }
447   return myWorkplaneID > 0;
448 }
449
450 // ============================================================================
451 //  Function: resolveConstraints
452 //  Class:    SketchSolver_Group
453 //  Purpose:  solve the set of constraints for the current group
454 // ============================================================================
455 bool SketchSolver_Group::resolveConstraints()
456 {
457   bool aResolved = false;
458   if (myStorage->isNeedToResolve() && !isEmpty()) {
459     myConstrSolver.setGroupID(myID);
460     myStorage->initializeSolver(myConstrSolver);
461
462     int aResult = SLVS_RESULT_OKAY;
463     try {
464       if (myStorage->hasDuplicatedConstraint())
465         aResult = SLVS_RESULT_INCONSISTENT;
466       else {
467         // To avoid overconstraint situation, we will remove temporary constraints one-by-one
468         // and try to find the case without overconstraint
469         bool isLastChance = false;
470         int aNbTemp = myStorage->numberTemporary();
471         while (true) {
472           aResult = myConstrSolver.solve();
473           if (aResult == SLVS_RESULT_OKAY || isLastChance)
474             break;
475           if (aNbTemp <= 0) {
476             // try to update parameters and resolve once again
477             ConstraintConstraintMap::iterator aConstrIt = myConstraints.begin();
478             for (; aConstrIt != myConstraints.end(); ++aConstrIt)
479               aConstrIt->second->update();
480             isLastChance = true;
481           } else
482             aNbTemp = myStorage->deleteTemporaryConstraint();
483           myStorage->initializeSolver(myConstrSolver);
484         }
485       }
486     } catch (...) {
487 //      Events_Error::send(SketchSolver_Error::SOLVESPACE_CRASH(), this);
488       if (myPrevSolved) {
489         sendMessage(EVENT_SOLVER_FAILED);
490         myPrevSolved = false;
491       }
492       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::SOLVESPACE_CRASH());
493       return false;
494     }
495     if (aResult == SLVS_RESULT_OKAY) {  // solution succeeded, store results into correspondent attributes
496       myFeatureStorage->blockEvents(true);
497       ConstraintConstraintMap::iterator aConstrIter = myConstraints.begin();
498       for (; aConstrIter != myConstraints.end(); aConstrIter++)
499         aConstrIter->second->refresh();
500       myFeatureStorage->blockEvents(false);
501       if (!myPrevSolved) {
502         sendMessage(EVENT_SOLVER_REPAIRED);
503         myPrevSolved = true;
504       }
505       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
506     } else if (!myConstraints.empty()) {
507 //      Events_Error::send(SketchSolver_Error::CONSTRAINTS(), this);
508       if (myPrevSolved) {
509         sendMessage(EVENT_SOLVER_FAILED);
510         myPrevSolved = false;
511       }
512       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::CONSTRAINTS());
513     }
514
515     aResolved = true;
516   }
517   removeTemporaryConstraints();
518   myStorage->setNeedToResolve(false);
519   return aResolved;
520 }
521
522 // ============================================================================
523 //  Function: mergeGroups
524 //  Class:    SketchSolver_Group
525 //  Purpose:  append specified group to the current group
526 // ============================================================================
527 void SketchSolver_Group::mergeGroups(const SketchSolver_Group& theGroup)
528 {
529   // If specified group is empty, no need to merge
530   if (theGroup.isEmpty())
531     return;
532   if (!myFeatureStorage)
533     myFeatureStorage = FeatureStoragePtr(new SketchSolver_FeatureStorage);
534
535   std::vector<ConstraintPtr> aComplexConstraints;
536   ConstraintConstraintMap::const_iterator aConstrIter = theGroup.myConstraints.begin();
537   // append simple constraints
538   for (; aConstrIter != theGroup.myConstraints.end(); aConstrIter++)
539     if (isComplexConstraint(aConstrIter->first))
540       aComplexConstraints.push_back(aConstrIter->first);
541     else
542       changeConstraint(aConstrIter->first);
543   // append complex constraints
544   std::vector<ConstraintPtr>::iterator aComplexIter = aComplexConstraints.begin();
545   for (; aComplexIter != aComplexConstraints.end(); aComplexIter++)
546       changeConstraint(*aComplexIter);
547 }
548
549 // ============================================================================
550 //  Function: splitGroup
551 //  Class:    SketchSolver_Group
552 //  Purpose:  divide the group into several subgroups
553 // ============================================================================
554 void SketchSolver_Group::splitGroup(std::vector<SketchSolver_Group*>& theCuts)
555 {
556   // Obtain constraints, which should be separated
557   FeatureStoragePtr aNewFeatStorage(new SketchSolver_FeatureStorage);
558   std::vector<ConstraintPtr> anUnusedConstraints;
559   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
560   for ( ; aCIter != myConstraints.end(); aCIter++) {
561     std::list<ConstraintPtr> aBaseConstraints = aCIter->second->constraints();
562     std::list<ConstraintPtr>::iterator anIter = aBaseConstraints.begin();
563     for (; anIter != aBaseConstraints.end(); anIter++)
564       if (aNewFeatStorage->isInteract(*anIter)) {
565         aNewFeatStorage->changeConstraint(*anIter);
566       } else
567         anUnusedConstraints.push_back(*anIter);
568   }
569
570   // Check the unused constraints once again, because they may become interacted with new storage since adding constraints
571   std::vector<ConstraintPtr>::iterator aUnuseIt = anUnusedConstraints.begin();
572   while (aUnuseIt != anUnusedConstraints.end()) {
573     if (aNewFeatStorage->isInteract(*aUnuseIt)) {
574       size_t aShift = aUnuseIt - anUnusedConstraints.begin();
575       anUnusedConstraints.erase(aUnuseIt);
576       aUnuseIt = anUnusedConstraints.begin() + aShift;
577       continue;
578     }
579     aUnuseIt++;
580   }
581
582   std::vector<SketchSolver_Group*>::iterator aCutsIter;
583   aUnuseIt = anUnusedConstraints.begin();
584   for ( ; aUnuseIt != anUnusedConstraints.end(); aUnuseIt++) {
585     // Remove unused constraints
586     removeConstraint(*aUnuseIt);
587     // Try to append constraint to already existent group
588     for (aCutsIter = theCuts.begin(); aCutsIter != theCuts.end(); aCutsIter++)
589       if ((*aCutsIter)->isInteract(*aUnuseIt)) {
590         (*aCutsIter)->changeConstraint(*aUnuseIt);
591         break;
592       }
593     if (aCutsIter == theCuts.end()) {
594       // Add new group
595       SketchSolver_Group* aGroup = new SketchSolver_Group(mySketch);
596       aGroup->changeConstraint(*aUnuseIt);
597       theCuts.push_back(aGroup);
598     }
599   }
600 }
601
602 // ============================================================================
603 //  Function: isConsistent
604 //  Class:    SketchSolver_Group
605 //  Purpose:  search removed entities and constraints
606 // ============================================================================
607 bool SketchSolver_Group::isConsistent()
608 {
609   if (!myFeatureStorage) // no one constraint is initialized yet
610     return true;
611
612   bool aResult = myFeatureStorage->isConsistent();
613   if (!aResult) {
614     // remove invalid entities
615     std::set<ConstraintPtr> anInvalidConstraints;
616     ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
617     for (; aCIter != myConstraints.end(); ++aCIter) {
618       if (!aCIter->first->data() || !aCIter->first->data()->isValid())
619         anInvalidConstraints.insert(aCIter->first);
620     }
621     std::set<ConstraintPtr>::const_iterator aRemoveIt = anInvalidConstraints.begin();
622     for (; aRemoveIt != anInvalidConstraints.end(); ++aRemoveIt)
623       removeConstraint(*aRemoveIt);
624   }
625   return aResult;
626 }
627
628 // ============================================================================
629 //  Function: removeTemporaryConstraints
630 //  Class:    SketchSolver_Group
631 //  Purpose:  remove all transient SLVS_C_WHERE_DRAGGED constraints after
632 //            resolving the set of constraints
633 // ============================================================================
634 void SketchSolver_Group::removeTemporaryConstraints()
635 {
636   myTempConstraints.clear();
637   while (myStorage->numberTemporary())
638     myStorage->deleteTemporaryConstraint();
639   // Clean lists of removed entities in the storage
640   std::set<Slvs_hParam> aRemPar;
641   std::set<Slvs_hEntity> aRemEnt;
642   std::set<Slvs_hConstraint> aRemCon;
643   myStorage->getRemoved(aRemPar, aRemEnt, aRemCon);
644   myStorage->setNeedToResolve(false);
645 }
646
647 // ============================================================================
648 //  Function: removeConstraint
649 //  Class:    SketchSolver_Group
650 //  Purpose:  remove constraint and all unused entities
651 // ============================================================================
652 void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
653 {
654   bool isFullyRemoved = true;
655   myFeatureStorage->removeConstraint(theConstraint);
656   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
657   for (; aCIter != myConstraints.end(); aCIter++)
658     if (aCIter->second->hasConstraint(theConstraint)) {
659       if (!aCIter->second->remove(theConstraint)) // the constraint is not fully removed
660         isFullyRemoved = false;
661       break;
662     }
663   if (aCIter == myConstraints.end())
664     return;
665
666   if (isFullyRemoved)
667     myConstraints.erase(aCIter);
668   else if (aCIter != myConstraints.end() &&
669            aCIter->first->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
670     // Update multicoincidence
671     std::list<ConstraintPtr> aMultiCoinc;
672     SolverConstraintPtr aCoincidence = aCIter->second;
673     while (aCIter != myConstraints.end()) {
674       if (aCIter->second != aCoincidence) {
675         ++aCIter;
676         continue;
677       }
678       if (aCIter->first != theConstraint)
679         aMultiCoinc.push_back(aCIter->first);
680       aCIter->second->remove(aCIter->first);
681       ConstraintConstraintMap::iterator aRemoveIt = aCIter++;
682       myConstraints.erase(aRemoveIt);
683     }
684
685     std::list<ConstraintPtr>::iterator anIt = aMultiCoinc.begin();
686     for (; anIt != aMultiCoinc.end(); ++anIt)
687       changeConstraint(*anIt);
688   }
689 }
690
691 // ============================================================================
692 //  Function: isComplexConstraint
693 //  Class:    SketchSolver_Group
694 //  Purpose:  verifies the constraint is complex, i.e. it needs another constraints to be created before
695 // ============================================================================
696 bool SketchSolver_Group::isComplexConstraint(FeaturePtr theConstraint)
697 {
698   return theConstraint->getKind() == SketchPlugin_ConstraintFillet::ID() ||
699          theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID() ||
700          theConstraint->getKind() == SketchPlugin_ConstraintTangent::ID();
701 }
702
703 // ============================================================================
704 //  Function: setTemporary
705 //  Class:    SketchSolver_Group
706 //  Purpose:  append given constraint to th group of temporary constraints
707 // ============================================================================
708 void SketchSolver_Group::setTemporary(SolverConstraintPtr theConstraint)
709 {
710   theConstraint->makeTemporary();
711   myTempConstraints.insert(theConstraint);
712 }
713
714
715 // ============================================================================
716 //  Function: checkFeatureValidity
717 //  Class:    SketchSolver_Group
718 //  Purpose:  verifies is the feature valid
719 // ============================================================================
720 bool SketchSolver_Group::checkFeatureValidity(FeaturePtr theFeature)
721 {
722   if (!theFeature || !theFeature->data()->isValid())
723     return true;
724
725   SessionPtr aMgr = ModelAPI_Session::get();
726   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
727   return aFactory->validate(theFeature);
728 }
729