]> SALOME platform Git repositories - modules/shaper.git/blob - src/SketchSolver/SketchSolver_ConstraintGroup.cpp
Salome HOME
Merge branch 'master' of newgeom:newgeom
[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   // Get parameters of workplane
806   boost::shared_ptr<ModelAPI_Attribute> aDirX = mySketch->data()->attribute(
807       SketchPlugin_Sketch::DIRX_ID());
808   boost::shared_ptr<ModelAPI_Attribute> aDirY = mySketch->data()->attribute(
809       SketchPlugin_Sketch::DIRY_ID());
810   boost::shared_ptr<ModelAPI_Attribute> aNorm = mySketch->data()->attribute(
811       SketchPlugin_Sketch::NORM_ID());
812   boost::shared_ptr<ModelAPI_Attribute> anOrigin = mySketch->data()->attribute(
813       SketchPlugin_Sketch::ORIGIN_ID());
814   // Transform them into SolveSpace format
815   Slvs_hEntity aNormalWP = changeNormal(aDirX, aDirY, aNorm);
816   if (!aNormalWP)
817     return false;
818   Slvs_hEntity anOriginWP = changeEntity(anOrigin);
819   if (!anOriginWP)
820     return false;
821
822   if (!myWorkplane.h) {
823     // Create workplane
824     myWorkplane = Slvs_MakeWorkplane(++myEntityMaxID, myID, anOriginWP, aNormalWP);
825     // Workplane should be added to the list of entities
826     myEntities.push_back(myWorkplane);
827     myEntOfConstr.push_back(false);
828   }
829   return true;
830 }
831
832 // ============================================================================
833 //  Function: changeParameter
834 //  Class:    SketchSolver_ConstraintGroup
835 //  Purpose:  create/update value of parameter
836 // ============================================================================
837 Slvs_hParam SketchSolver_ConstraintGroup::changeParameter(
838     const double& theParam, std::vector<Slvs_Param>::const_iterator& thePrmIter)
839 {
840   if (thePrmIter != myParams.end()) {  // Parameter should be updated
841     int aParamPos = thePrmIter - myParams.begin();
842     if (fabs(thePrmIter->val - theParam) > tolerance) {
843       myNeedToSolve = true;  // parameter is changed, need to resolve constraints
844       myParams[aParamPos].val = theParam;
845     }
846     thePrmIter++;
847     return myParams[aParamPos].h;
848   }
849
850   // Newly created parameter
851   Slvs_Param aParam = Slvs_MakeParam(++myParamMaxID, myID, theParam);
852   myParams.push_back(aParam);
853   myNeedToSolve = true;
854   // The list of parameters is changed, move iterator to the end of the list to avoid problems
855   thePrmIter = myParams.end();
856   return aParam.h;
857 }
858
859 // ============================================================================
860 //  Function: resolveConstraints
861 //  Class:    SketchSolver_ConstraintGroup
862 //  Purpose:  solve the set of constraints for the current group
863 // ============================================================================
864 bool SketchSolver_ConstraintGroup::resolveConstraints()
865 {
866   if (!myNeedToSolve)
867     return false;
868
869   myConstrSolver.setGroupID(myID);
870   myConstrSolver.setParameters(myParams);
871   myConstrSolver.setEntities(myEntities);
872   myConstrSolver.setConstraints(myConstraints);
873   myConstrSolver.setDraggedParameters(myTempPointWhereDragged);
874
875   int aResult = myConstrSolver.solve();
876   if (aResult == SLVS_RESULT_OKAY) {  // solution succeeded, store results into correspondent attributes
877                                       // Obtain result into the same list of parameters
878     if (!myConstrSolver.getResult(myParams))
879       return true;
880
881     // We should go through the attributes map, because only attributes have valued parameters
882     std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator anEntIter =
883         myEntityAttrMap.begin();
884     for (; anEntIter != myEntityAttrMap.end(); anEntIter++)
885       if (updateAttribute(anEntIter->first, anEntIter->second))
886         updateRelatedConstraints(anEntIter->first);
887   } else if (!myConstraints.empty())
888     Events_Error::send(SketchSolver_Error::CONSTRAINTS(), this);
889
890   removeTemporaryConstraints();
891   myNeedToSolve = false;
892   return true;
893 }
894
895 // ============================================================================
896 //  Function: mergeGroups
897 //  Class:    SketchSolver_ConstraintGroup
898 //  Purpose:  append specified group to the current group
899 // ============================================================================
900 void SketchSolver_ConstraintGroup::mergeGroups(const SketchSolver_ConstraintGroup& theGroup)
901 {
902   // If specified group is empty, no need to merge
903   if (theGroup.myConstraintMap.empty())
904     return;
905
906   // Map between old and new indexes of SolveSpace constraints
907   std::map<Slvs_hConstraint, Slvs_hConstraint> aConstrMap;
908
909   // Add all constraints from theGroup to the current group
910   ConstraintMap::const_iterator aConstrIter = theGroup.myConstraintMap.begin();
911   for (; aConstrIter != theGroup.myConstraintMap.end(); aConstrIter++)
912     if (changeConstraint(aConstrIter->first))
913       aConstrMap[aConstrIter->second.back()] = myConstrMaxID;  // the constraint was added => store its ID
914
915   // Add temporary constraints from theGroup
916   std::list<Slvs_hConstraint>::const_iterator aTempConstrIter = theGroup.myTempConstraints.begin();
917   for (; aTempConstrIter != theGroup.myTempConstraints.end(); aTempConstrIter++) {
918     std::map<Slvs_hConstraint, Slvs_hConstraint>::iterator aFind = aConstrMap.find(
919         *aTempConstrIter);
920     if (aFind != aConstrMap.end())
921       myTempConstraints.push_back(aFind->second);
922   }
923
924   if (myTempPointWhereDragged.empty())
925     myTempPointWhereDragged = theGroup.myTempPointWhereDragged;
926   else if (!theGroup.myTempPointWhereDragged.empty()) {  // Need to create additional transient constraint
927     std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator aFeatureIter =
928         theGroup.myEntityAttrMap.begin();
929     for (; aFeatureIter != theGroup.myEntityAttrMap.end(); aFeatureIter++)
930       if (aFeatureIter->second == myTempPointWDrgdID) {
931         addTemporaryConstraintWhereDragged(aFeatureIter->first);
932         break;
933       }
934   }
935
936   myNeedToSolve = myNeedToSolve || theGroup.myNeedToSolve;
937 }
938
939 // ============================================================================
940 //  Function: splitGroup
941 //  Class:    SketchSolver_ConstraintGroup
942 //  Purpose:  divide the group into several subgroups
943 // ============================================================================
944 void SketchSolver_ConstraintGroup::splitGroup(std::vector<SketchSolver_ConstraintGroup*>& theCuts)
945 {
946   // Divide constraints and entities into several groups
947   std::vector<std::set<Slvs_hEntity> > aGroupsEntities;
948   std::vector<std::set<Slvs_hConstraint> > aGroupsConstr;
949   int aMaxNbEntities = 0;  // index of the group with maximal nuber of elements (this group will be left in the current)
950   std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
951   for (; aConstrIter != myConstraints.end(); aConstrIter++) {
952     Slvs_hEntity aConstrEnt[] = { aConstrIter->ptA, aConstrIter->ptB, aConstrIter->entityA,
953         aConstrIter->entityB };
954     std::vector<int> anIndexes;
955     // Go through the groupped entities and find even one of entities of current constraint
956     std::vector<std::set<Slvs_hEntity> >::iterator aGrEntIter;
957     for (aGrEntIter = aGroupsEntities.begin(); aGrEntIter != aGroupsEntities.end(); aGrEntIter++) {
958       bool isFound = false;
959       for (int i = 0; i < 4 && !isFound; i++)
960         if (aConstrEnt[i] != 0) {
961           isFound = (aGrEntIter->find(aConstrEnt[i]) != aGrEntIter->end());
962           // Also we need to check sub-entities
963           int aEntPos = Search(aConstrEnt[i], myEntities);
964           Slvs_hEntity* aSub = myEntities[aEntPos].point;
965           for (int j = 0; *aSub != 0 && j < 4 && !isFound; aSub++, j++)
966             isFound = (aGrEntIter->find(*aSub) != aGrEntIter->end());
967         }
968       if (isFound)
969         anIndexes.push_back(aGrEntIter - aGroupsEntities.begin());
970     }
971     // Add new group if no one is found
972     if (anIndexes.empty()) {
973       std::set<Slvs_hEntity> aNewGrEnt;
974       for (int i = 0; i < 4; i++)
975         if (aConstrEnt[i] != 0) {
976           aNewGrEnt.insert(aConstrEnt[i]);
977           int aEntPos = Search(aConstrEnt[i], myEntities);
978           Slvs_hEntity* aSub = myEntities[aEntPos].point;
979           for (int j = 0; *aSub != 0 && j < 4; aSub++, j++)
980             aNewGrEnt.insert(*aSub);
981         }
982       std::set<Slvs_hConstraint> aNewGrConstr;
983       aNewGrConstr.insert(aConstrIter->h);
984
985       aGroupsEntities.push_back(aNewGrEnt);
986       aGroupsConstr.push_back(aNewGrConstr);
987       if (aNewGrEnt.size() > aGroupsEntities[aMaxNbEntities].size())
988         aMaxNbEntities = aGroupsEntities.size() - 1;
989     } else {  // Add entities indexes into the found group
990       aGrEntIter = aGroupsEntities.begin() + anIndexes.front();
991       for (int i = 0; i < 4; i++)
992         if (aConstrEnt[i] != 0) {
993           aGrEntIter->insert(aConstrEnt[i]);
994           int aEntPos = Search(aConstrEnt[i], myEntities);
995           Slvs_hEntity* aSub = myEntities[aEntPos].point;
996           for (int j = 0; *aSub != 0 && j < 4; aSub++, j++)
997             aGrEntIter->insert(*aSub);
998         }
999       aGroupsConstr[anIndexes.front()].insert(aConstrIter->h);
1000       if (aGrEntIter->size() > aGroupsEntities[aMaxNbEntities].size())
1001         aMaxNbEntities = aGrEntIter - aGroupsEntities.begin();
1002       if (anIndexes.size() > 1) {  // There are found several connected groups, merge them
1003         std::vector<std::set<Slvs_hEntity> >::iterator aFirstGroup = aGroupsEntities.begin()
1004             + anIndexes.front();
1005         std::vector<std::set<Slvs_hConstraint> >::iterator aFirstConstr = aGroupsConstr.begin()
1006             + anIndexes.front();
1007         std::vector<int>::iterator anInd = anIndexes.begin();
1008         for (++anInd; anInd != anIndexes.end(); anInd++) {
1009           aFirstGroup->insert(aGroupsEntities[*anInd].begin(), aGroupsEntities[*anInd].end());
1010           aFirstConstr->insert(aGroupsConstr[*anInd].begin(), aGroupsConstr[*anInd].end());
1011         }
1012         if (aFirstGroup->size() > aGroupsEntities[aMaxNbEntities].size())
1013           aMaxNbEntities = anIndexes.front();
1014         // Remove merged groups
1015         for (anInd = anIndexes.end() - 1; anInd != anIndexes.begin(); anInd--) {
1016           aGroupsEntities.erase(aGroupsEntities.begin() + (*anInd));
1017           aGroupsConstr.erase(aGroupsConstr.begin() + (*anInd));
1018         }
1019       }
1020     }
1021   }
1022
1023   if (aGroupsEntities.size() <= 1)
1024     return;
1025
1026   // Remove the group with maximum elements as it will be left in the current group
1027   aGroupsEntities.erase(aGroupsEntities.begin() + aMaxNbEntities);
1028   aGroupsConstr.erase(aGroupsConstr.begin() + aMaxNbEntities);
1029
1030   // Add new groups of constraints and divide current group
1031   std::vector<SketchSolver_ConstraintGroup*> aNewGroups;
1032   for (int i = aGroupsEntities.size(); i > 0; i--) {
1033     SketchSolver_ConstraintGroup* aG = new SketchSolver_ConstraintGroup(mySketch);
1034     aNewGroups.push_back(aG);
1035   }
1036   ConstraintMap::const_iterator aConstrMapIter = myConstraintMap.begin();
1037   int aConstrMapPos = 0;  // position of iterator in the map (used to restore iterator after removing constraint)
1038   while (aConstrMapIter != myConstraintMap.end()) {
1039     std::vector<std::set<Slvs_hConstraint> >::const_iterator aGIter = aGroupsConstr.begin();
1040     std::vector<SketchSolver_ConstraintGroup*>::iterator aGroup = aNewGroups.begin();
1041     for (; aGIter != aGroupsConstr.end(); aGIter++, aGroup++)
1042       if (aGIter->find(aConstrMapIter->second.front()) != aGIter->end()) {
1043         (*aGroup)->changeConstraint(aConstrMapIter->first);
1044         removeConstraint(aConstrMapIter->first);
1045         // restore iterator
1046         aConstrMapIter = myConstraintMap.begin();
1047         for (int i = 0; i < aConstrMapPos; i++)
1048           aConstrMapIter++;
1049         break;
1050       }
1051     if (aGIter == aGroupsConstr.end()) {
1052       aConstrMapIter++;
1053       aConstrMapPos++;
1054     }
1055   }
1056
1057   theCuts.insert(theCuts.end(), aNewGroups.begin(), aNewGroups.end());
1058 }
1059
1060 // ============================================================================
1061 //  Function: updateGroup
1062 //  Class:    SketchSolver_ConstraintGroup
1063 //  Purpose:  search removed entities and constraints
1064 // ============================================================================
1065 bool SketchSolver_ConstraintGroup::updateGroup()
1066 {
1067   ConstraintMap::reverse_iterator aConstrIter = myConstraintMap.rbegin();
1068   bool isAllValid = true;
1069   bool isCCRemoved = false;  // indicates that at least one of coincidence constraints was removed
1070   int aConstrIndex = 0;
1071   while (/*isAllValid && */aConstrIter != myConstraintMap.rend()) {
1072     if (!aConstrIter->first->data() || !aConstrIter->first->data()->isValid()) {
1073       if (aConstrIter->first->getKind().compare(SketchPlugin_ConstraintCoincidence::ID()) == 0)
1074         isCCRemoved = true;
1075       removeConstraint(aConstrIter->first);
1076       isAllValid = false;
1077       // Get back the correct position of iterator after the "remove" operation
1078       aConstrIter = myConstraintMap.rbegin();
1079       for (int i = 0; i < aConstrIndex && aConstrIter != myConstraintMap.rend(); i++)
1080         aConstrIter++;
1081     } else {
1082       aConstrIter++;
1083       aConstrIndex++;
1084     }
1085   }
1086
1087   // Check if some entities are invalid too
1088   std::set<Slvs_hEntity> anEntToRemove;
1089   std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator
1090       anAttrIter = myEntityAttrMap.begin();
1091   while (anAttrIter != myEntityAttrMap.end()) {
1092     if (!anAttrIter->first->owner() || !anAttrIter->first->owner()->data() ||
1093         !anAttrIter->first->owner()->data()->isValid()) {
1094       anEntToRemove.insert(anAttrIter->second);
1095       std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator
1096           aRemovedIter = anAttrIter;
1097       anAttrIter++;
1098       myEntityAttrMap.erase(aRemovedIter);
1099     } else
1100       anAttrIter++;
1101   }
1102   std::map<FeaturePtr, Slvs_hEntity>::iterator aFeatIter = myEntityFeatMap.begin();
1103   while (aFeatIter != myEntityFeatMap.end()) {
1104     if (!aFeatIter->first || !aFeatIter->first->data() ||
1105         !aFeatIter->first->data()->isValid()) {
1106       anEntToRemove.insert(aFeatIter->second);
1107       std::map<FeaturePtr, Slvs_hEntity>::iterator aRemovedIter = aFeatIter;
1108       aFeatIter++;
1109       myEntityFeatMap.erase(aRemovedIter);
1110     } else
1111       aFeatIter++;
1112   }
1113   removeEntitiesById(anEntToRemove);
1114
1115   // Probably, need to update coincidence constraints
1116   if (isCCRemoved && !myExtraCoincidence.empty()) {
1117     // Make a copy, because the new list of unused constrtaints will be generated
1118     std::set<boost::shared_ptr<SketchPlugin_Constraint> > anExtraCopy = myExtraCoincidence;
1119     myExtraCoincidence.clear();
1120
1121     std::set<boost::shared_ptr<SketchPlugin_Constraint> >::iterator aCIter = anExtraCopy.begin();
1122     for (; aCIter != anExtraCopy.end(); aCIter++)
1123       if ((*aCIter)->data() && (*aCIter)->data()->isValid())
1124         changeConstraint(*aCIter);
1125   }
1126
1127   return !isAllValid;
1128 }
1129
1130 // ============================================================================
1131 //  Function: updateAttribute
1132 //  Class:    SketchSolver_ConstraintGroup
1133 //  Purpose:  update features of sketch after resolving constraints
1134 // ============================================================================
1135 bool SketchSolver_ConstraintGroup::updateAttribute(
1136     boost::shared_ptr<ModelAPI_Attribute> theAttribute, const Slvs_hEntity& theEntityID)
1137 {
1138   // Search the position of the first parameter of the entity
1139   int anEntPos = Search(theEntityID, myEntities);
1140   int aFirstParamPos = Search(myEntities[anEntPos].param[0], myParams);
1141
1142   // Look over supported types of entities
1143
1144   // Point in 3D
1145   boost::shared_ptr<GeomDataAPI_Point> aPoint = boost::dynamic_pointer_cast<GeomDataAPI_Point>(
1146       theAttribute);
1147   if (aPoint) {
1148     if (fabs(aPoint->x() - myParams[aFirstParamPos].val) > tolerance
1149         || fabs(aPoint->y() - myParams[aFirstParamPos + 1].val) > tolerance
1150         || fabs(aPoint->z() - myParams[aFirstParamPos + 2].val) > tolerance) {
1151       aPoint->setValue(myParams[aFirstParamPos].val, myParams[aFirstParamPos + 1].val,
1152                        myParams[aFirstParamPos + 2].val);
1153       return true;
1154     }
1155     return false;
1156   }
1157
1158   // Point in 2D
1159   boost::shared_ptr<GeomDataAPI_Point2D> aPoint2D =
1160       boost::dynamic_pointer_cast<GeomDataAPI_Point2D>(theAttribute);
1161   if (aPoint2D) {
1162     if (fabs(aPoint2D->x() - myParams[aFirstParamPos].val) > tolerance
1163         || fabs(aPoint2D->y() - myParams[aFirstParamPos + 1].val) > tolerance) {
1164       aPoint2D->setValue(myParams[aFirstParamPos].val, myParams[aFirstParamPos + 1].val);
1165       return true;
1166     }
1167     return false;
1168   }
1169
1170   // Scalar value
1171   AttributeDoublePtr aScalar = boost::dynamic_pointer_cast<ModelAPI_AttributeDouble>(theAttribute);
1172   if (aScalar) {
1173     if (fabs(aScalar->value() - myParams[aFirstParamPos].val) > tolerance) {
1174       aScalar->setValue(myParams[aFirstParamPos].val);
1175       return true;
1176     }
1177     return false;
1178   }
1179
1180   /// \todo Support other types of entities
1181   return false;
1182 }
1183
1184 // ============================================================================
1185 //  Function: updateEntityIfPossible
1186 //  Class:    SketchSolver_ConstraintGroup
1187 //  Purpose:  search the entity in this group and update it
1188 // ============================================================================
1189 void SketchSolver_ConstraintGroup::updateEntityIfPossible(
1190     boost::shared_ptr<ModelAPI_Attribute> theEntity)
1191 {
1192   if (myEntityAttrMap.find(theEntity) != myEntityAttrMap.end()) {
1193     // If the attribute is a point and it is changed (the group needs to rebuild),
1194     // probably user has dragged this point into this position,
1195     // so it is necessary to add constraint which will guarantee the point will not change
1196
1197     // Store myNeedToSolve flag to verify the entity is really changed
1198     bool aNeedToSolveCopy = myNeedToSolve;
1199     myNeedToSolve = false;
1200
1201     changeEntity(theEntity);
1202
1203     if (myNeedToSolve)  // the entity is changed
1204     {
1205       // Verify the entity is a point and add temporary constraint of permanency
1206       boost::shared_ptr<GeomDataAPI_Point> aPoint = boost::dynamic_pointer_cast<GeomDataAPI_Point>(
1207           theEntity);
1208       boost::shared_ptr<GeomDataAPI_Point2D> aPoint2D = boost::dynamic_pointer_cast<
1209           GeomDataAPI_Point2D>(theEntity);
1210       if (aPoint || aPoint2D)
1211         addTemporaryConstraintWhereDragged(theEntity);
1212     }
1213
1214     // Restore flag of changes
1215     myNeedToSolve = myNeedToSolve || aNeedToSolveCopy;
1216
1217     if (myNeedToSolve)
1218       updateRelatedConstraints(theEntity);
1219   }
1220 }
1221
1222 // ============================================================================
1223 //  Function: addTemporaryConstraintWhereDragged
1224 //  Class:    SketchSolver_ConstraintGroup
1225 //  Purpose:  add transient constraint SLVS_C_WHERE_DRAGGED for the entity, 
1226 //            which was moved by user
1227 // ============================================================================
1228 void SketchSolver_ConstraintGroup::addTemporaryConstraintWhereDragged(
1229     boost::shared_ptr<ModelAPI_Attribute> theEntity,
1230     bool theAllowToFit)
1231 {
1232   // Find identifier of the entity
1233   std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::const_iterator anEntIter =
1234       myEntityAttrMap.find(theEntity);
1235   if (anEntIter == myEntityAttrMap.end())
1236     return;
1237
1238   // Get identifiers of all dragged points
1239   std::set<Slvs_hEntity> aDraggedPntID;
1240   aDraggedPntID.insert(myTempPointWDrgdID);
1241   std::list<Slvs_hConstraint>::const_iterator aTmpCoIter = myTempConstraints.begin();
1242   for (; aTmpCoIter != myTempConstraints.end(); aTmpCoIter++) {
1243     unsigned int aConstrPos = Search(*aTmpCoIter, myConstraints);
1244     if (aConstrPos < myConstraints.size())
1245       aDraggedPntID.insert(myConstraints[aConstrPos].ptA);
1246   }
1247   std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
1248   for (; aConstrIter != myConstraints.end(); aConstrIter++)
1249     if (aConstrIter->type == SLVS_C_WHERE_DRAGGED)
1250       aDraggedPntID.insert(aConstrIter->ptA);
1251   // Find whether there is a point coincident with theEntity, which already has SLVS_C_WHERE_DRAGGED
1252   std::vector<std::set<Slvs_hEntity> >::iterator aCoPtIter = myCoincidentPoints.begin();
1253   for (; aCoPtIter != myCoincidentPoints.end(); aCoPtIter++) {
1254     if (aCoPtIter->find(anEntIter->second) == aCoPtIter->end())
1255       continue;  // the entity was not found in current set
1256
1257     // Find one of already created SLVS_C_WHERE_DRAGGED constraints in current set of coincident points
1258     std::set<Slvs_hEntity>::const_iterator aDrgIter = aDraggedPntID.begin();
1259     for (; aDrgIter != aDraggedPntID.end(); aDrgIter++)
1260       if (aCoPtIter->find(*aDrgIter) != aCoPtIter->end())
1261         return;  // the SLVS_C_WHERE_DRAGGED constraint already exists
1262   }
1263   if (aDraggedPntID.find(anEntIter->second) != aDraggedPntID.end())
1264     return;
1265
1266   // If this is a first dragged point, its parameters should be placed 
1267   // into Slvs_System::dragged field to avoid system inconsistense
1268   if (myTempPointWhereDragged.empty() && theAllowToFit) {
1269     int anEntPos = Search(anEntIter->second, myEntities);
1270     Slvs_hParam* aDraggedParam = myEntities[anEntPos].param;
1271     for (int i = 0; i < 4; i++, aDraggedParam++)
1272       if (*aDraggedParam != 0)
1273         myTempPointWhereDragged.push_back(*aDraggedParam);
1274     myTempPointWDrgdID = myEntities[anEntPos].h;
1275     return;
1276   }
1277
1278   // Create additional SLVS_C_WHERE_DRAGGED constraint if myTempPointWhereDragged field is not empty
1279   Slvs_Constraint aWDConstr = Slvs_MakeConstraint(++myConstrMaxID, myID, SLVS_C_WHERE_DRAGGED,
1280                                                   myWorkplane.h, 0.0, anEntIter->second, 0, 0, 0);
1281   myConstraints.push_back(aWDConstr);
1282   myTempConstraints.push_back(aWDConstr.h);
1283 }
1284
1285 // ============================================================================
1286 //  Function: removeTemporaryConstraints
1287 //  Class:    SketchSolver_ConstraintGroup
1288 //  Purpose:  remove all transient SLVS_C_WHERE_DRAGGED constraints after
1289 //            resolving the set of constraints
1290 // ============================================================================
1291 void SketchSolver_ConstraintGroup::removeTemporaryConstraints(
1292     const std::set<Slvs_hConstraint>& theRemoved)
1293 {
1294   std::list<Slvs_hConstraint>::reverse_iterator aTmpConstrIter;
1295   for (aTmpConstrIter = myTempConstraints.rbegin(); aTmpConstrIter != myTempConstraints.rend();
1296       aTmpConstrIter++) {
1297     if (!theRemoved.empty() && theRemoved.find(*aTmpConstrIter) == theRemoved.end())
1298       continue;
1299     unsigned int aConstrPos = Search(*aTmpConstrIter, myConstraints);
1300     if (aConstrPos >= myConstraints.size())
1301       continue;
1302     myConstraints.erase(myConstraints.begin() + aConstrPos);
1303
1304     // If the removing constraint has higher index, decrease the indexer
1305     if (*aTmpConstrIter == myConstrMaxID)
1306       myConstrMaxID--;
1307   }
1308   myTempConstraints.clear();
1309
1310   // Clear basic dragged point
1311   myTempPointWhereDragged.clear();
1312   myTempPointWDrgdID = SLVS_E_UNKNOWN;
1313 }
1314
1315 // ============================================================================
1316 //  Function: removeConstraint
1317 //  Class:    SketchSolver_ConstraintGroup
1318 //  Purpose:  remove constraint and all unused entities
1319 // ============================================================================
1320 void SketchSolver_ConstraintGroup::removeConstraint(
1321     boost::shared_ptr<SketchPlugin_Constraint> theConstraint)
1322 {
1323   ConstraintMap::iterator anIterToRemove = myConstraintMap.find(theConstraint);
1324   if (anIterToRemove == myConstraintMap.end())
1325     return;
1326
1327   std::vector<Slvs_hConstraint> aCnstrToRemove = anIterToRemove->second;
1328   // Remove constraint from the map
1329   myConstraintMap.erase(anIterToRemove);
1330
1331   std::set<Slvs_hEntity> anEntToRemove;
1332   
1333   // Find unused entities
1334   std::vector<Slvs_hConstraint>::iterator aCnstrToRemoveIter = aCnstrToRemove.begin();
1335   for (; aCnstrToRemoveIter != aCnstrToRemove.end(); aCnstrToRemoveIter++) {
1336     int aConstrPos = Search(*aCnstrToRemoveIter, myConstraints);
1337     Slvs_hEntity aCnstEnt[] = { myConstraints[aConstrPos].ptA, myConstraints[aConstrPos].ptB,
1338         myConstraints[aConstrPos].entityA, myConstraints[aConstrPos].entityB };
1339     for (int i = 0; i < 4; i++)
1340       if (aCnstEnt[i] != 0)
1341         anEntToRemove.insert(aCnstEnt[i]);
1342     myConstraints.erase(myConstraints.begin() + aConstrPos);
1343     if (*aCnstrToRemoveIter == myConstrMaxID)
1344       myConstrMaxID--;
1345   }
1346
1347   // Find all entities which are based on these unused
1348   std::vector<Slvs_Entity>::const_iterator anEntIter = myEntities.begin();
1349   for ( ; anEntIter != myEntities.end(); anEntIter++)
1350     if (anEntIter->type == SLVS_E_LINE_SEGMENT || anEntIter->type == SLVS_E_CIRCLE ||
1351         anEntIter->type == SLVS_E_ARC_OF_CIRCLE) {
1352       for (int i = 0; i < 4; i++)
1353         if (anEntToRemove.find(anEntIter->point[i]) != anEntToRemove.end()) {
1354           anEntToRemove.insert(anEntIter->h);
1355           for (int j = 0; j < 4; j++)
1356             if (anEntIter->param[j] != 0)
1357               anEntToRemove.insert(anEntIter->point[j]);
1358           break;
1359         }
1360     }
1361
1362   std::vector<Slvs_Constraint>::const_iterator aConstrIter = myConstraints.begin();
1363   for (; aConstrIter != myConstraints.end(); aConstrIter++) {
1364     Slvs_hEntity aEnts[] = { aConstrIter->ptA, aConstrIter->ptB, aConstrIter->entityA, aConstrIter
1365         ->entityB };
1366     for (int i = 0; i < 4; i++)
1367       if (aEnts[i] != 0 && anEntToRemove.find(aEnts[i]) != anEntToRemove.end())
1368         anEntToRemove.erase(aEnts[i]);
1369   }
1370
1371   if (anEntToRemove.empty())
1372     return;
1373
1374   // Remove unused entities
1375   std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator anEntAttrIter =
1376       myEntityAttrMap.begin();
1377   while (anEntAttrIter != myEntityAttrMap.end()) {
1378     if (anEntToRemove.find(anEntAttrIter->second) != anEntToRemove.end()) {
1379       std::map<boost::shared_ptr<ModelAPI_Attribute>, Slvs_hEntity>::iterator aRemovedIter =
1380           anEntAttrIter;
1381       anEntAttrIter++;
1382       myEntityAttrMap.erase(aRemovedIter);
1383     } else
1384       anEntAttrIter++;
1385   }
1386   std::map<FeaturePtr, Slvs_hEntity>::iterator anEntFeatIter = myEntityFeatMap.begin();
1387   while (anEntFeatIter != myEntityFeatMap.end()) {
1388     if (anEntToRemove.find(anEntFeatIter->second) != anEntToRemove.end()) {
1389       std::map<FeaturePtr, Slvs_hEntity>::iterator aRemovedIter = anEntFeatIter;
1390       anEntFeatIter++;
1391       myEntityFeatMap.erase(aRemovedIter);
1392     } else
1393       anEntFeatIter++;
1394   }
1395
1396   removeEntitiesById(anEntToRemove);
1397
1398   if (myCoincidentPoints.size() == 1 && myCoincidentPoints.front().empty())
1399     myCoincidentPoints.clear();
1400 }
1401
1402 // ============================================================================
1403 //  Function: removeEntitiesById
1404 //  Class:    SketchSolver_ConstraintGroup
1405 //  Purpose:  Removes specified entities and their parameters
1406 // ============================================================================
1407 void SketchSolver_ConstraintGroup::removeEntitiesById(const std::set<Slvs_hEntity>& theEntities)
1408 {
1409   std::set<Slvs_hEntity>::const_reverse_iterator aRemIter = theEntities.rbegin();
1410   for (; aRemIter != theEntities.rend(); aRemIter++) {
1411     unsigned int anEntPos = Search(*aRemIter, myEntities);
1412     if (anEntPos >= myEntities.size())
1413       continue;
1414     if (myEntities[anEntPos].param[0] != 0) {
1415       unsigned int aParamPos = Search(myEntities[anEntPos].param[0], myParams);
1416       if (aParamPos >= myParams.size())
1417         continue;
1418       int aNbParams = 0;
1419       while (myEntities[anEntPos].param[aNbParams] != 0)
1420         aNbParams++;
1421       if (myEntities[anEntPos].param[aNbParams - 1] == myParamMaxID)
1422         myParamMaxID -= aNbParams;
1423       myParams.erase(myParams.begin() + aParamPos, myParams.begin() + aParamPos + aNbParams);
1424       if (*aRemIter == myEntityMaxID)
1425         myEntityMaxID--;
1426     }
1427     myEntities.erase(myEntities.begin() + anEntPos);
1428     myEntOfConstr.erase(myEntOfConstr.begin() + anEntPos);
1429
1430     // Remove entity's ID from the lists of conincident points
1431     std::vector<std::set<Slvs_hEntity> >::iterator aCoPtIter = myCoincidentPoints.begin();
1432     for (; aCoPtIter != myCoincidentPoints.end(); aCoPtIter++)
1433       aCoPtIter->erase(*aRemIter);
1434   }
1435 }
1436
1437 // ============================================================================
1438 //  Function: addCoincidentPoints
1439 //  Class:    SketchSolver_ConstraintGroup
1440 //  Purpose:  add coincident point the appropriate list of such points
1441 // ============================================================================
1442 bool SketchSolver_ConstraintGroup::addCoincidentPoints(const Slvs_hEntity& thePoint1,
1443                                                        const Slvs_hEntity& thePoint2)
1444 {
1445   std::vector<std::set<Slvs_hEntity> >::iterator aCoPtIter = myCoincidentPoints.begin();
1446   std::vector<std::set<Slvs_hEntity> >::iterator aFirstFound = myCoincidentPoints.end();
1447   while (aCoPtIter != myCoincidentPoints.end()) {
1448     bool isFound[2] = {  // indicate which point ID was already in coincidence constraint
1449         aCoPtIter->find(thePoint1) != aCoPtIter->end(), aCoPtIter->find(thePoint2)
1450             != aCoPtIter->end(), };
1451     if (isFound[0] && isFound[1])  // points are already connected by coincidence constraints => no need additional one
1452       return false;
1453     if ((isFound[0] && !isFound[1]) || (!isFound[0] && isFound[1])) {
1454       if (aFirstFound != myCoincidentPoints.end()) {  // there are two groups of coincident points connected by created constraint => merge them
1455         int aFirstFoundShift = aFirstFound - myCoincidentPoints.begin();
1456         int aCurrentShift = aCoPtIter - myCoincidentPoints.begin();
1457         aFirstFound->insert(aCoPtIter->begin(), aCoPtIter->end());
1458         myCoincidentPoints.erase(aCoPtIter);
1459         aFirstFound = myCoincidentPoints.begin() + aFirstFoundShift;
1460         aCoPtIter = myCoincidentPoints.begin() + aCurrentShift;
1461         continue;
1462       } else {
1463         aCoPtIter->insert(isFound[0] ? thePoint2 : thePoint1);
1464         aFirstFound = aCoPtIter;
1465       }
1466     }
1467     aCoPtIter++;
1468   }
1469   // No points were found, need to create new set
1470   if (aFirstFound == myCoincidentPoints.end()) {
1471     std::set<Slvs_hEntity> aNewSet;
1472     aNewSet.insert(thePoint1);
1473     aNewSet.insert(thePoint2);
1474     myCoincidentPoints.push_back(aNewSet);
1475   }
1476
1477   return true;
1478 }
1479
1480 // ============================================================================
1481 //  Function: updateRelatedConstraints
1482 //  Class:    SketchSolver_ConstraintGroup
1483 //  Purpose:  emit the signal to update constraints
1484 // ============================================================================
1485 void SketchSolver_ConstraintGroup::updateRelatedConstraints(
1486     boost::shared_ptr<ModelAPI_Attribute> theEntity) const
1487 {
1488   ConstraintMap::const_iterator aConstrIter = myConstraintMap.begin();
1489   for (; aConstrIter != myConstraintMap.end(); aConstrIter++) {
1490     std::list<boost::shared_ptr<ModelAPI_Attribute> > anAttributes = aConstrIter->first->data()
1491         ->attributes(std::string());
1492
1493     std::list<boost::shared_ptr<ModelAPI_Attribute> >::iterator anAttrIter = anAttributes.begin();
1494     for (; anAttrIter != anAttributes.end(); anAttrIter++) {
1495       bool isUpd = (*anAttrIter == theEntity);
1496       boost::shared_ptr<ModelAPI_AttributeRefAttr> aRefAttr = boost::dynamic_pointer_cast<
1497           ModelAPI_AttributeRefAttr>(*anAttrIter);
1498       if (aRefAttr && !aRefAttr->isObject() && aRefAttr->attr() == theEntity)
1499         isUpd = true;
1500
1501       if (isUpd) {
1502         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
1503         ModelAPI_EventCreator::get()->sendUpdated(aConstrIter->first, anEvent);
1504         break;
1505       }
1506     }
1507   }
1508 }
1509
1510 void SketchSolver_ConstraintGroup::updateRelatedConstraints(
1511     boost::shared_ptr<ModelAPI_Feature> theFeature) const
1512 {
1513   ConstraintMap::const_iterator aConstrIter = myConstraintMap.begin();
1514   for (; aConstrIter != myConstraintMap.end(); aConstrIter++) {
1515     std::list<boost::shared_ptr<ModelAPI_Attribute> > anAttributes = aConstrIter->first->data()
1516         ->attributes(std::string());
1517
1518     std::list<boost::shared_ptr<ModelAPI_Attribute> >::iterator anAttrIter = anAttributes.begin();
1519     for (; anAttrIter != anAttributes.end(); anAttrIter++) {
1520       boost::shared_ptr<ModelAPI_AttributeRefAttr> aRefAttr = boost::dynamic_pointer_cast<
1521           ModelAPI_AttributeRefAttr>(*anAttrIter);
1522       if (aRefAttr && aRefAttr->isObject() && aRefAttr->object() == theFeature) {
1523         static Events_ID anEvent = Events_Loop::eventByName(EVENT_OBJECT_UPDATED);
1524         ModelAPI_EventCreator::get()->sendUpdated(aConstrIter->first, anEvent);
1525         break;
1526       }
1527     }
1528   }
1529 }
1530
1531 // ========================================================
1532 // =========      Auxiliary functions       ===============
1533 // ========================================================
1534
1535 template<typename T>
1536 int Search(const uint32_t& theEntityID, const std::vector<T>& theEntities)
1537 {
1538   int aResIndex = theEntityID <= theEntities.size() ? theEntityID - 1 : 0;
1539   int aVecSize = theEntities.size();
1540   while (aResIndex >= 0 && theEntities[aResIndex].h > theEntityID)
1541     aResIndex--;
1542   while (aResIndex < aVecSize && aResIndex >= 0 && theEntities[aResIndex].h < theEntityID)
1543     aResIndex++;
1544   if (aResIndex == -1)
1545     aResIndex = aVecSize;
1546   return aResIndex;
1547 }