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