Salome HOME
Boost has been removed from code
[modules/shaper.git] / src / SketchSolver / SketchSolver_ConstraintGroup.cpp
1 // File:    SketchSolver_ConstraintGroup.cpp
2 // Created: 27 May 2014
3 // Author:  Artem ZHIDKOV
4
5 #include "SketchSolver_ConstraintGroup.h"
6
7 #include <SketchSolver_Constraint.h>
8
9 #include <Events_Error.h>
10 #include <Events_Loop.h>
11 #include <GeomAPI_XY.h>
12 #include <GeomAPI_Pnt2d.h>
13 #include <GeomDataAPI_Dir.h>
14 #include <GeomDataAPI_Point.h>
15 #include <GeomDataAPI_Point2D.h>
16 #include <ModelAPI_AttributeDouble.h>
17 #include <ModelAPI_AttributeRefList.h>
18 #include <ModelAPI_Document.h>
19 #include <ModelAPI_Events.h>
20 #include <ModelAPI_ResultConstruction.h>
21
22 #include <SketchPlugin_Constraint.h>
23 #include <SketchPlugin_ConstraintLength.h>
24 #include <SketchPlugin_ConstraintCoincidence.h>
25 #include <SketchPlugin_ConstraintRigid.h>
26
27 #include <SketchPlugin_Arc.h>
28 #include <SketchPlugin_Circle.h>
29 #include <SketchPlugin_Line.h>
30 #include <SketchPlugin_Point.h>
31 #include <SketchPlugin_Sketch.h>
32
33 #include <math.h>
34 #include <assert.h>
35
36 /// Tolerance for value of parameters
37 const double tolerance = 1.e-10;
38
39 /*
40  * Collects all sketch solver error' codes
41  * as inline static functions
42  * TODO: Move this class into a separate file
43  */
44 class SketchSolver_Error
45 {
46  public:
47   /// The value parameter for the constraint
48   inline static const std::string& CONSTRAINTS()
49   {
50     static const std::string MY_ERROR_VALUE("Conflicting constraints");
51     return MY_ERROR_VALUE;
52   }
53 };
54
55 /// This value is used to give unique index to the groups
56 static Slvs_hGroup myGroupIndexer = 0;
57
58 /** \brief Search the entity/parameter with specified ID in the list of elements
59  *  \param[in] theEntityID unique ID of the element
60  *  \param[in] theEntities list of elements
61  *  \return position of the found element or -1 if the element is not found
62  */
63 template<typename T>
64 static int Search(const uint32_t& theEntityID, const std::vector<T>& theEntities);
65
66 // ========================================================
67 // =========  SketchSolver_ConstraintGroup  ===============
68 // ========================================================
69
70 SketchSolver_ConstraintGroup::SketchSolver_ConstraintGroup(
71     std::shared_ptr<ModelAPI_CompositeFeature> theWorkplane)
72     : myID(++myGroupIndexer),
73       myParamMaxID(0),
74       myEntityMaxID(0),
75       myConstrMaxID(0),
76       myConstraintMap(),
77       myNeedToSolve(false),
78       myConstrSolver()
79 {
80   myParams.clear();
81   myEntities.clear();
82   myEntOfConstr.clear();
83   myConstraints.clear();
84
85   myTempConstraints.clear();
86   myTempPointWhereDragged.clear();
87   myTempPointWDrgdID = 0;
88
89   // Initialize workplane
90   myWorkplane.h = SLVS_E_UNKNOWN;
91 #ifndef NDEBUG
92   assert(addWorkplane(theWorkplane));
93 #else
94   addWorkplane(theWorkplane);
95 #endif
96 }
97
98 SketchSolver_ConstraintGroup::~SketchSolver_ConstraintGroup()
99 {
100   myParams.clear();
101   myEntities.clear();
102   myEntOfConstr.clear();
103   myConstraints.clear();
104   myConstraintMap.clear();
105   myTempConstraints.clear();
106   myTempPointWhereDragged.clear();
107
108   // If the group with maximal identifier is deleted, decrease the indexer
109   if (myID == myGroupIndexer)
110     myGroupIndexer--;
111 }
112
113 // ============================================================================
114 //  Function: isBaseWorkplane
115 //  Class:    SketchSolver_ConstraintGroup
116 //  Purpose:  verify the group is based on the given workplane
117 // ============================================================================
118 bool SketchSolver_ConstraintGroup::isBaseWorkplane(
119     std::shared_ptr<ModelAPI_CompositeFeature> theWorkplane) const
120 {
121   return theWorkplane == mySketch;
122 }
123
124 // ============================================================================
125 //  Function: isInteract
126 //  Class:    SketchSolver_ConstraintGroup
127 //  Purpose:  verify are there any entities in the group used by given constraint
128 // ============================================================================
129 bool SketchSolver_ConstraintGroup::isInteract(
130     std::shared_ptr<SketchPlugin_Feature> theFeature) const
131 {
132   // Check the group is empty
133   if (isEmpty())
134     return true;
135
136   // Check if the feature is already in the group
137   if (myEntityFeatMap.find(theFeature) != myEntityFeatMap.end())
138     return true;
139   std::shared_ptr<SketchPlugin_Constraint> aConstr =
140       std::dynamic_pointer_cast<SketchPlugin_Constraint>(theFeature);
141   if (aConstr && myConstraintMap.find(aConstr) != myConstraintMap.end())
142     return true;
143
144   // Go through the attributes and verify if some of them already in the group
145   std::list<std::shared_ptr<ModelAPI_Attribute>> 
146       anAttrList = theFeature->data()->attributes(std::string());
147   std::list<std::shared_ptr<ModelAPI_Attribute>>::const_iterator
148       anAttrIter = anAttrList.begin();
149   for ( ; anAttrIter != anAttrList.end(); anAttrIter++) {
150     std::shared_ptr<ModelAPI_AttributeRefAttr> aCAttrRef =
151         std::dynamic_pointer_cast<ModelAPI_AttributeRefAttr>(*anAttrIter);
152     if (!aCAttrRef || !aCAttrRef->isObject()) {
153       std::shared_ptr<ModelAPI_Attribute> anAttr = 
154           aCAttrRef ? aCAttrRef->attr() : *anAttrIter;
155       if (myEntityAttrMap.find(anAttr) != myEntityAttrMap.end())
156         return true;
157     } else {
158       ResultConstructionPtr aRC = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(
159           aCAttrRef->object());
160       if (!aRC)
161         continue;
162       std::shared_ptr<ModelAPI_Document> aDoc = aRC->document();
163       FeaturePtr aFeature = aDoc->feature(aRC);
164       if (myEntityFeatMap.find(aFeature) != myEntityFeatMap.end())
165         return true;
166       // search attributes of a feature to be parameters of constraint
167       std::list<std::shared_ptr<ModelAPI_Attribute> > aFeatAttrList =
168           aFeature->data()->attributes(std::string());
169       std::list<std::shared_ptr<ModelAPI_Attribute> >::const_iterator aFAIter = aFeatAttrList
170           .begin();
171       for (; aFAIter != aFeatAttrList.end(); aFAIter++)
172         if (myEntityAttrMap.find(*aFAIter) != myEntityAttrMap.end())
173           return true;
174     }
175   }
176
177   // Entities did not found
178   return false;
179 }
180
181 // ============================================================================
182 //  Function: checkConstraintConsistence
183 //  Class:    SketchSolver_ConstraintGroup
184 //  Purpose:  verifies and changes parameters of the constraint
185 // ============================================================================
186 void SketchSolver_ConstraintGroup::checkConstraintConsistence(Slvs_Constraint& theConstraint)
187 {
188   if (theConstraint.type == SLVS_C_PT_LINE_DISTANCE) {
189     // Get constraint parameters and check the sign of constraint value
190
191     // point coordinates
192     int aPtPos = Search(theConstraint.ptA, myEntities);
193     int aPtParamPos = Search(myEntities[aPtPos].param[0], myParams);
194     std::shared_ptr<GeomAPI_XY> aPoint(
195         new GeomAPI_XY(myParams[aPtParamPos].val, myParams[aPtParamPos + 1].val));
196
197     // line coordinates
198     int aLnPos = Search(theConstraint.entityA, myEntities);
199     aPtPos = Search(myEntities[aLnPos].point[0], myEntities);
200     aPtParamPos = Search(myEntities[aPtPos].param[0], myParams);
201     std::shared_ptr<GeomAPI_XY> aStart(
202         new GeomAPI_XY(-myParams[aPtParamPos].val, -myParams[aPtParamPos + 1].val));
203     aPtPos = Search(myEntities[aLnPos].point[1], myEntities);
204     aPtParamPos = Search(myEntities[aPtPos].param[0], myParams);
205     std::shared_ptr<GeomAPI_XY> aEnd(
206         new GeomAPI_XY(myParams[aPtParamPos].val, myParams[aPtParamPos + 1].val));
207
208     aEnd = aEnd->added(aStart);
209     aPoint = aPoint->added(aStart);
210     if (aPoint->cross(aEnd) * theConstraint.valA < 0.0)
211       theConstraint.valA *= -1.0;
212   }
213 }
214
215 // ============================================================================
216 //  Function: changeConstraint
217 //  Class:    SketchSolver_ConstraintGroup
218 //  Purpose:  create/update the constraint in the group
219 // ============================================================================
220 bool SketchSolver_ConstraintGroup::changeConstraint(
221     std::shared_ptr<SketchPlugin_Constraint> theConstraint)
222 {
223   // There is no workplane yet, something wrong
224   if (myWorkplane.h == SLVS_E_UNKNOWN)
225     return false;
226
227   if (theConstraint && theConstraint->getKind() == SketchPlugin_ConstraintRigid::ID())
228     return changeRigidConstraint(theConstraint);
229
230   // Search this constraint in the current group to update it
231   ConstraintMap::const_iterator aConstrMapIter = myConstraintMap.find(theConstraint);
232   std::vector<Slvs_Constraint>::iterator aConstrIter;
233   if (aConstrMapIter != myConstraintMap.end()) {
234     int aConstrPos = Search(aConstrMapIter->second.front(), myConstraints);
235     aConstrIter = myConstraints.begin() + aConstrPos;
236   }
237
238   // Get constraint type and verify the constraint parameters are correct
239   SketchSolver_Constraint aConstraint(theConstraint);
240   int aConstrType = aConstraint.getType();
241   if (aConstrType == SLVS_C_UNKNOWN
242       || (aConstrMapIter != myConstraintMap.end() && aConstrIter->type != aConstrType))
243     return false;
244   const std::vector<std::string>& aConstraintAttributes = aConstraint.getAttributes();
245
246   // Create constraint parameters
247   double aDistance = 0.0;  // scalar value of the constraint
248   AttributeDoublePtr aDistAttr = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(
249       theConstraint->data()->attribute(SketchPlugin_Constraint::VALUE()));
250   if (aDistAttr) {
251     aDistance = aDistAttr->value();
252     // Issue #196: checking the positivity of the distance constraint
253     if (aDistance < tolerance &&
254        (aConstrType == SLVS_C_PT_PT_DISTANCE || aConstrType == SLVS_C_PT_LINE_DISTANCE))
255       return false;
256     // SketchPlugin circle defined by its radius, but SolveSpace uses constraint for diameter
257     if (aConstrType == SLVS_C_DIAMETER)
258       aDistance *= 2.0;
259     if (aConstrMapIter != myConstraintMap.end()
260         && fabs(aConstrIter->valA - aDistance) > tolerance) {
261       myNeedToSolve = true;
262       aConstrIter->valA = aDistance;
263     }
264   }
265
266   size_t aNbTmpConstraints = myTempConstraints.size();
267   Slvs_hEntity aConstrEnt[CONSTRAINT_ATTR_SIZE];  // parameters of the constraint
268   for (unsigned int indAttr = 0; indAttr < CONSTRAINT_ATTR_SIZE; indAttr++) {
269     aConstrEnt[indAttr] = SLVS_E_UNKNOWN;
270     std::shared_ptr<ModelAPI_AttributeRefAttr> aConstrAttr = std::dynamic_pointer_cast<
271         ModelAPI_AttributeRefAttr>(
272         theConstraint->data()->attribute(aConstraintAttributes[indAttr]));
273     if (!aConstrAttr)
274       continue;
275
276     // Convert the object of the attribute to the feature
277     FeaturePtr aFeature;
278     if (aConstrAttr->isObject() && aConstrAttr->object()) {
279       ResultConstructionPtr aRC = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(
280           aConstrAttr->object());
281       if (!aRC)
282         continue;
283       std::shared_ptr<ModelAPI_Document> aDoc = aRC->document();
284       aFeature = aDoc->feature(aRC);
285     }
286
287     // For the length constraint the start and end points of the line should be added to the entities list instead of line
288     if (aConstrType == SLVS_C_PT_PT_DISTANCE
289         && theConstraint->getKind().compare(SketchPlugin_ConstraintLength::ID()) == 0) {
290       Slvs_hEntity aLineEnt = changeEntity(aFeature);
291       int aEntPos = Search(aLineEnt, myEntities);
292       aConstrEnt[indAttr++] = myEntities[aEntPos].point[0];
293       aConstrEnt[indAttr++] = myEntities[aEntPos].point[1];
294       while (indAttr < CONSTRAINT_ATTR_SIZE)
295         aConstrEnt[indAttr++] = 0;
296       break;  // there should be no other entities
297     } else if (aConstrAttr->isObject())
298       aConstrEnt[indAttr] = changeEntity(aFeature);
299     else
300       aConstrEnt[indAttr] = changeEntity(aConstrAttr->attr());
301   }
302
303   if (aConstrMapIter == myConstraintMap.end()) { // Add new constraint
304     // Several points may be coincident, it is not necessary to store all constraints between them.
305     // Try to find sequence of coincident points which connects the points of new constraint
306     if (aConstrType == SLVS_C_POINTS_COINCIDENT) {
307       if (aConstrEnt[0] == aConstrEnt[1])  // no need to add self coincidence
308         return false;
309       if (!addCoincidentPoints(aConstrEnt[0], aConstrEnt[1])) {
310         myExtraCoincidence.insert(theConstraint);  // the constraint is stored for further purposes
311         return false;
312       }
313       if (aNbTmpConstraints < myTempConstraints.size()) {
314         // There was added temporary constraint. Check that there is no coincident points which already rigid.
315
316         // Get list of already fixed points
317         std::set<Slvs_hEntity> anAlreadyFixed;
318         std::vector<Slvs_Constraint>::const_iterator aCIter = myConstraints.begin();
319         for (; aCIter != myConstraints.end(); aCIter++)
320           if (aCIter->type == SLVS_C_WHERE_DRAGGED) {
321             std::list<Slvs_hConstraint>::const_iterator aTmpIt = myTempConstraints.begin();
322             for (; aTmpIt != myTempConstraints.end(); aTmpIt++)
323               if (*aTmpIt == aCIter->h)
324                 break;
325             if (aTmpIt == myTempConstraints.end())
326               anAlreadyFixed.insert(aCIter->ptA);
327           }
328
329         std::set<Slvs_hConstraint> aTmpConstrToDelete;
330         std::list<Slvs_hConstraint>::reverse_iterator aTmpIter = myTempConstraints.rbegin();
331         size_t aCurSize = myTempConstraints.size();
332         for (; aCurSize > aNbTmpConstraints && aTmpIter != myTempConstraints.rend();
333             aTmpIter++, aCurSize--) {
334           int aConstrPos = Search(*aTmpIter, myConstraints);
335           std::vector<std::set<Slvs_hEntity> >::const_iterator
336             aCoincIter = myCoincidentPoints.begin();
337           for (; aCoincIter != myCoincidentPoints.end(); aCoincIter++)
338             if (aCoincIter->find(myConstraints[aConstrPos].ptA) != aCoincIter->end()) {
339               std::set<Slvs_hEntity>::const_iterator anIt;
340               for (anIt = aCoincIter->begin(); anIt != aCoincIter->end(); anIt++)
341                 if (anAlreadyFixed.find(*anIt) != anAlreadyFixed.end()) {
342                   aTmpConstrToDelete.insert(*aTmpIter);
343                   break;
344                 }
345               break;
346             }
347         }
348         if (!aTmpConstrToDelete.empty())
349           removeTemporaryConstraints(aTmpConstrToDelete);
350       }
351     }
352
353     // Create SolveSpace constraint structure
354     Slvs_Constraint aConstraint = Slvs_MakeConstraint(++myConstrMaxID, myID, aConstrType,
355                                                       myWorkplane.h, aDistance, aConstrEnt[0],
356                                                       aConstrEnt[1], aConstrEnt[2], aConstrEnt[3]);
357     myConstraints.push_back(aConstraint);
358     myConstraintMap[theConstraint] = std::vector<Slvs_hEntity>(1, aConstraint.h);
359     int aConstrPos = Search(aConstraint.h, myConstraints);
360     aConstrIter = myConstraints.begin() + aConstrPos;
361     myNeedToSolve = true;
362   } else { // Attributes of constraint may be changed => update constraint
363     Slvs_hEntity* aCurrentAttr[] = {&aConstrIter->ptA, &aConstrIter->ptB,
364                                    &aConstrIter->entityA, &aConstrIter->entityB,
365                                    &aConstrIter->entityC, &aConstrIter->entityD};
366     for (unsigned int indAttr = 0; indAttr < CONSTRAINT_ATTR_SIZE; indAttr++) {
367       if (*(aCurrentAttr[indAttr]) != aConstrEnt[indAttr])
368       {
369         *(aCurrentAttr[indAttr]) = aConstrEnt[indAttr];
370         myNeedToSolve = true;
371       }
372     }
373   }
374
375   // Update flags of entities to be used by constraints
376   for (unsigned int indAttr = 0; indAttr < CONSTRAINT_ATTR_SIZE; indAttr++)
377     if (aConstrEnt[indAttr] != 0) {
378       int aPos = Search(aConstrEnt[indAttr], myEntities);
379       myEntOfConstr[aPos] = true;
380       // Sub-entities should be used implcitly
381       Slvs_hEntity* aEntPtr = myEntities[aPos].point;
382       while (*aEntPtr != 0) {
383         aPos = Search(*aEntPtr, myEntities);
384         myEntOfConstr[aPos] = true;
385         aEntPtr++;
386       }
387     }
388
389   checkConstraintConsistence(*aConstrIter);
390   return true;
391 }
392
393 // ============================================================================
394 //  Function: changeRigidConstraint
395 //  Class:    SketchSolver_ConstraintGroup
396 //  Purpose:  create/update the "Rigid" constraint in the group
397 // ============================================================================
398 bool SketchSolver_ConstraintGroup::changeRigidConstraint(
399     std::shared_ptr<SketchPlugin_Constraint> theConstraint)
400 {
401   // Search this constraint in the current group to update it
402   ConstraintMap::const_iterator aConstrMapIter = myConstraintMap.find(theConstraint);
403   std::vector<Slvs_Constraint>::iterator aConstrIter;
404   if (aConstrMapIter != myConstraintMap.end()) {
405     int aConstrPos = Search(aConstrMapIter->second.front(), myConstraints);
406     aConstrIter = myConstraints.begin() + aConstrPos;
407   }
408
409   // Get constraint type and verify the constraint parameters are correct
410   SketchSolver_Constraint aConstraint(theConstraint);
411   int aConstrType = aConstraint.getType();
412   if (aConstrType == SLVS_C_UNKNOWN
413       || (aConstrMapIter != myConstraintMap.end() && aConstrIter->type != aConstrType))
414     return false;
415   const std::vector<std::string>& aConstraintAttributes = aConstraint.getAttributes();
416
417   Slvs_hEntity aConstrEnt = SLVS_E_UNKNOWN;
418   std::shared_ptr<ModelAPI_AttributeRefAttr> aConstrAttr = std::dynamic_pointer_cast<
419       ModelAPI_AttributeRefAttr>(
420       theConstraint->data()->attribute(aConstraintAttributes[0]));
421   if (!aConstrAttr)
422     return false;
423
424   // Convert the object of the attribute to the feature
425   FeaturePtr aFeature;
426   if (aConstrAttr->isObject() && aConstrAttr->object()) {
427     ResultConstructionPtr aRC = std::dynamic_pointer_cast<ModelAPI_ResultConstruction>(
428         aConstrAttr->object());
429     if (!aRC)
430       return false;
431     std::shared_ptr<ModelAPI_Document> aDoc = aRC->document();
432     aFeature = aDoc->feature(aRC);
433   }
434
435   aConstrEnt = aConstrAttr->isObject() ? changeEntity(aFeature) : changeEntity(aConstrAttr->attr());
436
437   if (aConstrMapIter == myConstraintMap.end()) { // Add new constraint
438     // Check the fixed entity is not a point.
439     std::shared_ptr<ModelAPI_AttributeRefAttr> aConstrAttr = std::dynamic_pointer_cast<
440         ModelAPI_AttributeRefAttr>(theConstraint->data()->attribute(aConstraintAttributes[0]));
441     std::shared_ptr<GeomDataAPI_Point> aPoint =
442         std::dynamic_pointer_cast<GeomDataAPI_Point>(aConstrAttr->attr());
443     std::shared_ptr<GeomDataAPI_Point2D> aPoint2D =
444         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(aConstrAttr->attr());
445     if (aPoint || aPoint2D) {
446       // Create SolveSpace constraint structure
447       Slvs_Constraint aConstraint = Slvs_MakeConstraint(
448           ++myConstrMaxID, myID, aConstrType, myWorkplane.h, 0.0,
449           aConstrEnt, SLVS_E_UNKNOWN, SLVS_E_UNKNOWN, SLVS_E_UNKNOWN);
450       myConstraints.push_back(aConstraint);
451       myConstraintMap[theConstraint] = std::vector<Slvs_hEntity>(1, aConstraint.h);
452       int aConstrPos = Search(aConstraint.h, myConstraints);
453       aConstrIter = myConstraints.begin() + aConstrPos;
454       myNeedToSolve = true;
455     } else {
456       myConstraintMap[theConstraint] = std::vector<Slvs_hEntity>();
457
458       // To avoid SolveSpace problems:
459       // * if the circle is rigid, we will fix its center and radius;
460       // * if the arc is rigid, we will fix its start and end points and radius.
461       double aRadius = 0.0;
462       bool isArc = false;
463       bool isCircle = false;
464       if (aFeature) {
465         if (aFeature->getKind() == SketchPlugin_Arc::ID()) {
466           std::shared_ptr<GeomDataAPI_Point2D> aCenter =
467               std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
468               aFeature->data()->attribute(SketchPlugin_Arc::CENTER_ID()));
469           std::shared_ptr<GeomDataAPI_Point2D> aStart =
470               std::dynamic_pointer_cast<GeomDataAPI_Point2D>(
471               aFeature->data()->attribute(SketchPlugin_Arc::START_ID()));
472           aRadius = aStart->pnt()->distance(aCenter->pnt());
473           isArc = true;
474         } else if (aFeature->getKind() == SketchPlugin_Circle::ID()) {
475           aRadius = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(
476               aFeature->data()->attribute(SketchPlugin_Circle::RADIUS_ID()))->value();
477           isCircle = true;
478         }
479       }
480
481       // Get list of already fixed points
482       std::set<Slvs_hEntity> anAlreadyFixed;
483       std::vector<Slvs_Constraint>::const_iterator aCIter = myConstraints.begin();
484       for (; aCIter != myConstraints.end(); aCIter++)
485         if (aCIter->type == SLVS_C_WHERE_DRAGGED)
486           anAlreadyFixed.insert(aCIter->ptA);
487
488       // Create constraints to fix the parameters of the entity
489       int aEntPos = Search(aConstrEnt, myEntities);
490       Slvs_hEntity* aPointsPtr = myEntities[aEntPos].point;
491       if (isArc) aPointsPtr++; // avoid to fix center of arc
492       while (*aPointsPtr != 0) {
493         // Avoid to create additional "Rigid" constraints for coincident points
494         bool isCoincAlreadyFixed = false;
495         if (!anAlreadyFixed.empty()) {
496           if (anAlreadyFixed.find(*aPointsPtr) != anAlreadyFixed.end())
497             isCoincAlreadyFixed = true;
498
499           std::vector<std::set<Slvs_hEntity> >::const_iterator aCoincIter =
500               myCoincidentPoints.begin();
501           for (; !isCoincAlreadyFixed && aCoincIter != myCoincidentPoints.end(); aCoincIter++) {
502             if (aCoincIter->find(*aPointsPtr) == aCoincIter->end())
503               continue;
504             std::set<Slvs_hEntity>::const_iterator anIter = anAlreadyFixed.begin();
505             for (; !isCoincAlreadyFixed && anIter != anAlreadyFixed.end(); anIter++)
506               if (aCoincIter->find(*anIter) != aCoincIter->end())
507                 isCoincAlreadyFixed = true;
508           }
509         }
510
511         if (!isCoincAlreadyFixed) {
512           Slvs_Constraint aConstraint = Slvs_MakeConstraint(
513               ++myConstrMaxID, myID, aConstrType, myWorkplane.h, 0.0,
514               *aPointsPtr, SLVS_E_UNKNOWN, SLVS_E_UNKNOWN, SLVS_E_UNKNOWN);
515           myConstraints.push_back(aConstraint);
516           myConstraintMap[theConstraint].push_back(aConstraint.h);
517         }
518         aPointsPtr++;
519       }
520
521       if (isArc || isCircle) { // add radius constraint
522         Slvs_Constraint aConstraint = Slvs_MakeConstraint(
523             ++myConstrMaxID, myID, SLVS_C_DIAMETER, myWorkplane.h, 2.0 * aRadius,
524             SLVS_E_UNKNOWN, SLVS_E_UNKNOWN, aConstrEnt, SLVS_E_UNKNOWN);
525         myConstraints.push_back(aConstraint);
526         myConstraintMap[theConstraint].push_back(aConstraint.h);
527       }
528
529       // The object is already rigid, so there is no constraints added
530       if (myConstraintMap[theConstraint].empty()) {
531         myConstraintMap.erase(theConstraint);
532         myNeedToSolve = false;
533       }
534       else
535         myNeedToSolve = true;
536     }
537   }
538   return true;
539 }
540
541 // ============================================================================
542 //  Function: changeEntity
543 //  Class:    SketchSolver_ConstraintGroup
544 //  Purpose:  create/update the element affected by any constraint
545 // ============================================================================
546 Slvs_hEntity SketchSolver_ConstraintGroup::changeEntity(
547     std::shared_ptr<ModelAPI_Attribute> theEntity)
548 {
549   // If the entity is already in the group, try to find it
550   std::map<std::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator aEntIter =
551       myEntityAttrMap.find(theEntity);
552   int aEntPos;
553   std::vector<Slvs_Param>::const_iterator aParamIter;  // looks at first parameter of already existent entity or at the end of vector otherwise
554   if (aEntIter == myEntityAttrMap.end())  // no such entity => should be created
555     aParamIter = myParams.end();
556   else {  // the entity already exists
557     aEntPos = Search(aEntIter->second, myEntities);
558     int aParamPos = Search(myEntities[aEntPos].param[0], myParams);
559     aParamIter = myParams.begin() + aParamPos;
560   }
561   const bool isEntExists = (aEntIter != myEntityAttrMap.end());  // defines that the entity already exists
562   const bool isNeedToSolve = myNeedToSolve;
563   myNeedToSolve = false;
564
565   if (isEntExists) {
566     // Verify that the entity is not used by "Rigid" constraint.
567     // If it is used, the object should not move.
568     std::vector<std::set<Slvs_hEntity> >::iterator aCoincIter = myCoincidentPoints.begin();
569     for (; aCoincIter != myCoincidentPoints.end(); aCoincIter++)
570       if (aCoincIter->find(aEntIter->second) != aCoincIter->end())
571         break;
572     std::set<Slvs_hEntity> aCoincident;
573     if (aCoincIter != myCoincidentPoints.end()) {
574       aCoincident = *aCoincIter;
575       aCoincident.erase(aEntIter->second);
576
577       std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
578       for (; aConstrIter != myConstraints.end(); aConstrIter++)
579         if (aConstrIter->type == SLVS_C_WHERE_DRAGGED &&
580             aCoincident.find(aConstrIter->ptA) != aCoincident.end()) {
581           myNeedToSolve = true;
582           return aEntIter->second;
583         }
584     }
585   }
586
587   // Look over supported types of entities
588   Slvs_Entity aNewEntity;
589   aNewEntity.h = SLVS_E_UNKNOWN;
590
591   // Point in 3D
592   std::shared_ptr<GeomDataAPI_Point> aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point>(
593       theEntity);
594   if (aPoint) {
595     Slvs_hParam aX = changeParameter(aPoint->x(), aParamIter);
596     Slvs_hParam aY = changeParameter(aPoint->y(), aParamIter);
597     Slvs_hParam aZ = changeParameter(aPoint->z(), aParamIter);
598     if (!isEntExists) // New entity
599       aNewEntity = Slvs_MakePoint3d(++myEntityMaxID, myID, aX, aY, aZ);
600   } else {
601     // All entities except 3D points are created on workplane. So, if there is no workplane yet, then error
602     if (myWorkplane.h == SLVS_E_UNKNOWN)
603       return SLVS_E_UNKNOWN;
604
605     // Point in 2D
606     std::shared_ptr<GeomDataAPI_Point2D> aPoint2D =
607         std::dynamic_pointer_cast<GeomDataAPI_Point2D>(theEntity);
608     if (aPoint2D) {
609       Slvs_hParam aU = changeParameter(aPoint2D->x(), aParamIter);
610       Slvs_hParam aV = changeParameter(aPoint2D->y(), aParamIter);
611       if (!isEntExists) // New entity
612         aNewEntity = Slvs_MakePoint2d(++myEntityMaxID, myID, myWorkplane.h, aU, aV);
613     } else {
614       // Scalar value (used for the distance entities)
615       AttributeDoublePtr aScalar = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(theEntity);
616       if (aScalar) {
617         Slvs_hParam aValue = changeParameter(aScalar->value(), aParamIter);
618         if (!isEntExists) // New entity
619           aNewEntity = Slvs_MakeDistance(++myEntityMaxID, myID, myWorkplane.h, aValue);
620       }
621     }
622   }
623   /// \todo Other types of entities
624
625   Slvs_hEntity aResult = SLVS_E_UNKNOWN; // Unsupported or wrong entity type
626
627   if (isEntExists) {
628     myNeedToSolve = myNeedToSolve || isNeedToSolve;
629     aResult = aEntIter->second;
630   } else if (aNewEntity.h != SLVS_E_UNKNOWN) {
631     myEntities.push_back(aNewEntity);
632     myEntOfConstr.push_back(false);
633     myEntityAttrMap[theEntity] = aNewEntity.h;
634     aResult = aNewEntity.h;
635   }
636
637   // If the attribute was changed by the user, we need to fix it before solving
638   if (myNeedToSolve && theEntity->isImmutable())
639     addTemporaryConstraintWhereDragged(theEntity, false);
640
641   return aResult;
642 }
643
644 // ============================================================================
645 //  Function: changeEntity
646 //  Class:    SketchSolver_ConstraintGroup
647 //  Purpose:  create/update the element defined by the feature affected by any constraint
648 // ============================================================================
649 Slvs_hEntity SketchSolver_ConstraintGroup::changeEntity(FeaturePtr theEntity)
650 {
651   if (!theEntity->data()->isValid())
652     return SLVS_E_UNKNOWN;
653   // If the entity is already in the group, try to find it
654   std::map<FeaturePtr, Slvs_hEntity>::const_iterator aEntIter = myEntityFeatMap.find(theEntity);
655   // defines that the entity already exists
656   const bool isEntExists = (myEntityFeatMap.find(theEntity) != myEntityFeatMap.end());
657   
658   Slvs_Entity aNewEntity;
659   aNewEntity.h = SLVS_E_UNKNOWN;
660
661   // SketchPlugin features
662   std::shared_ptr<SketchPlugin_Feature> aFeature = std::dynamic_pointer_cast<
663       SketchPlugin_Feature>(theEntity);
664   if (aFeature) {  // Verify the feature by its kind
665     const std::string& aFeatureKind = aFeature->getKind();
666     AttributePtr anAttribute;
667
668     // Line
669     if (aFeatureKind.compare(SketchPlugin_Line::ID()) == 0) {
670       anAttribute = aFeature->data()->attribute(SketchPlugin_Line::START_ID());
671       if (!anAttribute->isInitialized()) return SLVS_E_UNKNOWN;
672       Slvs_hEntity aStart = changeEntity(anAttribute);
673
674       anAttribute = aFeature->data()->attribute(SketchPlugin_Line::END_ID());
675       if (!anAttribute->isInitialized()) return SLVS_E_UNKNOWN;
676       Slvs_hEntity aEnd = changeEntity(anAttribute);
677
678       if (!isEntExists) // New entity
679         aNewEntity = Slvs_MakeLineSegment(++myEntityMaxID, myID, myWorkplane.h, aStart, aEnd);
680     }
681     // Circle
682     else if (aFeatureKind.compare(SketchPlugin_Circle::ID()) == 0) {
683       anAttribute = aFeature->data()->attribute(SketchPlugin_Circle::CENTER_ID());
684       if (!anAttribute->isInitialized()) return SLVS_E_UNKNOWN;
685       Slvs_hEntity aCenter = changeEntity(anAttribute);
686
687       anAttribute = aFeature->data()->attribute(SketchPlugin_Circle::RADIUS_ID());
688       if (!anAttribute->isInitialized()) return SLVS_E_UNKNOWN;
689       Slvs_hEntity aRadius = changeEntity(anAttribute);
690
691       if (!isEntExists) // New entity
692         aNewEntity = Slvs_MakeCircle(++myEntityMaxID, myID, myWorkplane.h, aCenter,
693                                      myWorkplane.normal, aRadius);
694     }
695     // Arc
696     else if (aFeatureKind.compare(SketchPlugin_Arc::ID()) == 0) {
697       anAttribute = aFeature->data()->attribute(SketchPlugin_Arc::CENTER_ID());
698       if (!anAttribute->isInitialized()) return SLVS_E_UNKNOWN;
699       Slvs_hEntity aCenter = changeEntity(anAttribute);
700
701       anAttribute = aFeature->data()->attribute(SketchPlugin_Arc::START_ID());
702       if (!anAttribute->isInitialized()) return SLVS_E_UNKNOWN;
703       Slvs_hEntity aStart = changeEntity(anAttribute);
704
705       anAttribute = aFeature->data()->attribute(SketchPlugin_Arc::END_ID());
706       if (!anAttribute->isInitialized()) return SLVS_E_UNKNOWN;
707       Slvs_hEntity aEnd = changeEntity(anAttribute);
708
709       if (!isEntExists)
710         aNewEntity = Slvs_MakeArcOfCircle(++myEntityMaxID, myID, myWorkplane.h,
711                                           myWorkplane.normal, aCenter, aStart, aEnd);
712     }
713     // Point (it has low probability to be an attribute of constraint, so it is checked at the end)
714     else if (aFeatureKind.compare(SketchPlugin_Point::ID()) == 0) {
715       anAttribute = aFeature->data()->attribute(SketchPlugin_Point::COORD_ID());
716       if (!anAttribute->isInitialized()) return SLVS_E_UNKNOWN;
717       Slvs_hEntity aPoint = changeEntity(anAttribute);
718
719       if (isEntExists)
720         return aEntIter->second;
721
722       // Both the sketch point and its attribute (coordinates) link to the same SolveSpace point identifier
723       myEntityFeatMap[theEntity] = aPoint;
724       myNeedToSolve = true;
725       return aPoint;
726     }
727   }
728   /// \todo Other types of features
729
730   if (isEntExists)
731     return aEntIter->second;
732
733   if (aNewEntity.h != SLVS_E_UNKNOWN) {
734     myEntities.push_back(aNewEntity);
735     myEntOfConstr.push_back(false);
736     myEntityFeatMap[theEntity] = aNewEntity.h;
737     myNeedToSolve = true;
738     return aNewEntity.h;
739   }
740
741   // Unsupported or wrong entity type
742   return SLVS_E_UNKNOWN;
743 }
744
745 // ============================================================================
746 //  Function: changeNormal
747 //  Class:    SketchSolver_ConstraintGroup
748 //  Purpose:  create/update the normal of workplane
749 // ============================================================================
750 Slvs_hEntity SketchSolver_ConstraintGroup::changeNormal(
751     std::shared_ptr<ModelAPI_Attribute> theDirX, std::shared_ptr<ModelAPI_Attribute> theDirY,
752     std::shared_ptr<ModelAPI_Attribute> theNorm)
753 {
754   std::shared_ptr<GeomDataAPI_Dir> aDirX = std::dynamic_pointer_cast<GeomDataAPI_Dir>(theDirX);
755   std::shared_ptr<GeomDataAPI_Dir> aDirY = std::dynamic_pointer_cast<GeomDataAPI_Dir>(theDirY);
756   if (!aDirX || !aDirY || (fabs(aDirX->x()) + fabs(aDirX->y()) + fabs(aDirX->z()) < tolerance)
757       || (fabs(aDirY->x()) + fabs(aDirY->y()) + fabs(aDirY->z()) < tolerance))
758     return SLVS_E_UNKNOWN;
759
760   // quaternion parameters of normal vector
761   double qw, qx, qy, qz;
762   Slvs_MakeQuaternion(aDirX->x(), aDirX->y(), aDirX->z(), aDirY->x(), aDirY->y(), aDirY->z(), &qw,
763                       &qx, &qy, &qz);
764   double aNormCoord[4] = { qw, qx, qy, qz };
765
766   // Try to find existent normal
767   std::map<std::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator aEntIter =
768       myEntityAttrMap.find(theNorm);
769   std::vector<Slvs_Param>::const_iterator aParamIter;  // looks to the first parameter of already existent entity or to the end of vector otherwise
770   if (aEntIter == myEntityAttrMap.end())  // no such entity => should be created
771     aParamIter = myParams.end();
772   else {  // the entity already exists, update it
773     int aEntPos = Search(aEntIter->second, myEntities);
774     int aParamPos = Search(myEntities[aEntPos].param[0], myParams);
775     aParamIter = myParams.begin() + aParamPos;
776   }
777
778   // Change parameters of the normal
779   Slvs_hParam aNormParams[4];
780   for (int i = 0; i < 4; i++)
781     aNormParams[i] = changeParameter(aNormCoord[i], aParamIter);
782
783   if (aEntIter != myEntityAttrMap.end())  // the entity already exists
784     return aEntIter->second;
785
786   // Create a normal
787   Slvs_Entity aNormal = Slvs_MakeNormal3d(++myEntityMaxID, myID, aNormParams[0], aNormParams[1],
788                                           aNormParams[2], aNormParams[3]);
789   myEntities.push_back(aNormal);
790   myEntOfConstr.push_back(false);
791   myEntityAttrMap[theNorm] = aNormal.h;
792   return aNormal.h;
793 }
794
795 // ============================================================================
796 //  Function: addWorkplane
797 //  Class:    SketchSolver_ConstraintGroup
798 //  Purpose:  create workplane for the group
799 // ============================================================================
800 bool SketchSolver_ConstraintGroup::addWorkplane(std::shared_ptr<ModelAPI_CompositeFeature> theSketch)
801 {
802   if (myWorkplane.h || theSketch->getKind().compare(SketchPlugin_Sketch::ID()) != 0)
803     return false;  // the workplane already exists or the function parameter is not Sketch
804
805   mySketch = theSketch;
806   updateWorkplane();
807   return true;
808 }
809
810 // ============================================================================
811 //  Function: updateWorkplane
812 //  Class:    SketchSolver_ConstraintGroup
813 //  Purpose:  update parameters of workplane
814 // ============================================================================
815 bool SketchSolver_ConstraintGroup::updateWorkplane()
816 {
817   if (!mySketch->data())
818     return false; // case sketch is deleted
819   // Get parameters of workplane
820   std::shared_ptr<ModelAPI_Attribute> aDirX = mySketch->data()->attribute(
821       SketchPlugin_Sketch::DIRX_ID());
822   std::shared_ptr<ModelAPI_Attribute> aDirY = mySketch->data()->attribute(
823       SketchPlugin_Sketch::DIRY_ID());
824   std::shared_ptr<ModelAPI_Attribute> aNorm = mySketch->data()->attribute(
825       SketchPlugin_Sketch::NORM_ID());
826   std::shared_ptr<ModelAPI_Attribute> anOrigin = mySketch->data()->attribute(
827       SketchPlugin_Sketch::ORIGIN_ID());
828   // Transform them into SolveSpace format
829   Slvs_hEntity aNormalWP = changeNormal(aDirX, aDirY, aNorm);
830   if (!aNormalWP)
831     return false;
832   Slvs_hEntity anOriginWP = changeEntity(anOrigin);
833   if (!anOriginWP)
834     return false;
835
836   if (!myWorkplane.h) {
837     // Create workplane
838     myWorkplane = Slvs_MakeWorkplane(++myEntityMaxID, myID, anOriginWP, aNormalWP);
839     // Workplane should be added to the list of entities
840     myEntities.push_back(myWorkplane);
841     myEntOfConstr.push_back(false);
842   }
843   return true;
844 }
845
846 // ============================================================================
847 //  Function: changeParameter
848 //  Class:    SketchSolver_ConstraintGroup
849 //  Purpose:  create/update value of parameter
850 // ============================================================================
851 Slvs_hParam SketchSolver_ConstraintGroup::changeParameter(
852     const double& theParam, std::vector<Slvs_Param>::const_iterator& thePrmIter)
853 {
854   if (thePrmIter != myParams.end()) {  // Parameter should be updated
855     int aParamPos = thePrmIter - myParams.begin();
856     if (fabs(thePrmIter->val - theParam) > tolerance) {
857       myNeedToSolve = true;  // parameter is changed, need to resolve constraints
858       myParams[aParamPos].val = theParam;
859     }
860     thePrmIter++;
861     return myParams[aParamPos].h;
862   }
863
864   // Newly created parameter
865   Slvs_Param aParam = Slvs_MakeParam(++myParamMaxID, myID, theParam);
866   myParams.push_back(aParam);
867   myNeedToSolve = true;
868   // The list of parameters is changed, move iterator to the end of the list to avoid problems
869   thePrmIter = myParams.end();
870   return aParam.h;
871 }
872
873 // ============================================================================
874 //  Function: resolveConstraints
875 //  Class:    SketchSolver_ConstraintGroup
876 //  Purpose:  solve the set of constraints for the current group
877 // ============================================================================
878 bool SketchSolver_ConstraintGroup::resolveConstraints()
879 {
880   if (!myNeedToSolve)
881     return false;
882
883   myConstrSolver.setGroupID(myID);
884   myConstrSolver.setParameters(myParams);
885   myConstrSolver.setEntities(myEntities);
886   myConstrSolver.setConstraints(myConstraints);
887   myConstrSolver.setDraggedParameters(myTempPointWhereDragged);
888
889   int aResult = myConstrSolver.solve();
890   if (aResult == SLVS_RESULT_OKAY) {  // solution succeeded, store results into correspondent attributes
891                                       // Obtain result into the same list of parameters
892     if (!myConstrSolver.getResult(myParams))
893       return true;
894
895     // We should go through the attributes map, because only attributes have valued parameters
896     std::map<std::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator anEntIter =
897         myEntityAttrMap.begin();
898     for (; anEntIter != myEntityAttrMap.end(); anEntIter++)
899       if (updateAttribute(anEntIter->first, anEntIter->second))
900         updateRelatedConstraints(anEntIter->first);
901   } else if (!myConstraints.empty())
902     Events_Error::send(SketchSolver_Error::CONSTRAINTS(), this);
903
904   removeTemporaryConstraints();
905   myNeedToSolve = false;
906   return true;
907 }
908
909 // ============================================================================
910 //  Function: mergeGroups
911 //  Class:    SketchSolver_ConstraintGroup
912 //  Purpose:  append specified group to the current group
913 // ============================================================================
914 void SketchSolver_ConstraintGroup::mergeGroups(const SketchSolver_ConstraintGroup& theGroup)
915 {
916   // If specified group is empty, no need to merge
917   if (theGroup.myConstraintMap.empty())
918     return;
919
920   // Map between old and new indexes of SolveSpace constraints
921   std::map<Slvs_hConstraint, Slvs_hConstraint> aConstrMap;
922
923   // Add all constraints from theGroup to the current group
924   ConstraintMap::const_iterator aConstrIter = theGroup.myConstraintMap.begin();
925   for (; aConstrIter != theGroup.myConstraintMap.end(); aConstrIter++)
926     if (changeConstraint(aConstrIter->first))
927       aConstrMap[aConstrIter->second.back()] = myConstrMaxID;  // the constraint was added => store its ID
928
929   // Add temporary constraints from theGroup
930   std::list<Slvs_hConstraint>::const_iterator aTempConstrIter = theGroup.myTempConstraints.begin();
931   for (; aTempConstrIter != theGroup.myTempConstraints.end(); aTempConstrIter++) {
932     std::map<Slvs_hConstraint, Slvs_hConstraint>::iterator aFind = aConstrMap.find(
933         *aTempConstrIter);
934     if (aFind != aConstrMap.end())
935       myTempConstraints.push_back(aFind->second);
936   }
937
938   if (myTempPointWhereDragged.empty())
939     myTempPointWhereDragged = theGroup.myTempPointWhereDragged;
940   else if (!theGroup.myTempPointWhereDragged.empty()) {  // Need to create additional transient constraint
941     std::map<std::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator aFeatureIter =
942         theGroup.myEntityAttrMap.begin();
943     for (; aFeatureIter != theGroup.myEntityAttrMap.end(); aFeatureIter++)
944       if (aFeatureIter->second == myTempPointWDrgdID) {
945         addTemporaryConstraintWhereDragged(aFeatureIter->first);
946         break;
947       }
948   }
949
950   myNeedToSolve = myNeedToSolve || theGroup.myNeedToSolve;
951 }
952
953 // ============================================================================
954 //  Function: splitGroup
955 //  Class:    SketchSolver_ConstraintGroup
956 //  Purpose:  divide the group into several subgroups
957 // ============================================================================
958 void SketchSolver_ConstraintGroup::splitGroup(std::vector<SketchSolver_ConstraintGroup*>& theCuts)
959 {
960   // Divide constraints and entities into several groups
961   std::vector<std::set<Slvs_hEntity> > aGroupsEntities;
962   std::vector<std::set<Slvs_hConstraint> > aGroupsConstr;
963   int aMaxNbEntities = 0;  // index of the group with maximal nuber of elements (this group will be left in the current)
964   std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
965   for (; aConstrIter != myConstraints.end(); aConstrIter++) {
966     Slvs_hEntity aConstrEnt[] = { aConstrIter->ptA, aConstrIter->ptB, aConstrIter->entityA,
967         aConstrIter->entityB };
968     std::vector<int> anIndexes;
969     // Go through the groupped entities and find even one of entities of current constraint
970     std::vector<std::set<Slvs_hEntity> >::iterator aGrEntIter;
971     for (aGrEntIter = aGroupsEntities.begin(); aGrEntIter != aGroupsEntities.end(); aGrEntIter++) {
972       bool isFound = false;
973       for (int i = 0; i < 4 && !isFound; i++)
974         if (aConstrEnt[i] != 0) {
975           isFound = (aGrEntIter->find(aConstrEnt[i]) != aGrEntIter->end());
976           // Also we need to check sub-entities
977           int aEntPos = Search(aConstrEnt[i], myEntities);
978           if (aEntPos != myEntities.size()) { // MPV: to fix the crash on close
979             Slvs_hEntity* aSub = myEntities[aEntPos].point;
980             for (int j = 0; *aSub != 0 && j < 4 && !isFound; aSub++, j++)
981               isFound = (aGrEntIter->find(*aSub) != aGrEntIter->end());
982           }
983         }
984       if (isFound)
985         anIndexes.push_back(aGrEntIter - aGroupsEntities.begin());
986     }
987     // Add new group if no one is found
988     if (anIndexes.empty()) {
989       std::set<Slvs_hEntity> aNewGrEnt;
990       for (int i = 0; i < 4; i++)
991         if (aConstrEnt[i] != 0) {
992           aNewGrEnt.insert(aConstrEnt[i]);
993           int aEntPos = Search(aConstrEnt[i], myEntities);
994           if (aEntPos != myEntities.size()) { // MPV: to fix the crash on close
995             Slvs_hEntity* aSub = myEntities[aEntPos].point;
996             for (int j = 0; *aSub != 0 && j < 4; aSub++, j++)
997               aNewGrEnt.insert(*aSub);
998           }
999         }
1000       std::set<Slvs_hConstraint> aNewGrConstr;
1001       aNewGrConstr.insert(aConstrIter->h);
1002
1003       aGroupsEntities.push_back(aNewGrEnt);
1004       aGroupsConstr.push_back(aNewGrConstr);
1005       if (aNewGrEnt.size() > aGroupsEntities[aMaxNbEntities].size())
1006         aMaxNbEntities = aGroupsEntities.size() - 1;
1007     } else {  // Add entities indexes into the found group
1008       aGrEntIter = aGroupsEntities.begin() + anIndexes.front();
1009       for (int i = 0; i < 4; i++)
1010         if (aConstrEnt[i] != 0) {
1011           aGrEntIter->insert(aConstrEnt[i]);
1012           int aEntPos = Search(aConstrEnt[i], myEntities);
1013           if (aEntPos != myEntities.size()) { // MPV: to fix the crash on close
1014             Slvs_hEntity* aSub = myEntities[aEntPos].point;
1015             for (int j = 0; *aSub != 0 && j < 4; aSub++, j++)
1016               aGrEntIter->insert(*aSub);
1017           }
1018         }
1019       aGroupsConstr[anIndexes.front()].insert(aConstrIter->h);
1020       if (aGrEntIter->size() > aGroupsEntities[aMaxNbEntities].size())
1021         aMaxNbEntities = aGrEntIter - aGroupsEntities.begin();
1022       if (anIndexes.size() > 1) {  // There are found several connected groups, merge them
1023         std::vector<std::set<Slvs_hEntity> >::iterator aFirstGroup = aGroupsEntities.begin()
1024             + anIndexes.front();
1025         std::vector<std::set<Slvs_hConstraint> >::iterator aFirstConstr = aGroupsConstr.begin()
1026             + anIndexes.front();
1027         std::vector<int>::iterator anInd = anIndexes.begin();
1028         for (++anInd; anInd != anIndexes.end(); anInd++) {
1029           aFirstGroup->insert(aGroupsEntities[*anInd].begin(), aGroupsEntities[*anInd].end());
1030           aFirstConstr->insert(aGroupsConstr[*anInd].begin(), aGroupsConstr[*anInd].end());
1031         }
1032         if (aFirstGroup->size() > aGroupsEntities[aMaxNbEntities].size())
1033           aMaxNbEntities = anIndexes.front();
1034         // Remove merged groups
1035         for (anInd = anIndexes.end() - 1; anInd != anIndexes.begin(); anInd--) {
1036           aGroupsEntities.erase(aGroupsEntities.begin() + (*anInd));
1037           aGroupsConstr.erase(aGroupsConstr.begin() + (*anInd));
1038         }
1039       }
1040     }
1041   }
1042
1043   if (aGroupsEntities.size() <= 1)
1044     return;
1045
1046   // Remove the group with maximum elements as it will be left in the current group
1047   aGroupsEntities.erase(aGroupsEntities.begin() + aMaxNbEntities);
1048   aGroupsConstr.erase(aGroupsConstr.begin() + aMaxNbEntities);
1049
1050   // Add new groups of constraints and divide current group
1051   std::vector<SketchSolver_ConstraintGroup*> aNewGroups;
1052   for (int i = aGroupsEntities.size(); i > 0; i--) {
1053     SketchSolver_ConstraintGroup* aG = new SketchSolver_ConstraintGroup(mySketch);
1054     aNewGroups.push_back(aG);
1055   }
1056   ConstraintMap::const_iterator aConstrMapIter = myConstraintMap.begin();
1057   int aConstrMapPos = 0;  // position of iterator in the map (used to restore iterator after removing constraint)
1058   while (aConstrMapIter != myConstraintMap.end()) {
1059     std::vector<std::set<Slvs_hConstraint> >::const_iterator aGIter = aGroupsConstr.begin();
1060     std::vector<SketchSolver_ConstraintGroup*>::iterator aGroup = aNewGroups.begin();
1061     for (; aGIter != aGroupsConstr.end(); aGIter++, aGroup++)
1062       if (aGIter->find(aConstrMapIter->second.front()) != aGIter->end()) {
1063         (*aGroup)->changeConstraint(aConstrMapIter->first);
1064         removeConstraint(aConstrMapIter->first);
1065         // restore iterator
1066         aConstrMapIter = myConstraintMap.begin();
1067         for (int i = 0; i < aConstrMapPos; i++)
1068           aConstrMapIter++;
1069         break;
1070       }
1071     if (aGIter == aGroupsConstr.end()) {
1072       aConstrMapIter++;
1073       aConstrMapPos++;
1074     }
1075   }
1076
1077   theCuts.insert(theCuts.end(), aNewGroups.begin(), aNewGroups.end());
1078 }
1079
1080 // ============================================================================
1081 //  Function: updateGroup
1082 //  Class:    SketchSolver_ConstraintGroup
1083 //  Purpose:  search removed entities and constraints
1084 // ============================================================================
1085 bool SketchSolver_ConstraintGroup::updateGroup()
1086 {
1087   ConstraintMap::reverse_iterator aConstrIter = myConstraintMap.rbegin();
1088   bool isAllValid = true;
1089   bool isCCRemoved = false;  // indicates that at least one of coincidence constraints was removed
1090   int aConstrIndex = 0;
1091   while (/*isAllValid && */aConstrIter != myConstraintMap.rend()) {
1092     if (!aConstrIter->first->data() || !aConstrIter->first->data()->isValid()) {
1093       if (aConstrIter->first->getKind().compare(SketchPlugin_ConstraintCoincidence::ID()) == 0)
1094         isCCRemoved = true;
1095       removeConstraint(aConstrIter->first);
1096       isAllValid = false;
1097       // Get back the correct position of iterator after the "remove" operation
1098       aConstrIter = myConstraintMap.rbegin();
1099       for (int i = 0; i < aConstrIndex && aConstrIter != myConstraintMap.rend(); i++)
1100         aConstrIter++;
1101     } else {
1102       aConstrIter++;
1103       aConstrIndex++;
1104     }
1105   }
1106
1107   // Check if some entities are invalid too
1108   std::set<Slvs_hEntity> anEntToRemove;
1109   std::map<std::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator
1110       anAttrIter = myEntityAttrMap.begin();
1111   while (anAttrIter != myEntityAttrMap.end()) {
1112     if (!anAttrIter->first->owner() || !anAttrIter->first->owner()->data() ||
1113         !anAttrIter->first->owner()->data()->isValid()) {
1114       anEntToRemove.insert(anAttrIter->second);
1115       std::map<std::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator
1116           aRemovedIter = anAttrIter;
1117       anAttrIter++;
1118       myEntityAttrMap.erase(aRemovedIter);
1119     } else
1120       anAttrIter++;
1121   }
1122   std::map<FeaturePtr, Slvs_hEntity>::iterator aFeatIter = myEntityFeatMap.begin();
1123   while (aFeatIter != myEntityFeatMap.end()) {
1124     if (!aFeatIter->first || !aFeatIter->first->data() ||
1125         !aFeatIter->first->data()->isValid()) {
1126       anEntToRemove.insert(aFeatIter->second);
1127       std::map<FeaturePtr, Slvs_hEntity>::iterator aRemovedIter = aFeatIter;
1128       aFeatIter++;
1129       myEntityFeatMap.erase(aRemovedIter);
1130     } else
1131       aFeatIter++;
1132   }
1133   removeEntitiesById(anEntToRemove);
1134
1135   // Probably, need to update coincidence constraints
1136   if (isCCRemoved && !myExtraCoincidence.empty()) {
1137     // Make a copy, because the new list of unused constrtaints will be generated
1138     std::set<std::shared_ptr<SketchPlugin_Constraint> > anExtraCopy = myExtraCoincidence;
1139     myExtraCoincidence.clear();
1140
1141     std::set<std::shared_ptr<SketchPlugin_Constraint> >::iterator aCIter = anExtraCopy.begin();
1142     for (; aCIter != anExtraCopy.end(); aCIter++)
1143       if ((*aCIter)->data() && (*aCIter)->data()->isValid())
1144         changeConstraint(*aCIter);
1145   }
1146
1147   return !isAllValid;
1148 }
1149
1150 // ============================================================================
1151 //  Function: updateAttribute
1152 //  Class:    SketchSolver_ConstraintGroup
1153 //  Purpose:  update features of sketch after resolving constraints
1154 // ============================================================================
1155 bool SketchSolver_ConstraintGroup::updateAttribute(
1156     std::shared_ptr<ModelAPI_Attribute> theAttribute, const Slvs_hEntity& theEntityID)
1157 {
1158   // Search the position of the first parameter of the entity
1159   int anEntPos = Search(theEntityID, myEntities);
1160   int aFirstParamPos = Search(myEntities[anEntPos].param[0], myParams);
1161
1162   // Look over supported types of entities
1163
1164   // Point in 3D
1165   std::shared_ptr<GeomDataAPI_Point> aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point>(
1166       theAttribute);
1167   if (aPoint) {
1168     if (fabs(aPoint->x() - myParams[aFirstParamPos].val) > tolerance
1169         || fabs(aPoint->y() - myParams[aFirstParamPos + 1].val) > tolerance
1170         || fabs(aPoint->z() - myParams[aFirstParamPos + 2].val) > tolerance) {
1171       aPoint->setValue(myParams[aFirstParamPos].val, myParams[aFirstParamPos + 1].val,
1172                        myParams[aFirstParamPos + 2].val);
1173       return true;
1174     }
1175     return false;
1176   }
1177
1178   // Point in 2D
1179   std::shared_ptr<GeomDataAPI_Point2D> aPoint2D =
1180       std::dynamic_pointer_cast<GeomDataAPI_Point2D>(theAttribute);
1181   if (aPoint2D) {
1182     if (fabs(aPoint2D->x() - myParams[aFirstParamPos].val) > tolerance
1183         || fabs(aPoint2D->y() - myParams[aFirstParamPos + 1].val) > tolerance) {
1184       aPoint2D->setValue(myParams[aFirstParamPos].val, myParams[aFirstParamPos + 1].val);
1185       return true;
1186     }
1187     return false;
1188   }
1189
1190   // Scalar value
1191   AttributeDoublePtr aScalar = std::dynamic_pointer_cast<ModelAPI_AttributeDouble>(theAttribute);
1192   if (aScalar) {
1193     if (fabs(aScalar->value() - myParams[aFirstParamPos].val) > tolerance) {
1194       aScalar->setValue(myParams[aFirstParamPos].val);
1195       return true;
1196     }
1197     return false;
1198   }
1199
1200   /// \todo Support other types of entities
1201   return false;
1202 }
1203
1204 // ============================================================================
1205 //  Function: updateEntityIfPossible
1206 //  Class:    SketchSolver_ConstraintGroup
1207 //  Purpose:  search the entity in this group and update it
1208 // ============================================================================
1209 void SketchSolver_ConstraintGroup::updateEntityIfPossible(
1210     std::shared_ptr<ModelAPI_Attribute> theEntity)
1211 {
1212   if (myEntityAttrMap.find(theEntity) != myEntityAttrMap.end()) {
1213     // If the attribute is a point and it is changed (the group needs to rebuild),
1214     // probably user has dragged this point into this position,
1215     // so it is necessary to add constraint which will guarantee the point will not change
1216
1217     // Store myNeedToSolve flag to verify the entity is really changed
1218     bool aNeedToSolveCopy = myNeedToSolve;
1219     myNeedToSolve = false;
1220
1221     changeEntity(theEntity);
1222
1223     if (myNeedToSolve)  // the entity is changed
1224     {
1225       // Verify the entity is a point and add temporary constraint of permanency
1226       std::shared_ptr<GeomDataAPI_Point> aPoint = std::dynamic_pointer_cast<GeomDataAPI_Point>(
1227           theEntity);
1228       std::shared_ptr<GeomDataAPI_Point2D> aPoint2D = std::dynamic_pointer_cast<
1229           GeomDataAPI_Point2D>(theEntity);
1230       if (aPoint || aPoint2D)
1231         addTemporaryConstraintWhereDragged(theEntity);
1232     }
1233
1234     // Restore flag of changes
1235     myNeedToSolve = myNeedToSolve || aNeedToSolveCopy;
1236
1237     if (myNeedToSolve)
1238       updateRelatedConstraints(theEntity);
1239   }
1240 }
1241
1242 // ============================================================================
1243 //  Function: addTemporaryConstraintWhereDragged
1244 //  Class:    SketchSolver_ConstraintGroup
1245 //  Purpose:  add transient constraint SLVS_C_WHERE_DRAGGED for the entity, 
1246 //            which was moved by user
1247 // ============================================================================
1248 void SketchSolver_ConstraintGroup::addTemporaryConstraintWhereDragged(
1249     std::shared_ptr<ModelAPI_Attribute> theEntity,
1250     bool theAllowToFit)
1251 {
1252   // Find identifier of the entity
1253   std::map<std::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator anEntIter =
1254       myEntityAttrMap.find(theEntity);
1255   if (anEntIter == myEntityAttrMap.end())
1256     return;
1257
1258   // Get identifiers of all dragged points
1259   std::set<Slvs_hEntity> aDraggedPntID;
1260   aDraggedPntID.insert(myTempPointWDrgdID);
1261   std::list<Slvs_hConstraint>::const_iterator aTmpCoIter = myTempConstraints.begin();
1262   for (; aTmpCoIter != myTempConstraints.end(); aTmpCoIter++) {
1263     unsigned int aConstrPos = Search(*aTmpCoIter, myConstraints);
1264     if (aConstrPos < myConstraints.size())
1265       aDraggedPntID.insert(myConstraints[aConstrPos].ptA);
1266   }
1267   std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
1268   for (; aConstrIter != myConstraints.end(); aConstrIter++)
1269     if (aConstrIter->type == SLVS_C_WHERE_DRAGGED)
1270       aDraggedPntID.insert(aConstrIter->ptA);
1271   // Find whether there is a point coincident with theEntity, which already has SLVS_C_WHERE_DRAGGED
1272   std::vector<std::set<Slvs_hEntity> >::iterator aCoPtIter = myCoincidentPoints.begin();
1273   for (; aCoPtIter != myCoincidentPoints.end(); aCoPtIter++) {
1274     if (aCoPtIter->find(anEntIter->second) == aCoPtIter->end())
1275       continue;  // the entity was not found in current set
1276
1277     // Find one of already created SLVS_C_WHERE_DRAGGED constraints in current set of coincident points
1278     std::set<Slvs_hEntity>::const_iterator aDrgIter = aDraggedPntID.begin();
1279     for (; aDrgIter != aDraggedPntID.end(); aDrgIter++)
1280       if (aCoPtIter->find(*aDrgIter) != aCoPtIter->end())
1281         return;  // the SLVS_C_WHERE_DRAGGED constraint already exists
1282   }
1283   if (aDraggedPntID.find(anEntIter->second) != aDraggedPntID.end())
1284     return;
1285
1286   // If this is a first dragged point, its parameters should be placed 
1287   // into Slvs_System::dragged field to avoid system inconsistense
1288   if (myTempPointWhereDragged.empty() && theAllowToFit) {
1289     int anEntPos = Search(anEntIter->second, myEntities);
1290     Slvs_hParam* aDraggedParam = myEntities[anEntPos].param;
1291     for (int i = 0; i < 4; i++, aDraggedParam++)
1292       if (*aDraggedParam != 0)
1293         myTempPointWhereDragged.push_back(*aDraggedParam);
1294     myTempPointWDrgdID = myEntities[anEntPos].h;
1295     return;
1296   }
1297
1298   // Create additional SLVS_C_WHERE_DRAGGED constraint if myTempPointWhereDragged field is not empty
1299   Slvs_Constraint aWDConstr = Slvs_MakeConstraint(++myConstrMaxID, myID, SLVS_C_WHERE_DRAGGED,
1300                                                   myWorkplane.h, 0.0, anEntIter->second, 0, 0, 0);
1301   myConstraints.push_back(aWDConstr);
1302   myTempConstraints.push_back(aWDConstr.h);
1303 }
1304
1305 // ============================================================================
1306 //  Function: removeTemporaryConstraints
1307 //  Class:    SketchSolver_ConstraintGroup
1308 //  Purpose:  remove all transient SLVS_C_WHERE_DRAGGED constraints after
1309 //            resolving the set of constraints
1310 // ============================================================================
1311 void SketchSolver_ConstraintGroup::removeTemporaryConstraints(
1312     const std::set<Slvs_hConstraint>& theRemoved)
1313 {
1314   std::list<Slvs_hConstraint>::reverse_iterator aTmpConstrIter;
1315   for (aTmpConstrIter = myTempConstraints.rbegin(); aTmpConstrIter != myTempConstraints.rend();
1316       aTmpConstrIter++) {
1317     if (!theRemoved.empty() && theRemoved.find(*aTmpConstrIter) == theRemoved.end())
1318       continue;
1319     unsigned int aConstrPos = Search(*aTmpConstrIter, myConstraints);
1320     if (aConstrPos >= myConstraints.size())
1321       continue;
1322     myConstraints.erase(myConstraints.begin() + aConstrPos);
1323
1324     // If the removing constraint has higher index, decrease the indexer
1325     if (*aTmpConstrIter == myConstrMaxID)
1326       myConstrMaxID--;
1327   }
1328   myTempConstraints.clear();
1329
1330   // Clear basic dragged point
1331   myTempPointWhereDragged.clear();
1332   myTempPointWDrgdID = SLVS_E_UNKNOWN;
1333 }
1334
1335 // ============================================================================
1336 //  Function: removeConstraint
1337 //  Class:    SketchSolver_ConstraintGroup
1338 //  Purpose:  remove constraint and all unused entities
1339 // ============================================================================
1340 void SketchSolver_ConstraintGroup::removeConstraint(
1341     std::shared_ptr<SketchPlugin_Constraint> theConstraint)
1342 {
1343   ConstraintMap::iterator anIterToRemove = myConstraintMap.find(theConstraint);
1344   if (anIterToRemove == myConstraintMap.end())
1345     return;
1346
1347   std::vector<Slvs_hConstraint> aCnstrToRemove = anIterToRemove->second;
1348   // Remove constraint from the map
1349   myConstraintMap.erase(anIterToRemove);
1350
1351   std::set<Slvs_hEntity> anEntToRemove;
1352   
1353   // Find unused entities
1354   std::vector<Slvs_hConstraint>::iterator aCnstrToRemoveIter = aCnstrToRemove.begin();
1355   for (; aCnstrToRemoveIter != aCnstrToRemove.end(); aCnstrToRemoveIter++) {
1356     int aConstrPos = Search(*aCnstrToRemoveIter, myConstraints);
1357     Slvs_hEntity aCnstEnt[] = { myConstraints[aConstrPos].ptA, myConstraints[aConstrPos].ptB,
1358         myConstraints[aConstrPos].entityA, myConstraints[aConstrPos].entityB };
1359     for (int i = 0; i < 4; i++)
1360       if (aCnstEnt[i] != 0)
1361         anEntToRemove.insert(aCnstEnt[i]);
1362     myConstraints.erase(myConstraints.begin() + aConstrPos);
1363     if (*aCnstrToRemoveIter == myConstrMaxID)
1364       myConstrMaxID--;
1365   }
1366
1367   // Find all entities which are based on these unused
1368   std::vector<Slvs_Entity>::const_iterator anEntIter = myEntities.begin();
1369   for ( ; anEntIter != myEntities.end(); anEntIter++)
1370     if (anEntIter->type == SLVS_E_LINE_SEGMENT || anEntIter->type == SLVS_E_CIRCLE ||
1371         anEntIter->type == SLVS_E_ARC_OF_CIRCLE) {
1372       for (int i = 0; i < 4; i++)
1373         if (anEntToRemove.find(anEntIter->point[i]) != anEntToRemove.end()) {
1374           anEntToRemove.insert(anEntIter->h);
1375           for (int j = 0; j < 4; j++)
1376             if (anEntIter->param[j] != 0)
1377               anEntToRemove.insert(anEntIter->point[j]);
1378           break;
1379         }
1380     }
1381
1382   std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
1383   for (; aConstrIter != myConstraints.end(); aConstrIter++) {
1384     Slvs_hEntity aEnts[] = { aConstrIter->ptA, aConstrIter->ptB, aConstrIter->entityA, aConstrIter
1385         ->entityB };
1386     for (int i = 0; i < 4; i++)
1387       if (aEnts[i] != 0 && anEntToRemove.find(aEnts[i]) != anEntToRemove.end())
1388         anEntToRemove.erase(aEnts[i]);
1389   }
1390
1391   if (anEntToRemove.empty())
1392     return;
1393
1394   // Remove unused entities
1395   std::map<std::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator anEntAttrIter =
1396       myEntityAttrMap.begin();
1397   while (anEntAttrIter != myEntityAttrMap.end()) {
1398     if (anEntToRemove.find(anEntAttrIter->second) != anEntToRemove.end()) {
1399       std::map<std::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator aRemovedIter =
1400           anEntAttrIter;
1401       anEntAttrIter++;
1402       myEntityAttrMap.erase(aRemovedIter);
1403     } else
1404       anEntAttrIter++;
1405   }
1406   std::map<FeaturePtr, Slvs_hEntity>::iterator anEntFeatIter = myEntityFeatMap.begin();
1407   while (anEntFeatIter != myEntityFeatMap.end()) {
1408     if (anEntToRemove.find(anEntFeatIter->second) != anEntToRemove.end()) {
1409       std::map<FeaturePtr, Slvs_hEntity>::iterator aRemovedIter = anEntFeatIter;
1410       anEntFeatIter++;
1411       myEntityFeatMap.erase(aRemovedIter);
1412     } else
1413       anEntFeatIter++;
1414   }
1415
1416   removeEntitiesById(anEntToRemove);
1417
1418   if (myCoincidentPoints.size() == 1 && myCoincidentPoints.front().empty())
1419     myCoincidentPoints.clear();
1420 }
1421
1422 // ============================================================================
1423 //  Function: removeEntitiesById
1424 //  Class:    SketchSolver_ConstraintGroup
1425 //  Purpose:  Removes specified entities and their parameters
1426 // ============================================================================
1427 void SketchSolver_ConstraintGroup::removeEntitiesById(const std::set<Slvs_hEntity>& theEntities)
1428 {
1429   std::set<Slvs_hEntity>::const_reverse_iterator aRemIter = theEntities.rbegin();
1430   for (; aRemIter != theEntities.rend(); aRemIter++) {
1431     unsigned int anEntPos = Search(*aRemIter, myEntities);
1432     if (anEntPos >= myEntities.size())
1433       continue;
1434     if (myEntities[anEntPos].param[0] != 0) {
1435       unsigned int aParamPos = Search(myEntities[anEntPos].param[0], myParams);
1436       if (aParamPos >= myParams.size())
1437         continue;
1438       int aNbParams = 0;
1439       while (myEntities[anEntPos].param[aNbParams] != 0)
1440         aNbParams++;
1441       if (myEntities[anEntPos].param[aNbParams - 1] == myParamMaxID)
1442         myParamMaxID -= aNbParams;
1443       myParams.erase(myParams.begin() + aParamPos, myParams.begin() + aParamPos + aNbParams);
1444       if (*aRemIter == myEntityMaxID)
1445         myEntityMaxID--;
1446     }
1447     myEntities.erase(myEntities.begin() + anEntPos);
1448     myEntOfConstr.erase(myEntOfConstr.begin() + anEntPos);
1449
1450     // Remove entity's ID from the lists of conincident points
1451     std::vector<std::set<Slvs_hEntity> >::iterator aCoPtIter = myCoincidentPoints.begin();
1452     for (; aCoPtIter != myCoincidentPoints.end(); aCoPtIter++)
1453       aCoPtIter->erase(*aRemIter);
1454   }
1455 }
1456
1457 // ============================================================================
1458 //  Function: addCoincidentPoints
1459 //  Class:    SketchSolver_ConstraintGroup
1460 //  Purpose:  add coincident point the appropriate list of such points
1461 // ============================================================================
1462 bool SketchSolver_ConstraintGroup::addCoincidentPoints(const Slvs_hEntity& thePoint1,
1463                                                        const Slvs_hEntity& thePoint2)
1464 {
1465   std::vector<std::set<Slvs_hEntity> >::iterator aCoPtIter = myCoincidentPoints.begin();
1466   std::vector<std::set<Slvs_hEntity> >::iterator aFirstFound = myCoincidentPoints.end();
1467   while (aCoPtIter != myCoincidentPoints.end()) {
1468     bool isFound[2] = {  // indicate which point ID was already in coincidence constraint
1469         aCoPtIter->find(thePoint1) != aCoPtIter->end(), aCoPtIter->find(thePoint2)
1470             != aCoPtIter->end(), };
1471     if (isFound[0] && isFound[1])  // points are already connected by coincidence constraints => no need additional one
1472       return false;
1473     if ((isFound[0] && !isFound[1]) || (!isFound[0] && isFound[1])) {
1474       if (aFirstFound != myCoincidentPoints.end()) {  // there are two groups of coincident points connected by created constraint => merge them
1475         int aFirstFoundShift = aFirstFound - myCoincidentPoints.begin();
1476         int aCurrentShift = aCoPtIter - myCoincidentPoints.begin();
1477         aFirstFound->insert(aCoPtIter->begin(), aCoPtIter->end());
1478         myCoincidentPoints.erase(aCoPtIter);
1479         aFirstFound = myCoincidentPoints.begin() + aFirstFoundShift;
1480         aCoPtIter = myCoincidentPoints.begin() + aCurrentShift;
1481         continue;
1482       } else {
1483         aCoPtIter->insert(isFound[0] ? thePoint2 : thePoint1);
1484         aFirstFound = aCoPtIter;
1485       }
1486     }
1487     aCoPtIter++;
1488   }
1489   // No points were found, need to create new set
1490   if (aFirstFound == myCoincidentPoints.end()) {
1491     std::set<Slvs_hEntity> aNewSet;
1492     aNewSet.insert(thePoint1);
1493     aNewSet.insert(thePoint2);
1494     myCoincidentPoints.push_back(aNewSet);
1495   }
1496
1497   return true;
1498 }
1499
1500 // ============================================================================
1501 //  Function: updateRelatedConstraints
1502 //  Class:    SketchSolver_ConstraintGroup
1503 //  Purpose:  emit the signal to update constraints
1504 // ============================================================================
1505 void SketchSolver_ConstraintGroup::updateRelatedConstraints(
1506     std::shared_ptr<ModelAPI_Attribute> theEntity) const
1507 {
1508   ConstraintMap::const_iterator aConstrIter = myConstraintMap.begin();
1509   for (; aConstrIter != myConstraintMap.end(); aConstrIter++) {
1510     std::list<std::shared_ptr<ModelAPI_Attribute> > anAttributes = aConstrIter->first->data()
1511         ->attributes(std::string());
1512
1513     std::list<std::shared_ptr<ModelAPI_Attribute> >::iterator anAttrIter = anAttributes.begin();
1514     for (; anAttrIter != anAttributes.end(); anAttrIter++) {
1515       bool isUpd = (*anAttrIter == theEntity);
1516       std::shared_ptr<ModelAPI_AttributeRefAttr> aRefAttr = std::dynamic_pointer_cast<
1517           ModelAPI_AttributeRefAttr>(*anAttrIter);
1518       if (aRefAttr && !aRefAttr->isObject() && aRefAttr->attr() == theEntity)
1519         isUpd = true;
1520
1521       if (isUpd) {
1522         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
1523         ModelAPI_EventCreator::get()->sendUpdated(aConstrIter->first, anEvent);
1524         break;
1525       }
1526     }
1527   }
1528 }
1529
1530 void SketchSolver_ConstraintGroup::updateRelatedConstraints(
1531     std::shared_ptr<ModelAPI_Feature> theFeature) const
1532 {
1533   ConstraintMap::const_iterator aConstrIter = myConstraintMap.begin();
1534   for (; aConstrIter != myConstraintMap.end(); aConstrIter++) {
1535     std::list<std::shared_ptr<ModelAPI_Attribute> > anAttributes = aConstrIter->first->data()
1536         ->attributes(std::string());
1537
1538     std::list<std::shared_ptr<ModelAPI_Attribute> >::iterator anAttrIter = anAttributes.begin();
1539     for (; anAttrIter != anAttributes.end(); anAttrIter++) {
1540       std::shared_ptr<ModelAPI_AttributeRefAttr> aRefAttr = std::dynamic_pointer_cast<
1541           ModelAPI_AttributeRefAttr>(*anAttrIter);
1542       if (aRefAttr && aRefAttr->isObject() && aRefAttr->object() == theFeature) {
1543         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
1544         ModelAPI_EventCreator::get()->sendUpdated(aConstrIter->first, anEvent);
1545         break;
1546       }
1547     }
1548   }
1549 }
1550
1551 // ========================================================
1552 // =========      Auxiliary functions       ===============
1553 // ========================================================
1554
1555 template<typename T>
1556 int Search(const uint32_t& theEntityID, const std::vector<T>& theEntities)
1557 {
1558   int aResIndex = theEntityID <= theEntities.size() ? theEntityID - 1 : 0;
1559   int aVecSize = theEntities.size();
1560   while (aResIndex >= 0 && theEntities[aResIndex].h > theEntityID)
1561     aResIndex--;
1562   while (aResIndex < aVecSize && aResIndex >= 0 && theEntities[aResIndex].h < theEntityID)
1563     aResIndex++;
1564   if (aResIndex == -1)
1565     aResIndex = aVecSize;
1566   return aResIndex;
1567 }