Salome HOME
Issue #901 - It is possible to define empty name for parameter
[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 void SketchSolver_Group::updateConstraints()
289 {
290   std::set<SolverConstraintPtr> aPostponed; // postponed constraints Multi-Rotation and Multi-Translation
291
292   ConstraintConstraintMap::iterator anIt = myConstraints.begin();
293   for (; anIt != myConstraints.end(); ++anIt) {
294     if (myChangedConstraints.find(anIt->first) == myChangedConstraints.end())
295       continue;
296     if (anIt->first->getKind() == SketchPlugin_MultiRotation::ID() ||
297         anIt->first->getKind() == SketchPlugin_MultiTranslation::ID())
298       aPostponed.insert(anIt->second);
299     else
300       anIt->second->update();
301   }
302
303   // Update postponed constraints
304   std::set<SolverConstraintPtr>::iterator aSCIter = aPostponed.begin();
305   for (; aSCIter != aPostponed.end(); ++aSCIter)
306     (*aSCIter)->update();
307
308   myChangedConstraints.clear();
309 }
310
311 bool SketchSolver_Group::updateFeature(std::shared_ptr<SketchPlugin_Feature> theFeature)
312 {
313   if (!checkFeatureValidity(theFeature))
314     return false;
315
316   std::set<ConstraintPtr> aConstraints =
317       myFeatureStorage->getConstraints(std::dynamic_pointer_cast<ModelAPI_Feature>(theFeature));
318   if (aConstraints.empty())
319     return false;
320   std::set<ConstraintPtr>::iterator aCIter = aConstraints.begin();
321   for (; aCIter != aConstraints.end(); aCIter++) {
322     ConstraintConstraintMap::iterator aSolConIter = myConstraints.find(*aCIter);
323     if (aSolConIter == myConstraints.end() || !aSolConIter->first->data() ||
324         !aSolConIter->first->data()->isValid())
325       continue;
326     myFeatureStorage->changeFeature(theFeature, aSolConIter->first);
327
328     aSolConIter->second->addFeature(theFeature);
329     myChangedConstraints.insert(aSolConIter->first);
330   }
331   return true;
332 }
333
334 void SketchSolver_Group::moveFeature(std::shared_ptr<SketchPlugin_Feature> theFeature)
335 {
336   // Firstly, create temporary rigid constraint
337   SolverConstraintPtr aConstraint =
338       SketchSolver_Builder::getInstance()->createMovementConstraint(theFeature);
339   if (!aConstraint)
340     return;
341   aConstraint->setGroup(this);
342   aConstraint->setStorage(myStorage);
343   if (aConstraint->error().empty())
344     setTemporary(aConstraint);
345   // Secondly, update the feature
346   updateFeature(theFeature);
347 }
348
349 // ============================================================================
350 //  Function: fixFeaturesList
351 //  Class:    SketchSolver_Group
352 //  Purpose:  Apply temporary rigid constraints for the list of features
353 // ============================================================================
354 void SketchSolver_Group::fixFeaturesList(AttributeRefListPtr theList)
355 {
356   std::list<ObjectPtr> aList = theList->list();
357   std::list<ObjectPtr>::iterator anIt = aList.begin();
358   std::list<FeaturePtr> aFeatures;
359   // Sort features, at begining there are features used by Equal constraint
360   for (; anIt != aList.end(); anIt++) {
361     if (!(*anIt))
362       continue;
363     FeaturePtr aFeature = ModelAPI_Feature::feature(*anIt);
364     std::set<ConstraintPtr> aConstraints = myFeatureStorage->getConstraints(aFeature);
365     std::set<ConstraintPtr>::iterator aCIter = aConstraints.begin();
366     for (; aCIter != aConstraints.end(); aCIter++)
367       if ((*aCIter)->getKind() == SketchPlugin_ConstraintEqual::ID())
368         break;
369     if (aCIter != aConstraints.end())
370       aFeatures.push_front(aFeature);
371     else
372       aFeatures.push_back(aFeature);
373   }
374
375   std::list<FeaturePtr>::iterator aFeatIter = aFeatures.begin();
376   for (; aFeatIter != aFeatures.end(); aFeatIter++) {
377     SolverConstraintPtr aConstraint =
378         SketchSolver_Builder::getInstance()->createRigidConstraint(*aFeatIter);
379     if (!aConstraint)
380       continue;
381     aConstraint->setGroup(this);
382     aConstraint->setStorage(myStorage);
383     setTemporary(aConstraint);
384   }
385 }
386
387 // ============================================================================
388 //  Function: addWorkplane
389 //  Class:    SketchSolver_Group
390 //  Purpose:  create workplane for the group
391 // ============================================================================
392 bool SketchSolver_Group::addWorkplane(CompositeFeaturePtr theSketch)
393 {
394   if (myWorkplaneID != SLVS_E_UNKNOWN || theSketch->getKind() != SketchPlugin_Sketch::ID())
395     return false;  // the workplane already exists or the function parameter is not Sketch
396
397   mySketch = theSketch;
398   updateWorkplane();
399   return true;
400 }
401
402 // ============================================================================
403 //  Function: updateWorkplane
404 //  Class:    SketchSolver_Group
405 //  Purpose:  update parameters of workplane
406 // ============================================================================
407 bool SketchSolver_Group::updateWorkplane()
408 {
409   if (!myStorage) // Create storage if not exists
410     myStorage = StoragePtr(new SketchSolver_Storage);
411   SketchSolver_Builder* aBuilder = SketchSolver_Builder::getInstance();
412
413   std::vector<Slvs_Entity> anEntities;
414   std::vector<Slvs_Param> aParams;
415   if (!aBuilder->createWorkplane(mySketch, anEntities, aParams))
416     return false;
417
418   if (myWorkplaneID == SLVS_E_UNKNOWN) {
419     myWorkplaneID = anEntities.back().h;
420     // Add new workplane elements
421     std::vector<Slvs_Param>::iterator aParIter = aParams.begin();
422     for (; aParIter != aParams.end(); aParIter++) {
423       aParIter->h = SLVS_E_UNKNOWN; // the ID should be generated by storage
424       aParIter->group = myID;
425       aParIter->h = myStorage->addParameter(*aParIter);
426     }
427     std::vector<Slvs_Entity>::iterator anEntIter = anEntities.begin();
428     for (; anEntIter != anEntities.end(); anEntIter++) {
429       anEntIter->h = SLVS_E_UNKNOWN; // the ID should be generated by storage
430       anEntIter->group = myID;
431       anEntIter->wrkpl = myWorkplaneID;
432       for (int i = 0; i < 4; i++)
433         if (anEntIter->param[i] != SLVS_E_UNKNOWN)
434           anEntIter->param[i] = aParams[anEntIter->param[i]-1].h;
435       for (int i = 0; i < 4; i++)
436         if (anEntIter->point[i] != SLVS_E_UNKNOWN)
437           anEntIter->point[i] = anEntities[anEntIter->point[i]-1].h;
438       anEntIter->h = myStorage->addEntity(*anEntIter);
439     }
440   } else {
441     // Update existent workplane
442     const Slvs_Entity& aWP = myStorage->getEntity(myWorkplaneID);
443     const Slvs_Entity& anOrigin = myStorage->getEntity(aWP.point[0]);
444     const Slvs_Entity& aNormal = myStorage->getEntity(aWP.normal);
445     // Get parameters and update them
446     Slvs_hParam aWPParams[7] = {
447         anOrigin.param[0], anOrigin.param[1], anOrigin.param[2],
448         aNormal.param[0], aNormal.param[1], aNormal.param[2], aNormal.param[3]
449       };
450     std::vector<Slvs_Param>::iterator aParIter = aParams.begin();
451     for (int i = 0; aParIter != aParams.end(); aParIter++, i++) {
452       Slvs_Param aParam = myStorage->getParameter(aWPParams[i]);
453       aParam.val = aParIter->val;
454       myStorage->updateParameter(aParam);
455     }
456   }
457   return myWorkplaneID > 0;
458 }
459
460 // ============================================================================
461 //  Function: resolveConstraints
462 //  Class:    SketchSolver_Group
463 //  Purpose:  solve the set of constraints for the current group
464 // ============================================================================
465 bool SketchSolver_Group::resolveConstraints()
466 {
467   if (!myChangedConstraints.empty())
468     updateConstraints();
469
470   bool aResolved = false;
471   if (myStorage->isNeedToResolve() && !isEmpty()) {
472     myConstrSolver.setGroupID(myID);
473     myStorage->initializeSolver(myConstrSolver);
474
475     int aResult = SLVS_RESULT_OKAY;
476     try {
477       if (myStorage->hasDuplicatedConstraint())
478         aResult = SLVS_RESULT_INCONSISTENT;
479       else {
480         // To avoid overconstraint situation, we will remove temporary constraints one-by-one
481         // and try to find the case without overconstraint
482         bool isLastChance = false;
483         int aNbTemp = myStorage->numberTemporary();
484         while (true) {
485           aResult = myConstrSolver.solve();
486           if (aResult == SLVS_RESULT_OKAY || isLastChance)
487             break;
488           if (aNbTemp <= 0) {
489             // try to update parameters and resolve once again
490             ConstraintConstraintMap::iterator aConstrIt = myConstraints.begin();
491             for (; aConstrIt != myConstraints.end(); ++aConstrIt)
492               aConstrIt->second->update();
493             isLastChance = true;
494           } else
495             aNbTemp = myStorage->deleteTemporaryConstraint();
496           myStorage->initializeSolver(myConstrSolver);
497         }
498       }
499     } catch (...) {
500 //      Events_Error::send(SketchSolver_Error::SOLVESPACE_CRASH(), this);
501       if (myPrevSolved) {
502         sendMessage(EVENT_SOLVER_FAILED);
503         myPrevSolved = false;
504       }
505       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::SOLVESPACE_CRASH());
506       return false;
507     }
508     if (aResult == SLVS_RESULT_OKAY) {  // solution succeeded, store results into correspondent attributes
509       myFeatureStorage->blockEvents(true);
510       ConstraintConstraintMap::iterator aConstrIter = myConstraints.begin();
511       for (; aConstrIter != myConstraints.end(); aConstrIter++)
512         aConstrIter->second->refresh();
513       myFeatureStorage->blockEvents(false);
514       if (!myPrevSolved) {
515         sendMessage(EVENT_SOLVER_REPAIRED);
516         myPrevSolved = true;
517       }
518       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue("");
519     } else if (!myConstraints.empty()) {
520 //      Events_Error::send(SketchSolver_Error::CONSTRAINTS(), this);
521       if (myPrevSolved) {
522         sendMessage(EVENT_SOLVER_FAILED);
523         myPrevSolved = false;
524       }
525       getWorkplane()->string(SketchPlugin_Sketch::SOLVER_ERROR())->setValue(SketchSolver_Error::CONSTRAINTS());
526     }
527
528     aResolved = true;
529   }
530   removeTemporaryConstraints();
531   myStorage->setNeedToResolve(false);
532   return aResolved;
533 }
534
535 // ============================================================================
536 //  Function: mergeGroups
537 //  Class:    SketchSolver_Group
538 //  Purpose:  append specified group to the current group
539 // ============================================================================
540 void SketchSolver_Group::mergeGroups(const SketchSolver_Group& theGroup)
541 {
542   // If specified group is empty, no need to merge
543   if (theGroup.isEmpty())
544     return;
545   if (!myFeatureStorage)
546     myFeatureStorage = FeatureStoragePtr(new SketchSolver_FeatureStorage);
547
548   std::vector<ConstraintPtr> aComplexConstraints;
549   ConstraintConstraintMap::const_iterator aConstrIter = theGroup.myConstraints.begin();
550   // append simple constraints
551   for (; aConstrIter != theGroup.myConstraints.end(); aConstrIter++)
552     if (isComplexConstraint(aConstrIter->first))
553       aComplexConstraints.push_back(aConstrIter->first);
554     else
555       changeConstraint(aConstrIter->first);
556   // append complex constraints
557   std::vector<ConstraintPtr>::iterator aComplexIter = aComplexConstraints.begin();
558   for (; aComplexIter != aComplexConstraints.end(); aComplexIter++)
559       changeConstraint(*aComplexIter);
560 }
561
562 // ============================================================================
563 //  Function: splitGroup
564 //  Class:    SketchSolver_Group
565 //  Purpose:  divide the group into several subgroups
566 // ============================================================================
567 void SketchSolver_Group::splitGroup(std::vector<SketchSolver_Group*>& theCuts)
568 {
569   // Obtain constraints, which should be separated
570   FeatureStoragePtr aNewFeatStorage(new SketchSolver_FeatureStorage);
571   std::vector<ConstraintPtr> anUnusedConstraints;
572   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
573   for ( ; aCIter != myConstraints.end(); aCIter++) {
574     std::list<ConstraintPtr> aBaseConstraints = aCIter->second->constraints();
575     std::list<ConstraintPtr>::iterator anIter = aBaseConstraints.begin();
576     for (; anIter != aBaseConstraints.end(); anIter++)
577       if (aNewFeatStorage->isInteract(*anIter)) {
578         aNewFeatStorage->changeConstraint(*anIter);
579       } else
580         anUnusedConstraints.push_back(*anIter);
581   }
582
583   // Check the unused constraints once again, because they may become interacted with new storage since adding constraints
584   std::vector<ConstraintPtr>::iterator aUnuseIt = anUnusedConstraints.begin();
585   while (aUnuseIt != anUnusedConstraints.end()) {
586     if (aNewFeatStorage->isInteract(*aUnuseIt)) {
587       size_t aShift = aUnuseIt - anUnusedConstraints.begin();
588       anUnusedConstraints.erase(aUnuseIt);
589       aUnuseIt = anUnusedConstraints.begin() + aShift;
590       continue;
591     }
592     aUnuseIt++;
593   }
594
595   std::vector<SketchSolver_Group*>::iterator aCutsIter;
596   aUnuseIt = anUnusedConstraints.begin();
597   for ( ; aUnuseIt != anUnusedConstraints.end(); aUnuseIt++) {
598     // Remove unused constraints
599     removeConstraint(*aUnuseIt);
600     // Try to append constraint to already existent group
601     for (aCutsIter = theCuts.begin(); aCutsIter != theCuts.end(); aCutsIter++)
602       if ((*aCutsIter)->isInteract(*aUnuseIt)) {
603         (*aCutsIter)->changeConstraint(*aUnuseIt);
604         break;
605       }
606     if (aCutsIter == theCuts.end()) {
607       // Add new group
608       SketchSolver_Group* aGroup = new SketchSolver_Group(mySketch);
609       aGroup->changeConstraint(*aUnuseIt);
610       theCuts.push_back(aGroup);
611     }
612   }
613 }
614
615 // ============================================================================
616 //  Function: isConsistent
617 //  Class:    SketchSolver_Group
618 //  Purpose:  search removed entities and constraints
619 // ============================================================================
620 bool SketchSolver_Group::isConsistent()
621 {
622   if (!myFeatureStorage) // no one constraint is initialized yet
623     return true;
624
625   bool aResult = myFeatureStorage->isConsistent();
626   if (!aResult) {
627     // remove invalid entities
628     std::set<ConstraintPtr> anInvalidConstraints;
629     ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
630     for (; aCIter != myConstraints.end(); ++aCIter) {
631       if (!aCIter->first->data() || !aCIter->first->data()->isValid())
632         anInvalidConstraints.insert(aCIter->first);
633     }
634     std::set<ConstraintPtr>::const_iterator aRemoveIt = anInvalidConstraints.begin();
635     for (; aRemoveIt != anInvalidConstraints.end(); ++aRemoveIt)
636       removeConstraint(*aRemoveIt);
637   }
638   return aResult;
639 }
640
641 // ============================================================================
642 //  Function: removeTemporaryConstraints
643 //  Class:    SketchSolver_Group
644 //  Purpose:  remove all transient SLVS_C_WHERE_DRAGGED constraints after
645 //            resolving the set of constraints
646 // ============================================================================
647 void SketchSolver_Group::removeTemporaryConstraints()
648 {
649   myTempConstraints.clear();
650   while (myStorage->numberTemporary())
651     myStorage->deleteTemporaryConstraint();
652   // Clean lists of removed entities in the storage
653   std::set<Slvs_hParam> aRemPar;
654   std::set<Slvs_hEntity> aRemEnt;
655   std::set<Slvs_hConstraint> aRemCon;
656   myStorage->getRemoved(aRemPar, aRemEnt, aRemCon);
657   myStorage->setNeedToResolve(false);
658 }
659
660 // ============================================================================
661 //  Function: removeConstraint
662 //  Class:    SketchSolver_Group
663 //  Purpose:  remove constraint and all unused entities
664 // ============================================================================
665 void SketchSolver_Group::removeConstraint(ConstraintPtr theConstraint)
666 {
667   bool isFullyRemoved = true;
668   myFeatureStorage->removeConstraint(theConstraint);
669   ConstraintConstraintMap::iterator aCIter = myConstraints.begin();
670   for (; aCIter != myConstraints.end(); aCIter++)
671     if (aCIter->second->hasConstraint(theConstraint)) {
672       if (!aCIter->second->remove(theConstraint)) // the constraint is not fully removed
673         isFullyRemoved = false;
674       break;
675     }
676   if (aCIter == myConstraints.end())
677     return;
678
679   if (isFullyRemoved)
680     myConstraints.erase(aCIter);
681   else if (aCIter != myConstraints.end() &&
682            aCIter->first->getKind() == SketchPlugin_ConstraintCoincidence::ID()) {
683     // Update multicoincidence
684     std::list<ConstraintPtr> aMultiCoinc;
685     SolverConstraintPtr aCoincidence = aCIter->second;
686     while (aCIter != myConstraints.end()) {
687       if (aCIter->second != aCoincidence) {
688         ++aCIter;
689         continue;
690       }
691       if (aCIter->first != theConstraint)
692         aMultiCoinc.push_back(aCIter->first);
693       aCIter->second->remove(aCIter->first);
694       ConstraintConstraintMap::iterator aRemoveIt = aCIter++;
695       myConstraints.erase(aRemoveIt);
696     }
697
698     std::list<ConstraintPtr>::iterator anIt = aMultiCoinc.begin();
699     for (; anIt != aMultiCoinc.end(); ++anIt)
700       changeConstraint(*anIt);
701   }
702 }
703
704 // ============================================================================
705 //  Function: isComplexConstraint
706 //  Class:    SketchSolver_Group
707 //  Purpose:  verifies the constraint is complex, i.e. it needs another constraints to be created before
708 // ============================================================================
709 bool SketchSolver_Group::isComplexConstraint(FeaturePtr theConstraint)
710 {
711   return theConstraint->getKind() == SketchPlugin_ConstraintFillet::ID() ||
712          theConstraint->getKind() == SketchPlugin_ConstraintMirror::ID() ||
713          theConstraint->getKind() == SketchPlugin_ConstraintTangent::ID();
714 }
715
716 // ============================================================================
717 //  Function: setTemporary
718 //  Class:    SketchSolver_Group
719 //  Purpose:  append given constraint to th group of temporary constraints
720 // ============================================================================
721 void SketchSolver_Group::setTemporary(SolverConstraintPtr theConstraint)
722 {
723   theConstraint->makeTemporary();
724   myTempConstraints.insert(theConstraint);
725 }
726
727
728 // ============================================================================
729 //  Function: checkFeatureValidity
730 //  Class:    SketchSolver_Group
731 //  Purpose:  verifies is the feature valid
732 // ============================================================================
733 bool SketchSolver_Group::checkFeatureValidity(FeaturePtr theFeature)
734 {
735   if (!theFeature || !theFeature->data()->isValid())
736     return true;
737
738   SessionPtr aMgr = ModelAPI_Session::get();
739   ModelAPI_ValidatorsFactory* aFactory = aMgr->validators();
740   return aFactory->validate(theFeature);
741 }
742