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